2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017-2018 Amdocs
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.sparky.dal;
23 import java.io.IOException;
25 import java.net.URISyntaxException;
26 import java.net.URLEncoder;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
31 import java.util.NoSuchElementException;
33 import javax.ws.rs.core.MediaType;
34 import javax.ws.rs.core.UriBuilder;
36 import org.apache.http.client.utils.URIBuilder;
37 import org.onap.aai.cl.api.Logger;
38 import org.onap.aai.cl.eelf.LoggerFactory;
39 import org.onap.aai.restclient.client.OperationResult;
40 import org.onap.aai.restclient.client.RestClient;
41 import org.onap.aai.restclient.enums.RestAuthenticationMode;
42 import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor;
43 import org.onap.aai.sparky.config.oxm.OxmEntityLookup;
44 import org.onap.aai.sparky.config.oxm.OxmModelLoader;
45 import org.onap.aai.sparky.dal.exception.ElasticSearchOperationException;
46 import org.onap.aai.sparky.dal.rest.RestClientConstructionException;
47 import org.onap.aai.sparky.dal.rest.RestClientFactory;
48 import org.onap.aai.sparky.dal.rest.config.RestEndpointConfig;
49 import org.onap.aai.sparky.logging.AaiUiMsgs;
50 import org.onap.aai.sparky.util.NodeUtils;
53 * The Class ActiveInventoryAdapter.
56 public class ActiveInventoryAdapter {
58 private static final Logger LOG =
59 LoggerFactory.getInstance().getLogger(ActiveInventoryAdapter.class);
61 private static final String HEADER_TRANS_ID = "X-TransactionId";
62 private static final String HEADER_FROM_APP_ID = "X-FromAppId";
63 private static final String HEADER_AUTHORIZATION = "Authorization";
65 private static final String HTTP_SCHEME = "http";
66 private static final String HTTPS_SCHEME = "https";
68 private static final String TRANSACTION_ID_PREFIX = "txnId-";
69 private static final String UI_APP_NAME = "AAI-UI";
71 private OxmModelLoader oxmModelLoader;
72 private OxmEntityLookup oxmEntityLookup;
73 private RestEndpointConfig endpointConfig;
75 private RestClient restClient;
78 * Instantiates a new active inventory adapter.
79 * @throws RestClientConstructionException
83 public ActiveInventoryAdapter(OxmModelLoader oxmModelLoader, OxmEntityLookup oxmEntityLookup,
84 RestEndpointConfig endpointConfig)
85 throws ElasticSearchOperationException, IOException, RestClientConstructionException {
87 this.oxmModelLoader = oxmModelLoader;
88 this.oxmEntityLookup = oxmEntityLookup;
89 this.endpointConfig = endpointConfig;
90 this.restClient = RestClientFactory.buildClient(endpointConfig);
94 protected Map<String, List<String>> getMessageHeaders() {
96 Map<String, List<String>> headers = new HashMap<String, List<String>>();
98 headers.putIfAbsent(HEADER_FROM_APP_ID, new ArrayList<String>());
99 headers.get(HEADER_FROM_APP_ID).add(UI_APP_NAME);
101 headers.putIfAbsent(HEADER_TRANS_ID, new ArrayList<String>());
102 headers.get(HEADER_TRANS_ID).add(TRANSACTION_ID_PREFIX + NodeUtils.getRandomTxnId());
104 if (endpointConfig.getRestAuthenticationMode() == RestAuthenticationMode.SSL_BASIC) {
106 headers.putIfAbsent(HEADER_AUTHORIZATION, new ArrayList<String>());
107 headers.get(HEADER_AUTHORIZATION).add(getBasicAuthenticationCredentials());
114 protected String getBasicAuthenticationCredentials() {
115 String usernameAndPassword = String.join(":", endpointConfig.getBasicAuthUserName(),
116 endpointConfig.getBasicAuthPassword());
117 return "Basic " + java.util.Base64.getEncoder().encodeToString(usernameAndPassword.getBytes());
120 public OxmEntityLookup getOxmEntityLookup() {
121 return oxmEntityLookup;
124 public void setOxmEntityLookup(OxmEntityLookup oxmEntityLookup) {
125 this.oxmEntityLookup = oxmEntityLookup;
128 protected String getResourceBasePath() {
130 String versionStr = null;
131 if (oxmModelLoader != null) {
132 versionStr = String.valueOf(oxmModelLoader.getLatestVersionNum());
135 return "/aai/v" + versionStr;
139 public static String extractResourcePath(String selflink) {
141 return new URI(selflink).getRawPath();
142 } catch (URISyntaxException uriSyntaxException) {
143 LOG.error(AaiUiMsgs.ERROR_EXTRACTING_RESOURCE_PATH_FROM_LINK,
144 uriSyntaxException.getMessage());
153 * @param resourceUrl the resource url
154 * @return the full url
155 * @throws Exception the exception
157 private String getFullUrl(String resourceUrl) throws Exception {
158 final String basePath = getResourceBasePath();
159 return String.format("https://%s:%s%s%s", endpointConfig.getEndpointIpAddress(),
160 endpointConfig.getEndpointServerPort(), basePath, resourceUrl);
163 public String getGenericQueryForSelfLink(String startNodeType, List<String> queryParams)
166 URIBuilder urlBuilder = new URIBuilder(getFullUrl("/search/generic-query"));
168 for (String queryParam : queryParams) {
169 urlBuilder.addParameter("key", queryParam);
172 urlBuilder.addParameter("start-node-type", startNodeType);
173 urlBuilder.addParameter("include", startNodeType);
175 final String constructedLink = urlBuilder.toString();
177 return constructedLink;
182 public OperationResult getSelfLinksByEntityType(String entityType) throws Exception {
185 * For this one, I want to dynamically construct the nodes-query for self-link discovery as a
186 * utility method that will use the OXM model entity data to drive the query as well.
189 if (entityType == null) {
190 throw new NullPointerException(
191 "Failed to getSelfLinksByEntityType() because entityType is null");
194 OxmEntityDescriptor entityDescriptor = oxmEntityLookup.getEntityDescriptors().get(entityType);
196 if (entityDescriptor == null) {
197 throw new NoSuchElementException("Failed to getSelfLinksByEntityType() because could"
198 + " not find entity descriptor from OXM with type = " + entityType);
202 final String primaryKeyStr =
203 NodeUtils.concatArray(entityDescriptor.getPrimaryKeyAttributeNames(), "/");
205 link = getFullUrl("/search/nodes-query?search-node-type=" + entityType + "&filter="
206 + primaryKeyStr + ":EXISTS");
209 return restClient.get(link, getMessageHeaders(), MediaType.APPLICATION_JSON_TYPE);
213 public OperationResult getSelfLinkForEntity(String entityType, String primaryKeyName,
214 String primaryKeyValue) throws Exception {
216 if (entityType == null) {
217 throw new NullPointerException("Failed to getSelfLinkForEntity() because entityType is null");
220 if (primaryKeyName == null) {
221 throw new NullPointerException(
222 "Failed to getSelfLinkForEntity() because primaryKeyName is null");
225 if (primaryKeyValue == null) {
226 throw new NullPointerException(
227 "Failed to getSelfLinkForEntity() because primaryKeyValue is null");
231 * Try to protect ourselves from illegal URI formatting exceptions caused by characters that
232 * aren't natively supported in a URI, but can be escaped to make them legal.
235 String encodedEntityType = URLEncoder.encode(entityType, "UTF-8");
236 String encodedPrimaryKeyName = URLEncoder.encode(primaryKeyName, "UTF-8");
237 String encodedPrimaryKeyValue = URLEncoder.encode(primaryKeyValue, "UTF-8");
241 if ("service-instance".equals(entityType)) {
243 link = getFullUrl("/search/generic-query?key=" + encodedEntityType + "."
244 + encodedPrimaryKeyName + ":" + encodedPrimaryKeyValue + "&start-node-type="
245 + encodedEntityType + "&include=customer&depth=2");
250 getFullUrl("/search/generic-query?key=" + encodedEntityType + "." + encodedPrimaryKeyName
251 + ":" + encodedPrimaryKeyValue + "&start-node-type=" + encodedEntityType);
255 return queryActiveInventoryWithRetries(link, "application/json",
256 endpointConfig.getNumRequestRetries());
262 * Our retry conditions should be very specific.
265 * @return true, if successful
267 private boolean shouldRetryRequest(OperationResult r) {
273 int rc = r.getResultCode();
288 * Query active inventory.
291 * @param acceptContentType the accept content type
292 * @return the operation result
294 // package protected for test classes instead of private
295 OperationResult queryActiveInventory(String url, String acceptContentType) {
297 return restClient.get(url, getMessageHeaders(), MediaType.APPLICATION_JSON_TYPE);
301 public RestEndpointConfig getEndpointConfig() {
302 return endpointConfig;
305 public void setEndpointConfig(RestEndpointConfig endpointConfig) {
306 this.endpointConfig = endpointConfig;
309 public OperationResult queryActiveInventoryWithRetries(String url, String responseType,
312 OperationResult result = null;
314 for (int retryCount = 0; retryCount < numRetries; retryCount++) {
316 LOG.debug(AaiUiMsgs.QUERY_AAI_RETRY_SEQ, url, String.valueOf(retryCount + 1));
318 result = queryActiveInventory(url, responseType);
321 * Record number of times we have attempted the request to later summarize how many times we
322 * are generally retrying over thousands of messages in a sync.
324 * If the number of retries is surprisingly high, then we need to understand why that is as
325 * the number of retries is also causing a heavier load on AAI beyond the throttling controls
326 * we already have in place in term of the transaction rate controller and number of
327 * parallelized threads per task processor.
330 result.setNumRetries(retryCount);
332 if (!shouldRetryRequest(result)) {
334 result.setFromCache(false);
335 LOG.debug(AaiUiMsgs.QUERY_AAI_RETRY_DONE_SEQ, url, String.valueOf(retryCount + 1));
342 * Sleep between re-tries to be nice to the target system.
345 } catch (InterruptedException exc) {
346 LOG.error(AaiUiMsgs.QUERY_AAI_WAIT_INTERRUPTION, exc.getLocalizedMessage());
349 LOG.error(AaiUiMsgs.QUERY_AAI_RETRY_FAILURE_WITH_SEQ, url, String.valueOf(retryCount + 1));
353 LOG.info(AaiUiMsgs.QUERY_AAI_RETRY_MAXED_OUT, url);
359 public String repairSelfLink(String selfLink) {
360 return repairSelfLink(selfLink, null);
364 * This method adds a scheme, host and port (if missing) to the passed-in URI.
365 * If these parts of the URI are already present, they will not be duplicated.
367 * @param selflink The URI to repair
368 * @param queryParams The query parameters as a single string
369 * @return The corrected URI (i.e. includes a scheme/host/port)
371 public String repairSelfLink(String selflink, String queryParams) {
372 if (selflink == null) {
376 UriBuilder builder = UriBuilder.fromPath(selflink).host(endpointConfig.getEndpointIpAddress())
377 .port(Integer.parseInt(endpointConfig.getEndpointServerPort()));
379 switch (endpointConfig.getRestAuthenticationMode()) {
383 builder.scheme(HTTPS_SCHEME);
388 builder.scheme(HTTP_SCHEME);
392 boolean includeQueryParams = ( (null != queryParams) && (!"".equals(queryParams)) );
394 /* builder.build().toString() will encode special characters to hexadecimal pairs prefixed with a '%'
395 so we're adding the query parameters separately, in their UTF-8 representations, so that
396 characters such as '?', '&', etc. remain intact as needed by the synchronizer */
397 return (builder.build().toString() + (includeQueryParams ? queryParams : ""));