Merge "Update License.txt"
[clamp.git] / src / main / java / org / onap / clamp / clds / client / DcaeDispatcherServices.java
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * ONAP CLAMP\r
4  * ================================================================================\r
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights\r
6  *                             reserved.\r
7  * ================================================================================\r
8  * Licensed under the Apache License, Version 2.0 (the "License");\r
9  * you may not use this file except in compliance with the License.\r
10  * You may obtain a copy of the License at\r
11  *\r
12  * http://www.apache.org/licenses/LICENSE-2.0\r
13  *\r
14  * Unless required by applicable law or agreed to in writing, software\r
15  * distributed under the License is distributed on an "AS IS" BASIS,\r
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
17  * See the License for the specific language governing permissions and\r
18  * limitations under the License.\r
19  * ============LICENSE_END============================================\r
20  * ===================================================================\r
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
22  */\r
23 \r
24 package org.onap.clamp.clds.client;\r
25 \r
26 import com.att.eelf.configuration.EELFLogger;\r
27 import com.att.eelf.configuration.EELFManager;\r
28 \r
29 import java.io.BufferedReader;\r
30 import java.io.DataOutputStream;\r
31 import java.io.IOException;\r
32 import java.io.InputStream;\r
33 import java.io.InputStreamReader;\r
34 import java.net.URL;\r
35 import java.util.Date;\r
36 import java.util.stream.Collectors;\r
37 \r
38 import javax.net.ssl.HttpsURLConnection;\r
39 import javax.ws.rs.BadRequestException;\r
40 \r
41 import org.json.simple.JSONObject;\r
42 import org.json.simple.parser.JSONParser;\r
43 import org.onap.clamp.clds.exception.DcaeDeploymentException;\r
44 import org.onap.clamp.clds.model.refprop.RefProp;\r
45 import org.onap.clamp.clds.util.LoggingUtils;\r
46 import org.springframework.beans.factory.annotation.Autowired;\r
47 \r
48 /**\r
49  * This class implements the communication with DCAE for the service\r
50  * deployments.\r
51  *\r
52  */\r
53 public class DcaeDispatcherServices {\r
54     protected static final EELFLogger logger        = EELFManager.getInstance().getLogger(DcaeDispatcherServices.class);\r
55     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();\r
56 \r
57     @Autowired\r
58     private RefProp                   refProp;\r
59 \r
60     /**\r
61      * Delete the deployment on DCAE.\r
62      * \r
63      * @param deploymentId\r
64      *            The deployment ID\r
65      * @return Return the URL Status\r
66      * @throws IOException\r
67      *             In case of issues with the Stream\r
68      */\r
69     public String deleteDeployment(String deploymentId) throws IOException {\r
70 \r
71         String statusUrl = null;\r
72         InputStream in = null;\r
73         Date startTime = new Date();\r
74         LoggingUtils.setTargetContext("DCAE", "deleteDeployment");\r
75         try {\r
76             String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments/" + deploymentId;\r
77             logger.info("Dcae Dispatcher url - " + url);\r
78             URL obj = new URL(url);\r
79             HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
80             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
81             conn.setRequestMethod("DELETE");\r
82             int responseCode = conn.getResponseCode();\r
83 \r
84             boolean requestFailed = true;\r
85             logger.info("responseCode=" + responseCode);\r
86             if (responseCode == 200 || responseCode == 202) {\r
87                 requestFailed = false;\r
88             }\r
89 \r
90             InputStream inStream = conn.getErrorStream();\r
91             if (inStream == null) {\r
92                 inStream = conn.getInputStream();\r
93             }\r
94 \r
95             String responseStr = null;\r
96             if (inStream != null) {\r
97                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inStream));\r
98                 String inputLine = null;\r
99                 StringBuffer response = new StringBuffer();\r
100                 while ((inputLine = bufferedReader.readLine()) != null) {\r
101                     response.append(inputLine);\r
102                 }\r
103                 responseStr = response.toString();\r
104             }\r
105 \r
106             if (responseStr != null) {\r
107                 if (requestFailed) {\r
108                     logger.error("requestFailed - responseStr=" + responseStr);\r
109                     throw new BadRequestException(responseStr);\r
110                 }\r
111             }\r
112 \r
113             logger.debug("response code " + responseCode);\r
114             in = conn.getInputStream();\r
115             logger.debug("res:" + responseStr);\r
116             JSONParser parser = new JSONParser();\r
117             Object obj0 = parser.parse(responseStr);\r
118             JSONObject jsonObj = (JSONObject) obj0;\r
119             JSONObject linksObj = (JSONObject) jsonObj.get("links");\r
120             statusUrl = (String) linksObj.get("status");\r
121             logger.debug("Status URL: " + statusUrl);\r
122 \r
123         } catch (Exception e) {\r
124             logger.error("Exception occurred during Delete Deployment Operation with DCAE", e);\r
125             throw new DcaeDeploymentException("Exception occurred during Delete Deployment Operation with DCAE", e);\r
126         } finally {\r
127             if (in != null) {\r
128                 in.close();\r
129             }\r
130             LoggingUtils.setTimeContext(startTime, new Date());\r
131             metricsLogger.info("deleteDeployment complete");\r
132         }\r
133 \r
134         return statusUrl;\r
135 \r
136     }\r
137 \r
138     /**\r
139      * Get the Operation Status from a specified URL.\r
140      * \r
141      * @param statusUrl\r
142      *            The URL provided by a previous DCAE Query\r
143      * @return The status\r
144      * @throws IOException\r
145      *             In case of issues with the Stream\r
146      * \r
147      */\r
148     public String getOperationStatus(String statusUrl) throws IOException {\r
149 \r
150         // Assigning processing status to monitor operation status further\r
151         String opStatus = "processing";\r
152         InputStream in = null;\r
153         Date startTime = new Date();\r
154         LoggingUtils.setTargetContext("DCAE", "getOperationStatus");\r
155         try {\r
156             URL obj = new URL(statusUrl);\r
157             HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
158             conn.setRequestMethod("GET");\r
159             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
160             int responseCode = conn.getResponseCode();\r
161             logger.debug("Deployment operation status response code - " + responseCode);\r
162             if (responseCode == 200) {\r
163                 in = conn.getInputStream();\r
164                 String res = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));\r
165                 JSONParser parser = new JSONParser();\r
166                 Object obj0 = parser.parse(res);\r
167                 JSONObject jsonObj = (JSONObject) obj0;\r
168                 String operationType = (String) jsonObj.get("operationType");\r
169                 String status = (String) jsonObj.get("status");\r
170                 logger.debug("Operation Type - " + operationType + ", Status " + status);\r
171                 opStatus = status;\r
172             }\r
173         } catch (Exception e) {\r
174             logger.error("Exception occurred during getOperationStatus Operation with DCAE", e);\r
175             logger.debug(e.getMessage()\r
176                     + " : got exception while retrieving status, trying again until we get 200 response code");\r
177         } finally {\r
178             if (in != null) {\r
179                 in.close();\r
180             }\r
181             LoggingUtils.setTimeContext(startTime, new Date());\r
182             metricsLogger.info("getOperationStatus complete");\r
183         }\r
184         return opStatus;\r
185     }\r
186 \r
187     /**\r
188      * This method send a getDeployments operation to DCAE.\r
189      * \r
190      * @throws IOException\r
191      *             In case of issues with the Stream\r
192      */\r
193     public void getDeployments() throws IOException {\r
194         InputStream in = null;\r
195         Date startTime = new Date();\r
196         LoggingUtils.setTargetContext("DCAE", "getDeployments");\r
197         try {\r
198             String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments";\r
199             logger.info("Dcae Dispatcher deployments url - " + url);\r
200             URL obj = new URL(url);\r
201             HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
202             conn.setRequestMethod("GET");\r
203             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
204             int responseCode = conn.getResponseCode();\r
205             logger.debug("response code " + responseCode);\r
206             in = conn.getInputStream();\r
207             String res = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));\r
208             logger.debug("res:" + res);\r
209         } catch (Exception e) {\r
210             logger.error("Exception occurred during getDeployments Operation with DCAE", e);\r
211             throw new DcaeDeploymentException("Exception occurred during getDeployments Operation with DCAE", e);\r
212         } finally {\r
213             if (in != null) {\r
214                 in.close();\r
215             }\r
216             LoggingUtils.setTimeContext(startTime, new Date());\r
217             metricsLogger.info("getDeployments complete");\r
218         }\r
219     }\r
220 \r
221     /**\r
222      * Returns status URL for createNewDeployment operation.\r
223      *\r
224      * @param deploymentId\r
225      *            The deployment ID\r
226      * @param serviceTypeId\r
227      *            Service type ID\r
228      * @return The status URL\r
229      * @throws IOException\r
230      *             In case of issues with the Stream\r
231      */\r
232     public String createNewDeployment(String deploymentId, String serviceTypeId) throws IOException {\r
233 \r
234         String statusUrl = null;\r
235         InputStream inStream = null;\r
236         BufferedReader in = null;\r
237         Date startTime = new Date();\r
238         LoggingUtils.setTargetContext("DCAE", "createNewDeployment");\r
239         try {\r
240             String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}";\r
241             logger.info("Dcae api Body String - " + apiBodyString);\r
242             String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments/" + deploymentId;\r
243             logger.info("Dcae Dispatcher Service url - " + url);\r
244             URL obj = new URL(url);\r
245             HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
246             conn.setRequestMethod("PUT");\r
247             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
248             conn.setRequestProperty("Content-Type", "application/json");\r
249             conn.setDoOutput(true);\r
250             try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {\r
251                 wr.writeBytes(apiBodyString);\r
252                 wr.flush();\r
253             }\r
254 \r
255             boolean requestFailed = true;\r
256             int responseCode = conn.getResponseCode();\r
257             logger.info("responseCode=" + responseCode);\r
258             if (responseCode == 200 || responseCode == 202) {\r
259                 requestFailed = false;\r
260             }\r
261 \r
262             inStream = conn.getErrorStream();\r
263             if (inStream == null) {\r
264                 inStream = conn.getInputStream();\r
265             }\r
266 \r
267             String responseStr = null;\r
268             if (inStream != null) {\r
269                 in = new BufferedReader(new InputStreamReader(inStream));\r
270 \r
271                 String inputLine = null;\r
272 \r
273                 StringBuffer response = new StringBuffer();\r
274 \r
275                 while ((inputLine = in.readLine()) != null) {\r
276                     response.append(inputLine);\r
277                 }\r
278 \r
279                 responseStr = response.toString();\r
280             }\r
281 \r
282             if (responseStr != null) {\r
283                 if (requestFailed) {\r
284                     logger.error("requestFailed - responseStr=" + responseStr);\r
285                     throw new BadRequestException(responseStr);\r
286                 }\r
287             }\r
288 \r
289             logger.debug("response code " + responseCode);\r
290             JSONParser parser = new JSONParser();\r
291             Object obj0 = parser.parse(responseStr);\r
292             JSONObject jsonObj = (JSONObject) obj0;\r
293             JSONObject linksObj = (JSONObject) jsonObj.get("links");\r
294             statusUrl = (String) linksObj.get("status");\r
295             logger.debug("Status URL: " + statusUrl);\r
296         } catch (Exception e) {\r
297             logger.error("Exception occurred during createNewDeployment Operation with DCAE", e);\r
298             throw new DcaeDeploymentException("Exception occurred during createNewDeployment Operation with DCAE", e);\r
299         } finally {\r
300             if (inStream != null) {\r
301                 inStream.close();\r
302             }\r
303             if (in != null) {\r
304                 in.close();\r
305             }\r
306             LoggingUtils.setTimeContext(startTime, new Date());\r
307             metricsLogger.info("createNewDeployment complete");\r
308         }\r
309         return statusUrl;\r
310     }\r
311 \r
312     /**\r
313      * Returns status URL for deleteExistingDeployment operation.\r
314      * \r
315      * @param deploymentId\r
316      *            The deployment ID\r
317      * @param serviceTypeId\r
318      *            The service Type ID\r
319      * @return The status URL\r
320      * @throws IOException\r
321      *             In case of issues with the Stream\r
322      */\r
323     public String deleteExistingDeployment(String deploymentId, String serviceTypeId) throws IOException {\r
324 \r
325         String statusUrl = null;\r
326         InputStream in = null;\r
327         Date startTime = new Date();\r
328         LoggingUtils.setTargetContext("DCAE", "deleteExistingDeployment");\r
329         try {\r
330             String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}";\r
331             logger.debug(apiBodyString);\r
332             String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments/" + deploymentId;\r
333             logger.info("Dcae Dispatcher deployments url - " + url);\r
334             URL obj = new URL(url);\r
335             HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
336             conn.setRequestMethod("DELETE");\r
337             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
338             conn.setRequestProperty("Content-Type", "application/json");\r
339             conn.setDoOutput(true);\r
340             DataOutputStream wr = new DataOutputStream(conn.getOutputStream());\r
341             wr.writeBytes(apiBodyString);\r
342             wr.flush();\r
343 \r
344             int responseCode = conn.getResponseCode();\r
345             logger.debug("response code " + responseCode);\r
346             in = conn.getInputStream();\r
347             String res = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));\r
348             logger.debug("res:" + res);\r
349             JSONParser parser = new JSONParser();\r
350             Object obj0 = parser.parse(res);\r
351             JSONObject jsonObj = (JSONObject) obj0;\r
352             JSONObject linksObj = (JSONObject) jsonObj.get("links");\r
353             statusUrl = (String) linksObj.get("status");\r
354             logger.debug("Status URL: " + statusUrl);\r
355         } catch (Exception e) {\r
356             logger.error("Exception occurred during deleteExistingDeployment Operation with DCAE", e);\r
357             throw new DcaeDeploymentException("Exception occurred during deleteExistingDeployment Operation with DCAE",\r
358                     e);\r
359         } finally {\r
360             if (in != null) {\r
361                 in.close();\r
362             }\r
363             LoggingUtils.setTimeContext(startTime, new Date());\r
364             metricsLogger.info("deleteExistingDeployment complete");\r
365         }\r
366         return statusUrl;\r
367     }\r
368 \r
369 }