Fix check style issues
[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 \r
30 import java.io.IOException;\r
31 import java.util.Date;\r
32 import java.util.List;\r
33 \r
34 import org.json.simple.JSONArray;\r
35 import org.json.simple.JSONObject;\r
36 import org.json.simple.parser.JSONParser;\r
37 import org.json.simple.parser.ParseException;\r
38 import org.onap.clamp.clds.config.ClampProperties;\r
39 import org.onap.clamp.clds.dao.CldsDao;\r
40 import org.onap.clamp.clds.model.CldsEvent;\r
41 import org.onap.clamp.clds.model.CldsModel;\r
42 import org.onap.clamp.clds.model.DcaeEvent;\r
43 import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;\r
44 import org.onap.clamp.clds.model.properties.Global;\r
45 import org.onap.clamp.clds.model.properties.ModelProperties;\r
46 import org.onap.clamp.clds.util.JsonUtils;\r
47 import org.onap.clamp.clds.util.LoggingUtils;\r
48 import org.springframework.beans.factory.annotation.Autowired;\r
49 import org.springframework.stereotype.Component;\r
50 \r
51 /**\r
52  * This class implements the communication with DCAE for the service inventory.\r
53  */\r
54 @Component\r
55 public class DcaeInventoryServices {\r
56 \r
57     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeInventoryServices.class);\r
58     protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();\r
59     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();\r
60     public static final String DCAE_INVENTORY_URL = "dcae.inventory.url";\r
61     public static final String DCAE_INVENTORY_RETRY_INTERVAL = "dcae.intentory.retry.interval";\r
62     public static final String DCAE_INVENTORY_RETRY_LIMIT = "dcae.intentory.retry.limit";\r
63     private final ClampProperties refProp;\r
64     private final CldsDao cldsDao;\r
65     private final DcaeHttpConnectionManager dcaeHttpConnectionManager;\r
66 \r
67     /**\r
68      * Constructor.\r
69      */\r
70     @Autowired\r
71     public DcaeInventoryServices(ClampProperties refProp, CldsDao cldsDao,\r
72         DcaeHttpConnectionManager dcaeHttpConnectionManager) {\r
73         this.refProp = refProp;\r
74         this.cldsDao = cldsDao;\r
75         this.dcaeHttpConnectionManager = dcaeHttpConnectionManager;\r
76     }\r
77 \r
78     /**\r
79      * Set the event inventory.\r
80      *\r
81      * @param cldsModel\r
82      *        The CldsModel\r
83      * @param userId\r
84      *        The user ID\r
85      * @throws ParseException\r
86      *         In case of DCAE Json parse exception\r
87      */\r
88     public void setEventInventory(CldsModel cldsModel, String userId) throws InterruptedException {\r
89         String artifactName = cldsModel.getControlName();\r
90         DcaeEvent dcaeEvent = new DcaeEvent();\r
91         DcaeInventoryResponse dcaeResponse = null;\r
92         Date startTime = new Date();\r
93         LoggingUtils.setTargetContext("DCAE", "setEventInventory");\r
94         if (artifactName != null) {\r
95             artifactName = artifactName + ".yml";\r
96         }\r
97         try {\r
98             // Below are the properties required for calling the dcae inventory\r
99             ModelProperties prop = new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), null, false,\r
100                 "{}", cldsModel.getPropText());\r
101             Global global = prop.getGlobal();\r
102             String invariantServiceUuid = global.getService();\r
103             List<String> resourceUuidList = global.getResourceVf();\r
104             String resourceUuid = "";\r
105             if (resourceUuidList != null && !resourceUuidList.isEmpty()) {\r
106                 resourceUuid = resourceUuidList.get(0);\r
107             }\r
108             /* Inventory service url is called in this method */\r
109             dcaeResponse = getDcaeInformation(artifactName, invariantServiceUuid, resourceUuid);\r
110             /* set dcae events */\r
111             dcaeEvent.setArtifactName(artifactName);\r
112             dcaeEvent.setEvent(DcaeEvent.EVENT_DISTRIBUTION);\r
113             LoggingUtils.setResponseContext("0", "Set inventory success", this.getClass().getName());\r
114         } catch (ParseException e) {\r
115             LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());\r
116             LoggingUtils.setErrorContext("900", "Set inventory error");\r
117             logger.error("Error during JSON decoding", e);\r
118         } catch (IOException ex) {\r
119             LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());\r
120             LoggingUtils.setErrorContext("900", "Set inventory error");\r
121             logger.error("Error during DCAE communication", ex);\r
122         } finally {\r
123             LoggingUtils.setTimeContext(startTime, new Date());\r
124             metricsLogger.info("setEventInventory complete");\r
125         }\r
126         this.analyzeAndSaveDcaeResponse(dcaeResponse, cldsModel, dcaeEvent, userId);\r
127     }\r
128 \r
129     private void analyzeAndSaveDcaeResponse(DcaeInventoryResponse dcaeResponse, CldsModel cldsModel,\r
130         DcaeEvent dcaeEvent, String userId) {\r
131         if (dcaeResponse != null) {\r
132             logger.info("Dcae Response for query on inventory: " + dcaeResponse);\r
133             String oldTypeId = cldsModel.getTypeId();\r
134             if (dcaeResponse.getTypeId() != null) {\r
135                 cldsModel.setTypeId(dcaeResponse.getTypeId());\r
136             }\r
137             if (dcaeResponse.getTypeName() != null) {\r
138                 cldsModel.setTypeName(dcaeResponse.getTypeName());\r
139             }\r
140             if (oldTypeId == null || !cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_DISTRIBUTE)\r
141                 || cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE)) {\r
142                 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userId, dcaeEvent.getCldsActionCd(),\r
143                     CldsEvent.ACTION_STATE_RECEIVED, null);\r
144             }\r
145             cldsModel.save(cldsDao, userId);\r
146         } else {\r
147             logger.info(cldsModel.getName() + " Model is not present in Dcae Inventory Service.");\r
148         }\r
149     }\r
150 \r
151     private int getTotalCountFromDcaeInventoryResponse(String responseStr) throws ParseException {\r
152         JSONParser parser = new JSONParser();\r
153         Object obj0 = parser.parse(responseStr);\r
154         JSONObject jsonObj = (JSONObject) obj0;\r
155         Long totalCount = (Long) jsonObj.get("totalCount");\r
156         return totalCount.intValue();\r
157     }\r
158 \r
159     private DcaeInventoryResponse getItemsFromDcaeInventoryResponse(String responseStr) throws ParseException {\r
160         JSONParser parser = new JSONParser();\r
161         Object obj0 = parser.parse(responseStr);\r
162         JSONObject jsonObj = (JSONObject) obj0;\r
163         JSONArray itemsArray = (JSONArray) jsonObj.get("items");\r
164         JSONObject dcaeServiceType0 = (JSONObject) itemsArray.get(0);\r
165         return JsonUtils.GSON.fromJson(dcaeServiceType0.toString(), 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         LoggingUtils.setTargetContext("DCAE", "getDcaeInformation");\r
186         String queryString = "?asdcResourceId=" + resourceUuid + "&asdcServiceId=" + serviceUuid + "&typeName="\r
187             + artifactName;\r
188         String fullUrl = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types" + queryString;\r
189         logger.info("Dcae Inventory Service full url - " + fullUrl);\r
190         DcaeInventoryResponse response = queryDcaeInventory(fullUrl);\r
191         LoggingUtils.setResponseContext("0", "Get Dcae Information success", this.getClass().getName());\r
192         Date startTime = new Date();\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