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;
24 import java.util.UUID;
26 import javax.ws.rs.core.Response;
27 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.MessageEnum;
39 import org.onap.so.logger.MsoLogger;
40 import org.onap.so.utils.CryptoUtils;
41 import org.onap.so.utils.TargetEntity;
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.";
55 private final HttpClientFactory httpClientFactory = new HttpClientFactory();
57 @Value("${mso.sdc.endpoint}")
58 private String sdcEndpoint;
59 @Value("${mso.sdc.activate.userid}")
60 private String sdcActivateUserId;
61 @Value("${mso.sdc.activate.instanceid}")
62 private String sdcActivateInstanceId;
63 @Value("${mso.sdc.client.auth}")
64 private String sdcClientAuth;
65 @Value("${mso.msoKey}")
66 private String msoKey;
69 * Send POST request to SDC for operational activation
70 * @param serviceModelVersionI - String
71 * @param operationalEnvironmentId - String
72 * @param workloadContext - String
73 * @return sdcResponseJsonObj - JSONObject object
74 * @throws JSONException
76 public JSONObject postActivateOperationalEnvironment(String serviceModelVersionId, String operationalEnvironmentId, String workloadContext) throws ApiException {
77 JSONObject sdcResponseJsonObj = new JSONObject();
80 String urlString = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId);
81 String jsonPayload = this.buildJsonWorkloadContext(workloadContext);
82 String basicAuthCred = getBasicAuth();
84 if ( basicAuthCred == null || "".equals(basicAuthCred) ) {
85 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
86 ValidateException validateException = new ValidateException.Builder(" SDC credentials 'mso.sdc.client.auth' not setup in properties file!",
87 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
89 throw validateException;
92 URL url = new URL(urlString);
94 HttpClient httpClient = httpClientFactory.newJsonClient(url, TargetEntity.SDC);
95 httpClient.addBasicAuthHeader(sdcClientAuth, msoKey);
96 httpClient.addAdditionalHeader("X-ECOMP-InstanceID", sdcActivateInstanceId);
97 httpClient.addAdditionalHeader("X-ECOMP-RequestID", UUID.randomUUID().toString());
98 httpClient.addAdditionalHeader("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE);
99 httpClient.addAdditionalHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE);
100 httpClient.addAdditionalHeader("USER_ID", sdcActivateUserId);
102 Response apiResponse = setHttpPostResponse(httpClient, jsonPayload);
103 int statusCode = apiResponse.getStatus();;
105 String responseData = apiResponse.readEntity(String.class);
106 sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);
108 } catch (Exception ex) {
109 msoLogger.debug("calling SDC Exception message: " + ex.getMessage());
110 String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage();
111 msoLogger.debug(errorMessage);
112 sdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
113 sdcResponseJsonObj.put("messageId", "");
114 sdcResponseJsonObj.put("message", errorMessage);
117 return sdcResponseJsonObj;
121 * set HttpPostResponse
122 * @param config - RESTConfig object
123 * @param jsonPayload - String
124 * @return client - RestClient object
126 public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException {
128 return client.post(jsonPayload);
129 }catch(Exception ex){
130 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
131 ValidateException validateException = new ValidateException.Builder("Bad request could not post payload",
132 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
134 throw validateException;
140 * @param sdcResponseJsonObj - JSONObject object
141 * @param statusCode - int
142 * @return enhancedAsdcResponseJsonObj - JSONObject object
144 public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) throws JSONException {
146 JSONObject enhancedAsdcResponseJsonObj = new JSONObject();
149 String messageId = "";
151 if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted
152 enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId"));
153 enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
154 enhancedAsdcResponseJsonObj.put("messageId", "");
155 enhancedAsdcResponseJsonObj.put("message", "Success");
158 if (sdcResponseJsonObj.has("requestError") ) {
159 JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject("requestError");
160 if (sdcResponseJsonObj.getJSONObject("requestError").has("serviceException") ) {
161 message = requestErrorObj.getJSONObject("serviceException").getString("text");
162 messageId = requestErrorObj.getJSONObject("serviceException").getString("messageId");
164 if (sdcResponseJsonObj.getJSONObject("requestError").has("policyException") ) {
165 message = requestErrorObj.getJSONObject("policyException").getString("text");
166 messageId = requestErrorObj.getJSONObject("policyException").getString("messageId");
168 enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
169 enhancedAsdcResponseJsonObj.put("messageId", messageId);
170 enhancedAsdcResponseJsonObj.put("message", message);
174 enhancedAsdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
175 enhancedAsdcResponseJsonObj.put("messageId", MESSAGE_UNDEFINED_ERROR);
176 enhancedAsdcResponseJsonObj.put("message", MESSAGE_UNEXPECTED_FORMAT);
179 return enhancedAsdcResponseJsonObj;
185 * @param serviceModelVersionId - String
186 * @param operationalEnvironmentId - String
187 * @return uriBuilder - String
189 public String buildUriBuilder(String serviceModelVersionId, String operationalEnvironmentId) {
190 String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId +"/activate";
191 UriBuilder uriBuilder = UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI)
193 return uriBuilder.build().toString();
198 * @param workloadContext - String
199 * @return String json
200 * @throws JSONException
202 public String buildJsonWorkloadContext(String workloadContext) throws JSONException {
203 return new JSONObject().put("workloadContext", workloadContext).toString();
209 * @param toDecrypt - String
210 * @param msokey - String
211 * @return result - String
213 public synchronized String decrypt(String toDecrypt, String msokey){
214 String result = null;
216 result = CryptoUtils.decrypt(toDecrypt, msokey);
219 catch (Exception e) {
220 msoLogger.debug("Failed to decrypt credentials: " + toDecrypt, e);
225 private String getBasicAuth() {
226 return decrypt(sdcClientAuth, msoKey);