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