Add Direct call DCAE.
[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  * ===================================================================\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 import com.fasterxml.jackson.databind.ObjectMapper;\r
30 import com.fasterxml.jackson.databind.node.ObjectNode;\r
31 \r
32 import java.io.IOException;\r
33 import java.security.GeneralSecurityException;\r
34 import java.util.Date;\r
35 import java.util.List;\r
36 \r
37 import javax.ws.rs.BadRequestException;\r
38 \r
39 import org.apache.commons.codec.DecoderException;\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 public class DcaeInventoryServices {\r
58 \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     private static final String DCAE_INVENTORY_URL = "DCAE_INVENTORY_URL";\r
63     @Autowired\r
64     private RefProp refProp;\r
65     @Autowired\r
66     private CldsDao cldsDao;\r
67 \r
68     /**\r
69      * Set the event inventory.\r
70      * \r
71      * @param cldsModel\r
72      *            The CldsModel\r
73      * @param userId\r
74      *            The user ID\r
75      * @throws GeneralSecurityException\r
76      *             In case of issue when decryting the DCAE password\r
77      * @throws ParseException\r
78      *             In case of DCAE Json parse exception\r
79      * @throws DecoderException\r
80      *             In case of issues with HexString decoding\r
81      */\r
82     public void setEventInventory(CldsModel cldsModel, String userId)\r
83             throws GeneralSecurityException, ParseException, DecoderException {\r
84         String artifactName = cldsModel.getControlName();\r
85         DcaeEvent dcaeEvent = new DcaeEvent();\r
86         String isDcaeInfoAvailable = null;\r
87         Date startTime = new Date();\r
88         LoggingUtils.setTargetContext("DCAE", "setEventInventory");\r
89         if (artifactName != null) {\r
90             artifactName = artifactName + ".yml";\r
91         }\r
92         try {\r
93             // Below are the properties required for calling the dcae inventory\r
94             ModelProperties prop = new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), null, false,\r
95                     "{}", cldsModel.getPropText());\r
96             Global global = prop.getGlobal();\r
97             String invariantServiceUuid = global.getService();\r
98             List<String> resourceUuidList = global.getResourceVf();\r
99             String resourceUuid = "";\r
100             if (resourceUuidList != null && !resourceUuidList.isEmpty()) {\r
101                 resourceUuid = resourceUuidList.get(0);\r
102             }\r
103             /* Inventory service url is called in this method */\r
104             isDcaeInfoAvailable = getDcaeInformation(artifactName, invariantServiceUuid, resourceUuid);\r
105             /* set dcae events */\r
106             dcaeEvent.setArtifactName(artifactName);\r
107             dcaeEvent.setEvent(DcaeEvent.EVENT_DISTRIBUTION);\r
108             LoggingUtils.setResponseContext("0", "Set inventory success", this.getClass().getName());\r
109         } catch (JsonProcessingException e) {\r
110                 LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());\r
111                 LoggingUtils.setErrorContext("900", "Set inventory error");\r
112             logger.error("Error during JSON decoding", e);\r
113         } catch (IOException ex) {\r
114                 LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());\r
115                 LoggingUtils.setErrorContext("900", "Set inventory error");\r
116             logger.error("Error during DCAE communication", 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                     || 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     /**\r
150      * DO a query to DCAE to get some Information.\r
151      * \r
152      * @param artifactName\r
153      *            The artifact Name\r
154      * @param serviceUuid\r
155      *            The service UUID\r
156      * @param resourceUuid\r
157      *            The resource UUID\r
158      * @return The DCAE inventory for the artifact\r
159      * @throws IOException\r
160      *             In case of issues with the stream\r
161      * @throws ParseException\r
162      *             In case of issues with the Json parsing\r
163      */\r
164     public String getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid)\r
165             throws IOException, ParseException {\r
166         Date startTime = new Date();\r
167         LoggingUtils.setTargetContext("DCAE", "getDcaeInformation");\r
168         String queryString = "?asdcResourceId=" + resourceUuid + "&asdcServiceId=" + serviceUuid + "&typeName="\r
169                 + artifactName;\r
170         String fullUrl = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types" + queryString;\r
171         logger.info("Dcae Inventory Service full url - " + fullUrl);\r
172         String daceInventoryResponse = null;\r
173         String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "GET", null, null);\r
174         JSONParser parser = new JSONParser();\r
175         Object obj0 = parser.parse(responseStr);\r
176         JSONObject jsonObj = (JSONObject) obj0;\r
177         Long totalCount = (Long) jsonObj.get("totalCount");\r
178         int numServices = totalCount.intValue();\r
179         if (numServices == 0) {\r
180             daceInventoryResponse = null;\r
181         } else if (numServices > 0) {\r
182             JSONArray itemsArray = (JSONArray) jsonObj.get("items");\r
183             JSONObject dcaeServiceType0 = (JSONObject) itemsArray.get(0);\r
184             daceInventoryResponse = dcaeServiceType0.toString();\r
185             logger.info(daceInventoryResponse);\r
186         }\r
187         LoggingUtils.setResponseContext("0", "Get Dcae Information success", this.getClass().getName());\r
188         LoggingUtils.setTimeContext(startTime, new Date());\r
189         metricsLogger.info("getDcaeInformation complete: number services returned=" + numServices);\r
190         return daceInventoryResponse;\r
191     }\r
192 \r
193     /**\r
194      * Inserts a new DCAEServiceType or updates an existing instance. If the\r
195      * typeName is same second time(already exists) then the\r
196      * DCAEServiceTypeRequest is updated\r
197      * \r
198      * @param blueprintTemplate\r
199      *            blueprint content\r
200      * @param owner\r
201      *            owner of the data\r
202      * @param typeName\r
203      *            The type/artifact Name\r
204      * @param typeVersion\r
205      *            type version\r
206      * @param asdcServiceId\r
207      *            The service UUID\r
208      * @param asdcResourceId\r
209      *            The vf UUID\r
210      * @return The DCAE inventory type id\r
211      */\r
212     public String createUpdateDCAEServiceType(String blueprintTemplate, String owner, String typeName, int typeVersion,\r
213             String asdcServiceId, String asdcResourceId) {\r
214         Date startTime = new Date();\r
215         LoggingUtils.setTargetContext("DCAE", "createDCAEServiceType");\r
216         String typeId = null;\r
217         try {\r
218             ObjectMapper mapper = new ObjectMapper();\r
219             ObjectNode dcaeServiceTypeRequest = mapper.createObjectNode();\r
220             dcaeServiceTypeRequest.put("blueprintTemplate", blueprintTemplate);\r
221             dcaeServiceTypeRequest.put("owner", owner);\r
222             dcaeServiceTypeRequest.put("typeName", typeName);\r
223             dcaeServiceTypeRequest.put("typeVersion", typeVersion);\r
224             dcaeServiceTypeRequest.put("asdcServiceId", asdcServiceId);\r
225             dcaeServiceTypeRequest.put("asdcResourceId", asdcResourceId);\r
226             String apiBodyString = dcaeServiceTypeRequest.toString();\r
227             logger.info("Dcae api Body String - " + apiBodyString);\r
228             String url = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types";\r
229             String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "POST", apiBodyString,\r
230                     "application/json");\r
231             // If the DCAEServiceTypeRequest is created successfully it will\r
232             // return a json object responce containing a node for newly created\r
233             // "typeId"\r
234             // The newly generated DCAEServiceTypeRequest can then be accessed\r
235             // via URL: https://<DCAE_INVENTORY_URL>/dcae-service-types/<typeId>\r
236             JSONParser parser = new JSONParser();\r
237             Object obj0 = parser.parse(responseStr);\r
238             JSONObject jsonObj = (JSONObject) obj0;\r
239             typeId = (String) jsonObj.get("typeId"); // need to save this\r
240                                                             // as\r
241                                                             // service_type_id\r
242                                                             // in model table\r
243         } catch (IOException | ParseException e) {\r
244             logger.error("Exception occurred during createupdateDCAEServiceType Operation with DCAE", e);\r
245             throw new BadRequestException("Exception occurred during createupdateDCAEServiceType Operation with DCAE",\r
246                     e);\r
247         } finally {\r
248                 if(typeId != null) {\r
249                         LoggingUtils.setResponseContext("0", "Create update DCAE ServiceType success", this.getClass().getName());\r
250                 } else {\r
251                         LoggingUtils.setResponseContext("900", "Create update DCAE ServiceType failed", this.getClass().getName());\r
252                 LoggingUtils.setErrorContext("900", "Create update DCAE ServiceType error");\r
253                 }\r
254             LoggingUtils.setTimeContext(startTime, new Date());\r
255             metricsLogger.info("createupdateDCAEServiceType complete");\r
256         }\r
257         return typeId;\r
258     }\r
259 }\r