Added tests for dcae dispacher services
[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-2018 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  * \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.JsonNode;\r
29 import com.fasterxml.jackson.databind.node.ObjectNode;\r
30 \r
31 import java.io.IOException;\r
32 import java.util.Date;\r
33 \r
34 import org.json.simple.JSONObject;\r
35 import org.json.simple.parser.JSONParser;\r
36 import org.json.simple.parser.ParseException;\r
37 import org.onap.clamp.clds.config.ClampProperties;\r
38 import org.onap.clamp.clds.exception.dcae.DcaeDeploymentException;\r
39 import org.onap.clamp.clds.util.LoggingUtils;\r
40 import org.springframework.beans.factory.annotation.Autowired;\r
41 import org.springframework.stereotype.Component;\r
42 \r
43 /**\r
44  * This class implements the communication with DCAE for the service\r
45  * deployments.\r
46  */\r
47 @Component\r
48 public class DcaeDispatcherServices {\r
49 \r
50     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeDispatcherServices.class);\r
51     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();\r
52     private final ClampProperties refProp;\r
53     private final DcaeHttpConnectionManager dcaeHttpConnectionManager;\r
54     private static final String STATUS_URL_LOG = "Status URL extracted: ";\r
55     private static final String DCAE_URL_PREFIX = "/dcae-deployments/";\r
56     private static final String DCAE_URL_PROPERTY_NAME = "dcae.dispatcher.url";\r
57     public static final String DCAE_REQUESTID_PROPERTY_NAME = "dcae.header.requestId";\r
58     private static final String DCAE_LINK_FIELD = "links";\r
59     private static final String DCAE_STATUS_FIELD = "status";\r
60 \r
61     @Autowired\r
62     public DcaeDispatcherServices(ClampProperties refProp, DcaeHttpConnectionManager dcaeHttpConnectionManager) {\r
63         this.refProp = refProp;\r
64         this.dcaeHttpConnectionManager = dcaeHttpConnectionManager;\r
65     }\r
66 \r
67 \r
68     public String getOperationStatusWithRetry(String operationStatusUrl) throws InterruptedException {\r
69         String operationStatus = "";\r
70         for (int i = 0; i < Integer.valueOf(refProp.getStringValue("dcae.dispatcher.retry.limit")); i++) {\r
71             logger.info("Trying to get Operation status on DCAE for url:" + operationStatusUrl);\r
72             operationStatus = getOperationStatus(operationStatusUrl);\r
73             logger.info("Current Status is:" + operationStatus);\r
74             if (!"processing".equalsIgnoreCase(operationStatus)) {\r
75                 return operationStatus;\r
76             } else {\r
77                 Thread.sleep(Integer.valueOf(refProp.getStringValue("dcae.dispatcher.retry.interval")));\r
78             }\r
79         }\r
80         logger.warn("Number of attempts on DCAE is over, stopping the getOperationStatus method");\r
81         return operationStatus;\r
82     }\r
83 \r
84     /**\r
85      * Get the Operation Status from a specified URL.\r
86      * \r
87      * @param statusUrl\r
88      *            The URL provided by a previous DCAE Query\r
89      * @return The status\r
90      */\r
91     public String getOperationStatus(String statusUrl) {\r
92         // Assigning processing status to monitor operation status further\r
93         String opStatus = "processing";\r
94         Date startTime = new Date();\r
95         LoggingUtils.setTargetContext("DCAE", "getOperationStatus");\r
96         try {\r
97             String responseStr = dcaeHttpConnectionManager.doDcaeHttpQuery(statusUrl, "GET", null, null);\r
98             JSONObject jsonObj = parseResponse(responseStr);\r
99             String operationType = (String) jsonObj.get("operationType");\r
100             String status = (String) jsonObj.get(DCAE_STATUS_FIELD);\r
101             logger.info("Operation Type - " + operationType + ", Status " + status);\r
102             LoggingUtils.setResponseContext("0", "Get operation status success", this.getClass().getName());\r
103             opStatus = status;\r
104         } catch (Exception e) {\r
105             LoggingUtils.setResponseContext("900", "Get operation status failed", this.getClass().getName());\r
106             LoggingUtils.setErrorContext("900", "Get operation status error");\r
107             logger.error("Exception occurred during getOperationStatus Operation with DCAE", e);\r
108         } finally {\r
109             LoggingUtils.setTimeContext(startTime, new Date());\r
110             metricsLogger.info("getOperationStatus complete");\r
111         }\r
112         return opStatus;\r
113     }\r
114 \r
115     /**\r
116      * This method send a getDeployments operation to DCAE.\r
117      */\r
118     public void getDeployments() {\r
119         Date startTime = new Date();\r
120         LoggingUtils.setTargetContext("DCAE", "getDeployments");\r
121         try {\r
122             String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX;\r
123             dcaeHttpConnectionManager.doDcaeHttpQuery(url, "GET", null, null);\r
124             LoggingUtils.setResponseContext("0", "Get deployments success", this.getClass().getName());\r
125         } catch (Exception e) {\r
126             LoggingUtils.setResponseContext("900", "Get deployments failed", this.getClass().getName());\r
127             LoggingUtils.setErrorContext("900", "Get deployments error");\r
128             logger.error("Exception occurred during getDeployments Operation with DCAE", e);\r
129             throw new DcaeDeploymentException("Exception occurred during getDeployments Operation with DCAE", e);\r
130         } finally {\r
131             LoggingUtils.setTimeContext(startTime, new Date());\r
132             metricsLogger.info("getDeployments complete");\r
133         }\r
134     }\r
135 \r
136     /**\r
137      * Returns status URL for createNewDeployment operation.\r
138      *\r
139      * @param deploymentId\r
140      *            The deployment ID\r
141      * @param serviceTypeId\r
142      *            Service type ID\r
143      * @param blueprintInputJson\r
144      *            The value for each blueprint parameters in a flat JSON\r
145      * @return The status URL\r
146      */\r
147     public String createNewDeployment(String deploymentId, String serviceTypeId, JsonNode blueprintInputJson) {\r
148         Date startTime = new Date();\r
149         LoggingUtils.setTargetContext("DCAE", "createNewDeployment");\r
150         try {\r
151             ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("dcae.deployment.template");\r
152             rootNode.put("serviceTypeId", serviceTypeId);\r
153             if (blueprintInputJson != null) {\r
154                 rootNode.set("inputs", blueprintInputJson);\r
155             }\r
156             String apiBodyString = rootNode.toString();\r
157             logger.info("Dcae api Body String - " + apiBodyString);\r
158             String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;\r
159             String statusUrl = getDcaeResponse(url, "PUT", apiBodyString, "application/json", DCAE_LINK_FIELD,\r
160                     DCAE_STATUS_FIELD);\r
161             LoggingUtils.setResponseContext("0", "Create new deployment failed", this.getClass().getName());\r
162             return statusUrl;\r
163         } catch (Exception e) {\r
164             LoggingUtils.setResponseContext("900", "Create new deployment failed", this.getClass().getName());\r
165             LoggingUtils.setErrorContext("900", "Create new deployment error");\r
166             logger.error("Exception occurred during createNewDeployment Operation with DCAE", e);\r
167             throw new DcaeDeploymentException("Exception occurred during createNewDeployment Operation with DCAE", e);\r
168         } finally {\r
169             LoggingUtils.setTimeContext(startTime, new Date());\r
170             metricsLogger.info("createNewDeployment complete");\r
171         }\r
172     }\r
173 \r
174     /***\r
175      * Returns status URL for deleteExistingDeployment operation.\r
176      * \r
177      * @param deploymentId\r
178      *            The deployment ID\r
179      * @param serviceTypeId\r
180      *            The service Type ID\r
181      * @return The status URL\r
182      */\r
183     public String deleteExistingDeployment(String deploymentId, String serviceTypeId) {\r
184         Date startTime = new Date();\r
185         LoggingUtils.setTargetContext("DCAE", "deleteExistingDeployment");\r
186         try {\r
187             String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}";\r
188             logger.info("Dcae api Body String - " + apiBodyString);\r
189             String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;\r
190             String statusUrl = getDcaeResponse(url, "DELETE", apiBodyString, "application/json", DCAE_LINK_FIELD,\r
191                     DCAE_STATUS_FIELD);\r
192             LoggingUtils.setResponseContext("0", "Delete existing deployment success", this.getClass().getName());\r
193             return statusUrl;\r
194 \r
195         } catch (Exception e) {\r
196             LoggingUtils.setResponseContext("900", "Delete existing deployment failed", this.getClass().getName());\r
197             LoggingUtils.setErrorContext("900", "Delete existing deployment error");\r
198             logger.error("Exception occurred during deleteExistingDeployment Operation with DCAE", e);\r
199             throw new DcaeDeploymentException("Exception occurred during deleteExistingDeployment Operation with DCAE",\r
200                     e);\r
201         } finally {\r
202             LoggingUtils.setTimeContext(startTime, new Date());\r
203             metricsLogger.info("deleteExistingDeployment complete");\r
204         }\r
205     }\r
206 \r
207     private String getDcaeResponse(String url, String requestMethod, String payload, String contentType, String node,\r
208             String nodeAttr) throws IOException, ParseException {\r
209         Date startTime = new Date();\r
210         try {\r
211             String responseStr = dcaeHttpConnectionManager.doDcaeHttpQuery(url, requestMethod, payload, contentType);\r
212             JSONObject jsonObj = parseResponse(responseStr);\r
213             JSONObject linksObj = (JSONObject) jsonObj.get(node);\r
214             String statusUrl = (String) linksObj.get(nodeAttr);\r
215             logger.info(STATUS_URL_LOG + statusUrl);\r
216             return statusUrl;\r
217         } catch (IOException | ParseException e) {\r
218             logger.error("Exception occurred getting response from DCAE", e);\r
219             throw e;\r
220         } finally {\r
221             LoggingUtils.setTimeContext(startTime, new Date());\r
222             metricsLogger.info("getDcaeResponse complete");\r
223         }\r
224     }\r
225 \r
226     private JSONObject parseResponse(String responseStr) throws ParseException {\r
227         JSONParser parser = new JSONParser();\r
228         Object obj0 = parser.parse(responseStr);\r
229         JSONObject jsonObj = (JSONObject) obj0;\r
230         return jsonObj;\r
231     }\r
232 }