Set all cross references of policy/models
[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-2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019-2020 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 import lombok.AllArgsConstructor;
33 import org.apache.commons.lang3.tuple.Pair;
34 import org.json.JSONArray;
35 import org.json.JSONObject;
36 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
37 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
38 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
39 import org.onap.policy.common.utils.coder.CoderException;
40 import org.onap.policy.common.utils.coder.StandardCoder;
41 import org.onap.policy.rest.RestManager;
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 @AllArgsConstructor
49 public final class AaiManager {
50
51     // TODO remove this class
52
53     /** The Constant logger. */
54     private static final Logger logger = LoggerFactory.getLogger(AaiManager.class);
55
56     private static final String APPLICATION_JSON = "application/json";
57
58     private static final StandardCoder CODER = new StandardCoder();
59
60     /** custom query and other AAI resource URLs. */
61     private static final String CQ_URL = "/aai/v21/query?format=resource";
62     private static final String TENANT_URL = "/aai/v21/search/nodes-query?"
63                     + "search-node-type=vserver&filter=vserver-name:EQUALS:";
64     private static final String PREFIX = "/aai/v21";
65     private static final String PNF_URL = PREFIX + "/network/pnfs/pnf/";
66     private static final String AAI_DEPTH_SUFFIX = "?depth=0";
67
68     // The REST manager used for processing REST calls for this AAI manager
69     private final RestManager restManager;
70
71     /**
72      * Creates the custom query payload from a tenant query response.
73      *
74      * @param getResponse response from the tenant query
75      * @return String Payload
76      */
77     private String createCustomQueryPayload(String getResponse) {
78
79         if (getResponse == null) {
80             return null;
81         } else {
82             var responseObj = new JSONObject(getResponse);
83             JSONArray resultsArray;
84             if (responseObj.has("result-data")) {
85                 resultsArray = (JSONArray) responseObj.get("result-data");
86             } else {
87                 return null;
88             }
89             var resourceLink = resultsArray.getJSONObject(0).getString("resource-link");
90             var start = resourceLink.replace(PREFIX, "");
91             var query = "query/closed-loop";
92             var payload = new JSONObject();
93             payload.put("start", start);
94             payload.put("query", query);
95             return payload.toString();
96
97         }
98     }
99
100     /**
101      * This method is used to get the information for custom query.
102      *
103      * @param url url of the get method
104      * @param username Aai username
105      * @param password Aai password
106      * @param requestId request ID
107      * @param vserver Id of the vserver
108      * @return String
109      */
110     private String getCustomQueryRequestPayload(String url, String username, String password, UUID requestId,
111                     String vserver) {
112
113         String urlGet = url + TENANT_URL;
114
115         var getResponse = getStringQuery(urlGet, username, password, requestId, vserver);
116         return createCustomQueryPayload(getResponse);
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 = this.restManager.put(url, username, password, headers, APPLICATION_JSON,
141                         requestJson);
142         logger.debug("RestManager.put after");
143
144         if (httpDetails == null) {
145             NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "AAI POST Null Response");
146             logger.debug("AAI POST Null Response to {}", url);
147             return null;
148         }
149
150         int httpResponseCode = httpDetails.getLeft();
151
152         NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "Response code: " + httpResponseCode);
153         NetLoggerUtil.getNetworkLogger().debug(httpDetails.getRight());
154
155         logger.debug(url);
156         logger.debug("{}", httpResponseCode);
157         logger.debug(httpDetails.getRight());
158
159         if (httpDetails.getRight() != null) {
160             return new AaiCqResponse(httpDetails.getRight());
161         }
162         return null;
163     }
164
165     /**
166      * Returns the string response of a get query.
167      *
168      * @param url Aai URL
169      * @param username Aai Username
170      * @param password Aai Password
171      * @param requestId AaiRequestId
172      * @param key Aai Key
173      * @return String returns the string from the get query
174      */
175     private String getStringQuery(final String url, final String username, final String password, final UUID requestId,
176                     final String key) {
177
178         Map<String, String> headers = createHeaders(requestId);
179
180         String urlGet = url + key;
181
182         var attemptsLeft = 3;
183
184         while (attemptsLeft-- > 0) {
185             NetLoggerUtil.getNetworkLogger().info("[OUT|{}|{}|]", CommInfrastructure.REST, urlGet);
186             Pair<Integer, String> httpDetailsGet = restManager.get(urlGet, username, password, headers);
187             if (httpDetailsGet == null) {
188                 NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "AAI POST Null Response");
189                 logger.debug("AAI GET Null Response to {}", urlGet);
190                 return null;
191             }
192
193             int httpResponseCode = httpDetailsGet.getLeft();
194
195             NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "Response code: " + httpResponseCode);
196             NetLoggerUtil.getNetworkLogger().debug(httpDetailsGet.getRight());
197
198             logger.debug(urlGet);
199             logger.debug("{}", httpResponseCode);
200             logger.debug(httpDetailsGet.getRight());
201
202             if (httpResponseCode == 200 && httpDetailsGet.getRight() != null) {
203                 return httpDetailsGet.getRight();
204             }
205             try {
206                 Thread.sleep(1000);
207             } catch (InterruptedException e) {
208                 Thread.currentThread().interrupt();
209             }
210
211         }
212
213         return null;
214     }
215
216     /**
217      * Create the headers for the HTTP request.
218      *
219      * @param requestId the request ID to insert in the headers
220      * @return the HTTP headers
221      */
222     private Map<String, String> createHeaders(final UUID requestId) {
223         Map<String, String> headers = new HashMap<>();
224
225         headers.put("X-FromAppId", "POLICY");
226         headers.put("X-TransactionId", requestId.toString());
227         headers.put("Accept", APPLICATION_JSON);
228
229         return headers;
230     }
231
232     /**
233      * Perform a GET request for a particular PNF by PNF ID towards A&AI.
234      *
235      * @param url the A&AI URL
236      * @param username the user name for authentication
237      * @param password the password for authentication
238      * @param requestId the UUID of the request
239      * @param pnfName the AAI unique identifier for PNF object
240      * @return HashMap of PNF properties
241      */
242     public Map<String, String> getPnf(String url, String username, String password, UUID requestId, String pnfName) {
243         String urlGet;
244         try {
245             urlGet = url + PNF_URL;
246             pnfName = URLEncoder.encode(pnfName, StandardCharsets.UTF_8.toString()) + AAI_DEPTH_SUFFIX;
247         } catch (UnsupportedEncodingException e) {
248             logger.error("Failed to encode the pnfName: {} using UTF-8", pnfName, e);
249             return null;
250         }
251         var responseGet = getStringQuery(urlGet, username, password, requestId, pnfName);
252         if (responseGet == null) {
253             logger.error("Null response from AAI for the url: {}.", urlGet);
254             return null;
255         }
256         try {
257             @SuppressWarnings("unchecked")
258             Map<String, String> pnfParams = CODER.decode(responseGet, HashMap.class);
259             // Map to AAI node.attribute notation
260             return pnfParams.entrySet().stream()
261                             .collect(Collectors.toMap(e -> "pnf." + e.getKey(), Map.Entry::getValue));
262         } catch (CoderException e) {
263             logger.error("Failed to fetch PNF from AAI", e);
264             return null;
265         }
266     }
267 }