8a4d561fbdaaaccb674e77be6469b7bbf0b1d294
[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.HashMap;
25 import java.util.Map;
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.logger.MessageEnum;
40 import org.onap.so.logger.MsoLogger;
41 import org.onap.so.utils.CryptoUtils;
42 import org.onap.so.utils.TargetEntity;
43 import org.springframework.beans.factory.annotation.Value;
44 import org.springframework.stereotype.Component;
45
46 @Component
47 public class SDCClientHelper {
48
49         private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.APIH, SDCClientHelper.class);
50         private static final String SDC_CONTENT_TYPE = "application/json";
51         private static final String SDC_ACCEPT_TYPE = "application/json";
52         private static String PARTIAL_SDC_URI = "/sdc/v1/catalog/services/";
53
54         private static String MESSAGE_UNDEFINED_ERROR = "Undefined Error Message!";
55         private static String MESSAGE_UNEXPECTED_FORMAT = "Unexpected response format from SDC.";
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 = new HttpClient(url, "application/json", TargetEntity.SDC);
95                         httpClient.addBasicAuthHeader(sdcClientAuth, msoKey);
96
97                         Response apiResponse = setHttpPostResponse(httpClient, jsonPayload);
98                         int statusCode = apiResponse.getStatus();;
99
100                         String responseData = apiResponse.readEntity(String.class);
101                         sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);
102
103                 } catch (Exception ex) {
104                         msoLogger.debug("calling SDC Exception message: " + ex.getMessage());
105                         String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage();
106                         msoLogger.debug(errorMessage);
107                         sdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
108                         sdcResponseJsonObj.put("messageId", "");
109                         sdcResponseJsonObj.put("message", errorMessage);
110
111                 }
112                 return sdcResponseJsonObj;
113         }
114
115         /**
116          * set  HttpPostResponse
117          * @param config - RESTConfig object
118          * @param jsonPayload - String
119          * @return client - RestClient object
120          */
121         public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException {
122                 try {
123             return client.post(jsonPayload);
124         }catch(Exception ex){
125             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
126             ValidateException validateException = new ValidateException.Builder("Bad request could not post payload",
127                     HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
128
129             throw validateException;
130         }
131         }
132
133         /**
134          * enhance Response
135          * @param sdcResponseJsonObj - JSONObject object
136          * @param statusCode - int
137          * @return enhancedAsdcResponseJsonObj - JSONObject object
138          */
139         public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) throws JSONException {
140
141                 JSONObject enhancedAsdcResponseJsonObj = new JSONObject();
142
143                 String message = "";
144                 String messageId = "";
145
146                 if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted
147                         enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId"));
148                         enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
149                         enhancedAsdcResponseJsonObj.put("messageId", "");
150                         enhancedAsdcResponseJsonObj.put("message", "Success");
151
152                 } else {  // error
153                         if (sdcResponseJsonObj.has("requestError") ) {
154                                 JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject("requestError");
155                                 if (sdcResponseJsonObj.getJSONObject("requestError").has("serviceException") ) {
156                                         message = requestErrorObj.getJSONObject("serviceException").getString("text");
157                                         messageId = requestErrorObj.getJSONObject("serviceException").getString("messageId");
158                                 }
159                                 if (sdcResponseJsonObj.getJSONObject("requestError").has("policyException") ) {
160                                         message = requestErrorObj.getJSONObject("policyException").getString("text");
161                                         messageId = requestErrorObj.getJSONObject("policyException").getString("messageId");
162                                 }
163                                 enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));
164                                 enhancedAsdcResponseJsonObj.put("messageId", messageId);
165                                 enhancedAsdcResponseJsonObj.put("message", message);
166
167                         } else {
168                                 // unexpected format
169                                 enhancedAsdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
170                                 enhancedAsdcResponseJsonObj.put("messageId", MESSAGE_UNDEFINED_ERROR);
171                                 enhancedAsdcResponseJsonObj.put("message", MESSAGE_UNEXPECTED_FORMAT);
172                         }
173                 }
174                 return enhancedAsdcResponseJsonObj;
175
176         }
177
178         /**
179          * Build Uri
180          * @param serviceModelVersionId - String
181          * @param operationalEnvironmentId - String
182          * @return uriBuilder - String
183          */
184         public String buildUriBuilder(String serviceModelVersionId,  String operationalEnvironmentId) {
185             String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId +"/activate";
186             UriBuilder uriBuilder =  UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI)
187                                                .path(path);
188             return  uriBuilder.build().toString();
189         }
190
191         /**
192          * Build JSON context
193          * @param  workloadContext - String
194          * @return String json
195          * @throws JSONException
196          */
197         public String buildJsonWorkloadContext(String workloadContext) throws JSONException {
198                 return new JSONObject().put("workloadContext", workloadContext).toString();
199
200         }
201
202         /**
203          * decrypt value
204          * @param toDecrypt - String
205          * @param msokey - String
206          * @return result - String
207          */
208         public synchronized String decrypt(String toDecrypt, String msokey){
209                 String result = null;
210                 try {
211                         result = CryptoUtils.decrypt(toDecrypt, msokey);
212
213                 }
214                 catch (Exception e) {
215                         msoLogger.debug("Failed to decrypt credentials: " + toDecrypt, e);
216                 }
217                 return result;
218         }
219
220         private String getBasicAuth() {
221                 return decrypt(sdcClientAuth, msoKey);
222         }
223 }
224