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.ErrorCode;
41 import org.onap.so.logger.MessageEnum;
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 String jsonPayload = this.buildJsonWorkloadContext(workloadContext);
86 String basicAuthCred = getBasicAuth();
88 if ( basicAuthCred == null || "".equals(basicAuthCred) ) {
89 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build();
90 ValidateException validateException = new ValidateException.Builder(" SDC credentials 'mso.sdc.client.auth' not setup in properties file!",
91 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
93 throw validateException;
96 URL url = new URL(urlString);
98 HttpClient httpClient = httpClientFactory.newJsonClient(url, TargetEntity.SDC);
99 httpClient.addBasicAuthHeader(sdcClientAuth, msoKey);
100 httpClient.addAdditionalHeader("X-ECOMP-InstanceID", sdcActivateInstanceId);
101 httpClient.addAdditionalHeader("X-ECOMP-RequestID", UUID.randomUUID().toString());
102 httpClient.addAdditionalHeader("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE);
103 httpClient.addAdditionalHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE);
104 httpClient.addAdditionalHeader("USER_ID", sdcActivateUserId);
106 Response apiResponse = setHttpPostResponse(httpClient, jsonPayload);
107 int statusCode = apiResponse.getStatus();;
109 String responseData = apiResponse.readEntity(String.class);
110 sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);
112 } catch (Exception ex) {
113 logger.debug("calling SDC Exception message: {}", ex.getMessage());
114 String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage();
115 logger.debug(errorMessage);
116 sdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
117 sdcResponseJsonObj.put("messageId", "");
118 sdcResponseJsonObj.put("message", errorMessage);
121 return sdcResponseJsonObj;
125 * set HttpPostResponse
126 * @param config - RESTConfig object
127 * @param jsonPayload - String
128 * @return client - RestClient object
130 public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException {
132 return client.post(jsonPayload);
133 }catch(Exception ex){
134 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build();
135 ValidateException validateException = new ValidateException.Builder("Bad request could not post payload",
136 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
138 throw validateException;
144 * @param sdcResponseJsonObj - JSONObject object
145 * @param statusCode - int
146 * @return enhancedAsdcResponseJsonObj - JSONObject object
148 public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) throws JSONException {
150 JSONObject enhancedAsdcResponseJsonObj = new JSONObject();
153 String messageId = "";
155 if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted
156 enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId"));
157 enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
158 enhancedAsdcResponseJsonObj.put("messageId", "");
159 enhancedAsdcResponseJsonObj.put("message", "Success");
162 if (sdcResponseJsonObj.has("requestError") ) {
163 JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject("requestError");
164 if (sdcResponseJsonObj.getJSONObject("requestError").has("serviceException") ) {
165 message = requestErrorObj.getJSONObject("serviceException").getString("text");
166 messageId = requestErrorObj.getJSONObject("serviceException").getString("messageId");
168 if (sdcResponseJsonObj.getJSONObject("requestError").has("policyException") ) {
169 message = requestErrorObj.getJSONObject("policyException").getString("text");
170 messageId = requestErrorObj.getJSONObject("policyException").getString("messageId");
172 enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
173 enhancedAsdcResponseJsonObj.put("messageId", messageId);
174 enhancedAsdcResponseJsonObj.put("message", message);
178 enhancedAsdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
179 enhancedAsdcResponseJsonObj.put("messageId", MESSAGE_UNDEFINED_ERROR);
180 enhancedAsdcResponseJsonObj.put("message", MESSAGE_UNEXPECTED_FORMAT);
183 return enhancedAsdcResponseJsonObj;
189 * @param serviceModelVersionId - String
190 * @param operationalEnvironmentId - String
191 * @return uriBuilder - String
193 public String buildUriBuilder(String serviceModelVersionId, String operationalEnvironmentId) {
194 String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId +"/activate";
195 UriBuilder uriBuilder = UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI)
197 return uriBuilder.build().toString();
202 * @param workloadContext - String
203 * @return String json
204 * @throws JSONException
206 public String buildJsonWorkloadContext(String workloadContext) throws JSONException {
207 return new JSONObject().put("workloadContext", workloadContext).toString();
213 * @param toDecrypt - String
214 * @param msokey - String
215 * @return result - String
217 public synchronized String decrypt(String toDecrypt, String msokey){
218 String result = null;
220 result = CryptoUtils.decrypt(toDecrypt, msokey);
223 catch (Exception e) {
224 logger.debug("Failed to decrypt credentials: {}", toDecrypt, e);
229 private String getBasicAuth() {
230 return decrypt(sdcClientAuth, msoKey);