Merge "Reorder modifiers"
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / openecomp / mso / apihandlerinfra / tenantisolation / helpers / AsdcClientHelper.java
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * ONAP - SO\r
4  * ================================================================================\r
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
6  * ================================================================================\r
7  * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * you may not use this file except in compliance with the License.\r
9  * You may obtain a copy of the License at\r
10  * \r
11  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * \r
13  * Unless required by applicable law or agreed to in writing, software\r
14  * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * See the License for the specific language governing permissions and\r
17  * limitations under the License.\r
18  * ============LICENSE_END=========================================================\r
19  */\r
20 \r
21 package org.openecomp.mso.apihandlerinfra.tenantisolation.helpers;\r
22 \r
23 import java.util.UUID;\r
24 \r
25 import javax.ws.rs.core.UriBuilder;\r
26 \r
27 import org.json.JSONObject;\r
28 import org.openecomp.mso.apihandlerinfra.tenantisolation.exceptions.AsdcClientCallFailed;\r
29 import org.openecomp.mso.logger.MsoLogger;\r
30 import org.openecomp.mso.properties.MsoJavaProperties;\r
31 import org.openecomp.mso.rest.APIResponse;\r
32 import org.openecomp.mso.rest.RESTClient;\r
33 import org.openecomp.mso.rest.RESTConfig;\r
34 \r
35 public class AsdcClientHelper {\r
36 \r
37         private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.APIH);\r
38         private String className = this.getClass().getSimpleName();\r
39         private String methodName = ""; \r
40         private String classMethodMessage = ""; \r
41         \r
42         private JSONObject asdcResponseJsonObj;\r
43 \r
44         protected MsoJavaProperties properties;\r
45         \r
46         public static final String ASDC_CONTENT_TYPE = "application/json";\r
47         public static final String ASDC_ACCEPT_TYPE = "application/json";       \r
48         \r
49         protected String instanceid;\r
50         protected String userid;\r
51         protected String asdcEndpoint; \r
52         protected String basicAuthCred;\r
53         protected String uri;   \r
54         \r
55         public static String PARTIAL_ASDC_URI = "/sdc/v1/catalog/services/";\r
56         \r
57         public AsdcClientHelper(MsoJavaProperties properties) {\r
58                 this.properties = properties;\r
59                 setAsdcProperties();\r
60 \r
61         };\r
62         \r
63         /**\r
64          * properties should be set during instantiation of this object\r
65          */     \r
66         private void setAsdcProperties() { \r
67                 String asdcClientAuth = this.properties.getProperty("mso.asdc.client.auth", null);              \r
68                 String msoKey = this.properties.getProperty("mso.msoKey", null);\r
69                 this.basicAuthCred = this.properties.decrypt(asdcClientAuth, msoKey);\r
70                 this.asdcEndpoint = this.properties.getProperty("asdc.endpoint", null);\r
71                 this.userid = this.properties.getProperty("asdc.activate.userid", null);\r
72                 this.instanceid = this.properties.getProperty("asdc.activate.instanceid", null);\r
73                 \r
74         }       \r
75         \r
76         /**\r
77          * Send POST request to ASDC for operational activation\r
78          * @param uri -  /sdc/v1/catalog/services/{serviceUUID}/distribution/{opEnvId}/activate\r
79          * @param jsonPayload - json string value of 'workloadContext'. \r
80          * @return JSONObject\r
81          */     \r
82         public JSONObject postActivateOperationalEnvironment(String serviceModelVersionId, String operationalEnvironmentId, String workloadContext) {\r
83 \r
84                 try {\r
85                         \r
86                         String url = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId);\r
87                         msoLogger.debug(" ASDC url : " + url);\r
88                         String jsonPayload = this.buildJsonWorkloadContext(workloadContext);\r
89                         msoLogger.debug(" ASDC jsonPayload : " + jsonPayload);\r
90                         asdcResponseJsonObj = new JSONObject();\r
91                         \r
92                         if ( basicAuthCred == null || "".equals(basicAuthCred) ) {              \r
93                                 String errorMessage = " ** ERROR: ASDC credentials 'mso.asdc.client.auth' not setup in properties file!";                               \r
94                                 throw new AsdcClientCallFailed(errorMessage);\r
95                         }\r
96                         \r
97                         RESTConfig config = new RESTConfig(url);\r
98                         RESTClient client = setRestClient(config);\r
99                         client.addAuthorizationHeader(basicAuthCred);\r
100                         \r
101                         APIResponse apiResponse = setHttpPostResponse(client, jsonPayload);\r
102                         int statusCode = apiResponse.getStatusCode();\r
103                         msoLogger.debug(" ASDC return code : " + statusCode);\r
104                         String responseData = apiResponse.getResponseBodyAsString();\r
105                         msoLogger.debug(" ASDC responseData : " + responseData);                        \r
106                         asdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode);\r
107                         \r
108                 } catch (Exception ex) {\r
109                         msoLogger.debug("calling ASDC Exception message: " + ex.getMessage());\r
110                         String errorMessage = " Encountered Error while calling ASDC POST Activate. " + ex.getMessage();\r
111                         msoLogger.debug(errorMessage);\r
112                         asdcResponseJsonObj.put("statusCode", "500"); \r
113                         asdcResponseJsonObj.put("messageId", "");                       \r
114                         asdcResponseJsonObj.put("message", errorMessage);\r
115 \r
116                 }\r
117                 return asdcResponseJsonObj;\r
118                 \r
119         }\r
120         \r
121         /**\r
122          * set RESTClient   \r
123          * @return RestClient object\r
124          */     \r
125         public RESTClient setRestClient(RESTConfig config) throws Exception {\r
126                 \r
127                 RESTClient client = new RESTClient(config).addHeader("X-ECOMP-InstanceID", instanceid)\r
128                                   .addHeader("X-ECOMP-RequestID", UUID.randomUUID().toString())\r
129                                   .addHeader("Content-Type", AsdcClientHelper.ASDC_CONTENT_TYPE)\r
130                                   .addHeader("Accept", AsdcClientHelper.ASDC_ACCEPT_TYPE)\r
131                                   .addHeader("USER_ID", userid);\r
132                 return client;\r
133                 \r
134         }       \r
135         \r
136         public APIResponse setHttpPostResponse(RESTClient client, String jsonPayload) throws Exception { \r
137                 return client.httpPost(jsonPayload);\r
138                 \r
139         }       \r
140         \r
141         \r
142         public JSONObject enhanceJsonResponse(JSONObject asdcResponseJsonObj, int statusCode) {\r
143 \r
144                 if (statusCode == 202) { // Accepted\r
145                         asdcResponseJsonObj.put("statusCode", Integer.toString(statusCode));\r
146                         asdcResponseJsonObj.put("messageId", "");\r
147                         asdcResponseJsonObj.put("message", "Success");                                  \r
148                         \r
149                 } else {  // error\r
150                         String message = "Undefined Error Message!";\r
151                         String messageId = "";                  \r
152                         if (asdcResponseJsonObj.has("requestError") ) {\r
153                                 JSONObject requestErrorObj = asdcResponseJsonObj.getJSONObject("requestError");\r
154                                 if (asdcResponseJsonObj.getJSONObject("requestError").has("serviceException") ) {\r
155                                         message = requestErrorObj.getJSONObject("serviceException").getString("text");\r
156                                         messageId = requestErrorObj.getJSONObject("serviceException").getString("messageId");\r
157                                 } \r
158                                 if (asdcResponseJsonObj.getJSONObject("requestError").has("policyException") ) {\r
159                                                 message = requestErrorObj.getJSONObject("policyException").getString("text");\r
160                                                 messageId = requestErrorObj.getJSONObject("policyException").getString("messageId");\r
161                                 }                                       \r
162 \r
163                         } \r
164                         asdcResponseJsonObj.put("statusCode", Integer.toString(statusCode)); \r
165                         asdcResponseJsonObj.put("messageId", messageId);\r
166                         asdcResponseJsonObj.put("message", message);\r
167                 }\r
168                 \r
169                 return asdcResponseJsonObj;\r
170                 \r
171         }\r
172         \r
173         /**\r
174          * Build Uri   \r
175          * @return String uri\r
176          */             \r
177         public String buildUriBuilder(String serviceModelVersionId,  String operationalEnvironmentId) {\r
178             String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId +"/activate";\r
179             UriBuilder uriBuilder =  UriBuilder.fromPath(asdcEndpoint + AsdcClientHelper.PARTIAL_ASDC_URI)\r
180                                                .path(path);\r
181             return  uriBuilder.build().toString();\r
182         }\r
183         \r
184         /**\r
185          * Build JSON context  \r
186          * @return String json\r
187          */             \r
188         public String buildJsonWorkloadContext(String workloadContext) {\r
189                 return new JSONObject().put("workloadContext", workloadContext).toString();\r
190                 \r
191         }\r
192         \r
193         /**\r
194          * get asdc instanceId of this object\r
195          */             \r
196         public String getAsdcInstanceId() {\r
197                 return this.instanceid;\r
198         }\r
199         \r
200         /**\r
201          * get asdc asdcEndpoint of this object\r
202          */             \r
203         public String getAsdcEndpoint() {\r
204                 return this.asdcEndpoint;\r
205         }       \r
206 \r
207         /**\r
208          * get asdc asdcUserId of this object\r
209          */             \r
210         public String getAsdcUserId() {\r
211                 return this.userid;\r
212         }       \r
213         \r
214         \r
215         \r
216 }\r