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;
25 import javax.ws.rs.core.Response;
26 import javax.ws.rs.core.UriBuilder;
28 import org.apache.http.HttpStatus;
29 import org.json.JSONException;
30 import org.json.JSONObject;
31 import org.onap.so.apihandler.common.ErrorNumbers;
32 import org.onap.so.apihandlerinfra.exceptions.ApiException;
33 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
34 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
35 import org.onap.so.client.HttpClient;
36 import org.onap.so.client.HttpClientFactory;
37 import org.onap.so.logger.MessageEnum;
38 import org.onap.so.logger.MsoLogger;
39 import org.onap.so.utils.CryptoUtils;
40 import org.onap.so.utils.TargetEntity;
41 import org.springframework.beans.factory.annotation.Value;
42 import org.springframework.stereotype.Component;
45 public class SDCClientHelper {
47 private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.APIH, SDCClientHelper.class);
48 private static final String SDC_CONTENT_TYPE = "application/json";
49 private static final String SDC_ACCEPT_TYPE = "application/json";
50 private static String PARTIAL_SDC_URI = "/sdc/v1/catalog/services/";
52 private static String MESSAGE_UNDEFINED_ERROR = "Undefined Error Message!";
53 private static String MESSAGE_UNEXPECTED_FORMAT = "Unexpected response format from SDC.";
54 private final HttpClientFactory httpClientFactory = new HttpClientFactory();
56 @Value("${mso.sdc.endpoint}")
57 private String sdcEndpoint;
58 @Value("${mso.sdc.activate.userid}")
59 private String sdcActivateUserId;
60 @Value("${mso.sdc.activate.instanceid}")
61 private String sdcActivateInstanceId;
62 @Value("${mso.sdc.client.auth}")
63 private String sdcClientAuth;
64 @Value("${mso.msoKey}")
65 private String msoKey;
68 * Send POST request to SDC for operational activation
69 * @param serviceModelVersionI - String
70 * @param operationalEnvironmentId - String
71 * @param workloadContext - String
72 * @return sdcResponseJsonObj - JSONObject object
73 * @throws JSONException
75 public JSONObject postActivateOperationalEnvironment(String serviceModelVersionId, String operationalEnvironmentId, String workloadContext) throws ApiException {
76 JSONObject sdcResponseJsonObj = new JSONObject();
79 String urlString = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId);
80 String jsonPayload = this.buildJsonWorkloadContext(workloadContext);
81 String basicAuthCred = getBasicAuth();
83 if ( basicAuthCred == null || "".equals(basicAuthCred) ) {
84 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
85 ValidateException validateException = new ValidateException.Builder(" SDC credentials 'mso.sdc.client.auth' not setup in properties file!",
86 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
88 throw validateException;
91 URL url = new URL(urlString);
93 HttpClient httpClient = httpClientFactory.newJsonClient(url, TargetEntity.SDC);
94 httpClient.addBasicAuthHeader(sdcClientAuth, msoKey);
96 Response apiResponse = setHttpPostResponse(httpClient, jsonPayload);
97 int statusCode = apiResponse.getStatus();;
99 String responseData = apiResponse.readEntity(String.class);
100 sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);
102 } catch (Exception ex) {
103 msoLogger.debug("calling SDC Exception message: " + ex.getMessage());
104 String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage();
105 msoLogger.debug(errorMessage);
106 sdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
107 sdcResponseJsonObj.put("messageId", "");
108 sdcResponseJsonObj.put("message", errorMessage);
111 return sdcResponseJsonObj;
115 * set HttpPostResponse
116 * @param config - RESTConfig object
117 * @param jsonPayload - String
118 * @return client - RestClient object
120 public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException {
122 return client.post(jsonPayload);
123 }catch(Exception ex){
124 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
125 ValidateException validateException = new ValidateException.Builder("Bad request could not post payload",
126 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
128 throw validateException;
134 * @param sdcResponseJsonObj - JSONObject object
135 * @param statusCode - int
136 * @return enhancedAsdcResponseJsonObj - JSONObject object
138 public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) throws JSONException {
140 JSONObject enhancedAsdcResponseJsonObj = new JSONObject();
143 String messageId = "";
145 if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted
146 enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId"));
147 enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
148 enhancedAsdcResponseJsonObj.put("messageId", "");
149 enhancedAsdcResponseJsonObj.put("message", "Success");
152 if (sdcResponseJsonObj.has("requestError") ) {
153 JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject("requestError");
154 if (sdcResponseJsonObj.getJSONObject("requestError").has("serviceException") ) {
155 message = requestErrorObj.getJSONObject("serviceException").getString("text");
156 messageId = requestErrorObj.getJSONObject("serviceException").getString("messageId");
158 if (sdcResponseJsonObj.getJSONObject("requestError").has("policyException") ) {
159 message = requestErrorObj.getJSONObject("policyException").getString("text");
160 messageId = requestErrorObj.getJSONObject("policyException").getString("messageId");
162 enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
163 enhancedAsdcResponseJsonObj.put("messageId", messageId);
164 enhancedAsdcResponseJsonObj.put("message", message);
168 enhancedAsdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
169 enhancedAsdcResponseJsonObj.put("messageId", MESSAGE_UNDEFINED_ERROR);
170 enhancedAsdcResponseJsonObj.put("message", MESSAGE_UNEXPECTED_FORMAT);
173 return enhancedAsdcResponseJsonObj;
179 * @param serviceModelVersionId - String
180 * @param operationalEnvironmentId - String
181 * @return uriBuilder - String
183 public String buildUriBuilder(String serviceModelVersionId, String operationalEnvironmentId) {
184 String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId +"/activate";
185 UriBuilder uriBuilder = UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI)
187 return uriBuilder.build().toString();
192 * @param workloadContext - String
193 * @return String json
194 * @throws JSONException
196 public String buildJsonWorkloadContext(String workloadContext) throws JSONException {
197 return new JSONObject().put("workloadContext", workloadContext).toString();
203 * @param toDecrypt - String
204 * @param msokey - String
205 * @return result - String
207 public synchronized String decrypt(String toDecrypt, String msokey){
208 String result = null;
210 result = CryptoUtils.decrypt(toDecrypt, msokey);
213 catch (Exception e) {
214 msoLogger.debug("Failed to decrypt credentials: " + toDecrypt, e);
219 private String getBasicAuth() {
220 return decrypt(sdcClientAuth, msoKey);