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.so.logger.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.BusinessProcesssError)
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("X-ECOMP-RequestID", UUID.randomUUID().toString());
112 httpClient.addAdditionalHeader("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE);
113 httpClient.addAdditionalHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE);
114 httpClient.addAdditionalHeader("USER_ID", sdcActivateUserId);
116 Response apiResponse = setHttpPostResponse(httpClient, jsonPayload);
117 int statusCode = apiResponse.getStatus();;
119 String responseData = apiResponse.readEntity(String.class);
120 sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);
122 } catch (Exception ex) {
123 logger.debug("calling SDC Exception message:", ex);
124 String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage();
125 logger.debug(errorMessage);
126 sdcResponseJsonObj.put(STATUS_CODE, String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
127 sdcResponseJsonObj.put(MESSAGE_ID, "");
128 sdcResponseJsonObj.put(MESSAGE, errorMessage);
131 return sdcResponseJsonObj;
135 * set HttpPostResponse
137 * @param config - RESTConfig object
138 * @param jsonPayload - String
139 * @return client - RestClient object
141 public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException {
143 return client.post(jsonPayload);
144 } catch (Exception ex) {
145 ErrorLoggerInfo errorLoggerInfo =
146 new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
149 throw new ValidateException.Builder("Bad request could not post payload", HttpStatus.SC_BAD_REQUEST,
150 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
157 * @param sdcResponseJsonObj - JSONObject object
158 * @param statusCode - int
159 * @return enhancedAsdcResponseJsonObj - JSONObject object
161 public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) {
163 JSONObject enhancedAsdcResponseJsonObj = new JSONObject();
166 String messageId = "";
168 if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted
169 enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId"));
170 enhancedAsdcResponseJsonObj.put(STATUS_CODE, Integer.toString(statusCode));
171 enhancedAsdcResponseJsonObj.put(MESSAGE_ID, "");
172 enhancedAsdcResponseJsonObj.put(MESSAGE, "Success");
175 if (sdcResponseJsonObj.has(REQUEST_ERROR)) {
176 JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject(REQUEST_ERROR);
177 if (sdcResponseJsonObj.getJSONObject(REQUEST_ERROR).has(SERVICE_EXCEPTION)) {
178 message = requestErrorObj.getJSONObject(SERVICE_EXCEPTION).getString("text");
179 messageId = requestErrorObj.getJSONObject(SERVICE_EXCEPTION).getString(MESSAGE_ID);
181 if (sdcResponseJsonObj.getJSONObject(REQUEST_ERROR).has(POLICY_EXCEPTION)) {
182 message = requestErrorObj.getJSONObject(POLICY_EXCEPTION).getString("text");
183 messageId = requestErrorObj.getJSONObject(POLICY_EXCEPTION).getString(MESSAGE_ID);
185 enhancedAsdcResponseJsonObj.put(STATUS_CODE, Integer.toString(statusCode));
186 enhancedAsdcResponseJsonObj.put(MESSAGE_ID, messageId);
187 enhancedAsdcResponseJsonObj.put(MESSAGE, message);
191 enhancedAsdcResponseJsonObj.put(STATUS_CODE,
192 String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
193 enhancedAsdcResponseJsonObj.put(MESSAGE_ID, MESSAGE_UNDEFINED_ERROR);
194 enhancedAsdcResponseJsonObj.put(MESSAGE, MESSAGE_UNEXPECTED_FORMAT);
197 return enhancedAsdcResponseJsonObj;
204 * @param serviceModelVersionId - String
205 * @param operationalEnvironmentId - String
206 * @return uriBuilder - String
208 public String buildUriBuilder(String serviceModelVersionId, String operationalEnvironmentId) {
209 String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId + "/activate";
210 UriBuilder uriBuilder = UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI).path(path);
211 return uriBuilder.build().toString();
217 * @param workloadContext - String
218 * @return String json
219 * @throws JSONException
221 public String buildJsonWorkloadContext(String workloadContext) {
222 return new JSONObject().put("workloadContext", workloadContext).toString();
229 * @param toDecrypt - String
230 * @param msokey - String
231 * @return result - String
233 public synchronized String decrypt(String toDecrypt, String msokey) {
234 String result = null;
236 result = CryptoUtils.decrypt(toDecrypt, msokey);
238 } catch (Exception e) {
239 logger.debug("Failed to decrypt credentials: {}", toDecrypt, e);
244 private String getBasicAuth() {
245 return decrypt(sdcClientAuth, msoKey);