8f80e07ca074294e363c8c5e8a560e5642efa288
[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.BufferedReader;\r
31 import java.io.IOException;\r
32 import java.io.InputStreamReader;\r
33 import java.net.HttpURLConnection;\r
34 import java.net.URL;\r
35 import java.util.Date;\r
36 import java.util.List;\r
37 \r
38 import javax.ws.rs.BadRequestException;\r
39 \r
40 import org.json.simple.JSONArray;\r
41 import org.json.simple.JSONObject;\r
42 import org.json.simple.parser.JSONParser;\r
43 import org.json.simple.parser.ParseException;\r
44 import org.onap.clamp.clds.dao.CldsDao;\r
45 import org.onap.clamp.clds.model.CldsEvent;\r
46 import org.onap.clamp.clds.model.CldsModel;\r
47 import org.onap.clamp.clds.model.DcaeEvent;\r
48 import org.onap.clamp.clds.model.prop.Global;\r
49 import org.onap.clamp.clds.model.prop.ModelProperties;\r
50 import org.onap.clamp.clds.model.refprop.RefProp;\r
51 import org.onap.clamp.clds.util.LoggingUtils;\r
52 import org.springframework.beans.factory.annotation.Autowired;\r
53 \r
54 /**\r
55  * This class implements the communication with DCAE for the service inventory.\r
56  *\r
57  */\r
58 public class DcaeInventoryServices {\r
59     protected static final EELFLogger logger        = EELFManager.getInstance().getLogger(DcaeInventoryServices.class);\r
60     protected static final EELFLogger auditLogger   = EELFManager.getInstance().getAuditLogger();\r
61     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();\r
62 \r
63     @Autowired\r
64     private RefProp                   refProp;\r
65 \r
66     @Autowired\r
67     private CldsDao                   cldsDao;\r
68 \r
69     @Autowired\r
70     private SdcCatalogServices        sdcCatalogServices;\r
71 \r
72     /**\r
73      * Set the event inventory.\r
74      * \r
75      * @param cldsModel\r
76      *            The CldsModel\r
77      * @param userId\r
78      *            The user ID\r
79      * @throws ParseException\r
80      *             In case of issues during the parsing of DCAE answer\r
81      */\r
82     public void setEventInventory(CldsModel cldsModel, String userId) throws ParseException {\r
83         String artifactName = cldsModel.getControlName();\r
84         DcaeEvent dcaeEvent = new DcaeEvent();\r
85         String isDcaeInfoAvailable = null;\r
86         Date startTime = new Date();\r
87         LoggingUtils.setTargetContext("DCAE", "setEventInventory");\r
88         if (artifactName != null) {\r
89             artifactName = artifactName + ".yml";\r
90         }\r
91         try {\r
92             /*\r
93              * Below are the properties required for calling the dcae inventory\r
94              * url call\r
95              */\r
96             ModelProperties prop = new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), null, false,\r
97                     "{}", cldsModel.getPropText());\r
98             Global global = prop.getGlobal();\r
99             String invariantServiceUuid = global.getService();\r
100             List<String> resourceUuidList = global.getResourceVf();\r
101             String serviceUuid = sdcCatalogServices.getServiceUuidFromServiceInvariantId(invariantServiceUuid);\r
102             String resourceUuid = "";\r
103             if (resourceUuidList != null && !resourceUuidList.isEmpty()) {\r
104                 resourceUuid = resourceUuidList.get(0);\r
105             }\r
106             /* Invemtory service url is called in this method */\r
107             isDcaeInfoAvailable = getDcaeInformation(artifactName, serviceUuid, resourceUuid);\r
108 \r
109             /* set dcae events */\r
110             dcaeEvent.setArtifactName(artifactName);\r
111             dcaeEvent.setEvent(DcaeEvent.EVENT_DISTRIBUTION);\r
112 \r
113         } catch (JsonProcessingException e) {\r
114             logger.error("Error during JSON decoding", e);\r
115         } catch (IOException ex) {\r
116             logger.error("Error during JSON decoding", ex);\r
117         } finally {\r
118             LoggingUtils.setTimeContext(startTime, new Date());\r
119             metricsLogger.info("setEventInventory complete");\r
120         }\r
121         /* Null whether the DCAE has items lenght or not */\r
122         if (isDcaeInfoAvailable != null) {\r
123             /* Inserting Event in to DB */\r
124             logger.info(isDcaeInfoAvailable);\r
125             JSONParser parser = new JSONParser();\r
126             Object obj0 = parser.parse(isDcaeInfoAvailable);\r
127             JSONObject jsonObj = (JSONObject) obj0;\r
128             String oldTypeId = cldsModel.getTypeId();\r
129             String newTypeId = "";\r
130             if (jsonObj.get("typeId") != null) {\r
131                 newTypeId = jsonObj.get("typeId").toString();\r
132                 cldsModel.setTypeId(jsonObj.get("typeId").toString());\r
133             }\r
134             // cldsModel.setTypeName(cldsModel.getControlName().toString()+".yml");\r
135             if (jsonObj.get("typeName") != null) {\r
136                 cldsModel.setTypeName(jsonObj.get("typeName").toString());\r
137             }\r
138             if (oldTypeId == null || !oldTypeId.equalsIgnoreCase(newTypeId)) {\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\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 String getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid)\r
164             throws IOException, ParseException {\r
165         Date startTime = new Date();\r
166         LoggingUtils.setTargetContext("DCAE", "getDcaeInformation");\r
167         String queryString = "?sdcResourceId=" + resourceUuid + "&sdcServiceId=" + serviceUuid + "&typeName="\r
168                 + artifactName;\r
169         String fullUrl = refProp.getStringValue("DCAE_INVENTORY_URL") + "/dcae-service-types" + queryString;\r
170 \r
171         logger.info("Dcae Inventory Service full url - " + fullUrl);\r
172         String daceInventoryResponse = null;\r
173         URL inventoryUrl = new URL(fullUrl);\r
174 \r
175         HttpURLConnection conn = (HttpURLConnection) inventoryUrl.openConnection();\r
176         conn.setRequestMethod("GET");\r
177         String reqid = LoggingUtils.getRequestId();\r
178         logger.info("reqid set to " + reqid);\r
179         conn.setRequestProperty("X-ECOMP-RequestID", reqid);\r
180 \r
181         boolean requestFailed = true;\r
182         int responseCode = conn.getResponseCode();\r
183         if (responseCode == 200) {\r
184             requestFailed = false;\r
185         }\r
186 \r
187         StringBuilder response = new StringBuilder();\r
188 \r
189         try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {\r
190             String inputLine = null;\r
191 \r
192             while ((inputLine = in.readLine()) != null) {\r
193                 response.append(inputLine);\r
194             }\r
195         }\r
196         String responseStr = response.toString();\r
197         if (responseStr != null) {\r
198             if (requestFailed) {\r
199                 logger.error("requestFailed - responseStr=" + response);\r
200                 throw new BadRequestException(responseStr);\r
201             }\r
202         }\r
203         String jsonResponseString = response.toString();\r
204         JSONParser parser = new JSONParser();\r
205         Object obj0 = parser.parse(jsonResponseString);\r
206 \r
207         JSONObject jsonObj = (JSONObject) obj0;\r
208 \r
209         Long totalCount = (Long) jsonObj.get("totalCount");\r
210 \r
211         int numServices = totalCount.intValue();\r
212         if (numServices == 0) {\r
213             daceInventoryResponse = null;\r
214         } else if (numServices > 0) {\r
215             JSONArray itemsArray = (JSONArray) jsonObj.get("items");\r
216             JSONObject dcaeServiceType0 = (JSONObject) itemsArray.get(0);\r
217             daceInventoryResponse = dcaeServiceType0.toString();\r
218             logger.info(daceInventoryResponse);\r
219         }\r
220         LoggingUtils.setTimeContext(startTime, new Date());\r
221         metricsLogger.info("getDcaeInformation complete: number services returned=" + numServices);\r
222         return daceInventoryResponse;\r
223     }\r
224 \r
225 }\r