migrate model-impl from drools-applications
[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
27 import java.util.HashMap;
28 import java.util.Map;
29 import java.util.UUID;
30
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     /**
53      * Constructor, create the AAI manager with the specified REST manager.
54      *
55      * @param restManager the rest manager to use for REST calls
56      */
57     public AaiManager(final RestManager restManager) {
58         this.restManager = restManager;
59     }
60
61     /**
62      * Post a query to A&AI.
63      *
64      * @param url the A&AI URL
65      * @param username the user name for authentication
66      * @param password the password for authentication
67      * @param request the request to issue towards A&AI
68      * @param requestId the UUID of the request
69      * @return the response from A&AI
70      */
71     public AaiNqResponse postQuery(String url, String username, String password, AaiNqRequest request, UUID requestId) {
72
73         final Map<String, String> headers = createHeaders(requestId);
74
75         url = url + "/aai/search/named-query";
76
77         logger.debug("RestManager.post before");
78         String requestJson = Serialization.gsonPretty.toJson(request);
79         NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, url, requestJson);
80         Pair<Integer, String> httpDetails =
81                 restManager.post(url, username, password, headers, "application/json", requestJson);
82         logger.debug("RestManager.post after");
83
84         if (httpDetails == null) {
85             logger.info("AAI POST Null Response to {}", url);
86             return null;
87         }
88
89         int httpResponseCode = httpDetails.first;
90
91         logger.info(url);
92         logger.info("{}", httpResponseCode);
93         logger.info(httpDetails.second);
94
95         if (httpDetails.second != null) {
96             return composeResponse(httpDetails, url, AaiNqResponse.class);
97         }
98         return null;
99     }
100
101     /**
102      * Perform a GET request for a particular virtual server towards A&AI.
103      *
104      * @param urlGet the A&AI URL
105      * @param username the user name for authentication
106      * @param password the password for authentication
107      * @param requestId the UUID of the request
108      * @param key the key of the virtual server
109      * @return the response for the virtual server from A&AI
110      */
111     public AaiGetVserverResponse getQueryByVserverName(String urlGet, String username, String password, UUID requestId,
112             String key) {
113         return getQuery(urlGet, username, password, requestId, key, AaiGetVserverResponse.class);
114     }
115
116     /**
117      * Perform a GET request for a particular VNF by VNF ID towards A&AI.
118      *
119      * @param urlGet the A&AI URL
120      * @param username the user name for authentication
121      * @param password the password for authentication
122      * @param requestId the UUID of the request
123      * @param key the ID of the VNF
124      * @return the response for the virtual server from A&AI
125      */
126     public AaiGetVnfResponse getQueryByVnfId(String urlGet, String username, String password, UUID requestId,
127             String key) {
128         return getQuery(urlGet, username, password, requestId, key, AaiGetVnfResponse.class);
129     }
130
131     /**
132      * Perform a GET request for a particular VNF by VNF name towards A&AI.
133      *
134      * @param urlGet the A&AI URL
135      * @param username the user name for authentication
136      * @param password the password for authentication
137      * @param requestId the UUID of the request
138      * @param key the name of the VNF
139      * @return the response for the virtual server from A&AI
140      */
141     public AaiGetVnfResponse getQueryByVnfName(String urlGet, String username, String password, UUID requestId,
142             String key) {
143         return getQuery(urlGet, username, password, requestId, key, AaiGetVnfResponse.class);
144     }
145
146     /**
147      * Perform a GET query for a particular entity towards A&AI.
148      *
149      * @param <T> the generic type for the response
150      * @param urlGet the A&AI URL
151      * @param username the user name for authentication
152      * @param password the password for authentication
153      * @param requestId the UUID of the request
154      * @param key the name of the VNF
155      * @param classOfT the class of the response to return
156      * @return the response for the virtual server from A&AI
157      */
158     private <T> T getQuery(final String url, final String username, final String password, final UUID requestId,
159             final String key, final Class<T> classOfResponse) {
160
161         Map<String, String> headers = createHeaders(requestId);
162
163         String urlGet = url + key;
164
165         int attemptsLeft = 3;
166
167         while (attemptsLeft-- > 0) {
168             NetLoggerUtil.getNetworkLogger().info("[OUT|{}|{}|]", CommInfrastructure.REST, urlGet);
169             Pair<Integer, String> httpDetailsGet = restManager.get(urlGet, username, password, headers);
170             if (httpDetailsGet == null) {
171                 logger.info("AAI GET Null Response to {}", urlGet);
172                 return null;
173             }
174
175             int httpResponseCode = httpDetailsGet.first;
176
177             logger.info(urlGet);
178             logger.info("{}", httpResponseCode);
179             logger.info(httpDetailsGet.second);
180
181             if (httpResponseCode == 200) {
182                 T responseGet = composeResponse(httpDetailsGet, urlGet, classOfResponse);
183                 if (responseGet != null) {
184                     return responseGet;
185                 }
186             }
187             try {
188                 Thread.sleep(1000);
189             } catch (InterruptedException e) {
190                 Thread.currentThread().interrupt();
191             }
192
193         }
194
195         return null;
196     }
197
198     /**
199      * Create the headers for the HTTP request.
200      *
201      * @param requestId the request ID to insert in the headers
202      * @return the HTTP headers
203      */
204     private Map<String, String> createHeaders(final UUID requestId) {
205         Map<String, String> headers = new HashMap<>();
206
207         headers.put("X-FromAppId", "POLICY");
208         headers.put("X-TransactionId", requestId.toString());
209         headers.put("Accept", "application/json");
210
211         return headers;
212     }
213
214     /**
215      * This method uses Google's GSON to create a response object from a JSON string.
216      *
217      * @param <T> the generic type
218      * @param httpDetails the HTTP response
219      * @param url the URL from which the response came
220      * @param classOfResponse The response class
221      * @return an instance of the response class
222      * @throws JsonSyntaxException on GSON errors instantiating the response
223      */
224     private <T> T composeResponse(final Pair<Integer, String> httpDetails, final String url,
225             final Class<T> classOfResponse) {
226         try {
227             T response = Serialization.gsonPretty.fromJson(httpDetails.second, classOfResponse);
228             NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, httpDetails.second);
229             return response;
230         } catch (JsonSyntaxException e) {
231             logger.error("postQuery threw: ", e);
232             return null;
233         }
234     }
235 }