2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017 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 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.onap.aai.sparky.dal;
25 import java.io.IOException;
27 import java.net.URISyntaxException;
28 import java.net.URLEncoder;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
33 import java.util.NoSuchElementException;
35 import javax.ws.rs.core.MediaType;
36 import javax.ws.rs.core.UriBuilder;
38 import org.apache.http.client.utils.URIBuilder;
39 import org.onap.aai.cl.api.Logger;
40 import org.onap.aai.cl.eelf.LoggerFactory;
41 import org.onap.aai.restclient.client.OperationResult;
42 import org.onap.aai.restclient.client.RestClient;
43 import org.onap.aai.restclient.enums.RestAuthenticationMode;
44 import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor;
45 import org.onap.aai.sparky.config.oxm.OxmEntityLookup;
46 import org.onap.aai.sparky.config.oxm.OxmModelLoader;
47 import org.onap.aai.sparky.dal.exception.ElasticSearchOperationException;
48 import org.onap.aai.sparky.dal.rest.RestClientConstructionException;
49 import org.onap.aai.sparky.dal.rest.RestClientFactory;
50 import org.onap.aai.sparky.dal.rest.config.RestEndpointConfig;
51 import org.onap.aai.sparky.logging.AaiUiMsgs;
52 import org.onap.aai.sparky.util.NodeUtils;
55 * The Class ActiveInventoryAdapter.
58 public class ActiveInventoryAdapter {
60 private static final Logger LOG =
61 LoggerFactory.getInstance().getLogger(ActiveInventoryAdapter.class);
63 private static final String HEADER_TRANS_ID = "X-TransactionId";
64 private static final String HEADER_FROM_APP_ID = "X-FromAppId";
65 private static final String HEADER_AUTHORIZATION = "Authorization";
67 private static final String HTTP_SCHEME = "http";
68 private static final String HTTPS_SCHEME = "https";
70 private static final String TRANSACTION_ID_PREFIX = "txnId-";
71 private static final String UI_APP_NAME = "AAI-UI";
73 private OxmModelLoader oxmModelLoader;
74 private OxmEntityLookup oxmEntityLookup;
75 private RestEndpointConfig endpointConfig;
77 private RestClient restClient;
80 * Instantiates a new active inventory adapter.
81 * @throws RestClientConstructionException
85 public ActiveInventoryAdapter(OxmModelLoader oxmModelLoader, OxmEntityLookup oxmEntityLookup,
86 RestEndpointConfig endpointConfig)
87 throws ElasticSearchOperationException, IOException, RestClientConstructionException {
89 this.oxmModelLoader = oxmModelLoader;
90 this.oxmEntityLookup = oxmEntityLookup;
91 this.endpointConfig = endpointConfig;
92 this.restClient = RestClientFactory.buildClient(endpointConfig);
96 protected Map<String, List<String>> getMessageHeaders() {
98 Map<String, List<String>> headers = new HashMap<String, List<String>>();
100 headers.putIfAbsent(HEADER_FROM_APP_ID, new ArrayList<String>());
101 headers.get(HEADER_FROM_APP_ID).add(UI_APP_NAME);
103 headers.putIfAbsent(HEADER_TRANS_ID, new ArrayList<String>());
104 headers.get(HEADER_TRANS_ID).add(TRANSACTION_ID_PREFIX + NodeUtils.getRandomTxnId());
106 if (endpointConfig.getRestAuthenticationMode() == RestAuthenticationMode.SSL_BASIC) {
108 headers.putIfAbsent(HEADER_AUTHORIZATION, new ArrayList<String>());
109 headers.get(HEADER_AUTHORIZATION).add(getBasicAuthenticationCredentials());
116 protected String getBasicAuthenticationCredentials() {
117 String usernameAndPassword = String.join(":", endpointConfig.getBasicAuthUserName(),
118 endpointConfig.getBasicAuthPassword());
119 return "Basic " + java.util.Base64.getEncoder().encodeToString(usernameAndPassword.getBytes());
122 public OxmEntityLookup getOxmEntityLookup() {
123 return oxmEntityLookup;
126 public void setOxmEntityLookup(OxmEntityLookup oxmEntityLookup) {
127 this.oxmEntityLookup = oxmEntityLookup;
130 protected String getResourceBasePath() {
132 String versionStr = null;
133 if (oxmModelLoader != null) {
134 versionStr = String.valueOf(oxmModelLoader.getLatestVersionNum());
137 return "/aai/v" + versionStr;
141 public static String extractResourcePath(String selflink) {
143 return new URI(selflink).getRawPath();
144 } catch (URISyntaxException uriSyntaxException) {
145 LOG.error(AaiUiMsgs.ERROR_EXTRACTING_RESOURCE_PATH_FROM_LINK,
146 uriSyntaxException.getMessage());
155 * @param resourceUrl the resource url
156 * @return the full url
157 * @throws Exception the exception
159 private String getFullUrl(String resourceUrl) throws Exception {
160 final String basePath = getResourceBasePath();
161 return String.format("https://%s:%s%s%s", endpointConfig.getEndpointIpAddress(),
162 endpointConfig.getEndpointServerPort(), basePath, resourceUrl);
165 public String getGenericQueryForSelfLink(String startNodeType, List<String> queryParams)
168 URIBuilder urlBuilder = new URIBuilder(getFullUrl("/search/generic-query"));
170 for (String queryParam : queryParams) {
171 urlBuilder.addParameter("key", queryParam);
174 urlBuilder.addParameter("start-node-type", startNodeType);
175 urlBuilder.addParameter("include", startNodeType);
177 final String constructedLink = urlBuilder.toString();
179 return constructedLink;
184 public OperationResult getSelfLinksByEntityType(String entityType) throws Exception {
187 * For this one, I want to dynamically construct the nodes-query for self-link discovery as a
188 * utility method that will use the OXM model entity data to drive the query as well.
191 if (entityType == null) {
192 throw new NullPointerException(
193 "Failed to getSelfLinksByEntityType() because entityType is null");
196 OxmEntityDescriptor entityDescriptor = oxmEntityLookup.getEntityDescriptors().get(entityType);
198 if (entityDescriptor == null) {
199 throw new NoSuchElementException("Failed to getSelfLinksByEntityType() because could"
200 + " not find entity descriptor from OXM with type = " + entityType);
204 final String primaryKeyStr =
205 NodeUtils.concatArray(entityDescriptor.getPrimaryKeyAttributeNames(), "/");
207 link = getFullUrl("/search/nodes-query?search-node-type=" + entityType + "&filter="
208 + primaryKeyStr + ":EXISTS");
210 return restClient.get(link, getMessageHeaders(), MediaType.APPLICATION_JSON_TYPE);
214 public OperationResult getSelfLinkForEntity(String entityType, String primaryKeyName,
215 String primaryKeyValue) throws Exception {
217 if (entityType == null) {
218 throw new NullPointerException("Failed to getSelfLinkForEntity() because entityType is null");
221 if (primaryKeyName == null) {
222 throw new NullPointerException(
223 "Failed to getSelfLinkForEntity() because primaryKeyName is null");
226 if (primaryKeyValue == null) {
227 throw new NullPointerException(
228 "Failed to getSelfLinkForEntity() because primaryKeyValue is null");
232 * Try to protect ourselves from illegal URI formatting exceptions caused by characters that
233 * aren't natively supported in a URI, but can be escaped to make them legal.
236 String encodedEntityType = URLEncoder.encode(entityType, "UTF-8");
237 String encodedPrimaryKeyName = URLEncoder.encode(primaryKeyName, "UTF-8");
238 String encodedPrimaryKeyValue = URLEncoder.encode(primaryKeyValue, "UTF-8");
242 if ("service-instance".equals(entityType)) {
244 link = getFullUrl("/search/generic-query?key=" + encodedEntityType + "."
245 + encodedPrimaryKeyName + ":" + encodedPrimaryKeyValue + "&start-node-type="
246 + encodedEntityType + "&include=customer&depth=2");
251 getFullUrl("/search/generic-query?key=" + encodedEntityType + "." + encodedPrimaryKeyName
252 + ":" + encodedPrimaryKeyValue + "&start-node-type=" + encodedEntityType);
256 return queryActiveInventoryWithRetries(link, "application/json",
257 endpointConfig.getNumRequestRetries());
263 * Our retry conditions should be very specific.
266 * @return true, if successful
268 private boolean shouldRetryRequest(OperationResult r) {
274 int rc = r.getResultCode();
289 * Query active inventory.
292 * @param acceptContentType the accept content type
293 * @return the operation result
295 // package protected for test classes instead of private
296 OperationResult queryActiveInventory(String url, String acceptContentType) {
298 return restClient.get(url, getMessageHeaders(), MediaType.APPLICATION_JSON_TYPE);
302 public RestEndpointConfig getEndpointConfig() {
303 return endpointConfig;
306 public void setEndpointConfig(RestEndpointConfig endpointConfig) {
307 this.endpointConfig = endpointConfig;
310 public OperationResult queryActiveInventoryWithRetries(String url, String responseType,
313 OperationResult result = null;
315 for (int retryCount = 0; retryCount < numRetries; retryCount++) {
317 LOG.debug(AaiUiMsgs.QUERY_AAI_RETRY_SEQ, url, String.valueOf(retryCount + 1));
319 result = queryActiveInventory(url, responseType);
322 * Record number of times we have attempted the request to later summarize how many times we
323 * are generally retrying over thousands of messages in a sync.
325 * If the number of retries is surprisingly high, then we need to understand why that is as
326 * the number of retries is also causing a heavier load on AAI beyond the throttling controls
327 * we already have in place in term of the transaction rate controller and number of
328 * parallelized threads per task processor.
331 result.setNumRetries(retryCount);
333 if (!shouldRetryRequest(result)) {
335 result.setFromCache(false);
336 LOG.debug(AaiUiMsgs.QUERY_AAI_RETRY_DONE_SEQ, url, String.valueOf(retryCount + 1));
343 * Sleep between re-tries to be nice to the target system.
346 } catch (InterruptedException exc) {
347 LOG.error(AaiUiMsgs.QUERY_AAI_WAIT_INTERRUPTION, exc.getLocalizedMessage());
350 LOG.error(AaiUiMsgs.QUERY_AAI_RETRY_FAILURE_WITH_SEQ, url, String.valueOf(retryCount + 1));
354 LOG.info(AaiUiMsgs.QUERY_AAI_RETRY_MAXED_OUT, url);
360 public String repairSelfLink(String selfLink) {
361 return repairSelfLink(selfLink, null);
365 * This method adds a scheme, host and port (if missing) to the passed-in URI.
366 * If these parts of the URI are already present, they will not be duplicated.
368 * @param selflink The URI to repair
369 * @param queryParams The query parameters as a single string
370 * @return The corrected URI (i.e. includes a scheme/host/port)
372 public String repairSelfLink(String selflink, String queryParams) {
373 if (selflink == null) {
377 UriBuilder builder = UriBuilder.fromPath(selflink).host(endpointConfig.getEndpointIpAddress())
378 .port(Integer.parseInt(endpointConfig.getEndpointServerPort()));
380 switch (endpointConfig.getRestAuthenticationMode()) {
384 builder.scheme(HTTPS_SCHEME);
389 builder.scheme(HTTP_SCHEME);
393 boolean includeQueryParams = ( (null != queryParams) && (!"".equals(queryParams)) );
395 /* builder.build().toString() will encode special characters to hexadecimal pairs prefixed with a '%'
396 so we're adding the query parameters separately, in their UTF-8 representations, so that
397 characters such as '?', '&', etc. remain intact as needed by the synchronizer */
398 return (builder.build().toString() + (includeQueryParams ? queryParams : ""));