7aa6e0f8319e5ab9c34fd2cba776234c58134012
[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.logging.filter.base.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.BusinessProcessError)
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("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE);
112             httpClient.addAdditionalHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE);
113             httpClient.addAdditionalHeader("USER_ID", sdcActivateUserId);
114
115             Response apiResponse = setHttpPostResponse(httpClient, jsonPayload);
116             int statusCode = apiResponse.getStatus();;
117
118             String responseData = apiResponse.readEntity(String.class);
119             sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);
120
121         } catch (Exception ex) {
122             logger.debug("calling SDC Exception message:", ex);
123             String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage();
124             logger.debug(errorMessage);
125             sdcResponseJsonObj.put(STATUS_CODE, String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
126             sdcResponseJsonObj.put(MESSAGE_ID, "");
127             sdcResponseJsonObj.put(MESSAGE, errorMessage);
128
129         }
130         return sdcResponseJsonObj;
131     }
132
133     /**
134      * set HttpPostResponse
135      * 
136      * @param config - RESTConfig object
137      * @param jsonPayload - String
138      * @return client - RestClient object
139      */
140     public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException {
141         try {
142             return client.post(jsonPayload);
143         } catch (Exception ex) {
144             ErrorLoggerInfo errorLoggerInfo =
145                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcessError)
146                             .build();
147
148             throw new ValidateException.Builder("Bad request could not post payload", HttpStatus.SC_BAD_REQUEST,
149                     ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
150         }
151     }
152
153     /**
154      * enhance Response
155      * 
156      * @param sdcResponseJsonObj - JSONObject object
157      * @param statusCode - int
158      * @return enhancedAsdcResponseJsonObj - JSONObject object
159      */
160     public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) {
161
162         JSONObject enhancedAsdcResponseJsonObj = new JSONObject();
163
164         String message = "";
165         String messageId = "";
166
167         if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted
168             enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId"));
169             enhancedAsdcResponseJsonObj.put(STATUS_CODE, Integer.toString(statusCode));
170             enhancedAsdcResponseJsonObj.put(MESSAGE_ID, "");
171             enhancedAsdcResponseJsonObj.put(MESSAGE, "Success");
172
173         } else { // error
174             if (sdcResponseJsonObj.has(REQUEST_ERROR)) {
175                 JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject(REQUEST_ERROR);
176                 if (sdcResponseJsonObj.getJSONObject(REQUEST_ERROR).has(SERVICE_EXCEPTION)) {
177                     message = requestErrorObj.getJSONObject(SERVICE_EXCEPTION).getString("text");
178                     messageId = requestErrorObj.getJSONObject(SERVICE_EXCEPTION).getString(MESSAGE_ID);
179                 }
180                 if (sdcResponseJsonObj.getJSONObject(REQUEST_ERROR).has(POLICY_EXCEPTION)) {
181                     message = requestErrorObj.getJSONObject(POLICY_EXCEPTION).getString("text");
182                     messageId = requestErrorObj.getJSONObject(POLICY_EXCEPTION).getString(MESSAGE_ID);
183                 }
184                 enhancedAsdcResponseJsonObj.put(STATUS_CODE, Integer.toString(statusCode));
185                 enhancedAsdcResponseJsonObj.put(MESSAGE_ID, messageId);
186                 enhancedAsdcResponseJsonObj.put(MESSAGE, message);
187
188             } else {
189                 // unexpected format
190                 enhancedAsdcResponseJsonObj.put(STATUS_CODE,
191                         String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
192                 enhancedAsdcResponseJsonObj.put(MESSAGE_ID, MESSAGE_UNDEFINED_ERROR);
193                 enhancedAsdcResponseJsonObj.put(MESSAGE, MESSAGE_UNEXPECTED_FORMAT);
194             }
195         }
196         return enhancedAsdcResponseJsonObj;
197
198     }
199
200     /**
201      * Build Uri
202      * 
203      * @param serviceModelVersionId - String
204      * @param operationalEnvironmentId - String
205      * @return uriBuilder - String
206      */
207     public String buildUriBuilder(String serviceModelVersionId, String operationalEnvironmentId) {
208         String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId + "/activate";
209         UriBuilder uriBuilder = UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI).path(path);
210         return uriBuilder.build().toString();
211     }
212
213     /**
214      * Build JSON context
215      * 
216      * @param workloadContext - String
217      * @return String json
218      * @throws JSONException
219      */
220     public String buildJsonWorkloadContext(String workloadContext) {
221         return new JSONObject().put("workloadContext", workloadContext).toString();
222
223     }
224
225     /**
226      * decrypt value
227      * 
228      * @param toDecrypt - String
229      * @param msokey - String
230      * @return result - String
231      */
232     public synchronized String decrypt(String toDecrypt, String msokey) {
233         String result = null;
234         try {
235             result = CryptoUtils.decrypt(toDecrypt, msokey);
236
237         } catch (Exception e) {
238             logger.debug("Failed to decrypt credentials: {}", toDecrypt, e);
239         }
240         return result;
241     }
242
243     private String getBasicAuth() {
244         return decrypt(sdcClientAuth, msoKey);
245     }
246 }
247