Remove useless exception
[clamp.git] / src / main / java / org / onap / clamp / clds / client / DcaeInventoryServices.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.core.JsonProcessingException;\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 import java.util.List;\r
34 \r
35 import javax.ws.rs.BadRequestException;\r
36 \r
37 import org.json.simple.JSONArray;\r
38 import org.json.simple.JSONObject;\r
39 import org.json.simple.parser.JSONParser;\r
40 import org.json.simple.parser.ParseException;\r
41 import org.onap.clamp.clds.config.ClampProperties;\r
42 import org.onap.clamp.clds.dao.CldsDao;\r
43 import org.onap.clamp.clds.model.CldsEvent;\r
44 import org.onap.clamp.clds.model.CldsModel;\r
45 import org.onap.clamp.clds.model.DcaeEvent;\r
46 import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;\r
47 import org.onap.clamp.clds.model.properties.Global;\r
48 import org.onap.clamp.clds.model.properties.ModelProperties;\r
49 import org.onap.clamp.clds.util.JacksonUtils;\r
50 import org.onap.clamp.clds.util.LoggingUtils;\r
51 import org.springframework.beans.factory.annotation.Autowired;\r
52 import org.springframework.stereotype.Component;\r
53 \r
54 /**\r
55  * This class implements the communication with DCAE for the service inventory.\r
56  */\r
57 @Component\r
58 public class DcaeInventoryServices {\r
59 \r
60     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeInventoryServices.class);\r
61     protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();\r
62     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();\r
63     public static final String DCAE_INVENTORY_URL = "dcae.inventory.url";\r
64     public static final String DCAE_INVENTORY_RETRY_INTERVAL = "dcae.intentory.retry.interval";\r
65     public static final String DCAE_INVENTORY_RETRY_LIMIT = "dcae.intentory.retry.limit";\r
66     public static final String DCAE_TYPE_NAME = "typeName";\r
67     public static final String DCAE_TYPE_ID = "typeId";\r
68     @Autowired\r
69     private ClampProperties refProp;\r
70     @Autowired\r
71     private CldsDao cldsDao;\r
72 \r
73     /**\r
74      * Set the event inventory.\r
75      * \r
76      * @param cldsModel\r
77      *            The CldsModel\r
78      * @param userId\r
79      *            The user ID\r
80      * @throws ParseException\r
81      *             In case of DCAE Json parse exception\r
82      */\r
83     public void setEventInventory(CldsModel cldsModel, String userId) throws ParseException, InterruptedException {\r
84         String artifactName = cldsModel.getControlName();\r
85         DcaeEvent dcaeEvent = new DcaeEvent();\r
86         DcaeInventoryResponse dcaeResponse = null;\r
87         Date startTime = new Date();\r
88         LoggingUtils.setTargetContext("DCAE", "setEventInventory");\r
89         if (artifactName != null) {\r
90             artifactName = artifactName + ".yml";\r
91         }\r
92         try {\r
93             // Below are the properties required for calling the dcae inventory\r
94             ModelProperties prop = new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), null, false,\r
95                     "{}", cldsModel.getPropText());\r
96             Global global = prop.getGlobal();\r
97             String invariantServiceUuid = global.getService();\r
98             List<String> resourceUuidList = global.getResourceVf();\r
99             String resourceUuid = "";\r
100             if (resourceUuidList != null && !resourceUuidList.isEmpty()) {\r
101                 resourceUuid = resourceUuidList.get(0);\r
102             }\r
103             /* Inventory service url is called in this method */\r
104             dcaeResponse = getDcaeInformation(artifactName, invariantServiceUuid, resourceUuid);\r
105             /* set dcae events */\r
106             dcaeEvent.setArtifactName(artifactName);\r
107             dcaeEvent.setEvent(DcaeEvent.EVENT_DISTRIBUTION);\r
108             LoggingUtils.setResponseContext("0", "Set inventory success", this.getClass().getName());\r
109         } catch (JsonProcessingException e) {\r
110             LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());\r
111             LoggingUtils.setErrorContext("900", "Set inventory error");\r
112             logger.error("Error during JSON decoding", e);\r
113         } catch (IOException ex) {\r
114             LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());\r
115             LoggingUtils.setErrorContext("900", "Set inventory error");\r
116             logger.error("Error during DCAE communication", ex);\r
117         } finally {\r
118             LoggingUtils.setTimeContext(startTime, new Date());\r
119             metricsLogger.info("setEventInventory complete");\r
120         }\r
121         this.analyzeAndSaveDcaeResponse(dcaeResponse, cldsModel, dcaeEvent, userId);\r
122     }\r
123 \r
124     private void analyzeAndSaveDcaeResponse(DcaeInventoryResponse dcaeResponse, CldsModel cldsModel,\r
125             DcaeEvent dcaeEvent, String userId) {\r
126         if (dcaeResponse != null) {\r
127             logger.info("Dcae Response for query on inventory: " + dcaeResponse);\r
128             String oldTypeId = cldsModel.getTypeId();\r
129             String newTypeId = "";\r
130             if (dcaeResponse.getTypeId() != null) {\r
131                 newTypeId = dcaeResponse.getTypeId();\r
132                 cldsModel.setTypeId(dcaeResponse.getTypeId());\r
133             }\r
134             if (dcaeResponse.getTypeName() != null) {\r
135                 cldsModel.setTypeName(dcaeResponse.getTypeName());\r
136             }\r
137             if (oldTypeId == null || !oldTypeId.equalsIgnoreCase(newTypeId)\r
138                     || cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE)) {\r
139                 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userId, dcaeEvent.getCldsActionCd(),\r
140                         CldsEvent.ACTION_STATE_RECEIVED, null);\r
141             }\r
142             cldsModel.save(cldsDao, userId);\r
143         } else {\r
144             logger.info(cldsModel.getName() + " Model is not present in Dcae Inventory Service.");\r
145         }\r
146     }\r
147 \r
148     /**\r
149      * DO a query to DCAE to get some Information.\r
150      * \r
151      * @param artifactName\r
152      *            The artifact Name\r
153      * @param serviceUuid\r
154      *            The service UUID\r
155      * @param resourceUuid\r
156      *            The resource UUID\r
157      * @return The DCAE inventory for the artifact in DcaeInventoryResponse\r
158      * @throws IOException\r
159      *             In case of issues with the stream\r
160      * @throws ParseException\r
161      *             In case of issues with the Json parsing\r
162      */\r
163     public DcaeInventoryResponse getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid)\r
164             throws IOException, ParseException, InterruptedException {\r
165         Date startTime = new Date();\r
166         LoggingUtils.setTargetContext("DCAE", "getDcaeInformation");\r
167         String queryString = "?asdcResourceId=" + resourceUuid + "&asdcServiceId=" + serviceUuid + "&typeName="\r
168                 + artifactName;\r
169         String fullUrl = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types" + queryString;\r
170         logger.info("Dcae Inventory Service full url - " + fullUrl);\r
171         String dcaeInventoryResponse = null;\r
172         String responseStr = queryDCAEInventory(fullUrl);\r
173         JSONParser parser = new JSONParser();\r
174         Object obj0 = parser.parse(responseStr);\r
175         JSONObject jsonObj = (JSONObject) obj0;\r
176         Long totalCount = (Long) jsonObj.get("totalCount");\r
177         int numServices = totalCount.intValue();\r
178         if (numServices > 0) {\r
179             JSONArray itemsArray = (JSONArray) jsonObj.get("items");\r
180             JSONObject dcaeServiceType0 = (JSONObject) itemsArray.get(0);\r
181             dcaeInventoryResponse = dcaeServiceType0.toString();\r
182             logger.info("getDcaeInformation, answer from DCAE inventory:" + dcaeInventoryResponse);\r
183         }\r
184         LoggingUtils.setResponseContext("0", "Get Dcae Information success", this.getClass().getName());\r
185         LoggingUtils.setTimeContext(startTime, new Date());\r
186         metricsLogger.info("getDcaeInformation complete: number services returned=" + numServices);\r
187         return JacksonUtils.getObjectMapperInstance().readValue(dcaeInventoryResponse, DcaeInventoryResponse.class);\r
188     }\r
189 \r
190     private String queryDCAEInventory(String fullUrl) throws IOException, InterruptedException {\r
191         int retryInterval = 0;\r
192         int retryLimit = 1;\r
193         if (refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT) != null) {\r
194             retryLimit = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT));\r
195         }\r
196         if (refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL) != null) {\r
197             retryInterval = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL));\r
198         }\r
199         int i = 0;\r
200         while (i < retryLimit) {\r
201             i++;\r
202             try {\r
203                 return DcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "GET", null, null);\r
204             } catch (BadRequestException e) {\r
205                 if (i == retryLimit) {\r
206                     // reach the retry limit, but still failed to connect to\r
207                     // DCAE\r
208                     throw e;\r
209                 } else {\r
210                     // wait for a while and try to connect to DCAE again\r
211                     Thread.sleep(retryInterval);\r
212                 }\r
213             }\r
214         }\r
215         // normally it should not go to this branch. It should either return the\r
216         // DCAE query result, or throw exception\r
217         return null;\r
218     }\r
219 \r
220     /**\r
221      * Inserts a new DCAEServiceType or updates an existing instance. If the\r
222      * typeName is same second time(already exists) then the\r
223      * DCAEServiceTypeRequest is updated\r
224      * \r
225      * @param blueprintTemplate\r
226      *            blueprint content\r
227      * @param owner\r
228      *            owner of the data\r
229      * @param typeName\r
230      *            The type/artifact Name\r
231      * @param typeVersion\r
232      *            type version\r
233      * @param asdcServiceId\r
234      *            The service UUID\r
235      * @param asdcResourceId\r
236      *            The vf UUID\r
237      * @return The DCAE inventory type id\r
238      */\r
239     public String createupdateDCAEServiceType(String blueprintTemplate, String owner, String typeName, int typeVersion,\r
240             String asdcServiceId, String asdcResourceId) {\r
241         Date startTime = new Date();\r
242         LoggingUtils.setTargetContext("DCAE", "createDCAEServiceType");\r
243         String typeId = null;\r
244         try {\r
245             ObjectNode dcaeServiceTypeRequest = JacksonUtils.getObjectMapperInstance().createObjectNode();\r
246             dcaeServiceTypeRequest.put("blueprintTemplate", blueprintTemplate);\r
247             dcaeServiceTypeRequest.put("owner", owner);\r
248             dcaeServiceTypeRequest.put("typeName", typeName);\r
249             dcaeServiceTypeRequest.put("typeVersion", typeVersion);\r
250             dcaeServiceTypeRequest.put("asdcServiceId", asdcServiceId);\r
251             dcaeServiceTypeRequest.put("asdcResourceId", asdcResourceId);\r
252             String apiBodyString = dcaeServiceTypeRequest.toString();\r
253             logger.info("Dcae api Body String - " + apiBodyString);\r
254             String url = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types";\r
255             String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "POST", apiBodyString,\r
256                     "application/json");\r
257             // If the DCAEServiceTypeRequest is created successfully it will\r
258             // return a json object responce containing a node for newly created\r
259             // "typeId"\r
260             // The newly generated DCAEServiceTypeRequest can then be accessed\r
261             // via URL: https://<DCAE_INVENTORY_URL>/dcae-service-types/<typeId>\r
262             JSONParser parser = new JSONParser();\r
263             Object obj0 = parser.parse(responseStr);\r
264             JSONObject jsonObj = (JSONObject) obj0;\r
265             typeId = (String) jsonObj.get("typeId"); // need to save this\r
266                                                      // as\r
267                                                      // service_type_id\r
268                                                      // in model table\r
269         } catch (IOException | ParseException e) {\r
270             logger.error("Exception occurred during createupdateDCAEServiceType Operation with DCAE", e);\r
271             throw new BadRequestException("Exception occurred during createupdateDCAEServiceType Operation with DCAE",\r
272                     e);\r
273         } finally {\r
274             if (typeId != null) {\r
275                 LoggingUtils.setResponseContext("0", "Create update DCAE ServiceType success",\r
276                         this.getClass().getName());\r
277             } else {\r
278                 LoggingUtils.setResponseContext("900", "Create update DCAE ServiceType failed",\r
279                         this.getClass().getName());\r
280                 LoggingUtils.setErrorContext("900", "Create update DCAE ServiceType error");\r
281             }\r
282             LoggingUtils.setTimeContext(startTime, new Date());\r
283             metricsLogger.info("createupdateDCAEServiceType complete");\r
284         }\r
285         return typeId;\r
286     }\r
287 }\r