Supports new aai changes.
[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-2019 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 com.google.gson.JsonSyntaxException;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.UUID;
29 import org.json.JSONArray;
30 import org.json.JSONObject;
31 import org.onap.policy.aai.util.Serialization;
32 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
33 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
34 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
35 import org.onap.policy.rest.RestManager;
36 import org.onap.policy.rest.RestManager.Pair;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * This class handles communication towards and responses from A&AI for this module.
42  */
43 public final class AaiManager {
44
45     /** The Constant logger. */
46     private static final Logger logger = LoggerFactory.getLogger(AaiManager.class);
47
48     /** The rest manager. */
49     // The REST manager used for processing REST calls for this AAI manager
50     private final RestManager restManager;
51
52     /** custom query URLs. */
53     private static final String CQ_URL = "/aai/v16/query?format=resource";
54     private static final String TENANT_URL =
55             "/aai/v16/search/nodes-query?search-node-type=vserver&filter=vserver-name:EQUALS:";
56     private static final String PREFIX = "/aai/v16";
57
58
59     /**
60      * Constructor, create the AAI manager with the specified REST manager.
61      *
62      * @param restManager the rest manager to use for REST calls
63      */
64     public AaiManager(final RestManager restManager) {
65         this.restManager = restManager;
66     }
67
68     /**
69      * Creates the custom query payload from a tenant query response.
70      *
71      * @param getResponse response from the tenant query
72      * @return String Payload
73      */
74     private String createCustomQueryPayload(String getResponse) {
75
76         if (getResponse == null) {
77             return null;
78         } else {
79             JSONObject responseObj = new JSONObject(getResponse);
80             JSONArray resultsArray = new JSONArray();
81             if (responseObj.has("result-data")) {
82                 resultsArray = (JSONArray) responseObj.get("result-data");
83             } else {
84                 return null;
85             }
86             String resourceLink = resultsArray.getJSONObject(0).getString("resource-link");
87             String start = resourceLink.replace(PREFIX, "");
88             String query = "query/closed-loop";
89             JSONObject payload = new JSONObject();
90             payload.put("start", start);
91             payload.put("query", query);
92             return payload.toString();
93
94         }
95     }
96
97
98     /**
99      * This method is used to get the information for custom query.
100      *
101      * @param url url of the get method
102      * @param username Aai username
103      * @param password Aai password
104      * @param requestId request ID
105      * @param vserver Id of the vserver
106      * @return String
107      */
108     private String getCustomQueryRequestPayload(String url, String username, String password, UUID requestId,
109             String vserver) {
110
111         String urlGet = url + TENANT_URL;
112
113         String getResponse = getStringQuery(urlGet, username, password, requestId, vserver);
114         return createCustomQueryPayload(getResponse);
115     }
116
117
118
119     /**
120      * Calls Aai and returns a custom query response for a vserver.
121      *
122      * @param url Aai url
123      * @param username Aai Username
124      * @param password Aai Password
125      * @param requestId request ID
126      * @param vserver Vserver
127      * @return AaiCqResponse response from Aai for custom query
128      */
129     public AaiCqResponse getCustomQueryResponse(String url, String username, String password, UUID requestId,
130             String vserver) {
131
132         final Map<String, String> headers = createHeaders(requestId);
133
134         logger.debug("RestManager.put before");
135         String requestJson = getCustomQueryRequestPayload(url, username, password, requestId, vserver);
136         NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, url, requestJson);
137
138         url = url + CQ_URL;
139
140         Pair<Integer, String> httpDetails =
141                 this.restManager.put(url, username, password, headers, "application/json", requestJson);
142         logger.debug("RestManager.put after");
143
144         if (httpDetails == null) {
145             logger.info("AAI POST Null Response to {}", url);
146             return null;
147         }
148
149         int httpResponseCode = httpDetails.first;
150
151         logger.info(url);
152         logger.info("{}", httpResponseCode);
153         logger.info(httpDetails.second);
154
155         if (httpDetails.second != null) {
156             String resp = httpDetails.second;
157             return new AaiCqResponse(resp);
158         }
159         return null;
160     }
161
162
163
164     /**
165      * Returns the string response of a get query.
166      *
167      * @param url Aai URL
168      * @param username Aai Username
169      * @param password Aai Password
170      * @param requestId AaiRequestId
171      * @param key Aai Key
172      * @return String returns the string from the get query
173      */
174     private String getStringQuery(final String url, final String username, final String password, final UUID requestId,
175             final String key) {
176
177         Map<String, String> headers = createHeaders(requestId);
178
179         String urlGet = url + key;
180
181         int attemptsLeft = 3;
182
183         while (attemptsLeft-- > 0) {
184             NetLoggerUtil.getNetworkLogger().info("[OUT|{}|{}|]", CommInfrastructure.REST, urlGet);
185             Pair<Integer, String> httpDetailsGet = restManager.get(urlGet, username, password, headers);
186             if (httpDetailsGet == null) {
187                 logger.info("AAI GET Null Response to {}", urlGet);
188                 return null;
189             }
190
191             int httpResponseCode = httpDetailsGet.first;
192
193             logger.info(urlGet);
194             logger.info("{}", httpResponseCode);
195             logger.info(httpDetailsGet.second);
196
197             if (httpResponseCode == 200) {
198                 String responseGet = httpDetailsGet.second;
199                 if (responseGet != null) {
200                     return responseGet;
201                 }
202             }
203             try {
204                 Thread.sleep(1000);
205             } catch (InterruptedException e) {
206                 Thread.currentThread().interrupt();
207             }
208
209         }
210
211         return null;
212     }
213
214
215     /**
216      * Post a query to A&AI.
217      *
218      * @param url the A&AI URL
219      * @param username the user name for authentication
220      * @param password the password for authentication
221      * @param request the request to issue towards A&AI
222      * @param requestId the UUID of the request
223      * @return the response from A&AI
224      */
225     public AaiNqResponse postQuery(String url, String username, String password, AaiNqRequest request, UUID requestId) {
226
227         final Map<String, String> headers = createHeaders(requestId);
228
229         url = url + "/aai/search/named-query";
230
231         logger.debug("RestManager.post before");
232         String requestJson = Serialization.gsonPretty.toJson(request);
233         NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, url, requestJson);
234         Pair<Integer, String> httpDetails =
235                 restManager.post(url, username, password, headers, "application/json", requestJson);
236         logger.debug("RestManager.post after");
237
238         if (httpDetails == null) {
239             logger.info("AAI POST Null Response to {}", url);
240             return null;
241         }
242
243         int httpResponseCode = httpDetails.first;
244
245         logger.info(url);
246         logger.info("{}", httpResponseCode);
247         logger.info(httpDetails.second);
248
249         if (httpDetails.second != null) {
250             return composeResponse(httpDetails, url, AaiNqResponse.class);
251         }
252         return null;
253     }
254
255     /**
256      * Perform a GET request for a particular virtual server towards A&AI.
257      *
258      * @param urlGet the A&AI URL
259      * @param username the user name for authentication
260      * @param password the password for authentication
261      * @param requestId the UUID of the request
262      * @param key the key of the virtual server
263      * @return the response for the virtual server from A&AI
264      */
265     public AaiGetVserverResponse getQueryByVserverName(String urlGet, String username, String password, UUID requestId,
266             String key) {
267         return getQuery(urlGet, username, password, requestId, key, AaiGetVserverResponse.class);
268     }
269
270     /**
271      * Perform a GET request for a particular VNF by VNF ID towards A&AI.
272      *
273      * @param urlGet the A&AI URL
274      * @param username the user name for authentication
275      * @param password the password for authentication
276      * @param requestId the UUID of the request
277      * @param key the ID of the VNF
278      * @return the response for the virtual server from A&AI
279      */
280     public AaiGetVnfResponse getQueryByVnfId(String urlGet, String username, String password, UUID requestId,
281             String key) {
282         return getQuery(urlGet, username, password, requestId, key, AaiGetVnfResponse.class);
283     }
284
285     /**
286      * Perform a GET request for a particular VNF by VNF name towards A&AI.
287      *
288      * @param urlGet the A&AI URL
289      * @param username the user name for authentication
290      * @param password the password for authentication
291      * @param requestId the UUID of the request
292      * @param key the name of the VNF
293      * @return the response for the virtual server from A&AI
294      */
295     public AaiGetVnfResponse getQueryByVnfName(String urlGet, String username, String password, UUID requestId,
296             String key) {
297         return getQuery(urlGet, username, password, requestId, key, AaiGetVnfResponse.class);
298     }
299
300     /**
301      * Perform a GET query for a particular entity towards A&AI.
302      *
303      * @param <T> the generic type for the response
304      * @param urlGet the A&AI URL
305      * @param username the user name for authentication
306      * @param password the password for authentication
307      * @param requestId the UUID of the request
308      * @param key the name of the VNF
309      * @param classOfT the class of the response to return
310      * @return the response for the virtual server from A&AI
311      */
312     private <T> T getQuery(final String url, final String username, final String password, final UUID requestId,
313             final String key, final Class<T> classOfResponse) {
314
315         Map<String, String> headers = createHeaders(requestId);
316
317         String urlGet = url + key;
318
319         int attemptsLeft = 3;
320
321         while (attemptsLeft-- > 0) {
322             NetLoggerUtil.getNetworkLogger().info("[OUT|{}|{}|]", CommInfrastructure.REST, urlGet);
323             Pair<Integer, String> httpDetailsGet = restManager.get(urlGet, username, password, headers);
324             if (httpDetailsGet == null) {
325                 logger.info("AAI GET Null Response to {}", urlGet);
326                 return null;
327             }
328
329             int httpResponseCode = httpDetailsGet.first;
330
331             logger.info(urlGet);
332             logger.info("{}", httpResponseCode);
333             logger.info(httpDetailsGet.second);
334
335             if (httpResponseCode == 200) {
336                 T responseGet = composeResponse(httpDetailsGet, urlGet, classOfResponse);
337                 if (responseGet != null) {
338                     return responseGet;
339                 }
340             }
341             try {
342                 Thread.sleep(1000);
343             } catch (InterruptedException e) {
344                 Thread.currentThread().interrupt();
345             }
346
347         }
348
349         return null;
350     }
351
352     /**
353      * Create the headers for the HTTP request.
354      *
355      * @param requestId the request ID to insert in the headers
356      * @return the HTTP headers
357      */
358     private Map<String, String> createHeaders(final UUID requestId) {
359         Map<String, String> headers = new HashMap<>();
360
361         headers.put("X-FromAppId", "POLICY");
362         headers.put("X-TransactionId", requestId.toString());
363         headers.put("Accept", "application/json");
364
365         return headers;
366     }
367
368
369     /**
370      * This method uses Google's GSON to create a response object from a JSON string.
371      *
372      * @param <T> the generic type
373      * @param httpDetails the HTTP response
374      * @param url the URL from which the response came
375      * @param classOfResponse The response class
376      * @return an instance of the response class
377      * @throws JsonSyntaxException on GSON errors instantiating the response
378      */
379     private <T> T composeResponse(final Pair<Integer, String> httpDetails, final String url,
380             final Class<T> classOfResponse) {
381         try {
382             T response = Serialization.gsonPretty.fromJson(httpDetails.second, classOfResponse);
383             NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, httpDetails.second);
384             return response;
385         } catch (JsonSyntaxException e) {
386             logger.error("postQuery threw: ", e);
387             return null;
388         }
389     }
390 }