de5edb5b545d02acdaa77849bc58f780c19d9150
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
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=========================================================
21  */
22
23 package org.onap.so.apihandlerinfra.tenantisolation.helpers;
24
25 import java.net.URL;
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;
46
47 @Component
48 public class SDCClientHelper {
49
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/";
54
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();
58
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";
65
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;
76
77     /**
78      * Send POST request to SDC for operational activation
79      * 
80      * @param serviceModelVersionI - String
81      * @param operationalEnvironmentId - String
82      * @param workloadContext - String
83      * @return sdcResponseJsonObj - JSONObject object
84      * @throws JSONException
85      */
86     public JSONObject postActivateOperationalEnvironment(String serviceModelVersionId, String operationalEnvironmentId,
87             String workloadContext) throws ApiException {
88         JSONObject sdcResponseJsonObj = new JSONObject();
89
90         try {
91             String urlString = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId);
92             String jsonPayload = this.buildJsonWorkloadContext(workloadContext);
93             String basicAuthCred = getBasicAuth();
94
95             if (basicAuthCred == null || "".equals(basicAuthCred)) {
96                 ErrorLoggerInfo errorLoggerInfo =
97                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
98                                 .build();
99
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)
103                                 .build();
104             }
105
106             URL url = new URL(urlString);
107
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);
115
116             Response apiResponse = setHttpPostResponse(httpClient, jsonPayload);
117             int statusCode = apiResponse.getStatus();;
118
119             String responseData = apiResponse.readEntity(String.class);
120             sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);
121
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);
129
130         }
131         return sdcResponseJsonObj;
132     }
133
134     /**
135      * set HttpPostResponse
136      * 
137      * @param config - RESTConfig object
138      * @param jsonPayload - String
139      * @return client - RestClient object
140      */
141     public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException {
142         try {
143             return client.post(jsonPayload);
144         } catch (Exception ex) {
145             ErrorLoggerInfo errorLoggerInfo =
146                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
147                             .build();
148
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();
151         }
152     }
153
154     /**
155      * enhance Response
156      * 
157      * @param sdcResponseJsonObj - JSONObject object
158      * @param statusCode - int
159      * @return enhancedAsdcResponseJsonObj - JSONObject object
160      */
161     public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) {
162
163         JSONObject enhancedAsdcResponseJsonObj = new JSONObject();
164
165         String message = "";
166         String messageId = "";
167
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");
173
174         } else { // error
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);
180                 }
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);
184                 }
185                 enhancedAsdcResponseJsonObj.put(STATUS_CODE, Integer.toString(statusCode));
186                 enhancedAsdcResponseJsonObj.put(MESSAGE_ID, messageId);
187                 enhancedAsdcResponseJsonObj.put(MESSAGE, message);
188
189             } else {
190                 // unexpected format
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);
195             }
196         }
197         return enhancedAsdcResponseJsonObj;
198
199     }
200
201     /**
202      * Build Uri
203      * 
204      * @param serviceModelVersionId - String
205      * @param operationalEnvironmentId - String
206      * @return uriBuilder - String
207      */
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();
212     }
213
214     /**
215      * Build JSON context
216      * 
217      * @param workloadContext - String
218      * @return String json
219      * @throws JSONException
220      */
221     public String buildJsonWorkloadContext(String workloadContext) {
222         return new JSONObject().put("workloadContext", workloadContext).toString();
223
224     }
225
226     /**
227      * decrypt value
228      * 
229      * @param toDecrypt - String
230      * @param msokey - String
231      * @return result - String
232      */
233     public synchronized String decrypt(String toDecrypt, String msokey) {
234         String result = null;
235         try {
236             result = CryptoUtils.decrypt(toDecrypt, msokey);
237
238         } catch (Exception e) {
239             logger.debug("Failed to decrypt credentials: {}", toDecrypt, e);
240         }
241         return result;
242     }
243
244     private String getBasicAuth() {
245         return decrypt(sdcClientAuth, msoKey);
246     }
247 }
248