Fix DCAE connection issue
[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 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.\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 \r
30 import java.io.IOException;\r
31 import java.security.GeneralSecurityException;\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.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.prop.Global;\r
44 import org.onap.clamp.clds.model.prop.ModelProperties;\r
45 import org.onap.clamp.clds.model.refprop.RefProp;\r
46 import org.onap.clamp.clds.util.LoggingUtils;\r
47 import org.springframework.beans.factory.annotation.Autowired;\r
48 \r
49 /**\r
50  * \r
51  * This class implements the communication with DCAE for the service inventory.\r
52  *\r
53  * \r
54  * \r
55  */\r
56 public class DcaeInventoryServices {\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     @Autowired\r
61     private RefProp                   refProp;\r
62     @Autowired\r
63     private CldsDao                   cldsDao;\r
64 \r
65     /**\r
66      * \r
67      * Set the event inventory.\r
68      * \r
69      * @param cldsModel\r
70      *            The CldsModel\r
71      * @param userId\r
72      *            The user ID\r
73      * @throws GeneralSecurityException\r
74      *             In case of issue when decryting the DCAE password\r
75      * @throws ParseException\r
76      *             In case of DCAE Json parse exception\r
77      */\r
78     public void setEventInventory(CldsModel cldsModel, String userId) throws GeneralSecurityException, ParseException {\r
79         String artifactName = cldsModel.getControlName();\r
80         DcaeEvent dcaeEvent = new DcaeEvent();\r
81         String isDcaeInfoAvailable = null;\r
82         Date startTime = new Date();\r
83         LoggingUtils.setTargetContext("DCAE", "setEventInventory");\r
84         if (artifactName != null) {\r
85             artifactName = artifactName + ".yml";\r
86         }\r
87         try {\r
88             /*\r
89              * \r
90              * Below are the properties required for calling the dcae inventory\r
91              * \r
92              * url call\r
93              * \r
94              */\r
95             ModelProperties prop = new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), null, false,\r
96                     "{}", cldsModel.getPropText());\r
97             Global global = prop.getGlobal();\r
98             String invariantServiceUuid = global.getService();\r
99             List<String> resourceUuidList = global.getResourceVf();\r
100             String resourceUuid = "";\r
101             if (resourceUuidList != null && !resourceUuidList.isEmpty()) {\r
102                 resourceUuid = resourceUuidList.get(0);\r
103             }\r
104             /* Invemtory service url is called in this method */\r
105             isDcaeInfoAvailable = getDcaeInformation(artifactName, invariantServiceUuid, resourceUuid);\r
106             /* set dcae events */\r
107             dcaeEvent.setArtifactName(artifactName);\r
108             dcaeEvent.setEvent(DcaeEvent.EVENT_DISTRIBUTION);\r
109         } catch (JsonProcessingException e) {\r
110             logger.error("Error during JSON decoding", e);\r
111         } catch (IOException ex) {\r
112             logger.error("Error during DCAE communication", ex);\r
113         } finally {\r
114             LoggingUtils.setTimeContext(startTime, new Date());\r
115             metricsLogger.info("setEventInventory complete");\r
116         }\r
117         /* Null whether the DCAE has items lenght or not */\r
118         if (isDcaeInfoAvailable != null) {\r
119             /* Inserting Event in to DB */\r
120             logger.info(isDcaeInfoAvailable);\r
121             JSONParser parser = new JSONParser();\r
122             Object obj0 = parser.parse(isDcaeInfoAvailable);\r
123             JSONObject jsonObj = (JSONObject) obj0;\r
124             String oldTypeId = cldsModel.getTypeId();\r
125             String newTypeId = "";\r
126             if (jsonObj.get("typeId") != null) {\r
127                 newTypeId = jsonObj.get("typeId").toString();\r
128                 cldsModel.setTypeId(jsonObj.get("typeId").toString());\r
129             }\r
130             // cldsModel.setTypeName(cldsModel.getControlName().toString()+".yml");\r
131             if (jsonObj.get("typeName") != null) {\r
132                 cldsModel.setTypeName(jsonObj.get("typeName").toString());\r
133             }\r
134             if (oldTypeId == null || !oldTypeId.equalsIgnoreCase(newTypeId)) {\r
135                 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userId, dcaeEvent.getCldsActionCd(),\r
136                         CldsEvent.ACTION_STATE_RECEIVED, null);\r
137             }\r
138             cldsModel.save(cldsDao, userId);\r
139         } else {\r
140             logger.info(cldsModel.getName() + " Model is not present in Dcae Inventory Service.");\r
141         }\r
142     }\r
143 \r
144     /**\r
145      * DO a query to DCAE to get some Information.\r
146      * \r
147      * @param artifactName\r
148      *            The artifact Name\r
149      * @param serviceUuid\r
150      *            The service UUID\r
151      * @param resourceUuid\r
152      *            The resource UUID\r
153      * @return The DCAE inventory for the artifact\r
154      * @throws IOException\r
155      * @throws ParseException\r
156      * \r
157      */\r
158     public String getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid)\r
159             throws IOException, ParseException {\r
160         Date startTime = new Date();\r
161         LoggingUtils.setTargetContext("DCAE", "getDcaeInformation");\r
162         String queryString = "?asdcResourceId=" + resourceUuid + "&asdcServiceId=" + serviceUuid + "&typeName="\r
163                 + artifactName;\r
164         String fullUrl = refProp.getStringValue("DCAE_INVENTORY_URL") + "/dcae-service-types" + queryString;\r
165         logger.info("Dcae Inventory Service full url - " + fullUrl);\r
166         String daceInventoryResponse = null;\r
167         String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "GET", null, null);\r
168         JSONParser parser = new JSONParser();\r
169         Object obj0 = parser.parse(responseStr);\r
170         JSONObject jsonObj = (JSONObject) obj0;\r
171         Long totalCount = (Long) jsonObj.get("totalCount");\r
172         int numServices = totalCount.intValue();\r
173         if (numServices == 0) {\r
174             daceInventoryResponse = null;\r
175         } else if (numServices > 0) {\r
176             JSONArray itemsArray = (JSONArray) jsonObj.get("items");\r
177             JSONObject dcaeServiceType0 = (JSONObject) itemsArray.get(0);\r
178             daceInventoryResponse = dcaeServiceType0.toString();\r
179             logger.info(daceInventoryResponse);\r
180         }\r
181         LoggingUtils.setTimeContext(startTime, new Date());\r
182         metricsLogger.info("getDcaeInformation complete: number services returned=" + numServices);\r
183         return daceInventoryResponse;\r
184     }\r
185 }\r