2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
23 package org.onap.so.apihandlerinfra.tenantisolation.helpers;
26 import java.util.UUID;
27 import javax.ws.rs.core.Response;
28 import javax.ws.rs.core.UriBuilder;
29 import org.apache.http.HttpStatus;
30 import org.json.JSONException;
31 import org.json.JSONObject;
32 import org.onap.so.apihandler.common.ErrorNumbers;
33 import org.onap.so.apihandlerinfra.exceptions.ApiException;
34 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
35 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
36 import org.onap.so.client.HttpClient;
37 import org.onap.so.client.HttpClientFactory;
38 import org.onap.logging.filter.base.ErrorCode;
39 import org.onap.so.logger.MessageEnum;
40 import org.onap.so.utils.CryptoUtils;
41 import org.onap.logging.filter.base.ONAPComponents;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.springframework.beans.factory.annotation.Value;
45 import org.springframework.stereotype.Component;
48 public class SDCClientHelper {
50 private static Logger logger = LoggerFactory.getLogger(SDCClientHelper.class);
51 private static final String SDC_CONTENT_TYPE = "application/json";
52 private static final String SDC_ACCEPT_TYPE = "application/json";
53 private static final String PARTIAL_SDC_URI = "/sdc/v1/catalog/services/";
55 private static final String MESSAGE_UNDEFINED_ERROR = "Undefined Error Message!";
56 private static final String MESSAGE_UNEXPECTED_FORMAT = "Unexpected response format from SDC.";
57 private final HttpClientFactory httpClientFactory = new HttpClientFactory();
59 private static final String STATUS_CODE = "statusCode";
60 private static final String MESSAGE = "message";
61 private static final String MESSAGE_ID = "messageId";
62 private static final String REQUEST_ERROR = "requestError";
63 private static final String SERVICE_EXCEPTION = "serviceException";
64 private static final String POLICY_EXCEPTION = "policyException";
66 @Value("${mso.sdc.endpoint}")
67 private String sdcEndpoint;
68 @Value("${mso.sdc.activate.userid}")
69 private String sdcActivateUserId;
70 @Value("${mso.sdc.activate.instanceid}")
71 private String sdcActivateInstanceId;
72 @Value("${mso.sdc.client.auth}")
73 private String sdcClientAuth;
74 @Value("${mso.msoKey}")
75 private String msoKey;
78 * Send POST request to SDC for operational activation
80 * @param serviceModelVersionI - String
81 * @param operationalEnvironmentId - String
82 * @param workloadContext - String
83 * @return sdcResponseJsonObj - JSONObject object
84 * @throws JSONException
86 public JSONObject postActivateOperationalEnvironment(String serviceModelVersionId, String operationalEnvironmentId,
87 String workloadContext) throws ApiException {
88 JSONObject sdcResponseJsonObj = new JSONObject();
91 String urlString = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId);
92 String jsonPayload = this.buildJsonWorkloadContext(workloadContext);
93 String basicAuthCred = getBasicAuth();
95 if (basicAuthCred == null || "".equals(basicAuthCred)) {
96 ErrorLoggerInfo errorLoggerInfo =
97 new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcessError)
100 throw new ValidateException.Builder(
101 " SDC credentials 'mso.sdc.client.auth' not setup in properties file!",
102 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo)
106 URL url = new URL(urlString);
108 HttpClient httpClient = httpClientFactory.newJsonClient(url, ONAPComponents.SDC);
109 httpClient.addBasicAuthHeader(sdcClientAuth, msoKey);
110 httpClient.addAdditionalHeader("X-ECOMP-InstanceID", sdcActivateInstanceId);
111 httpClient.addAdditionalHeader("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE);
112 httpClient.addAdditionalHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE);
113 httpClient.addAdditionalHeader("USER_ID", sdcActivateUserId);
115 Response apiResponse = setHttpPostResponse(httpClient, jsonPayload);
116 int statusCode = apiResponse.getStatus();;
118 String responseData = apiResponse.readEntity(String.class);
119 sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);
121 } catch (Exception ex) {
122 logger.debug("calling SDC Exception message:", ex);
123 String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage();
124 logger.debug(errorMessage);
125 sdcResponseJsonObj.put(STATUS_CODE, String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
126 sdcResponseJsonObj.put(MESSAGE_ID, "");
127 sdcResponseJsonObj.put(MESSAGE, errorMessage);
130 return sdcResponseJsonObj;
134 * set HttpPostResponse
136 * @param config - RESTConfig object
137 * @param jsonPayload - String
138 * @return client - RestClient object
140 public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException {
142 return client.post(jsonPayload);
143 } catch (Exception ex) {
144 ErrorLoggerInfo errorLoggerInfo =
145 new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcessError)
148 throw new ValidateException.Builder("Bad request could not post payload", HttpStatus.SC_BAD_REQUEST,
149 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
156 * @param sdcResponseJsonObj - JSONObject object
157 * @param statusCode - int
158 * @return enhancedAsdcResponseJsonObj - JSONObject object
160 public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) {
162 JSONObject enhancedAsdcResponseJsonObj = new JSONObject();
165 String messageId = "";
167 if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted
168 enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId"));
169 enhancedAsdcResponseJsonObj.put(STATUS_CODE, Integer.toString(statusCode));
170 enhancedAsdcResponseJsonObj.put(MESSAGE_ID, "");
171 enhancedAsdcResponseJsonObj.put(MESSAGE, "Success");
174 if (sdcResponseJsonObj.has(REQUEST_ERROR)) {
175 JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject(REQUEST_ERROR);
176 if (sdcResponseJsonObj.getJSONObject(REQUEST_ERROR).has(SERVICE_EXCEPTION)) {
177 message = requestErrorObj.getJSONObject(SERVICE_EXCEPTION).getString("text");
178 messageId = requestErrorObj.getJSONObject(SERVICE_EXCEPTION).getString(MESSAGE_ID);
180 if (sdcResponseJsonObj.getJSONObject(REQUEST_ERROR).has(POLICY_EXCEPTION)) {
181 message = requestErrorObj.getJSONObject(POLICY_EXCEPTION).getString("text");
182 messageId = requestErrorObj.getJSONObject(POLICY_EXCEPTION).getString(MESSAGE_ID);
184 enhancedAsdcResponseJsonObj.put(STATUS_CODE, Integer.toString(statusCode));
185 enhancedAsdcResponseJsonObj.put(MESSAGE_ID, messageId);
186 enhancedAsdcResponseJsonObj.put(MESSAGE, message);
190 enhancedAsdcResponseJsonObj.put(STATUS_CODE,
191 String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
192 enhancedAsdcResponseJsonObj.put(MESSAGE_ID, MESSAGE_UNDEFINED_ERROR);
193 enhancedAsdcResponseJsonObj.put(MESSAGE, MESSAGE_UNEXPECTED_FORMAT);
196 return enhancedAsdcResponseJsonObj;
203 * @param serviceModelVersionId - String
204 * @param operationalEnvironmentId - String
205 * @return uriBuilder - String
207 public String buildUriBuilder(String serviceModelVersionId, String operationalEnvironmentId) {
208 String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId + "/activate";
209 UriBuilder uriBuilder = UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI).path(path);
210 return uriBuilder.build().toString();
216 * @param workloadContext - String
217 * @return String json
218 * @throws JSONException
220 public String buildJsonWorkloadContext(String workloadContext) {
221 return new JSONObject().put("workloadContext", workloadContext).toString();
228 * @param toDecrypt - String
229 * @param msokey - String
230 * @return result - String
232 public synchronized String decrypt(String toDecrypt, String msokey) {
233 String result = null;
235 result = CryptoUtils.decrypt(toDecrypt, msokey);
237 } catch (Exception e) {
238 logger.debug("Failed to decrypt credentials: {}", toDecrypt, e);
243 private String getBasicAuth() {
244 return decrypt(sdcClientAuth, msoKey);