Merge "Add debugging of REST call"
[policy/drools-applications.git] / controlloop / common / 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 Samsung Electronics Co., Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.aai;
23
24 import com.google.gson.JsonSyntaxException;
25
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.UUID;
29
30 import org.onap.policy.aai.util.Serialization;
31 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
32 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
33 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
34 import org.onap.policy.rest.RestManager;
35 import org.onap.policy.rest.RestManager.Pair;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * This class handles communication towards and responses from A&AI for this module.
41  */
42 public final class AaiManager {
43
44     /** The Constant logger. */
45     private static final Logger logger = LoggerFactory.getLogger(AaiManager.class);
46
47     /** The rest manager. */
48     // The REST manager used for processing REST calls for this AAI manager
49     private final RestManager restManager;
50
51     /**
52      * Constructor, create the AAI manager with the specified REST manager.
53      *
54      * @param restManager the rest manager to use for REST calls
55      */
56     public AaiManager(final RestManager restManager) {
57         this.restManager = restManager;
58     }
59
60     /**
61      * Post a query to A&AI.
62      *
63      * @param url the A&AI URL
64      * @param username the user name for authentication
65      * @param password the password for authentication
66      * @param request the request to issue towards A&AI
67      * @param requestId the UUID of the request
68      * @return the response from A&AI
69      */
70     public AaiNqResponse postQuery(String url, String username, String password, AaiNqRequest request, UUID requestId) {
71
72         final Map<String, String> headers = createHeaders(requestId);
73
74         url = url + "/aai/search/named-query";
75
76         logger.debug("RestManager.post before");
77         String requestJson = Serialization.gsonPretty.toJson(request);
78         NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, url, requestJson);
79         Pair<Integer, String> httpDetails =
80                 restManager.post(url, username, password, headers, "application/json", requestJson);
81         logger.debug("RestManager.post after");
82
83         if (httpDetails == null) {
84             logger.info("AAI POST Null Response to {}", url);
85             return null;
86         }
87
88         int httpResponseCode = httpDetails.first;
89
90         logger.info(url);
91         logger.info("{}", httpResponseCode);
92         logger.info(httpDetails.second);
93
94         if (httpDetails.second != null) {
95             return composeResponse(httpDetails, url, AaiNqResponse.class);
96         }
97         return null;
98     }
99
100     /**
101      * Perform a GET request for a particular virtual server towards A&AI.
102      *
103      * @param urlGet the A&AI URL
104      * @param username the user name for authentication
105      * @param password the password for authentication
106      * @param requestId the UUID of the request
107      * @param key the key of the virtual server
108      * @return the response for the virtual server from A&AI
109      */
110     public AaiGetVserverResponse getQueryByVserverName(String urlGet, String username, String password, UUID requestId,
111             String key) {
112         return getQuery(urlGet, username, password, requestId, key, AaiGetVserverResponse.class);
113     }
114
115     /**
116      * Perform a GET request for a particular VNF by VNF ID towards A&AI.
117      *
118      * @param urlGet the A&AI URL
119      * @param username the user name for authentication
120      * @param password the password for authentication
121      * @param requestId the UUID of the request
122      * @param key the ID of the VNF
123      * @return the response for the virtual server from A&AI
124      */
125     public AaiGetVnfResponse getQueryByVnfId(String urlGet, String username, String password, UUID requestId,
126             String key) {
127         return getQuery(urlGet, username, password, requestId, key, AaiGetVnfResponse.class);
128     }
129
130     /**
131      * Perform a GET request for a particular VNF by VNF name towards A&AI.
132      *
133      * @param urlGet the A&AI URL
134      * @param username the user name for authentication
135      * @param password the password for authentication
136      * @param requestId the UUID of the request
137      * @param key the name of the VNF
138      * @return the response for the virtual server from A&AI
139      */
140     public AaiGetVnfResponse getQueryByVnfName(String urlGet, String username, String password, UUID requestId,
141             String key) {
142         return getQuery(urlGet, username, password, requestId, key, AaiGetVnfResponse.class);
143     }
144
145     /**
146      * Perform a GET query for a particular entity towards A&AI.
147      *
148      * @param <T> the generic type for the response
149      * @param urlGet the A&AI URL
150      * @param username the user name for authentication
151      * @param password the password for authentication
152      * @param requestId the UUID of the request
153      * @param key the name of the VNF
154      * @param classOfT the class of the response to return
155      * @return the response for the virtual server from A&AI
156      */
157     private <T> T getQuery(final String url, final String username, final String password, final UUID requestId,
158             final String key, final Class<T> classOfResponse) {
159
160         Map<String, String> headers = createHeaders(requestId);
161
162         String urlGet = url + key;
163
164         int attemptsLeft = 3;
165
166         while (attemptsLeft-- > 0) {
167             NetLoggerUtil.getNetworkLogger().info("[OUT|{}|{}|]", CommInfrastructure.REST, urlGet);
168             Pair<Integer, String> httpDetailsGet = restManager.get(urlGet, username, password, headers);
169             if (httpDetailsGet == null) {
170                 logger.info("AAI GET Null Response to {}", urlGet);
171                 return null;
172             }
173
174             int httpResponseCode = httpDetailsGet.first;
175
176             logger.info(urlGet);
177             logger.info("{}", httpResponseCode);
178             logger.info(httpDetailsGet.second);
179
180             if (httpResponseCode == 200) {
181                 T responseGet = composeResponse(httpDetailsGet, urlGet, classOfResponse);
182                 if (responseGet != null) {
183                     return responseGet;
184                 }
185             }
186             try {
187                 Thread.sleep(1000);
188             } catch (InterruptedException e) {
189                 Thread.currentThread().interrupt();
190             }
191
192         }
193
194         return null;
195     }
196
197     /**
198      * Create the headers for the HTTP request.
199      *
200      * @param requestId the request ID to insert in the headers
201      * @return the HTTP headers
202      */
203     private Map<String, String> createHeaders(final UUID requestId) {
204         Map<String, String> headers = new HashMap<>();
205
206         headers.put("X-FromAppId", "POLICY");
207         headers.put("X-TransactionId", requestId.toString());
208         headers.put("Accept", "application/json");
209
210         return headers;
211     }
212
213     /**
214      * This method uses Google's GSON to create a response object from a JSON string.
215      *
216      * @param <T> the generic type
217      * @param httpDetails the HTTP response
218      * @param url the URL from which the response came
219      * @param classOfResponse The response class
220      * @return an instance of the response class
221      * @throws JsonSyntaxException on GSON errors instantiating the response
222      */
223     private <T> T composeResponse(final Pair<Integer, String> httpDetails, final String url,
224             final Class<T> classOfResponse) {
225         try {
226             T response = Serialization.gsonPretty.fromJson(httpDetails.second, classOfResponse);
227             NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, httpDetails.second);
228             return response;
229         } catch (JsonSyntaxException e) {
230             logger.error("postQuery threw: ", e);
231             return null;
232         }
233     }
234 }