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;
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.client.HttpClientFactory;
40 import org.onap.so.logger.MessageEnum;
41 import org.onap.so.logger.MsoLogger;
42 import org.onap.so.utils.CryptoUtils;
43 import org.onap.so.utils.TargetEntity;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.springframework.beans.factory.annotation.Value;
47 import org.springframework.stereotype.Component;
50 public class SDCClientHelper {
52 private static Logger logger = LoggerFactory.getLogger(SDCClientHelper.class);
53 private static final String SDC_CONTENT_TYPE = "application/json";
54 private static final String SDC_ACCEPT_TYPE = "application/json";
55 private static String PARTIAL_SDC_URI = "/sdc/v1/catalog/services/";
57 private static String MESSAGE_UNDEFINED_ERROR = "Undefined Error Message!";
58 private static String MESSAGE_UNEXPECTED_FORMAT = "Unexpected response format from SDC.";
59 private final HttpClientFactory httpClientFactory = new HttpClientFactory();
61 @Value("${mso.sdc.endpoint}")
62 private String sdcEndpoint;
63 @Value("${mso.sdc.activate.userid}")
64 private String sdcActivateUserId;
65 @Value("${mso.sdc.activate.instanceid}")
66 private String sdcActivateInstanceId;
67 @Value("${mso.sdc.client.auth}")
68 private String sdcClientAuth;
69 @Value("${mso.msoKey}")
70 private String msoKey;
73 * Send POST request to SDC for operational activation
74 * @param serviceModelVersionI - String
75 * @param operationalEnvironmentId - String
76 * @param workloadContext - String
77 * @return sdcResponseJsonObj - JSONObject object
78 * @throws JSONException
80 public JSONObject postActivateOperationalEnvironment(String serviceModelVersionId, String operationalEnvironmentId, String workloadContext) throws ApiException {
81 JSONObject sdcResponseJsonObj = new JSONObject();
84 String urlString = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId);
85 logger.debug("Url ASDC Activate request: {}", urlString);
86 String jsonPayload = this.buildJsonWorkloadContext(workloadContext);
87 String basicAuthCred = getBasicAuth();
89 if ( basicAuthCred == null || "".equals(basicAuthCred) ) {
90 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
91 ValidateException validateException = new ValidateException.Builder(" SDC credentials 'mso.sdc.client.auth' not setup in properties file!",
92 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
94 throw validateException;
97 URL url = new URL(urlString);
99 HttpClient httpClient = httpClientFactory.newJsonClient(url, TargetEntity.SDC);
100 httpClient.addBasicAuthHeader(sdcClientAuth, msoKey);
101 httpClient.addAdditionalHeader("X-ECOMP-InstanceID", sdcActivateInstanceId);
102 httpClient.addAdditionalHeader("X-ECOMP-RequestID", UUID.randomUUID().toString());
103 httpClient.addAdditionalHeader("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE);
104 httpClient.addAdditionalHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE);
105 httpClient.addAdditionalHeader("USER_ID", sdcActivateUserId);
107 Response apiResponse = setHttpPostResponse(httpClient, jsonPayload);
108 int statusCode = apiResponse.getStatus();;
110 String responseData = apiResponse.readEntity(String.class);
111 sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);
113 } catch (Exception ex) {
114 logger.debug("calling SDC Exception message: {}", ex.getMessage());
115 String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage();
116 logger.debug(errorMessage);
117 sdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
118 sdcResponseJsonObj.put("messageId", "");
119 sdcResponseJsonObj.put("message", errorMessage);
122 return sdcResponseJsonObj;
126 * set HttpPostResponse
127 * @param config - RESTConfig object
128 * @param jsonPayload - String
129 * @return client - RestClient object
131 public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException {
133 return client.post(jsonPayload);
134 }catch(Exception ex){
135 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
136 ValidateException validateException = new ValidateException.Builder("Bad request could not post payload",
137 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
139 throw validateException;
145 * @param sdcResponseJsonObj - JSONObject object
146 * @param statusCode - int
147 * @return enhancedAsdcResponseJsonObj - JSONObject object
149 public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) throws JSONException {
151 JSONObject enhancedAsdcResponseJsonObj = new JSONObject();
154 String messageId = "";
156 if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted
157 enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId"));
158 enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
159 enhancedAsdcResponseJsonObj.put("messageId", "");
160 enhancedAsdcResponseJsonObj.put("message", "Success");
161 logger.debug("Url ASDC Activate response: {} {}", "distributionId ", sdcResponseJsonObj.get("distributionId"));
164 if (sdcResponseJsonObj.has("requestError") ) {
165 JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject("requestError");
166 if (sdcResponseJsonObj.getJSONObject("requestError").has("serviceException") ) {
167 message = requestErrorObj.getJSONObject("serviceException").getString("text");
168 messageId = requestErrorObj.getJSONObject("serviceException").getString("messageId");
170 if (sdcResponseJsonObj.getJSONObject("requestError").has("policyException") ) {
171 message = requestErrorObj.getJSONObject("policyException").getString("text");
172 messageId = requestErrorObj.getJSONObject("policyException").getString("messageId");
174 enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
175 enhancedAsdcResponseJsonObj.put("messageId", messageId);
176 enhancedAsdcResponseJsonObj.put("message", message);
180 enhancedAsdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
181 enhancedAsdcResponseJsonObj.put("messageId", MESSAGE_UNDEFINED_ERROR);
182 enhancedAsdcResponseJsonObj.put("message", MESSAGE_UNEXPECTED_FORMAT);
185 return enhancedAsdcResponseJsonObj;
191 * @param serviceModelVersionId - String
192 * @param operationalEnvironmentId - String
193 * @return uriBuilder - String
195 public String buildUriBuilder(String serviceModelVersionId, String operationalEnvironmentId) {
196 String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId +"/activate";
197 UriBuilder uriBuilder = UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI)
199 return uriBuilder.build().toString();
204 * @param workloadContext - String
205 * @return String json
206 * @throws JSONException
208 public String buildJsonWorkloadContext(String workloadContext) throws JSONException {
209 return new JSONObject().put("workloadContext", workloadContext).toString();
215 * @param toDecrypt - String
216 * @param msokey - String
217 * @return result - String
219 public synchronized String decrypt(String toDecrypt, String msokey){
220 String result = null;
222 result = CryptoUtils.decrypt(toDecrypt, msokey);
225 catch (Exception e) {
226 logger.debug("Failed to decrypt credentials: {}", toDecrypt, e);
231 private String getBasicAuth() {
232 return decrypt(sdcClientAuth, msoKey);