b5ba9281a600f0c8303b295bbc2c6e3f201fc00c
[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.so.utils.TargetEntity;
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 String PARTIAL_SDC_URI = "/sdc/v1/catalog/services/";
54
55     private static String MESSAGE_UNDEFINED_ERROR = "Undefined Error Message!";
56     private static String MESSAGE_UNEXPECTED_FORMAT = "Unexpected response format from SDC.";
57     private final HttpClientFactory httpClientFactory = new HttpClientFactory();
58
59     @Value("${mso.sdc.endpoint}")
60     private String sdcEndpoint;
61     @Value("${mso.sdc.activate.userid}")
62     private String sdcActivateUserId;
63     @Value("${mso.sdc.activate.instanceid}")
64     private String sdcActivateInstanceId;
65     @Value("${mso.sdc.client.auth}")
66     private String sdcClientAuth;
67     @Value("${mso.msoKey}")
68     private String msoKey;
69
70     /**
71      * Send POST request to SDC for operational activation
72      * 
73      * @param serviceModelVersionI - String
74      * @param operationalEnvironmentId - String
75      * @param workloadContext - String
76      * @return sdcResponseJsonObj - JSONObject object
77      * @throws JSONException
78      */
79     public JSONObject postActivateOperationalEnvironment(String serviceModelVersionId, String operationalEnvironmentId,
80             String workloadContext) throws ApiException {
81         JSONObject sdcResponseJsonObj = new JSONObject();
82
83         try {
84             String urlString = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId);
85             String jsonPayload = this.buildJsonWorkloadContext(workloadContext);
86             String basicAuthCred = getBasicAuth();
87
88             if (basicAuthCred == null || "".equals(basicAuthCred)) {
89                 ErrorLoggerInfo errorLoggerInfo =
90                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
91                                 .build();
92                 ValidateException validateException = new ValidateException.Builder(
93                         " SDC credentials 'mso.sdc.client.auth' not setup in properties file!",
94                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo)
95                                 .build();
96
97                 throw validateException;
98             }
99
100             URL url = new URL(urlString);
101
102             HttpClient httpClient = httpClientFactory.newJsonClient(url, TargetEntity.SDC);
103             httpClient.addBasicAuthHeader(sdcClientAuth, msoKey);
104             httpClient.addAdditionalHeader("X-ECOMP-InstanceID", sdcActivateInstanceId);
105             httpClient.addAdditionalHeader("X-ECOMP-RequestID", UUID.randomUUID().toString());
106             httpClient.addAdditionalHeader("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE);
107             httpClient.addAdditionalHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE);
108             httpClient.addAdditionalHeader("USER_ID", sdcActivateUserId);
109
110             Response apiResponse = setHttpPostResponse(httpClient, jsonPayload);
111             int statusCode = apiResponse.getStatus();;
112
113             String responseData = apiResponse.readEntity(String.class);
114             sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);
115
116         } catch (Exception ex) {
117             logger.debug("calling SDC Exception message: {}", ex.getMessage());
118             String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage();
119             logger.debug(errorMessage);
120             sdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
121             sdcResponseJsonObj.put("messageId", "");
122             sdcResponseJsonObj.put("message", errorMessage);
123
124         }
125         return sdcResponseJsonObj;
126     }
127
128     /**
129      * set HttpPostResponse
130      * 
131      * @param config - RESTConfig object
132      * @param jsonPayload - String
133      * @return client - RestClient object
134      */
135     public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException {
136         try {
137             return client.post(jsonPayload);
138         } catch (Exception ex) {
139             ErrorLoggerInfo errorLoggerInfo =
140                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
141                             .build();
142             ValidateException validateException =
143                     new ValidateException.Builder("Bad request could not post payload", HttpStatus.SC_BAD_REQUEST,
144                             ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
145
146             throw validateException;
147         }
148     }
149
150     /**
151      * enhance Response
152      * 
153      * @param sdcResponseJsonObj - JSONObject object
154      * @param statusCode - int
155      * @return enhancedAsdcResponseJsonObj - JSONObject object
156      */
157     public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) throws JSONException {
158
159         JSONObject enhancedAsdcResponseJsonObj = new JSONObject();
160
161         String message = "";
162         String messageId = "";
163
164         if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted
165             enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId"));
166             enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
167             enhancedAsdcResponseJsonObj.put("messageId", "");
168             enhancedAsdcResponseJsonObj.put("message", "Success");
169
170         } else { // error
171             if (sdcResponseJsonObj.has("requestError")) {
172                 JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject("requestError");
173                 if (sdcResponseJsonObj.getJSONObject("requestError").has("serviceException")) {
174                     message = requestErrorObj.getJSONObject("serviceException").getString("text");
175                     messageId = requestErrorObj.getJSONObject("serviceException").getString("messageId");
176                 }
177                 if (sdcResponseJsonObj.getJSONObject("requestError").has("policyException")) {
178                     message = requestErrorObj.getJSONObject("policyException").getString("text");
179                     messageId = requestErrorObj.getJSONObject("policyException").getString("messageId");
180                 }
181                 enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
182                 enhancedAsdcResponseJsonObj.put("messageId", messageId);
183                 enhancedAsdcResponseJsonObj.put("message", message);
184
185             } else {
186                 // unexpected format
187                 enhancedAsdcResponseJsonObj.put("statusCode",
188                         String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
189                 enhancedAsdcResponseJsonObj.put("messageId", MESSAGE_UNDEFINED_ERROR);
190                 enhancedAsdcResponseJsonObj.put("message", MESSAGE_UNEXPECTED_FORMAT);
191             }
192         }
193         return enhancedAsdcResponseJsonObj;
194
195     }
196
197     /**
198      * Build Uri
199      * 
200      * @param serviceModelVersionId - String
201      * @param operationalEnvironmentId - String
202      * @return uriBuilder - String
203      */
204     public String buildUriBuilder(String serviceModelVersionId, String operationalEnvironmentId) {
205         String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId + "/activate";
206         UriBuilder uriBuilder = UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI).path(path);
207         return uriBuilder.build().toString();
208     }
209
210     /**
211      * Build JSON context
212      * 
213      * @param workloadContext - String
214      * @return String json
215      * @throws JSONException
216      */
217     public String buildJsonWorkloadContext(String workloadContext) throws JSONException {
218         return new JSONObject().put("workloadContext", workloadContext).toString();
219
220     }
221
222     /**
223      * decrypt value
224      * 
225      * @param toDecrypt - String
226      * @param msokey - String
227      * @return result - String
228      */
229     public synchronized String decrypt(String toDecrypt, String msokey) {
230         String result = null;
231         try {
232             result = CryptoUtils.decrypt(toDecrypt, msokey);
233
234         } catch (Exception e) {
235             logger.debug("Failed to decrypt credentials: {}", toDecrypt, e);
236         }
237         return result;
238     }
239
240     private String getBasicAuth() {
241         return decrypt(sdcClientAuth, msoKey);
242     }
243 }
244