5ead7ddd7f4ab0ace4bf830fdaa070dd36a653d8
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.apihandlerinfra.tenantisolation.helpers;
22
23 import java.net.URL;
24 import java.util.UUID;
25
26 import javax.ws.rs.core.Response;
27 import javax.ws.rs.core.UriBuilder;
28
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.MessageEnum;
39 import org.onap.so.logger.MsoLogger;
40 import org.onap.so.utils.CryptoUtils;
41 import org.onap.so.utils.TargetEntity;
42 import org.springframework.beans.factory.annotation.Value;
43 import org.springframework.stereotype.Component;
44
45 @Component
46 public class SDCClientHelper {
47
48         private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.APIH, SDCClientHelper.class);
49         private static final String SDC_CONTENT_TYPE = "application/json";
50         private static final String SDC_ACCEPT_TYPE = "application/json";
51         private static String PARTIAL_SDC_URI = "/sdc/v1/catalog/services/";
52
53         private static String MESSAGE_UNDEFINED_ERROR = "Undefined Error Message!";
54         private static String MESSAGE_UNEXPECTED_FORMAT = "Unexpected response format from SDC.";
55         private final HttpClientFactory httpClientFactory = new HttpClientFactory();
56
57         @Value("${mso.sdc.endpoint}")
58         private String sdcEndpoint;
59         @Value("${mso.sdc.activate.userid}")
60         private String sdcActivateUserId;
61         @Value("${mso.sdc.activate.instanceid}")
62         private String sdcActivateInstanceId;
63         @Value("${mso.sdc.client.auth}")
64         private String sdcClientAuth;
65         @Value("${mso.msoKey}")
66         private String msoKey;
67
68         /**
69          * Send POST request to SDC for operational activation
70          * @param serviceModelVersionI -  String
71          * @param operationalEnvironmentId - String
72          * @param workloadContext - String
73          * @return sdcResponseJsonObj - JSONObject object
74          * @throws JSONException
75          */
76         public JSONObject postActivateOperationalEnvironment(String serviceModelVersionId, String operationalEnvironmentId, String workloadContext) throws ApiException {
77                 JSONObject sdcResponseJsonObj = new JSONObject();
78
79                 try {
80                         String urlString = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId);
81                         String jsonPayload = this.buildJsonWorkloadContext(workloadContext);
82                         String basicAuthCred = getBasicAuth();
83
84                         if ( basicAuthCred == null || "".equals(basicAuthCred) ) {
85                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
86                 ValidateException validateException = new ValidateException.Builder(" SDC credentials 'mso.sdc.client.auth' not setup in properties file!",
87                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
88
89                 throw validateException;
90                         }
91
92                         URL url = new URL(urlString);
93
94                         HttpClient httpClient = httpClientFactory.newJsonClient(url, TargetEntity.SDC);
95                         httpClient.addBasicAuthHeader(sdcClientAuth, msoKey);
96                         httpClient.addAdditionalHeader("X-ECOMP-InstanceID", sdcActivateInstanceId);
97                         httpClient.addAdditionalHeader("X-ECOMP-RequestID", UUID.randomUUID().toString());
98                         httpClient.addAdditionalHeader("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE);
99                         httpClient.addAdditionalHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE);
100                         httpClient.addAdditionalHeader("USER_ID", sdcActivateUserId);
101
102                         Response apiResponse = setHttpPostResponse(httpClient, jsonPayload);
103                         int statusCode = apiResponse.getStatus();;
104
105                         String responseData = apiResponse.readEntity(String.class);
106                         sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);
107
108                 } catch (Exception ex) {
109                         msoLogger.debug("calling SDC Exception message: " + ex.getMessage());
110                         String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage();
111                         msoLogger.debug(errorMessage);
112                         sdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
113                         sdcResponseJsonObj.put("messageId", "");
114                         sdcResponseJsonObj.put("message", errorMessage);
115
116                 }
117                 return sdcResponseJsonObj;
118         }
119
120         /**
121          * set  HttpPostResponse
122          * @param config - RESTConfig object
123          * @param jsonPayload - String
124          * @return client - RestClient object
125          */
126         public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException {
127                 try {
128             return client.post(jsonPayload);
129         }catch(Exception ex){
130             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
131             ValidateException validateException = new ValidateException.Builder("Bad request could not post payload",
132                     HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
133
134             throw validateException;
135         }
136         }
137
138         /**
139          * enhance Response
140          * @param sdcResponseJsonObj - JSONObject object
141          * @param statusCode - int
142          * @return enhancedAsdcResponseJsonObj - JSONObject object
143          */
144         public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) throws JSONException {
145
146                 JSONObject enhancedAsdcResponseJsonObj = new JSONObject();
147
148                 String message = "";
149                 String messageId = "";
150
151                 if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted
152                         enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId"));
153                         enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
154                         enhancedAsdcResponseJsonObj.put("messageId", "");
155                         enhancedAsdcResponseJsonObj.put("message", "Success");
156
157                 } else {  // error
158                         if (sdcResponseJsonObj.has("requestError") ) {
159                                 JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject("requestError");
160                                 if (sdcResponseJsonObj.getJSONObject("requestError").has("serviceException") ) {
161                                         message = requestErrorObj.getJSONObject("serviceException").getString("text");
162                                         messageId = requestErrorObj.getJSONObject("serviceException").getString("messageId");
163                                 }
164                                 if (sdcResponseJsonObj.getJSONObject("requestError").has("policyException") ) {
165                                         message = requestErrorObj.getJSONObject("policyException").getString("text");
166                                         messageId = requestErrorObj.getJSONObject("policyException").getString("messageId");
167                                 }
168                                 enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
169                                 enhancedAsdcResponseJsonObj.put("messageId", messageId);
170                                 enhancedAsdcResponseJsonObj.put("message", message);
171
172                         } else {
173                                 // unexpected format
174                                 enhancedAsdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
175                                 enhancedAsdcResponseJsonObj.put("messageId", MESSAGE_UNDEFINED_ERROR);
176                                 enhancedAsdcResponseJsonObj.put("message", MESSAGE_UNEXPECTED_FORMAT);
177                         }
178                 }
179                 return enhancedAsdcResponseJsonObj;
180
181         }
182
183         /**
184          * Build Uri
185          * @param serviceModelVersionId - String
186          * @param operationalEnvironmentId - String
187          * @return uriBuilder - String
188          */
189         public String buildUriBuilder(String serviceModelVersionId,  String operationalEnvironmentId) {
190             String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId +"/activate";
191             UriBuilder uriBuilder =  UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI)
192                                                .path(path);
193             return  uriBuilder.build().toString();
194         }
195
196         /**
197          * Build JSON context
198          * @param  workloadContext - String
199          * @return String json
200          * @throws JSONException
201          */
202         public String buildJsonWorkloadContext(String workloadContext) throws JSONException {
203                 return new JSONObject().put("workloadContext", workloadContext).toString();
204
205         }
206
207         /**
208          * decrypt value
209          * @param toDecrypt - String
210          * @param msokey - String
211          * @return result - String
212          */
213         public synchronized String decrypt(String toDecrypt, String msokey){
214                 String result = null;
215                 try {
216                         result = CryptoUtils.decrypt(toDecrypt, msokey);
217
218                 }
219                 catch (Exception e) {
220                         msoLogger.debug("Failed to decrypt credentials: " + toDecrypt, e);
221                 }
222                 return result;
223         }
224
225         private String getBasicAuth() {
226                 return decrypt(sdcClientAuth, msoKey);
227         }
228 }
229