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.Encryptor;
51 import org.onap.aai.sparky.util.NodeUtils;
52 import org.onap.aai.sparky.viewandinspect.config.SparkyConstants;
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;
94 * Add support for de-obfuscating basic auth password (if obfuscated)
97 if (endpointConfig.getRestAuthenticationMode() == RestAuthenticationMode.SSL_BASIC) {
98 String basicAuthPassword = endpointConfig.getBasicAuthPassword();
100 if (basicAuthPassword != null
101 && basicAuthPassword.startsWith(SparkyConstants.OBFUSCATION_PREFIX)) {
102 Encryptor enc = new Encryptor();
103 endpointConfig.setBasicAuthPassword(enc.decryptValue(basicAuthPassword));
107 this.restClient = RestClientFactory.buildClient(endpointConfig);
111 protected Map<String, List<String>> getMessageHeaders() {
113 Map<String, List<String>> headers = new HashMap<String, List<String>>();
115 headers.putIfAbsent(HEADER_FROM_APP_ID, new ArrayList<String>());
116 headers.get(HEADER_FROM_APP_ID).add(UI_APP_NAME);
118 headers.putIfAbsent(HEADER_TRANS_ID, new ArrayList<String>());
119 headers.get(HEADER_TRANS_ID).add(TRANSACTION_ID_PREFIX + NodeUtils.getRandomTxnId());
121 if (endpointConfig.getRestAuthenticationMode() == RestAuthenticationMode.SSL_BASIC) {
122 headers.putIfAbsent(HEADER_AUTHORIZATION, new ArrayList<String>());
123 headers.get(HEADER_AUTHORIZATION).add(getBasicAuthenticationCredentials());
129 protected String getBasicAuthenticationCredentials() {
131 String usernameAndPassword = String.join(":", endpointConfig.getBasicAuthUserName(),
132 endpointConfig.getBasicAuthPassword());
133 return "Basic " + java.util.Base64.getEncoder().encodeToString(usernameAndPassword.getBytes());
136 public OxmEntityLookup getOxmEntityLookup() {
137 return oxmEntityLookup;
140 public void setOxmEntityLookup(OxmEntityLookup oxmEntityLookup) {
141 this.oxmEntityLookup = oxmEntityLookup;
144 protected String getResourceBasePath() {
146 String versionStr = null;
147 if (oxmModelLoader != null) {
148 versionStr = String.valueOf(oxmModelLoader.getLatestVersionNum());
151 return "/aai/" + versionStr.toLowerCase();
155 public static String extractResourcePath(String selflink) {
157 return new URI(selflink).getRawPath();
158 } catch (URISyntaxException uriSyntaxException) {
159 LOG.error(AaiUiMsgs.ERROR_EXTRACTING_RESOURCE_PATH_FROM_LINK,
160 uriSyntaxException.getMessage());
169 * @param resourceUrl the resource url
170 * @return the full url
171 * @throws Exception the exception
173 private String getFullUrl(String resourceUrl) throws Exception {
174 final String basePath = getResourceBasePath();
175 return String.format("https://%s:%s%s%s", endpointConfig.getEndpointIpAddress(),
176 endpointConfig.getEndpointServerPort(), basePath, resourceUrl);
179 public String getGenericQueryForSelfLink(String startNodeType, List<String> queryParams)
182 URIBuilder urlBuilder = new URIBuilder(getFullUrl("/search/generic-query"));
184 for (String queryParam : queryParams) {
185 urlBuilder.addParameter("key", queryParam);
188 urlBuilder.addParameter("start-node-type", startNodeType);
189 urlBuilder.addParameter("include", startNodeType);
191 final String constructedLink = urlBuilder.toString();
193 return constructedLink;
198 public OperationResult getSelfLinksByEntityType(String entityType) throws Exception {
201 * For this one, I want to dynamically construct the nodes-query for self-link discovery as a
202 * utility method that will use the OXM model entity data to drive the query as well.
205 if (entityType == null) {
206 throw new NullPointerException(
207 "Failed to getSelfLinksByEntityType() because entityType is null");
210 OxmEntityDescriptor entityDescriptor = oxmEntityLookup.getEntityDescriptors().get(entityType);
212 if (entityDescriptor == null) {
213 throw new NoSuchElementException("Failed to getSelfLinksByEntityType() because could"
214 + " not find entity descriptor from OXM with type = " + entityType);
218 final String primaryKeyStr =
219 NodeUtils.concatArray(entityDescriptor.getPrimaryKeyAttributeNames(), "/");
221 link = getFullUrl("/search/nodes-query?search-node-type=" + entityType + "&filter="
222 + primaryKeyStr + ":EXISTS");
225 return restClient.get(link, getMessageHeaders(), MediaType.APPLICATION_JSON_TYPE);
229 public OperationResult getSelfLinkForEntity(String entityType, String primaryKeyName,
230 String primaryKeyValue) throws Exception {
232 if (entityType == null) {
233 throw new NullPointerException("Failed to getSelfLinkForEntity() because entityType is null");
236 if (primaryKeyName == null) {
237 throw new NullPointerException(
238 "Failed to getSelfLinkForEntity() because primaryKeyName is null");
241 if (primaryKeyValue == null) {
242 throw new NullPointerException(
243 "Failed to getSelfLinkForEntity() because primaryKeyValue is null");
247 * Try to protect ourselves from illegal URI formatting exceptions caused by characters that
248 * aren't natively supported in a URI, but can be escaped to make them legal.
251 String encodedEntityType = URLEncoder.encode(entityType, "UTF-8");
252 String encodedPrimaryKeyName = URLEncoder.encode(primaryKeyName, "UTF-8");
253 String encodedPrimaryKeyValue = URLEncoder.encode(primaryKeyValue, "UTF-8");
257 if ("service-instance".equals(entityType)) {
259 link = getFullUrl("/search/generic-query?key=" + encodedEntityType + "."
260 + encodedPrimaryKeyName + ":" + encodedPrimaryKeyValue + "&start-node-type="
261 + encodedEntityType + "&include=customer&depth=2");
266 getFullUrl("/search/generic-query?key=" + encodedEntityType + "." + encodedPrimaryKeyName
267 + ":" + encodedPrimaryKeyValue + "&start-node-type=" + encodedEntityType);
271 return queryActiveInventoryWithRetries(link, "application/json",
272 endpointConfig.getNumRequestRetries());
278 * Our retry conditions should be very specific.
281 * @return true, if successful
283 private boolean shouldRetryRequest(OperationResult r) {
289 int rc = r.getResultCode();
304 * Query active inventory.
307 * @param acceptContentType the accept content type
308 * @return the operation result
310 // package protected for test classes instead of private
311 OperationResult queryActiveInventory(String url, String acceptContentType) {
313 return restClient.get(url, getMessageHeaders(), MediaType.APPLICATION_JSON_TYPE);
317 public RestEndpointConfig getEndpointConfig() {
318 return endpointConfig;
321 public void setEndpointConfig(RestEndpointConfig endpointConfig) {
322 this.endpointConfig = endpointConfig;
325 public OperationResult queryActiveInventoryWithRetries(String url, String responseType,
328 OperationResult result = null;
330 for (int retryCount = 0; retryCount < numRetries; retryCount++) {
332 LOG.debug(AaiUiMsgs.QUERY_AAI_RETRY_SEQ, url, String.valueOf(retryCount + 1));
334 result = queryActiveInventory(url, responseType);
337 * Record number of times we have attempted the request to later summarize how many times we
338 * are generally retrying over thousands of messages in a sync.
340 * If the number of retries is surprisingly high, then we need to understand why that is as
341 * the number of retries is also causing a heavier load on AAI beyond the throttling controls
342 * we already have in place in term of the transaction rate controller and number of
343 * parallelized threads per task processor.
346 result.setNumRetries(retryCount);
348 if (!shouldRetryRequest(result)) {
350 result.setFromCache(false);
351 LOG.debug(AaiUiMsgs.QUERY_AAI_RETRY_DONE_SEQ, url, String.valueOf(retryCount + 1));
358 * Sleep between re-tries to be nice to the target system.
361 } catch (InterruptedException exc) {
362 LOG.error(AaiUiMsgs.QUERY_AAI_WAIT_INTERRUPTION, exc.getLocalizedMessage());
363 Thread.currentThread().interrupt();
366 LOG.error(AaiUiMsgs.QUERY_AAI_RETRY_FAILURE_WITH_SEQ, url, String.valueOf(retryCount + 1));
370 LOG.info(AaiUiMsgs.QUERY_AAI_RETRY_MAXED_OUT, url);
376 public String repairSelfLink(String selfLink) {
377 return repairSelfLink(selfLink, null);
381 * This method adds a scheme, host and port (if missing) to the passed-in URI.
382 * If these parts of the URI are already present, they will not be duplicated.
384 * @param selflink The URI to repair
385 * @param queryParams The query parameters as a single string
386 * @return The corrected URI (i.e. includes a scheme/host/port)
388 public String repairSelfLink(String selflink, String queryParams) {
389 if (selflink == null) {
393 UriBuilder builder = UriBuilder.fromPath(selflink).host(endpointConfig.getEndpointIpAddress())
394 .port(Integer.parseInt(endpointConfig.getEndpointServerPort()));
396 switch (endpointConfig.getRestAuthenticationMode()) {
400 builder.scheme(HTTPS_SCHEME);
405 builder.scheme(HTTP_SCHEME);
409 boolean includeQueryParams = ( (null != queryParams) && (!"".equals(queryParams)) );
411 /* builder.build().toString() will encode special characters to hexadecimal pairs prefixed with a '%'
412 so we're adding the query parameters separately, in their UTF-8 representations, so that
413 characters such as '?', '&', etc. remain intact as needed by the synchronizer */
414 return (builder.build().toString() + (includeQueryParams ? queryParams : ""));