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