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