718a2e997550824c8e802375c63349097d89ce2d
[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                 StringBuilder response = new StringBuilder();\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 && requestFailed) {\r
107                 logger.error("requestFailed - responseStr=" + responseStr);\r
108                 throw new BadRequestException(responseStr);\r
109             }\r
110 \r
111             logger.debug("response code " + responseCode);\r
112             in = conn.getInputStream();\r
113             logger.debug("res:" + responseStr);\r
114             JSONParser parser = new JSONParser();\r
115             Object obj0 = parser.parse(responseStr);\r
116             JSONObject jsonObj = (JSONObject) obj0;\r
117             JSONObject linksObj = (JSONObject) jsonObj.get("links");\r
118             statusUrl = (String) linksObj.get("status");\r
119             logger.debug("Status URL: " + statusUrl);\r
120 \r
121         } catch (Exception e) {\r
122             logger.error("Exception occurred during Delete Deployment Operation with DCAE", e);\r
123             throw new DcaeDeploymentException("Exception occurred during Delete Deployment Operation with DCAE", e);\r
124         } finally {\r
125             if (in != null) {\r
126                 in.close();\r
127             }\r
128             LoggingUtils.setTimeContext(startTime, new Date());\r
129             metricsLogger.info("deleteDeployment complete");\r
130         }\r
131 \r
132         return statusUrl;\r
133 \r
134     }\r
135 \r
136     /**\r
137      * Get the Operation Status from a specified URL.\r
138      * \r
139      * @param statusUrl\r
140      *            The URL provided by a previous DCAE Query\r
141      * @return The status\r
142      * @throws IOException\r
143      *             In case of issues with the Stream\r
144      * \r
145      */\r
146     public String getOperationStatus(String statusUrl) throws IOException {\r
147 \r
148         // Assigning processing status to monitor operation status further\r
149         String opStatus = "processing";\r
150         InputStream in = null;\r
151         Date startTime = new Date();\r
152         LoggingUtils.setTargetContext("DCAE", "getOperationStatus");\r
153         try {\r
154             URL obj = new URL(statusUrl);\r
155             HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
156             conn.setRequestMethod("GET");\r
157             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
158             int responseCode = conn.getResponseCode();\r
159             logger.debug("Deployment operation status response code - " + responseCode);\r
160             if (responseCode == 200) {\r
161                 in = conn.getInputStream();\r
162                 String res = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));\r
163                 JSONParser parser = new JSONParser();\r
164                 Object obj0 = parser.parse(res);\r
165                 JSONObject jsonObj = (JSONObject) obj0;\r
166                 String operationType = (String) jsonObj.get("operationType");\r
167                 String status = (String) jsonObj.get("status");\r
168                 logger.debug("Operation Type - " + operationType + ", Status " + status);\r
169                 opStatus = status;\r
170             }\r
171         } catch (Exception e) {\r
172             logger.error("Exception occurred during getOperationStatus Operation with DCAE", e);\r
173             logger.debug(e.getMessage()\r
174                     + " : got exception while retrieving status, trying again until we get 200 response code");\r
175         } finally {\r
176             if (in != null) {\r
177                 in.close();\r
178             }\r
179             LoggingUtils.setTimeContext(startTime, new Date());\r
180             metricsLogger.info("getOperationStatus complete");\r
181         }\r
182         return opStatus;\r
183     }\r
184 \r
185     /**\r
186      * This method send a getDeployments operation to DCAE.\r
187      * \r
188      * @throws IOException\r
189      *             In case of issues with the Stream\r
190      */\r
191     public void getDeployments() throws IOException {\r
192         InputStream in = null;\r
193         Date startTime = new Date();\r
194         LoggingUtils.setTargetContext("DCAE", "getDeployments");\r
195         try {\r
196             String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments";\r
197             logger.info("Dcae Dispatcher deployments url - " + url);\r
198             URL obj = new URL(url);\r
199             HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
200             conn.setRequestMethod("GET");\r
201             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
202             int responseCode = conn.getResponseCode();\r
203             logger.debug("response code " + responseCode);\r
204             in = conn.getInputStream();\r
205             String res = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));\r
206             logger.debug("res:" + res);\r
207         } catch (Exception e) {\r
208             logger.error("Exception occurred during getDeployments Operation with DCAE", e);\r
209             throw new DcaeDeploymentException("Exception occurred during getDeployments Operation with DCAE", e);\r
210         } finally {\r
211             if (in != null) {\r
212                 in.close();\r
213             }\r
214             LoggingUtils.setTimeContext(startTime, new Date());\r
215             metricsLogger.info("getDeployments complete");\r
216         }\r
217     }\r
218 \r
219     /**\r
220      * Returns status URL for createNewDeployment operation.\r
221      *\r
222      * @param deploymentId\r
223      *            The deployment ID\r
224      * @param serviceTypeId\r
225      *            Service type ID\r
226      * @return The status URL\r
227      * @throws IOException\r
228      *             In case of issues with the Stream\r
229      */\r
230     public String createNewDeployment(String deploymentId, String serviceTypeId) throws IOException {\r
231 \r
232         String statusUrl = null;\r
233         InputStream inStream = null;\r
234         BufferedReader in = null;\r
235         Date startTime = new Date();\r
236         LoggingUtils.setTargetContext("DCAE", "createNewDeployment");\r
237         try {\r
238             String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}";\r
239             logger.info("Dcae api Body String - " + apiBodyString);\r
240             String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments/" + deploymentId;\r
241             logger.info("Dcae Dispatcher Service url - " + url);\r
242             URL obj = new URL(url);\r
243             HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
244             conn.setRequestMethod("PUT");\r
245             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
246             conn.setRequestProperty("Content-Type", "application/json");\r
247             conn.setDoOutput(true);\r
248             try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {\r
249                 wr.writeBytes(apiBodyString);\r
250                 wr.flush();\r
251             }\r
252 \r
253             boolean requestFailed = true;\r
254             int responseCode = conn.getResponseCode();\r
255             logger.info("responseCode=" + responseCode);\r
256             if (responseCode == 200 || responseCode == 202) {\r
257                 requestFailed = false;\r
258             }\r
259 \r
260             inStream = conn.getErrorStream();\r
261             if (inStream == null) {\r
262                 inStream = conn.getInputStream();\r
263             }\r
264 \r
265             String responseStr = null;\r
266             if (inStream != null) {\r
267                 in = new BufferedReader(new InputStreamReader(inStream));\r
268 \r
269                 String inputLine = null;\r
270 \r
271                 StringBuilder response = new StringBuilder();\r
272 \r
273                 while ((inputLine = in.readLine()) != null) {\r
274                     response.append(inputLine);\r
275                 }\r
276 \r
277                 responseStr = response.toString();\r
278             }\r
279 \r
280             if (responseStr != null && requestFailed) {\r
281                 logger.error("requestFailed - responseStr=" + responseStr);\r
282                 throw new BadRequestException(responseStr);\r
283             }\r
284 \r
285             logger.debug("response code " + responseCode);\r
286             JSONParser parser = new JSONParser();\r
287             Object obj0 = parser.parse(responseStr);\r
288             JSONObject jsonObj = (JSONObject) obj0;\r
289             JSONObject linksObj = (JSONObject) jsonObj.get("links");\r
290             statusUrl = (String) linksObj.get("status");\r
291             logger.debug("Status URL: " + statusUrl);\r
292         } catch (Exception e) {\r
293             logger.error("Exception occurred during createNewDeployment Operation with DCAE", e);\r
294             throw new DcaeDeploymentException("Exception occurred during createNewDeployment Operation with DCAE", e);\r
295         } finally {\r
296             if (inStream != null) {\r
297                 inStream.close();\r
298             }\r
299             if (in != null) {\r
300                 in.close();\r
301             }\r
302             LoggingUtils.setTimeContext(startTime, new Date());\r
303             metricsLogger.info("createNewDeployment complete");\r
304         }\r
305         return statusUrl;\r
306     }\r
307 \r
308     /**\r
309      * Returns status URL for deleteExistingDeployment operation.\r
310      * \r
311      * @param deploymentId\r
312      *            The deployment ID\r
313      * @param serviceTypeId\r
314      *            The service Type ID\r
315      * @return The status URL\r
316      * @throws IOException\r
317      *             In case of issues with the Stream\r
318      */\r
319     public String deleteExistingDeployment(String deploymentId, String serviceTypeId) throws IOException {\r
320 \r
321         String statusUrl = null;\r
322         InputStream in = null;\r
323         Date startTime = new Date();\r
324         LoggingUtils.setTargetContext("DCAE", "deleteExistingDeployment");\r
325         try {\r
326             String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}";\r
327             logger.debug(apiBodyString);\r
328             String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments/" + deploymentId;\r
329             logger.info("Dcae Dispatcher deployments url - " + url);\r
330             URL obj = new URL(url);\r
331             HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
332             conn.setRequestMethod("DELETE");\r
333             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
334             conn.setRequestProperty("Content-Type", "application/json");\r
335             conn.setDoOutput(true);\r
336             DataOutputStream wr = new DataOutputStream(conn.getOutputStream());\r
337             wr.writeBytes(apiBodyString);\r
338             wr.flush();\r
339 \r
340             int responseCode = conn.getResponseCode();\r
341             logger.debug("response code " + responseCode);\r
342             in = conn.getInputStream();\r
343             String res = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));\r
344             logger.debug("res:" + res);\r
345             JSONParser parser = new JSONParser();\r
346             Object obj0 = parser.parse(res);\r
347             JSONObject jsonObj = (JSONObject) obj0;\r
348             JSONObject linksObj = (JSONObject) jsonObj.get("links");\r
349             statusUrl = (String) linksObj.get("status");\r
350             logger.debug("Status URL: " + statusUrl);\r
351         } catch (Exception e) {\r
352             logger.error("Exception occurred during deleteExistingDeployment Operation with DCAE", e);\r
353             throw new DcaeDeploymentException("Exception occurred during deleteExistingDeployment Operation with DCAE",\r
354                     e);\r
355         } finally {\r
356             if (in != null) {\r
357                 in.close();\r
358             }\r
359             LoggingUtils.setTimeContext(startTime, new Date());\r
360             metricsLogger.info("deleteExistingDeployment complete");\r
361         }\r
362         return statusUrl;\r
363     }\r
364 \r
365 }