Rework the submit operation
[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.onap.clamp.util.HttpConnectionManager;\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 HttpConnectionManager httpConnectionManager;\r
67 \r
68     /**\r
69      * Constructor.\r
70      */\r
71     @Autowired\r
72     public DcaeInventoryServices(ClampProperties refProp, CldsDao cldsDao,\r
73                 HttpConnectionManager httpConnectionManager) {\r
74         this.refProp = refProp;\r
75         this.cldsDao = cldsDao;\r
76         this.httpConnectionManager = httpConnectionManager;\r
77     }\r
78 \r
79     /**\r
80      * Set the event inventory.\r
81      *\r
82      * @param cldsModel\r
83      *        The CldsModel\r
84      * @param userId\r
85      *        The user ID\r
86      * @throws ParseException\r
87      *         In case of DCAE Json parse exception\r
88      */\r
89     public void setEventInventory(CldsModel cldsModel, String userId) throws InterruptedException {\r
90         String artifactName = cldsModel.getControlName();\r
91         DcaeEvent dcaeEvent = new DcaeEvent();\r
92         DcaeInventoryResponse dcaeResponse = null;\r
93         Date startTime = new Date();\r
94         LoggingUtils.setTargetContext("DCAE", "setEventInventory");\r
95         if (artifactName != null) {\r
96             artifactName = artifactName + ".yml";\r
97         }\r
98         try {\r
99             // Below are the properties required for calling the dcae inventory\r
100             ModelProperties prop = new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), null, false,\r
101                 "{}", cldsModel.getPropText());\r
102             Global global = prop.getGlobal();\r
103             String invariantServiceUuid = global.getService();\r
104             List<String> resourceUuidList = global.getResourceVf();\r
105             String resourceUuid = "";\r
106             if (resourceUuidList != null && !resourceUuidList.isEmpty()) {\r
107                 resourceUuid = resourceUuidList.get(0);\r
108             }\r
109             /* Inventory service url is called in this method */\r
110             dcaeResponse = getDcaeInformation(artifactName, invariantServiceUuid, resourceUuid);\r
111             /* set dcae events */\r
112             dcaeEvent.setArtifactName(artifactName);\r
113             dcaeEvent.setEvent(DcaeEvent.EVENT_DISTRIBUTION);\r
114             LoggingUtils.setResponseContext("0", "Set inventory success", this.getClass().getName());\r
115         } catch (ParseException e) {\r
116             LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());\r
117             LoggingUtils.setErrorContext("900", "Set inventory error");\r
118             logger.error("Error during JSON decoding", e);\r
119         } catch (IOException ex) {\r
120             LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());\r
121             LoggingUtils.setErrorContext("900", "Set inventory error");\r
122             logger.error("Error during DCAE communication", ex);\r
123         } finally {\r
124             LoggingUtils.setTimeContext(startTime, new Date());\r
125             metricsLogger.info("setEventInventory complete");\r
126         }\r
127         this.analyzeAndSaveDcaeResponse(dcaeResponse, cldsModel, dcaeEvent, userId);\r
128     }\r
129 \r
130     private void analyzeAndSaveDcaeResponse(DcaeInventoryResponse dcaeResponse, CldsModel cldsModel,\r
131         DcaeEvent dcaeEvent, String userId) {\r
132         if (dcaeResponse != null) {\r
133             logger.info("Dcae Response for query on inventory: " + dcaeResponse);\r
134             String oldTypeId = cldsModel.getTypeId();\r
135             if (dcaeResponse.getTypeId() != null) {\r
136                 cldsModel.setTypeId(dcaeResponse.getTypeId());\r
137             }\r
138             if (dcaeResponse.getTypeName() != null) {\r
139                 cldsModel.setTypeName(dcaeResponse.getTypeName());\r
140             }\r
141             if (oldTypeId == null || !cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_DISTRIBUTE)\r
142                 || cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE)) {\r
143                 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userId, dcaeEvent.getCldsActionCd(),\r
144                     CldsEvent.ACTION_STATE_RECEIVED, null);\r
145             }\r
146             cldsModel.save(cldsDao, userId);\r
147         } else {\r
148             logger.info(cldsModel.getName() + " Model is not present in Dcae Inventory Service.");\r
149         }\r
150     }\r
151 \r
152     private int getTotalCountFromDcaeInventoryResponse(String responseStr) throws ParseException {\r
153         JSONParser parser = new JSONParser();\r
154         Object obj0 = parser.parse(responseStr);\r
155         JSONObject jsonObj = (JSONObject) obj0;\r
156         Long totalCount = (Long) jsonObj.get("totalCount");\r
157         return totalCount.intValue();\r
158     }\r
159 \r
160     private DcaeInventoryResponse getItemsFromDcaeInventoryResponse(String responseStr) throws ParseException {\r
161         JSONParser parser = new JSONParser();\r
162         Object obj0 = parser.parse(responseStr);\r
163         JSONObject jsonObj = (JSONObject) obj0;\r
164         JSONArray itemsArray = (JSONArray) jsonObj.get("items");\r
165         JSONObject dcaeServiceType0 = (JSONObject) itemsArray.get(0);\r
166         return JsonUtils.GSON.fromJson(dcaeServiceType0.toString(), DcaeInventoryResponse.class);\r
167     }\r
168 \r
169     /**\r
170      * DO a query to DCAE to get some Information.\r
171      *\r
172      * @param artifactName\r
173      *        The artifact Name\r
174      * @param serviceUuid\r
175      *        The service UUID\r
176      * @param resourceUuid\r
177      *        The resource UUID\r
178      * @return The DCAE inventory for the artifact in DcaeInventoryResponse\r
179      * @throws IOException\r
180      *         In case of issues with the stream\r
181      * @throws ParseException\r
182      *         In case of issues with the Json parsing\r
183      */\r
184     public DcaeInventoryResponse getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid)\r
185         throws IOException, ParseException, InterruptedException {\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         Date startTime = new Date();\r
194         LoggingUtils.setTimeContext(startTime, new Date());\r
195         return response;\r
196     }\r
197 \r
198     private DcaeInventoryResponse queryDcaeInventory(String fullUrl)\r
199         throws IOException, InterruptedException, ParseException {\r
200         int retryInterval = 0;\r
201         int retryLimit = 1;\r
202         if (refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT) != null) {\r
203             retryLimit = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT));\r
204         }\r
205         if (refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL) != null) {\r
206             retryInterval = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL));\r
207         }\r
208         for (int i = 0; i < retryLimit; i++) {\r
209             metricsLogger.info("Attempt n°" + i + " to contact DCAE inventory");\r
210             String response = httpConnectionManager.doGeneralHttpQuery(fullUrl, "GET", null, null, "DCAE", null, null);\r
211             int totalCount = getTotalCountFromDcaeInventoryResponse(response);\r
212             metricsLogger.info("getDcaeInformation complete: totalCount returned=" + totalCount);\r
213             if (totalCount > 0) {\r
214                 logger.info("getDcaeInformation, answer from DCAE inventory:" + response);\r
215                 return getItemsFromDcaeInventoryResponse(response);\r
216             }\r
217             logger.info(\r
218                 "Dcae inventory totalCount returned is 0, so waiting " + retryInterval + "ms before retrying ...");\r
219             // wait for a while and try to connect to DCAE again\r
220             Thread.sleep(retryInterval);\r
221         }\r
222         logger.warn("Dcae inventory totalCount returned is still 0, after " + retryLimit + " attempts, returning NULL");\r
223         return null;\r
224     }\r
225 }\r