Update the policyName send to Policy
[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 import com.fasterxml.jackson.databind.node.ObjectNode;\r
29 \r
30 import java.io.BufferedReader;\r
31 import java.io.DataOutputStream;\r
32 import java.io.IOException;\r
33 import java.io.InputStream;\r
34 import java.io.InputStreamReader;\r
35 import java.net.URL;\r
36 import java.util.Date;\r
37 import java.util.stream.Collectors;\r
38 \r
39 import javax.net.ssl.HttpsURLConnection;\r
40 import javax.ws.rs.BadRequestException;\r
41 \r
42 import org.json.simple.JSONObject;\r
43 import org.json.simple.parser.JSONParser;\r
44 import org.onap.clamp.clds.exception.DcaeDeploymentException;\r
45 import org.onap.clamp.clds.model.refprop.RefProp;\r
46 import org.onap.clamp.clds.util.LoggingUtils;\r
47 import org.springframework.beans.factory.annotation.Autowired;\r
48 \r
49 /**\r
50  * This class implements the communication with DCAE for the service\r
51  * deployments.\r
52  *\r
53  */\r
54 public class DcaeDispatcherServices {\r
55     protected static final EELFLogger logger        = EELFManager.getInstance().getLogger(DcaeDispatcherServices.class);\r
56     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();\r
57 \r
58     @Autowired\r
59     private RefProp                   refProp;\r
60 \r
61     /**\r
62      * Delete the deployment on DCAE.\r
63      * \r
64      * @param deploymentId\r
65      *            The deployment ID\r
66      * @return Return the URL Status\r
67      * @throws IOException\r
68      *             In case of issues with the Stream\r
69      */\r
70     public String deleteDeployment(String deploymentId) throws IOException {\r
71 \r
72         String statusUrl = null;\r
73         InputStream in = null;\r
74         Date startTime = new Date();\r
75         LoggingUtils.setTargetContext("DCAE", "deleteDeployment");\r
76         try {\r
77             String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments/" + deploymentId;\r
78             logger.info("Dcae Dispatcher url - " + url);\r
79             URL obj = new URL(url);\r
80             HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
81             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
82             conn.setRequestMethod("DELETE");\r
83             int responseCode = conn.getResponseCode();\r
84 \r
85             boolean requestFailed = true;\r
86             logger.info("responseCode=" + responseCode);\r
87             if (responseCode == 200 || responseCode == 202) {\r
88                 requestFailed = false;\r
89             }\r
90 \r
91             InputStream inStream = conn.getErrorStream();\r
92             if (inStream == null) {\r
93                 inStream = conn.getInputStream();\r
94             }\r
95 \r
96             String responseStr = null;\r
97             if (inStream != null) {\r
98                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inStream));\r
99                 String inputLine = null;\r
100                 StringBuilder response = new StringBuilder();\r
101                 while ((inputLine = bufferedReader.readLine()) != null) {\r
102                     response.append(inputLine);\r
103                 }\r
104                 responseStr = response.toString();\r
105             }\r
106 \r
107             if (responseStr != null && requestFailed) {\r
108                 logger.error("requestFailed - responseStr=" + responseStr);\r
109                 throw new BadRequestException(responseStr);\r
110             }\r
111 \r
112             logger.debug("response code " + responseCode);\r
113             in = conn.getInputStream();\r
114             logger.debug("res:" + responseStr);\r
115             JSONParser parser = new JSONParser();\r
116             Object obj0 = parser.parse(responseStr);\r
117             JSONObject jsonObj = (JSONObject) obj0;\r
118             JSONObject linksObj = (JSONObject) jsonObj.get("links");\r
119             statusUrl = (String) linksObj.get("status");\r
120             logger.debug("Status URL: " + statusUrl);\r
121 \r
122         } catch (Exception e) {\r
123             logger.error("Exception occurred during Delete Deployment Operation with DCAE", e);\r
124             throw new DcaeDeploymentException("Exception occurred during Delete Deployment Operation with DCAE", e);\r
125         } finally {\r
126             if (in != null) {\r
127                 in.close();\r
128             }\r
129             LoggingUtils.setTimeContext(startTime, new Date());\r
130             metricsLogger.info("deleteDeployment complete");\r
131         }\r
132 \r
133         return statusUrl;\r
134 \r
135     }\r
136 \r
137     /**\r
138      * Get the Operation Status from a specified URL.\r
139      * \r
140      * @param statusUrl\r
141      *            The URL provided by a previous DCAE Query\r
142      * @return The status\r
143      * @throws IOException\r
144      *             In case of issues with the Stream\r
145      * \r
146      */\r
147     public String getOperationStatus(String statusUrl) throws IOException {\r
148 \r
149         // Assigning processing status to monitor operation status further\r
150         String opStatus = "processing";\r
151         InputStream in = null;\r
152         Date startTime = new Date();\r
153         LoggingUtils.setTargetContext("DCAE", "getOperationStatus");\r
154         try {\r
155             URL obj = new URL(statusUrl);\r
156             HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
157             conn.setRequestMethod("GET");\r
158             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
159             int responseCode = conn.getResponseCode();\r
160             logger.debug("Deployment operation status response code - " + responseCode);\r
161             if (responseCode == 200) {\r
162                 in = conn.getInputStream();\r
163                 String res = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));\r
164                 JSONParser parser = new JSONParser();\r
165                 Object obj0 = parser.parse(res);\r
166                 JSONObject jsonObj = (JSONObject) obj0;\r
167                 String operationType = (String) jsonObj.get("operationType");\r
168                 String status = (String) jsonObj.get("status");\r
169                 logger.debug("Operation Type - " + operationType + ", Status " + status);\r
170                 opStatus = status;\r
171             }\r
172         } catch (Exception e) {\r
173             logger.error("Exception occurred during getOperationStatus Operation with DCAE", e);\r
174             logger.debug(e.getMessage()\r
175                     + " : got exception while retrieving status, trying again until we get 200 response code");\r
176         } finally {\r
177             if (in != null) {\r
178                 in.close();\r
179             }\r
180             LoggingUtils.setTimeContext(startTime, new Date());\r
181             metricsLogger.info("getOperationStatus complete");\r
182         }\r
183         return opStatus;\r
184     }\r
185 \r
186     /**\r
187      * This method send a getDeployments operation to DCAE.\r
188      * \r
189      * @throws IOException\r
190      *             In case of issues with the Stream\r
191      */\r
192     public void getDeployments() throws IOException {\r
193         InputStream in = null;\r
194         Date startTime = new Date();\r
195         LoggingUtils.setTargetContext("DCAE", "getDeployments");\r
196         try {\r
197             String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments";\r
198             logger.info("Dcae Dispatcher deployments url - " + url);\r
199             URL obj = new URL(url);\r
200             HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
201             conn.setRequestMethod("GET");\r
202             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
203             int responseCode = conn.getResponseCode();\r
204             logger.debug("response code " + responseCode);\r
205             in = conn.getInputStream();\r
206             String res = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));\r
207             logger.debug("res:" + res);\r
208         } catch (Exception e) {\r
209             logger.error("Exception occurred during getDeployments Operation with DCAE", e);\r
210             throw new DcaeDeploymentException("Exception occurred during getDeployments Operation with DCAE", e);\r
211         } finally {\r
212             if (in != null) {\r
213                 in.close();\r
214             }\r
215             LoggingUtils.setTimeContext(startTime, new Date());\r
216             metricsLogger.info("getDeployments complete");\r
217         }\r
218     }\r
219 \r
220     /**\r
221      * Returns status URL for createNewDeployment operation.\r
222      *\r
223      * @param deploymentId\r
224      *            The deployment ID\r
225      * @param serviceTypeId\r
226      *            Service type ID\r
227      * @return The status URL\r
228      * @throws IOException\r
229      *             In case of issues with the Stream\r
230      */\r
231     public String createNewDeployment(String deploymentId, String serviceTypeId) throws IOException {\r
232 \r
233         String statusUrl = null;\r
234         InputStream inStream = null;\r
235         BufferedReader in = null;\r
236         Date startTime = new Date();\r
237         LoggingUtils.setTargetContext("DCAE", "createNewDeployment");\r
238         try {\r
239             ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("dcae.deployment.template");\r
240             ((ObjectNode) rootNode).put("serviceTypeId", serviceTypeId);\r
241             String apiBodyString = rootNode.toString();\r
242 \r
243             logger.info("Dcae api Body String - " + apiBodyString);\r
244             String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments/" + deploymentId;\r
245             logger.info("Dcae Dispatcher Service url - " + url);\r
246             URL obj = new URL(url);\r
247             HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
248             conn.setRequestMethod("PUT");\r
249             conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
250             conn.setRequestProperty("Content-Type", "application/json");\r
251             conn.setDoOutput(true);\r
252             try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {\r
253                 wr.writeBytes(apiBodyString);\r
254                 wr.flush();\r
255             }\r
256 \r
257             boolean requestFailed = true;\r
258             int responseCode = conn.getResponseCode();\r
259             logger.info("responseCode=" + responseCode);\r
260             if (responseCode == 200 || responseCode == 202) {\r
261                 requestFailed = false;\r
262             }\r
263 \r
264             inStream = conn.getErrorStream();\r
265             if (inStream == null) {\r
266                 inStream = conn.getInputStream();\r
267             }\r
268 \r
269             String responseStr = null;\r
270             if (inStream != null) {\r
271                 in = new BufferedReader(new InputStreamReader(inStream));\r
272 \r
273                 String inputLine = null;\r
274 \r
275                 StringBuilder response = new StringBuilder();\r
276 \r
277                 while ((inputLine = in.readLine()) != null) {\r
278                     response.append(inputLine);\r
279                 }\r
280 \r
281                 responseStr = response.toString();\r
282             }\r
283 \r
284             if (responseStr != null && requestFailed) {\r
285                 logger.error("requestFailed - responseStr=" + responseStr);\r
286                 throw new BadRequestException(responseStr);\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 }