Merge "Enhance readthedoc contents"
[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  * Modifications copyright (c) 2018 Nokia\r
21  * ===================================================================\r
22  *\r
23  */\r
24 \r
25 package org.onap.clamp.clds.client;\r
26 \r
27 import com.att.eelf.configuration.EELFLogger;\r
28 import com.att.eelf.configuration.EELFManager;\r
29 import com.fasterxml.jackson.core.JsonProcessingException;\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 org.json.simple.JSONArray;\r
36 import org.json.simple.JSONObject;\r
37 import org.json.simple.parser.JSONParser;\r
38 import org.json.simple.parser.ParseException;\r
39 import org.onap.clamp.clds.config.ClampProperties;\r
40 import org.onap.clamp.clds.dao.CldsDao;\r
41 import org.onap.clamp.clds.model.CldsEvent;\r
42 import org.onap.clamp.clds.model.CldsModel;\r
43 import org.onap.clamp.clds.model.DcaeEvent;\r
44 import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;\r
45 import org.onap.clamp.clds.model.properties.Global;\r
46 import org.onap.clamp.clds.model.properties.ModelProperties;\r
47 import org.onap.clamp.clds.util.JacksonUtils;\r
48 import org.onap.clamp.clds.util.LoggingUtils;\r
49 import org.springframework.beans.factory.annotation.Autowired;\r
50 import org.springframework.stereotype.Component;\r
51 \r
52 /**\r
53  * This class implements the communication with DCAE for the service inventory.\r
54  */\r
55 @Component\r
56 public class DcaeInventoryServices {\r
57 \r
58     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeInventoryServices.class);\r
59     protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();\r
60     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();\r
61     public static final String DCAE_INVENTORY_URL = "dcae.inventory.url";\r
62     public static final String DCAE_INVENTORY_RETRY_INTERVAL = "dcae.intentory.retry.interval";\r
63     public static final String DCAE_INVENTORY_RETRY_LIMIT = "dcae.intentory.retry.limit";\r
64     private final ClampProperties refProp;\r
65     private final CldsDao cldsDao;\r
66     private final DcaeHttpConnectionManager dcaeHttpConnectionManager;\r
67 \r
68     @Autowired\r
69     public DcaeInventoryServices(ClampProperties refProp, CldsDao cldsDao,\r
70         DcaeHttpConnectionManager dcaeHttpConnectionManager) {\r
71         this.refProp = refProp;\r
72         this.cldsDao = cldsDao;\r
73         this.dcaeHttpConnectionManager = dcaeHttpConnectionManager;\r
74     }\r
75 \r
76     /**\r
77      * Set the event inventory.\r
78      *\r
79      * @param cldsModel\r
80      *        The CldsModel\r
81      * @param userId\r
82      *        The user ID\r
83      * @throws ParseException\r
84      *         In case of DCAE Json parse exception\r
85      */\r
86     public void setEventInventory(CldsModel cldsModel, String userId) throws ParseException, InterruptedException {\r
87         String artifactName = cldsModel.getControlName();\r
88         DcaeEvent dcaeEvent = new DcaeEvent();\r
89         DcaeInventoryResponse dcaeResponse = null;\r
90         Date startTime = new Date();\r
91         LoggingUtils.setTargetContext("DCAE", "setEventInventory");\r
92         if (artifactName != null) {\r
93             artifactName = artifactName + ".yml";\r
94         }\r
95         try {\r
96             // Below are the properties required for calling the dcae inventory\r
97             ModelProperties prop = new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), null, false,\r
98                 "{}", cldsModel.getPropText());\r
99             Global global = prop.getGlobal();\r
100             String invariantServiceUuid = global.getService();\r
101             List<String> resourceUuidList = global.getResourceVf();\r
102             String resourceUuid = "";\r
103             if (resourceUuidList != null && !resourceUuidList.isEmpty()) {\r
104                 resourceUuid = resourceUuidList.get(0);\r
105             }\r
106             /* Inventory service url is called in this method */\r
107             dcaeResponse = getDcaeInformation(artifactName, invariantServiceUuid, resourceUuid);\r
108             /* set dcae events */\r
109             dcaeEvent.setArtifactName(artifactName);\r
110             dcaeEvent.setEvent(DcaeEvent.EVENT_DISTRIBUTION);\r
111             LoggingUtils.setResponseContext("0", "Set inventory success", this.getClass().getName());\r
112         } catch (JsonProcessingException e) {\r
113             LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());\r
114             LoggingUtils.setErrorContext("900", "Set inventory error");\r
115             logger.error("Error during JSON decoding", e);\r
116         } catch (IOException ex) {\r
117             LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());\r
118             LoggingUtils.setErrorContext("900", "Set inventory error");\r
119             logger.error("Error during DCAE communication", ex);\r
120         } finally {\r
121             LoggingUtils.setTimeContext(startTime, new Date());\r
122             metricsLogger.info("setEventInventory complete");\r
123         }\r
124         this.analyzeAndSaveDcaeResponse(dcaeResponse, cldsModel, dcaeEvent, userId);\r
125     }\r
126 \r
127     private void analyzeAndSaveDcaeResponse(DcaeInventoryResponse dcaeResponse, CldsModel cldsModel,\r
128         DcaeEvent dcaeEvent, String userId) {\r
129         if (dcaeResponse != null) {\r
130             logger.info("Dcae Response for query on inventory: " + dcaeResponse);\r
131             String oldTypeId = cldsModel.getTypeId();\r
132             if (dcaeResponse.getTypeId() != null) {\r
133                 cldsModel.setTypeId(dcaeResponse.getTypeId());\r
134             }\r
135             if (dcaeResponse.getTypeName() != null) {\r
136                 cldsModel.setTypeName(dcaeResponse.getTypeName());\r
137             }\r
138             if (oldTypeId == null || !cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_DISTRIBUTE)\r
139                 || cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE)) {\r
140                 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userId, dcaeEvent.getCldsActionCd(),\r
141                     CldsEvent.ACTION_STATE_RECEIVED, null);\r
142             }\r
143             cldsModel.save(cldsDao, userId);\r
144         } else {\r
145             logger.info(cldsModel.getName() + " Model is not present in Dcae Inventory Service.");\r
146         }\r
147     }\r
148 \r
149     private int getTotalCountFromDcaeInventoryResponse(String responseStr) throws ParseException {\r
150         JSONParser parser = new JSONParser();\r
151         Object obj0 = parser.parse(responseStr);\r
152         JSONObject jsonObj = (JSONObject) obj0;\r
153         Long totalCount = (Long) jsonObj.get("totalCount");\r
154         return totalCount.intValue();\r
155     }\r
156 \r
157     private DcaeInventoryResponse getItemsFromDcaeInventoryResponse(String responseStr)\r
158         throws ParseException, IOException {\r
159         JSONParser parser = new JSONParser();\r
160         Object obj0 = parser.parse(responseStr);\r
161         JSONObject jsonObj = (JSONObject) obj0;\r
162         JSONArray itemsArray = (JSONArray) jsonObj.get("items");\r
163         JSONObject dcaeServiceType0 = (JSONObject) itemsArray.get(0);\r
164         return JacksonUtils.getObjectMapperInstance().readValue(dcaeServiceType0.toString(),\r
165             DcaeInventoryResponse.class);\r
166     }\r
167 \r
168     /**\r
169      * DO a query to DCAE to get some Information.\r
170      *\r
171      * @param artifactName\r
172      *        The artifact Name\r
173      * @param serviceUuid\r
174      *        The service UUID\r
175      * @param resourceUuid\r
176      *        The resource UUID\r
177      * @return The DCAE inventory for the artifact in DcaeInventoryResponse\r
178      * @throws IOException\r
179      *         In case of issues with the stream\r
180      * @throws ParseException\r
181      *         In case of issues with the Json parsing\r
182      */\r
183     public DcaeInventoryResponse getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid)\r
184         throws IOException, ParseException, InterruptedException {\r
185         Date startTime = new Date();\r
186         LoggingUtils.setTargetContext("DCAE", "getDcaeInformation");\r
187         String queryString = "?asdcResourceId=" + resourceUuid + "&asdcServiceId=" + serviceUuid + "&typeName="\r
188             + artifactName;\r
189         String fullUrl = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types" + queryString;\r
190         logger.info("Dcae Inventory Service full url - " + fullUrl);\r
191         DcaeInventoryResponse response = queryDcaeInventory(fullUrl);\r
192         LoggingUtils.setResponseContext("0", "Get Dcae Information success", this.getClass().getName());\r
193         LoggingUtils.setTimeContext(startTime, new Date());\r
194         return response;\r
195     }\r
196 \r
197     private DcaeInventoryResponse queryDcaeInventory(String fullUrl)\r
198         throws IOException, InterruptedException, ParseException {\r
199         int retryInterval = 0;\r
200         int retryLimit = 1;\r
201         if (refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT) != null) {\r
202             retryLimit = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT));\r
203         }\r
204         if (refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL) != null) {\r
205             retryInterval = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL));\r
206         }\r
207         for (int i = 0; i < retryLimit; i++) {\r
208             metricsLogger.info("Attempt n°" + i + " to contact DCAE inventory");\r
209             String response = dcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "GET", null, null);\r
210             int totalCount = getTotalCountFromDcaeInventoryResponse(response);\r
211             metricsLogger.info("getDcaeInformation complete: totalCount returned=" + totalCount);\r
212             if (totalCount > 0) {\r
213                 logger.info("getDcaeInformation, answer from DCAE inventory:" + response);\r
214                 return getItemsFromDcaeInventoryResponse(response);\r
215             }\r
216             logger.info(\r
217                 "Dcae inventory totalCount returned is 0, so waiting " + retryInterval + "ms before retrying ...");\r
218             // wait for a while and try to connect to DCAE again\r
219             Thread.sleep(retryInterval);\r
220         }\r
221         logger.warn("Dcae inventory totalCount returned is still 0, after " + retryLimit + " attempts, returning NULL");\r
222         return null;\r
223     }\r
224 }\r