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;
23 import java.util.UUID;
25 import javax.ws.rs.core.Response;
26 import javax.ws.rs.core.UriBuilder;
28 import org.apache.http.HttpStatus;
29 import org.json.JSONException;
30 import org.json.JSONObject;
31 import org.onap.so.apihandler.common.ErrorNumbers;
32 import org.onap.so.apihandlerinfra.exceptions.ApiException;
33 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
34 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
35 import org.onap.so.logger.MessageEnum;
36 import org.onap.so.logger.MsoLogger;
37 import org.onap.so.rest.APIResponse;
38 import org.onap.so.rest.RESTClient;
39 import org.onap.so.rest.RESTConfig;
40 import org.onap.so.rest.RESTException;
41 import org.onap.so.utils.CryptoUtils;
42 import org.springframework.beans.factory.annotation.Value;
43 import org.springframework.stereotype.Component;
46 public class SDCClientHelper {
48 private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.APIH, SDCClientHelper.class);
49 private static final String SDC_CONTENT_TYPE = "application/json";
50 private static final String SDC_ACCEPT_TYPE = "application/json";
51 private static String PARTIAL_SDC_URI = "/sdc/v1/catalog/services/";
53 private static String MESSAGE_UNDEFINED_ERROR = "Undefined Error Message!";
54 private static String MESSAGE_UNEXPECTED_FORMAT = "Unexpected response format from SDC.";
56 @Value("${mso.sdc.endpoint}")
57 private String sdcEndpoint;
58 @Value("${mso.sdc.activate.userid}")
59 private String sdcActivateUserId;
60 @Value("${mso.sdc.activate.instanceid}")
61 private String sdcActivateInstanceId;
62 @Value("${mso.sdc.client.auth}")
63 private String sdcClientAuth;
64 @Value("${mso.msoKey}")
65 private String msoKey;
68 * Send POST request to SDC for operational activation
69 * @param serviceModelVersionI - String
70 * @param operationalEnvironmentId - String
71 * @param workloadContext - String
72 * @return sdcResponseJsonObj - JSONObject object
73 * @throws JSONException
75 public JSONObject postActivateOperationalEnvironment(String serviceModelVersionId, String operationalEnvironmentId, String workloadContext) throws ApiException {
76 JSONObject sdcResponseJsonObj = new JSONObject();
79 String url = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId);
80 String jsonPayload = this.buildJsonWorkloadContext(workloadContext);
81 String basicAuthCred = getBasicAuth();
83 if ( basicAuthCred == null || "".equals(basicAuthCred) ) {
84 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
85 ValidateException validateException = new ValidateException.Builder(" SDC credentials 'mso.sdc.client.auth' not setup in properties file!",
86 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
88 throw validateException;
91 RESTConfig config = new RESTConfig(url);
92 RESTClient client = setRestClient(config);
93 client.addAuthorizationHeader(basicAuthCred);
95 APIResponse apiResponse = setHttpPostResponse(client, jsonPayload);
96 int statusCode = apiResponse.getStatusCode();
98 String responseData = apiResponse.getResponseBodyAsString();
99 sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);
101 } catch (Exception ex) {
102 msoLogger.debug("calling SDC Exception message: " + ex.getMessage());
103 String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage();
104 msoLogger.debug(errorMessage);
105 sdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
106 sdcResponseJsonObj.put("messageId", "");
107 sdcResponseJsonObj.put("message", errorMessage);
110 return sdcResponseJsonObj;
115 * @param config - RESTConfig object
116 * @return client - RestClient object
118 public RESTClient setRestClient(RESTConfig config) throws Exception {
119 RESTClient client = new RESTClient(config).addHeader("X-ECOMP-InstanceID", sdcActivateInstanceId)
120 .addHeader("X-ECOMP-RequestID", UUID.randomUUID().toString())
121 .addHeader("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE)
122 .addHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE)
123 .addHeader("USER_ID", sdcActivateUserId);
128 * set HttpPostResponse
129 * @param config - RESTConfig object
130 * @param jsonPayload - String
131 * @return client - RestClient object
133 public APIResponse setHttpPostResponse(RESTClient client, String jsonPayload) throws ApiException {
135 return client.httpPost(jsonPayload);
136 }catch(RESTException ex){
137 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
138 ValidateException validateException = new ValidateException.Builder("Bad request could not post payload",
139 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
141 throw validateException;
147 * @param sdcResponseJsonObj - JSONObject object
148 * @param statusCode - int
149 * @return enhancedAsdcResponseJsonObj - JSONObject object
151 public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) throws JSONException {
153 JSONObject enhancedAsdcResponseJsonObj = new JSONObject();
156 String messageId = "";
158 if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted
159 enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId"));
160 enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
161 enhancedAsdcResponseJsonObj.put("messageId", "");
162 enhancedAsdcResponseJsonObj.put("message", "Success");
165 if (sdcResponseJsonObj.has("requestError") ) {
166 JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject("requestError");
167 if (sdcResponseJsonObj.getJSONObject("requestError").has("serviceException") ) {
168 message = requestErrorObj.getJSONObject("serviceException").getString("text");
169 messageId = requestErrorObj.getJSONObject("serviceException").getString("messageId");
171 if (sdcResponseJsonObj.getJSONObject("requestError").has("policyException") ) {
172 message = requestErrorObj.getJSONObject("policyException").getString("text");
173 messageId = requestErrorObj.getJSONObject("policyException").getString("messageId");
175 enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
176 enhancedAsdcResponseJsonObj.put("messageId", messageId);
177 enhancedAsdcResponseJsonObj.put("message", message);
181 enhancedAsdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
182 enhancedAsdcResponseJsonObj.put("messageId", MESSAGE_UNDEFINED_ERROR);
183 enhancedAsdcResponseJsonObj.put("message", MESSAGE_UNEXPECTED_FORMAT);
186 return enhancedAsdcResponseJsonObj;
192 * @param serviceModelVersionId - String
193 * @param operationalEnvironmentId - String
194 * @return uriBuilder - String
196 public String buildUriBuilder(String serviceModelVersionId, String operationalEnvironmentId) {
197 String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId +"/activate";
198 UriBuilder uriBuilder = UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI)
200 return uriBuilder.build().toString();
205 * @param workloadContext - String
206 * @return String json
207 * @throws JSONException
209 public String buildJsonWorkloadContext(String workloadContext) throws JSONException {
210 return new JSONObject().put("workloadContext", workloadContext).toString();
216 * @param toDecrypt - String
217 * @param msokey - String
218 * @return result - String
220 public synchronized String decrypt(String toDecrypt, String msokey){
221 String result = null;
223 result = CryptoUtils.decrypt(toDecrypt, msokey);
226 catch (Exception e) {
227 msoLogger.debug("Failed to decrypt credentials: " + toDecrypt, e);
232 private String getBasicAuth() {
233 return decrypt(sdcClientAuth, msoKey);