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