2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.so.apihandlerinfra.tenantisolation.helpers;
24 import java.util.HashMap;
26 import java.util.UUID;
28 import javax.ws.rs.core.Response;
29 import javax.ws.rs.core.UriBuilder;
31 import org.apache.http.HttpStatus;
32 import org.json.JSONException;
33 import org.json.JSONObject;
34 import org.onap.so.apihandler.common.ErrorNumbers;
35 import org.onap.so.apihandlerinfra.exceptions.ApiException;
36 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
37 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
38 import org.onap.so.client.HttpClient;
39 import org.onap.so.logger.MessageEnum;
40 import org.onap.so.logger.MsoLogger;
41 import org.onap.so.utils.CryptoUtils;
42 import org.onap.so.utils.TargetEntity;
43 import org.springframework.beans.factory.annotation.Value;
44 import org.springframework.stereotype.Component;
47 public class SDCClientHelper {
49 private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.APIH, SDCClientHelper.class);
50 private static final String SDC_CONTENT_TYPE = "application/json";
51 private static final String SDC_ACCEPT_TYPE = "application/json";
52 private static String PARTIAL_SDC_URI = "/sdc/v1/catalog/services/";
54 private static String MESSAGE_UNDEFINED_ERROR = "Undefined Error Message!";
55 private static String MESSAGE_UNEXPECTED_FORMAT = "Unexpected response format from SDC.";
57 @Value("${mso.sdc.endpoint}")
58 private String sdcEndpoint;
59 @Value("${mso.sdc.activate.userid}")
60 private String sdcActivateUserId;
61 @Value("${mso.sdc.activate.instanceid}")
62 private String sdcActivateInstanceId;
63 @Value("${mso.sdc.client.auth}")
64 private String sdcClientAuth;
65 @Value("${mso.msoKey}")
66 private String msoKey;
69 * Send POST request to SDC for operational activation
70 * @param serviceModelVersionI - String
71 * @param operationalEnvironmentId - String
72 * @param workloadContext - String
73 * @return sdcResponseJsonObj - JSONObject object
74 * @throws JSONException
76 public JSONObject postActivateOperationalEnvironment(String serviceModelVersionId, String operationalEnvironmentId, String workloadContext) throws ApiException {
77 JSONObject sdcResponseJsonObj = new JSONObject();
80 String urlString = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId);
81 String jsonPayload = this.buildJsonWorkloadContext(workloadContext);
82 String basicAuthCred = getBasicAuth();
84 if ( basicAuthCred == null || "".equals(basicAuthCred) ) {
85 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
86 ValidateException validateException = new ValidateException.Builder(" SDC credentials 'mso.sdc.client.auth' not setup in properties file!",
87 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
89 throw validateException;
92 URL url = new URL(urlString);
94 HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.SDC);
95 httpClient.addBasicAuthHeader(sdcClientAuth, msoKey);
97 Response apiResponse = setHttpPostResponse(httpClient, jsonPayload);
98 int statusCode = apiResponse.getStatus();;
100 String responseData = apiResponse.readEntity(String.class);
101 sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);
103 } catch (Exception ex) {
104 msoLogger.debug("calling SDC Exception message: " + ex.getMessage());
105 String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage();
106 msoLogger.debug(errorMessage);
107 sdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
108 sdcResponseJsonObj.put("messageId", "");
109 sdcResponseJsonObj.put("message", errorMessage);
112 return sdcResponseJsonObj;
116 * set HttpPostResponse
117 * @param config - RESTConfig object
118 * @param jsonPayload - String
119 * @return client - RestClient object
121 public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException {
123 return client.post(jsonPayload);
124 }catch(Exception ex){
125 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
126 ValidateException validateException = new ValidateException.Builder("Bad request could not post payload",
127 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
129 throw validateException;
135 * @param sdcResponseJsonObj - JSONObject object
136 * @param statusCode - int
137 * @return enhancedAsdcResponseJsonObj - JSONObject object
139 public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) throws JSONException {
141 JSONObject enhancedAsdcResponseJsonObj = new JSONObject();
144 String messageId = "";
146 if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted
147 enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId"));
148 enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
149 enhancedAsdcResponseJsonObj.put("messageId", "");
150 enhancedAsdcResponseJsonObj.put("message", "Success");
153 if (sdcResponseJsonObj.has("requestError") ) {
154 JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject("requestError");
155 if (sdcResponseJsonObj.getJSONObject("requestError").has("serviceException") ) {
156 message = requestErrorObj.getJSONObject("serviceException").getString("text");
157 messageId = requestErrorObj.getJSONObject("serviceException").getString("messageId");
159 if (sdcResponseJsonObj.getJSONObject("requestError").has("policyException") ) {
160 message = requestErrorObj.getJSONObject("policyException").getString("text");
161 messageId = requestErrorObj.getJSONObject("policyException").getString("messageId");
163 enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
164 enhancedAsdcResponseJsonObj.put("messageId", messageId);
165 enhancedAsdcResponseJsonObj.put("message", message);
169 enhancedAsdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
170 enhancedAsdcResponseJsonObj.put("messageId", MESSAGE_UNDEFINED_ERROR);
171 enhancedAsdcResponseJsonObj.put("message", MESSAGE_UNEXPECTED_FORMAT);
174 return enhancedAsdcResponseJsonObj;
180 * @param serviceModelVersionId - String
181 * @param operationalEnvironmentId - String
182 * @return uriBuilder - String
184 public String buildUriBuilder(String serviceModelVersionId, String operationalEnvironmentId) {
185 String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId +"/activate";
186 UriBuilder uriBuilder = UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI)
188 return uriBuilder.build().toString();
193 * @param workloadContext - String
194 * @return String json
195 * @throws JSONException
197 public String buildJsonWorkloadContext(String workloadContext) throws JSONException {
198 return new JSONObject().put("workloadContext", workloadContext).toString();
204 * @param toDecrypt - String
205 * @param msokey - String
206 * @return result - String
208 public synchronized String decrypt(String toDecrypt, String msokey){
209 String result = null;
211 result = CryptoUtils.decrypt(toDecrypt, msokey);
214 catch (Exception e) {
215 msoLogger.debug("Failed to decrypt credentials: " + toDecrypt, e);
220 private String getBasicAuth() {
221 return decrypt(sdcClientAuth, msoKey);