Fixed various sonar identified code smells
[clamp.git] / src / main / java / org / onap / clamp / clds / client / DcaeDispatcherServices.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Modifications Copyright (c) 2019 Samsung
9  * ================================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  * http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ============LICENSE_END============================================
22  * ===================================================================
23  *
24  */
25
26 package org.onap.clamp.clds.client;
27
28 import com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
30
31 import com.google.gson.JsonObject;
32 import java.io.IOException;
33 import java.util.Date;
34
35 import org.json.simple.JSONObject;
36 import org.json.simple.parser.JSONParser;
37 import org.json.simple.parser.ParseException;
38 import org.onap.clamp.clds.config.ClampProperties;
39 import org.onap.clamp.clds.exception.dcae.DcaeDeploymentException;
40 import org.onap.clamp.clds.util.LoggingUtils;
41 import org.onap.clamp.util.HttpConnectionManager;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.stereotype.Component;
44
45 /**
46  * This class implements the communication with DCAE for the service
47  * deployments.
48  */
49 @Component
50 public class DcaeDispatcherServices {
51
52     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeDispatcherServices.class);
53     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
54     private final ClampProperties refProp;
55     private final HttpConnectionManager dcaeHttpConnectionManager;
56     private static final String STATUS_URL_LOG = "Status URL extracted: ";
57     private static final String DCAE_URL_PREFIX = "/dcae-deployments/";
58     private static final String DCAE_URL_PROPERTY_NAME = "dcae.dispatcher.url";
59     private static final String DCAE_LINK_FIELD = "links";
60     private static final String DCAE_STATUS_FIELD = "status";
61
62     @Autowired
63     public DcaeDispatcherServices(ClampProperties refProp, HttpConnectionManager dcaeHttpConnectionManager) {
64         this.refProp = refProp;
65         this.dcaeHttpConnectionManager = dcaeHttpConnectionManager;
66     }
67
68     /**
69      * Get the Operation Status from a specified URL with retry.
70      * @param operationStatusUrl
71      *        The URL of the DCAE
72      * @return The status
73      * @throws InterruptedException Exception during the retry
74      */
75     public String getOperationStatusWithRetry(String operationStatusUrl) throws InterruptedException {
76         String operationStatus = "";
77         for (int i = 0; i < Integer.valueOf(refProp.getStringValue("dcae.dispatcher.retry.limit")); i++) {
78             logger.info("Trying to get Operation status on DCAE for url:" + operationStatusUrl);
79             operationStatus = getOperationStatus(operationStatusUrl);
80             logger.info("Current Status is:" + operationStatus);
81             if (!"processing".equalsIgnoreCase(operationStatus)) {
82                 return operationStatus;
83             } else {
84                 Thread.sleep(Integer.valueOf(refProp.getStringValue("dcae.dispatcher.retry.interval")));
85             }
86         }
87         logger.warn("Number of attempts on DCAE is over, stopping the getOperationStatus method");
88         return operationStatus;
89     }
90
91     /**
92      * Get the Operation Status from a specified URL.
93      * @param statusUrl
94      *        The URL provided by a previous DCAE Query
95      * @return The status
96      */
97     public String getOperationStatus(String statusUrl) {
98         // Assigning processing status to monitor operation status further
99         String opStatus = "processing";
100         Date startTime = new Date();
101         LoggingUtils.setTargetContext("DCAE", "getOperationStatus");
102         try {
103             String responseStr = dcaeHttpConnectionManager.doHttpRequest(statusUrl, "GET", null,
104                                                                          null, "DCAE", null,
105                                                                          null);
106             JSONObject jsonObj = parseResponse(responseStr);
107             String operationType = (String) jsonObj.get("operationType");
108             String status = (String) jsonObj.get(DCAE_STATUS_FIELD);
109             logger.info("Operation Type - " + operationType + ", Status " + status);
110             LoggingUtils.setResponseContext("0", "Get operation status success", this.getClass().getName());
111             opStatus = status;
112         } catch (Exception e) {
113             LoggingUtils.setResponseContext("900", "Get operation status failed", this.getClass().getName());
114             LoggingUtils.setErrorContext("900", "Get operation status error");
115             logger.error("Exception occurred during getOperationStatus Operation with DCAE", e);
116         } finally {
117             LoggingUtils.setTimeContext(startTime, new Date());
118             metricsLogger.info("getOperationStatus complete");
119         }
120         return opStatus;
121     }
122
123     /**
124      * Returns status URL for createNewDeployment operation.
125      * @param deploymentId
126      *        The deployment ID
127      * @param serviceTypeId
128      *        Service type ID
129      * @param blueprintInputJson
130      *        The value for each blueprint parameters in a flat JSON
131      * @return The status URL
132      */
133     public String createNewDeployment(String deploymentId, String serviceTypeId, JsonObject blueprintInputJson) {
134         Date startTime = new Date();
135         LoggingUtils.setTargetContext("DCAE", "createNewDeployment");
136         try {
137             JsonObject rootObject = refProp.getJsonTemplate("dcae.deployment.template").getAsJsonObject();
138             rootObject.addProperty("serviceTypeId", serviceTypeId);
139             if (blueprintInputJson != null) {
140                 rootObject.add("inputs", blueprintInputJson);
141             }
142             String apiBodyString = rootObject.toString();
143             logger.info("Dcae api Body String - " + apiBodyString);
144             String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;
145             String statusUrl = getDcaeResponse(url, "PUT", apiBodyString, "application/json", DCAE_LINK_FIELD,
146                 DCAE_STATUS_FIELD);
147             LoggingUtils.setResponseContext("0", "Create new deployment failed", this.getClass().getName());
148             return statusUrl;
149         } catch (Exception e) {
150             LoggingUtils.setResponseContext("900", "Create new deployment failed", this.getClass().getName());
151             LoggingUtils.setErrorContext("900", "Create new deployment error");
152             logger.error("Exception occurred during createNewDeployment Operation with DCAE", e);
153             throw new DcaeDeploymentException("Exception occurred during createNewDeployment Operation with DCAE", e);
154         } finally {
155             LoggingUtils.setTimeContext(startTime, new Date());
156             metricsLogger.info("createNewDeployment complete");
157         }
158     }
159
160     /***
161      * Returns status URL for deleteExistingDeployment operation.
162      *
163      * @param deploymentId
164      *        The deployment ID
165      * @param serviceTypeId
166      *        The service Type ID
167      * @return The status URL
168      */
169     public String deleteExistingDeployment(String deploymentId, String serviceTypeId) {
170         Date startTime = new Date();
171         LoggingUtils.setTargetContext("DCAE", "deleteExistingDeployment");
172         try {
173             String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}";
174             logger.info("Dcae api Body String - " + apiBodyString);
175             String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;
176             String statusUrl = getDcaeResponse(url, "DELETE", apiBodyString, "application/json", DCAE_LINK_FIELD,
177                 DCAE_STATUS_FIELD);
178             LoggingUtils.setResponseContext("0", "Delete existing deployment success", this.getClass().getName());
179             return statusUrl;
180
181         } catch (Exception e) {
182             LoggingUtils.setResponseContext("900", "Delete existing deployment failed", this.getClass().getName());
183             LoggingUtils.setErrorContext("900", "Delete existing deployment error");
184             logger.error("Exception occurred during deleteExistingDeployment Operation with DCAE", e);
185             throw new DcaeDeploymentException("Exception occurred during deleteExistingDeployment Operation with DCAE",
186                 e);
187         } finally {
188             LoggingUtils.setTimeContext(startTime, new Date());
189             metricsLogger.info("deleteExistingDeployment complete");
190         }
191     }
192
193     private String getDcaeResponse(String url, String requestMethod, String payload, String contentType, String node,
194         String nodeAttr) throws IOException, ParseException {
195         Date startTime = new Date();
196         try {
197             String responseStr = dcaeHttpConnectionManager.doHttpRequest(url, requestMethod, payload, contentType, "DCAE", null, null);
198             JSONObject jsonObj = parseResponse(responseStr);
199             JSONObject linksObj = (JSONObject) jsonObj.get(node);
200             String statusUrl = (String) linksObj.get(nodeAttr);
201             logger.info(STATUS_URL_LOG + statusUrl);
202             return statusUrl;
203         } catch (IOException | ParseException e) {
204             logger.error("Exception occurred getting response from DCAE", e);
205             throw e;
206         } finally {
207             LoggingUtils.setTimeContext(startTime, new Date());
208             metricsLogger.info("getDcaeResponse complete");
209         }
210     }
211
212     private JSONObject parseResponse(String responseStr) throws ParseException {
213         JSONParser parser = new JSONParser();
214         return (JSONObject) parser.parse(responseStr);
215     }
216 }