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.aai;
25 import java.io.IOException;
26 import java.net.URLEncoder;
27 import java.nio.ByteBuffer;
28 import java.util.List;
29 import java.util.NoSuchElementException;
31 import org.apache.http.client.utils.URIBuilder;
32 import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor;
33 import org.onap.aai.sparky.config.oxm.OxmModelLoader;
34 import org.onap.aai.sparky.dal.aai.config.ActiveInventoryConfig;
35 import org.onap.aai.sparky.dal.aai.config.ActiveInventoryRestConfig;
36 import org.onap.aai.sparky.dal.aai.enums.RestAuthenticationMode;
37 import org.onap.aai.sparky.dal.exception.ElasticSearchOperationException;
38 import org.onap.aai.sparky.dal.rest.OperationResult;
39 import org.onap.aai.sparky.dal.rest.RestClientBuilder;
40 import org.onap.aai.sparky.dal.rest.RestfulDataAccessor;
41 import org.onap.aai.sparky.logging.AaiUiMsgs;
42 import org.onap.aai.sparky.security.SecurityContextFactory;
43 import org.onap.aai.sparky.util.NodeUtils;
44 import org.onap.aai.cl.api.Logger;
45 import org.onap.aai.cl.eelf.LoggerFactory;
47 import com.sun.jersey.api.client.Client;
48 import com.sun.jersey.api.client.WebResource.Builder;
52 * The Class ActiveInventoryAdapter.
59 public class ActiveInventoryAdapter extends RestfulDataAccessor
60 implements ActiveInventoryDataProvider {
62 private static final Logger LOG =
63 LoggerFactory.getInstance().getLogger(ActiveInventoryAdapter.class);
65 private static final String HEADER_TRANS_ID = "X-TransactionId";
66 private static final String HEADER_FROM_APP_ID = "X-FromAppId";
67 private static final String HEADER_AUTHORIZATION = "Authorization";
69 private static final String TRANSACTION_ID_PREFIX = "txnId-";
70 private static final String UI_APP_NAME = "AAI-UI";
73 private ActiveInventoryConfig config;
76 * Instantiates a new active inventory adapter.
78 * @param restClientBuilder the rest client builder
79 * @throws ElasticSearchOperationException the elastic search operation exception
80 * @throws IOException Signals that an I/O exception has occurred.
82 public ActiveInventoryAdapter(RestClientBuilder restClientBuilder)
83 throws ElasticSearchOperationException, IOException {
84 super(restClientBuilder);
87 this.config = ActiveInventoryConfig.getConfig();
88 } catch (Exception exc) {
89 throw new ElasticSearchOperationException("Error getting active inventory configuration",
93 clientBuilder.setUseHttps(true);
95 clientBuilder.setValidateServerHostname(config.getAaiSslConfig().isValidateServerHostName());
97 SecurityContextFactory sslContextFactory = clientBuilder.getSslContextFactory();
99 sslContextFactory.setServerCertificationChainValidationEnabled(
100 config.getAaiSslConfig().isValidateServerCertificateChain());
102 if (config.getAaiRestConfig().getAuthenticationMode() == RestAuthenticationMode.SSL_CERT) {
103 sslContextFactory.setClientCertFileName(config.getAaiSslConfig().getKeystoreFilename());
104 sslContextFactory.setClientCertPassword(config.getAaiSslConfig().getKeystorePassword());
105 sslContextFactory.setTrustStoreFileName(config.getAaiSslConfig().getTruststoreFilename());
108 clientBuilder.setConnectTimeoutInMs(config.getAaiRestConfig().getConnectTimeoutInMs());
109 clientBuilder.setReadTimeoutInMs(config.getAaiRestConfig().getReadTimeoutInMs());
117 * org.onap.aai.sparky.dal.rest.RestfulDataAccessor#setClientDefaults(com.sun.jersey.api.client.
118 * Client, java.lang.String, java.lang.String, java.lang.String)
121 protected Builder setClientDefaults(Client client, String url, String payloadContentType,
122 String acceptContentType) {
123 Builder builder = super.setClientDefaults(client, url, payloadContentType, acceptContentType);
125 builder = builder.header(HEADER_FROM_APP_ID, UI_APP_NAME);
126 byte bytes[] = new byte[6];
127 txnIdGenerator.nextBytes(bytes);
129 builder.header(HEADER_TRANS_ID, TRANSACTION_ID_PREFIX + ByteBuffer.wrap(bytes).getInt());
131 if (config.getAaiRestConfig().getAuthenticationMode() == RestAuthenticationMode.SSL_BASIC) {
132 builder = builder.header(HEADER_AUTHORIZATION,
133 config.getAaiSslConfig().getBasicAuthenticationCredentials());
142 * @param resourceUrl the resource url
143 * @return the full url
144 * @throws Exception the exception
146 private String getFullUrl(String resourceUrl) throws Exception {
147 ActiveInventoryRestConfig aaiRestConfig = ActiveInventoryConfig.getConfig().getAaiRestConfig();
148 final String host = aaiRestConfig.getHost();
149 final String port = aaiRestConfig.getPort();
150 final String basePath = aaiRestConfig.getResourceBasePath();
151 return String.format("https://%s:%s%s%s", host, port, basePath, resourceUrl);
154 public String getGenericQueryForSelfLink(String startNodeType, List<String> queryParams)
157 URIBuilder urlBuilder = new URIBuilder(getFullUrl("/search/generic-query"));
159 for (String queryParam : queryParams) {
160 urlBuilder.addParameter("key", queryParam);
163 urlBuilder.addParameter("start-node-type", startNodeType);
164 urlBuilder.addParameter("include", startNodeType);
166 final String constructedLink = urlBuilder.toString();
168 // TODO: debug log for constructed link
170 return constructedLink;
179 * org.onap.aai.sparky.dal.aai.ActiveInventoryDataProvider#getSelfLinksByEntityType(java.lang.
183 public OperationResult getSelfLinksByEntityType(String entityType) throws Exception {
186 * For this one, I want to dynamically construct the nodes-query for self-link discovery as a
187 * utility method that will use the OXM model entity data to drive the query as well.
190 if (entityType == null) {
191 throw new NullPointerException(
192 "Failed to getSelfLinksByEntityType() because entityType is null");
195 OxmEntityDescriptor entityDescriptor =
196 OxmModelLoader.getInstance().getEntityDescriptor(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.getPrimaryKeyAttributeName(), "/");
207 link = getFullUrl("/search/nodes-query?search-node-type=" + entityType + "&filter="
208 + primaryKeyStr + ":EXISTS");
212 return doGet(link, "application/json");
220 * org.onap.aai.sparky.dal.aai.ActiveInventoryDataProvider#getSelfLinkForEntity(java.lang.String,
221 * java.lang.String, java.lang.String)
224 public OperationResult getSelfLinkForEntity(String entityType, String primaryKeyName,
225 String primaryKeyValue) throws Exception {
227 if (entityType == null) {
228 throw new NullPointerException("Failed to getSelfLinkForEntity() because entityType is null");
231 if (primaryKeyName == null) {
232 throw new NullPointerException(
233 "Failed to getSelfLinkForEntity() because primaryKeyName is null");
236 if (primaryKeyValue == null) {
237 throw new NullPointerException(
238 "Failed to getSelfLinkForEntity() because primaryKeyValue is null");
243 * Try to protect ourselves from illegal URI formatting exceptions caused by characters that
244 * aren't natively supported in a URI, but can be escaped to make them legal.
247 String encodedEntityType = URLEncoder.encode(entityType, "UTF-8");
248 String encodedPrimaryKeyName = URLEncoder.encode(primaryKeyName, "UTF-8");
249 String encodedPrimaryKeyValue = URLEncoder.encode(primaryKeyValue, "UTF-8");
253 if ("service-instance".equals(entityType)) {
255 link = getFullUrl("/search/generic-query?key=" + encodedEntityType + "."
256 + encodedPrimaryKeyName + ":" + encodedPrimaryKeyValue + "&start-node-type="
257 + encodedEntityType + "&include=customer&depth=2");
262 getFullUrl("/search/generic-query?key=" + encodedEntityType + "." + encodedPrimaryKeyName
263 + ":" + encodedPrimaryKeyValue + "&start-node-type=" + encodedEntityType);
267 return queryActiveInventoryWithRetries(link, "application/json",
268 this.config.getAaiRestConfig().getNumRequestRetries());
274 * Our retry conditions should be very specific.
277 * @return true, if successful
279 private boolean shouldRetryRequest(OperationResult r) {
285 int rc = r.getResultCode();
300 * Query active inventory.
303 * @param acceptContentType the accept content type
304 * @return the operation result
306 // package protected for test classes instead of private
307 OperationResult queryActiveInventory(String url, String acceptContentType) {
308 return doGet(url, acceptContentType);
315 * org.onap.aai.sparky.dal.aai.ActiveInventoryDataProvider#queryActiveInventoryWithRetries(java.
316 * lang.String, java.lang.String, int)
319 public OperationResult queryActiveInventoryWithRetries(String url, String responseType,
322 OperationResult result = null;
324 for (int x = 0; x < numRetries; x++) {
326 LOG.debug(AaiUiMsgs.QUERY_AAI_RETRY_SEQ, url, String.valueOf(x + 1));
328 result = queryActiveInventory(url, responseType);
331 * Record number of times we have attempted the request to later summarize how many times we
332 * are generally retrying over thousands of messages in a sync.
334 * If the number of retries is surprisingly high, then we need to understand why that is as
335 * the number of retries is also causing a heavier load on AAI beyond the throttling controls
336 * we already have in place in term of the transaction rate controller and number of
337 * parallelized threads per task processor.
340 result.setNumRequestRetries(x);
342 if (!shouldRetryRequest(result)) {
345 * if (myConfig.getAaiRestConfig().isCacheEnabled()) {
347 * CachedHttpRequest cachedRequest = new CachedHttpRequest();
348 * cachedRequest.setHttpRequestMethod("GET"); cachedRequest.setPayload("");
349 * cachedRequest.setPayloadMimeType(""); cachedRequest.setUrl(url);
350 * cachedRequest.setOperationType( TransactionStorageType.ACTIVE_INVENTORY_QUERY.getIndex()
353 * CachedHttpResponse cachedResponse = new CachedHttpResponse();
354 * cachedResponse.setPayload(result.getResult());
355 * cachedResponse.setPayloadMimeType("application/json");
356 * cachedResponse.setStatusCode(result.getResultCode());
358 * CachedHttpTransaction txn = new CachedHttpTransaction(cachedRequest, cachedResponse);
359 * storageProvider.persistTransaction(txn);
365 result.setResolvedLinkFromServer(true);
366 LOG.debug(AaiUiMsgs.QUERY_AAI_RETRY_DONE_SEQ, url, String.valueOf(x + 1));
373 * Sleep between re-tries to be nice to the target system.
376 } catch (InterruptedException exc) {
377 LOG.error(AaiUiMsgs.QUERY_AAI_WAIT_INTERRUPTION, exc.getLocalizedMessage());
380 LOG.error(AaiUiMsgs.QUERY_AAI_RETRY_FAILURE_WITH_SEQ, url, String.valueOf(x + 1));
384 result.setResolvedLinkFailure(true);
385 LOG.info(AaiUiMsgs.QUERY_AAI_RETRY_MAXED_OUT, url);
394 * @see org.onap.aai.sparky.dal.rest.RestfulDataAccessor#shutdown()
397 public void shutdown() {
398 // TODO Auto-generated method stub
400 if (entityCache != null) {
401 entityCache.shutdown();