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