Cleanup sonar bugs and security hotspot
[policy/models.git] / models-interactions / model-impl / aai / src / main / java / org / onap / policy / aai / AaiManager.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * aai
4  * ================================================================================
5  * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 Nordix Foundation.
7  * Modifications Copyright (C) 2019 Samsung Electronics Co., Ltd.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.aai;
24
25 import java.io.UnsupportedEncodingException;
26 import java.net.URLEncoder;
27 import java.nio.charset.StandardCharsets;
28 import java.util.HashMap;
29 import java.util.Map;
30 import java.util.UUID;
31 import java.util.stream.Collectors;
32
33 import org.json.JSONArray;
34 import org.json.JSONObject;
35 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
36 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
37 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
38 import org.onap.policy.common.utils.coder.CoderException;
39 import org.onap.policy.common.utils.coder.StandardCoder;
40 import org.onap.policy.rest.RestManager;
41 import org.onap.policy.rest.RestManager.Pair;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * This class handles communication towards and responses from A&AI for this module.
47  */
48 public final class AaiManager {
49
50     // TODO remove this class
51
52     /** The Constant logger. */
53     private static final Logger logger = LoggerFactory.getLogger(AaiManager.class);
54
55     private static final String APPLICATION_JSON = "application/json";
56
57     private static final StandardCoder CODER = new StandardCoder();
58
59     // The REST manager used for processing REST calls for this AAI manager
60     private final RestManager restManager;
61
62     /** custom query and other AAI resource URLs. */
63     private static final String CQ_URL = "/aai/v16/query?format=resource";
64     private static final String TENANT_URL = "/aai/v16/search/nodes-query?"
65                     + "search-node-type=vserver&filter=vserver-name:EQUALS:";
66     private static final String PREFIX = "/aai/v16";
67     private static final String PNF_URL = PREFIX + "/network/pnfs/pnf/";
68     private static final String AAI_DEPTH_SUFFIX = "?depth=0";
69
70     /**
71      * Constructor, create the AAI manager with the specified REST manager.
72      *
73      * @param restManager the rest manager to use for REST calls
74      */
75     public AaiManager(final RestManager restManager) {
76         this.restManager = restManager;
77     }
78
79     /**
80      * Creates the custom query payload from a tenant query response.
81      *
82      * @param getResponse response from the tenant query
83      * @return String Payload
84      */
85     private String createCustomQueryPayload(String getResponse) {
86
87         if (getResponse == null) {
88             return null;
89         } else {
90             JSONObject responseObj = new JSONObject(getResponse);
91             JSONArray resultsArray;
92             if (responseObj.has("result-data")) {
93                 resultsArray = (JSONArray) responseObj.get("result-data");
94             } else {
95                 return null;
96             }
97             String resourceLink = resultsArray.getJSONObject(0).getString("resource-link");
98             String start = resourceLink.replace(PREFIX, "");
99             String query = "query/closed-loop";
100             JSONObject payload = new JSONObject();
101             payload.put("start", start);
102             payload.put("query", query);
103             return payload.toString();
104
105         }
106     }
107
108     /**
109      * This method is used to get the information for custom query.
110      *
111      * @param url url of the get method
112      * @param username Aai username
113      * @param password Aai password
114      * @param requestId request ID
115      * @param vserver Id of the vserver
116      * @return String
117      */
118     private String getCustomQueryRequestPayload(String url, String username, String password, UUID requestId,
119                     String vserver) {
120
121         String urlGet = url + TENANT_URL;
122
123         String getResponse = getStringQuery(urlGet, username, password, requestId, vserver);
124         return createCustomQueryPayload(getResponse);
125     }
126
127     /**
128      * Calls Aai and returns a custom query response for a vserver.
129      *
130      * @param url Aai url
131      * @param username Aai Username
132      * @param password Aai Password
133      * @param requestId request ID
134      * @param vserver Vserver
135      * @return AaiCqResponse response from Aai for custom query
136      */
137     public AaiCqResponse getCustomQueryResponse(String url, String username, String password, UUID requestId,
138                     String vserver) {
139
140         final Map<String, String> headers = createHeaders(requestId);
141
142         logger.debug("RestManager.put before");
143         String requestJson = getCustomQueryRequestPayload(url, username, password, requestId, vserver);
144         NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, url, requestJson);
145
146         url = url + CQ_URL;
147
148         Pair<Integer, String> httpDetails = this.restManager.put(url, username, password, headers, APPLICATION_JSON,
149                         requestJson);
150         logger.debug("RestManager.put after");
151
152         if (httpDetails == null) {
153             NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "AAI POST Null Response");
154             logger.debug("AAI POST Null Response to {}", url);
155             return null;
156         }
157
158         int httpResponseCode = httpDetails.first;
159
160         NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "Response code: " + httpResponseCode);
161         NetLoggerUtil.getNetworkLogger().debug(httpDetails.second);
162
163         logger.debug(url);
164         logger.debug("{}", httpResponseCode);
165         logger.debug(httpDetails.second);
166
167         if (httpDetails.second != null) {
168             return new AaiCqResponse(httpDetails.second);
169         }
170         return null;
171     }
172
173     /**
174      * Returns the string response of a get query.
175      *
176      * @param url Aai URL
177      * @param username Aai Username
178      * @param password Aai Password
179      * @param requestId AaiRequestId
180      * @param key Aai Key
181      * @return String returns the string from the get query
182      */
183     private String getStringQuery(final String url, final String username, final String password, final UUID requestId,
184                     final String key) {
185
186         Map<String, String> headers = createHeaders(requestId);
187
188         String urlGet = url + key;
189
190         int attemptsLeft = 3;
191
192         while (attemptsLeft-- > 0) {
193             NetLoggerUtil.getNetworkLogger().info("[OUT|{}|{}|]", CommInfrastructure.REST, urlGet);
194             Pair<Integer, String> httpDetailsGet = restManager.get(urlGet, username, password, headers);
195             if (httpDetailsGet == null) {
196                 NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "AAI POST Null Response");
197                 logger.debug("AAI GET Null Response to {}", urlGet);
198                 return null;
199             }
200
201             int httpResponseCode = httpDetailsGet.first;
202
203             NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "Response code: " + httpResponseCode);
204             NetLoggerUtil.getNetworkLogger().debug(httpDetailsGet.second);
205
206             logger.debug(urlGet);
207             logger.debug("{}", httpResponseCode);
208             logger.debug(httpDetailsGet.second);
209
210             if (httpResponseCode == 200 && httpDetailsGet.second != null) {
211                 return httpDetailsGet.second;
212             }
213             try {
214                 Thread.sleep(1000);
215             } catch (InterruptedException e) {
216                 Thread.currentThread().interrupt();
217             }
218
219         }
220
221         return null;
222     }
223
224     /**
225      * Create the headers for the HTTP request.
226      *
227      * @param requestId the request ID to insert in the headers
228      * @return the HTTP headers
229      */
230     private Map<String, String> createHeaders(final UUID requestId) {
231         Map<String, String> headers = new HashMap<>();
232
233         headers.put("X-FromAppId", "POLICY");
234         headers.put("X-TransactionId", requestId.toString());
235         headers.put("Accept", APPLICATION_JSON);
236
237         return headers;
238     }
239
240     /**
241      * Perform a GET request for a particular PNF by PNF ID towards A&AI.
242      *
243      * @param url the A&AI URL
244      * @param username the user name for authentication
245      * @param password the password for authentication
246      * @param requestId the UUID of the request
247      * @param pnfName the AAI unique identifier for PNF object
248      * @return HashMap of PNF properties
249      */
250     public Map<String, String> getPnf(String url, String username, String password, UUID requestId, String pnfName) {
251         String urlGet;
252         try {
253             urlGet = url + PNF_URL;
254             pnfName = URLEncoder.encode(pnfName, StandardCharsets.UTF_8.toString()) + AAI_DEPTH_SUFFIX;
255         } catch (UnsupportedEncodingException e) {
256             logger.error("Failed to encode the pnfName: {} using UTF-8", pnfName, e);
257             return null;
258         }
259         String responseGet = getStringQuery(urlGet, username, password, requestId, pnfName);
260         if (responseGet == null) {
261             logger.error("Null response from AAI for the url: {}.", urlGet);
262             return null;
263         }
264         try {
265             @SuppressWarnings("unchecked")
266             Map<String, String> pnfParams = CODER.decode(responseGet, HashMap.class);
267             // Map to AAI node.attribute notation
268             return pnfParams.entrySet().stream()
269                             .collect(Collectors.toMap(e -> "pnf." + e.getKey(), Map.Entry::getValue));
270         } catch (CoderException e) {
271             logger.error("Failed to fetch PNF from AAI", e);
272             return null;
273         }
274     }
275 }