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