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.crossentityreference.sync;
 
  23 import static java.util.concurrent.CompletableFuture.supplyAsync;
 
  25 import java.io.IOException;
 
  26 import java.util.ArrayList;
 
  27 import java.util.Collection;
 
  28 import java.util.Deque;
 
  29 import java.util.Iterator;
 
  30 import java.util.List;
 
  32 import java.util.concurrent.ConcurrentHashMap;
 
  33 import java.util.concurrent.ConcurrentLinkedDeque;
 
  34 import java.util.concurrent.ExecutorService;
 
  35 import java.util.function.Supplier;
 
  37 import org.onap.aai.cl.api.Logger;
 
  38 import org.onap.aai.cl.eelf.LoggerFactory;
 
  39 import org.onap.aai.cl.mdc.MdcContext;
 
  40 import org.onap.aai.restclient.client.OperationResult;
 
  41 import org.onap.aai.sparky.config.oxm.CrossEntityReference;
 
  42 import org.onap.aai.sparky.config.oxm.CrossEntityReferenceDescriptor;
 
  43 import org.onap.aai.sparky.config.oxm.CrossEntityReferenceLookup;
 
  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.SearchableEntityLookup;
 
  47 import org.onap.aai.sparky.config.oxm.SearchableOxmEntityDescriptor;
 
  48 import org.onap.aai.sparky.dal.ActiveInventoryAdapter;
 
  49 import org.onap.aai.sparky.dal.NetworkTransaction;
 
  50 import org.onap.aai.sparky.dal.rest.HttpMethod;
 
  51 import org.onap.aai.sparky.logging.AaiUiMsgs;
 
  52 import org.onap.aai.sparky.sync.AbstractEntitySynchronizer;
 
  53 import org.onap.aai.sparky.sync.IndexSynchronizer;
 
  54 import org.onap.aai.sparky.sync.SynchronizerConstants;
 
  55 import org.onap.aai.sparky.sync.config.ElasticSearchSchemaConfig;
 
  56 import org.onap.aai.sparky.sync.config.NetworkStatisticsConfig;
 
  57 import org.onap.aai.sparky.sync.entity.IndexableCrossEntityReference;
 
  58 import org.onap.aai.sparky.sync.entity.MergableEntity;
 
  59 import org.onap.aai.sparky.sync.entity.SelfLinkDescriptor;
 
  60 import org.onap.aai.sparky.sync.enumeration.OperationState;
 
  61 import org.onap.aai.sparky.sync.enumeration.SynchronizerState;
 
  62 import org.onap.aai.sparky.sync.task.PerformActiveInventoryRetrieval;
 
  63 import org.onap.aai.sparky.sync.task.PerformElasticSearchPut;
 
  64 import org.onap.aai.sparky.sync.task.PerformElasticSearchRetrieval;
 
  65 import org.onap.aai.sparky.sync.task.PerformElasticSearchUpdate;
 
  66 import org.onap.aai.sparky.util.NodeUtils;
 
  69 import com.fasterxml.jackson.core.JsonProcessingException;
 
  70 import com.fasterxml.jackson.databind.JsonNode;
 
  71 import com.fasterxml.jackson.databind.ObjectReader;
 
  72 import com.fasterxml.jackson.databind.node.ArrayNode;
 
  75  * The Class CrossEntityReferenceSynchronizer.
 
  77 public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer
 
  78     implements IndexSynchronizer {
 
  81    * The Class RetryCrossEntitySyncContainer.
 
  83   private class RetryCrossEntitySyncContainer {
 
  84     NetworkTransaction txn;
 
  85     IndexableCrossEntityReference icer;
 
  88      * Instantiates a new retry cross entity sync container.
 
  91      * @param icer the icer
 
  93     public RetryCrossEntitySyncContainer(NetworkTransaction txn,
 
  94         IndexableCrossEntityReference icer) {
 
  99     public NetworkTransaction getNetworkTransaction() {
 
 103     public IndexableCrossEntityReference getIndexableCrossEntityReference() {
 
 108   private static final Logger LOG =
 
 109       LoggerFactory.getInstance().getLogger(CrossEntityReferenceSynchronizer.class);
 
 111   private static final String SERVICE_INSTANCE = "service-instance";
 
 113   private Deque<SelfLinkDescriptor> selflinks;
 
 114   private Deque<RetryCrossEntitySyncContainer> retryQueue;
 
 115   private Map<String, Integer> retryLimitTracker;
 
 116   private boolean isAllWorkEnumerated;
 
 117   protected ExecutorService esPutExecutor;
 
 118   private CrossEntityReferenceLookup crossEntityReferenceLookup;
 
 119   private OxmEntityLookup oxmEntityLookup;
 
 120   private SearchableEntityLookup searchableEntityLookup;
 
 124    * Instantiates a new cross entity reference synchronizer.
 
 126    * @throws Exception the exception
 
 128   public CrossEntityReferenceSynchronizer(ElasticSearchSchemaConfig schemaConfig,
 
 129       int internalSyncWorkers, int aaiWorkers, int esWorkers, NetworkStatisticsConfig aaiStatConfig,
 
 130       NetworkStatisticsConfig esStatConfig, CrossEntityReferenceLookup crossEntityReferenceLookup,
 
 131       OxmEntityLookup oxmEntityLookup, SearchableEntityLookup searchableEntityLookup) throws Exception {
 
 132     super(LOG, "CERS", internalSyncWorkers, aaiWorkers, esWorkers, schemaConfig.getIndexName(),
 
 133         aaiStatConfig, esStatConfig);
 
 134     this.crossEntityReferenceLookup = crossEntityReferenceLookup;
 
 135     this.oxmEntityLookup = oxmEntityLookup;
 
 136     this.searchableEntityLookup = searchableEntityLookup;
 
 137     this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
 
 138     this.retryQueue = new ConcurrentLinkedDeque<RetryCrossEntitySyncContainer>();
 
 139     this.retryLimitTracker = new ConcurrentHashMap<String, Integer>();
 
 140     this.synchronizerName = "Cross Reference Entity Synchronizer";
 
 141     this.isAllWorkEnumerated = false;
 
 142     this.esPutExecutor = NodeUtils.createNamedExecutor("CERS-ES-PUT", 5, LOG);
 
 143     this.aaiEntityStats.intializeEntityCounters(
 
 144         crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().keySet());
 
 146     this.esEntityStats.intializeEntityCounters(
 
 147         crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().keySet());
 
 148     this.syncDurationInMs = -1;
 
 152    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
 
 155   public OperationState doSync() {
 
 156     this.syncDurationInMs = -1;
 
 157         String txnID = NodeUtils.getRandomTxnId();
 
 158     MdcContext.initialize(txnID, "CrossEntitySynchronizer", "", "Sync", "");
 
 161     syncStartedTimeStampInMs = System.currentTimeMillis();
 
 163     return OperationState.OK;
 
 167   public SynchronizerState getState() {
 
 169       return SynchronizerState.PERFORMING_SYNCHRONIZATION;
 
 172     return SynchronizerState.IDLE;
 
 176    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
 
 179   public String getStatReport(boolean showFinalReport) {
 
 180     syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
 
 181     return getStatReport(syncDurationInMs, showFinalReport);
 
 185    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
 
 188   public void shutdown() {
 
 189     this.shutdownExecutors();
 
 193   protected boolean isSyncDone() {
 
 194     int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
 
 196     if (totalWorkOnHand > 0 || !isAllWorkEnumerated) {
 
 206    * @return the operation state
 
 208   private OperationState launchSyncFlow() {
 
 209         final Map<String,String> contextMap = MDC.getCopyOfContextMap();
 
 210     Map<String, CrossEntityReferenceDescriptor> descriptorMap =
 
 211         crossEntityReferenceLookup.getCrossReferenceEntityDescriptors();
 
 213     if (descriptorMap.isEmpty()) {
 
 214       LOG.error(AaiUiMsgs.ERROR_LOADING_OXM);
 
 216       return OperationState.ERROR;
 
 219     Collection<String> syncTypes = descriptorMap.keySet();
 
 224        * launch a parallel async thread to process the documents for each entity-type (to max the of
 
 225        * the configured executor anyway)
 
 228       aaiWorkOnHand.set(syncTypes.size());
 
 230       for (String key : syncTypes) {
 
 232         supplyAsync(new Supplier<Void>() {
 
 236                 MDC.setContextMap(contextMap);
 
 237             OperationResult typeLinksResult = null;
 
 239               typeLinksResult = aaiAdapter.getSelfLinksByEntityType(key);
 
 240               aaiWorkOnHand.decrementAndGet();
 
 241               processEntityTypeSelfLinks(typeLinksResult);
 
 242             } catch (Exception exc) {
 
 243               LOG.error(AaiUiMsgs.ERROR_GENERIC,
 
 244                   "An error occurred processing entity selflinks. Error: " + exc.getMessage());
 
 250         }, aaiExecutor).whenComplete((result, error) -> {
 
 252             LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, error.getMessage());
 
 257       while (aaiWorkOnHand.get() != 0) {
 
 259         if (LOG.isDebugEnabled()) {
 
 260           LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
 
 266       aaiWorkOnHand.set(selflinks.size());
 
 267       isAllWorkEnumerated = true;
 
 270       while (!isSyncDone()) {
 
 276        * Make sure we don't hang on to retries that failed which could cause issues during future
 
 279       retryLimitTracker.clear();
 
 281     } catch (Exception exc) {
 
 282       LOG.error(AaiUiMsgs.ERROR_GENERIC,
 
 283           "An error occurred during entity synchronization. Error: " + exc.getMessage());
 
 287     return OperationState.OK;
 
 293   private void performSync() {
 
 294     while (selflinks.peek() != null) {
 
 296       SelfLinkDescriptor linkDescriptor = selflinks.poll();
 
 297       aaiWorkOnHand.decrementAndGet();
 
 299       CrossEntityReferenceDescriptor descriptor = null;
 
 301       if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
 
 303         descriptor = crossEntityReferenceLookup.getCrossReferenceEntityDescriptors()
 
 304             .get(linkDescriptor.getEntityType());
 
 306         if (descriptor == null) {
 
 307           LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
 
 308           // go to next element in iterator
 
 312         if (descriptor.hasCrossEntityReferences()) {
 
 314           NetworkTransaction txn = new NetworkTransaction();
 
 315           txn.setDescriptor(descriptor);
 
 316           txn.setLink(linkDescriptor.getSelfLink());
 
 317           txn.setQueryParameters(linkDescriptor.getDepthModifier());
 
 318           txn.setOperationType(HttpMethod.GET);
 
 319           txn.setEntityType(linkDescriptor.getEntityType());
 
 321           aaiWorkOnHand.incrementAndGet();
 
 323           supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiAdapter), aaiExecutor)
 
 324               .whenComplete((result, error) -> {
 
 326                 aaiWorkOnHand.decrementAndGet();
 
 329                   LOG.error(AaiUiMsgs.SELF_LINK_GET, error.getLocalizedMessage());
 
 331                   if (result == null) {
 
 332                     LOG.error(AaiUiMsgs.SELF_LINK_CROSS_REF_SYNC);
 
 334                     updateActiveInventoryCounters(result);
 
 335                     fetchDocumentForUpsert(result);
 
 345    * Process entity type self links.
 
 347    * @param operationResult the operation result
 
 349   private void processEntityTypeSelfLinks(OperationResult operationResult) {
 
 351     final String jsonResult = operationResult.getResult();
 
 353     if (jsonResult != null && jsonResult.length() > 0) {
 
 356         JsonNode rootNode = mapper.readTree(jsonResult);
 
 357         JsonNode resultData = rootNode.get("result-data");
 
 359         if (resultData.isArray()) {
 
 360           ArrayNode resultDataArrayNode = (ArrayNode) resultData;
 
 362           Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
 
 364           while (elementIterator.hasNext()) {
 
 365             JsonNode element = elementIterator.next();
 
 367             final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
 
 368             final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
 
 370             if (resourceType != null && resourceLink != null) {
 
 371               CrossEntityReferenceDescriptor descriptor = crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().get(resourceType);
 
 373               if (descriptor == null) {
 
 374                 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
 
 375                 // go to next element in iterator
 
 378               if (descriptor.hasCrossEntityReferences()) {
 
 379                 selflinks.add(new SelfLinkDescriptor(
 
 380                         resourceLink, SynchronizerConstants.DEPTH_ALL_MODIFIER, resourceType));
 
 385       } catch (IOException exc) {
 
 386         // TODO // TODO -> LOG, waht should be logged here?
 
 394    * By providing the entity type and a json node for the entity, determine the
 
 395    * primary key name(s) + primary key value(s) sufficient to build an entity query string
 
 396    * of the following format:
 
 398    *      <entityType>.<primaryKeyNames>:<primaryKeyValues>
 
 400    * @return - a composite string in the above format or null
 
 402   private String determineEntityQueryString(String entityType, JsonNode entityJsonNode) {
 
 404     OxmEntityDescriptor entityDescriptor =
 
 405         oxmEntityLookup.getEntityDescriptors().get(entityType);
 
 407     String queryString = null;
 
 409     if ( entityDescriptor != null ) {
 
 411       final List<String> primaryKeyNames = entityDescriptor.getPrimaryKeyAttributeNames();
 
 412       final List<String> keyValues = new ArrayList<String>();
 
 413       NodeUtils.extractFieldValuesFromObject(entityJsonNode, primaryKeyNames, keyValues);
 
 415       queryString = entityType + "." + NodeUtils.concatArray(primaryKeyNames,"/") + ":" + NodeUtils.concatArray(keyValues);
 
 425    * Fetch document for upsert.
 
 429   private void fetchDocumentForUpsert(NetworkTransaction txn) {
 
 431     if (!txn.getOperationResult().wasSuccessful()) {
 
 432       LOG.error(AaiUiMsgs.SELF_LINK_GET, txn.getOperationResult().getResult());
 
 436     CrossEntityReferenceDescriptor cerDescriptor = crossEntityReferenceLookup
 
 437         .getCrossReferenceEntityDescriptors().get(txn.getDescriptor().getEntityName());
 
 439     if (cerDescriptor != null && cerDescriptor.hasCrossEntityReferences()) {
 
 441       final String jsonResult = txn.getOperationResult().getResult();
 
 443       if (jsonResult != null && jsonResult.length() > 0) {
 
 446          * Here's what we are going to do:
 
 448          * <li>Extract primary key name and value from the parent type.
 
 449          * <li>Extract the primary key and value from the nested child instance.
 
 450          * <li>Build a generic query to discover the self-link for the nested-child-instance using
 
 452          * <li>Set the self-link on the child.
 
 453          * <li>Generate the id that will allow the elastic-search upsert to work.
 
 454          * <li>Rinse and repeat.
 
 457           CrossEntityReference cerDefinition = cerDescriptor.getCrossEntityReference();
 
 459           if (cerDefinition != null) {
 
 460             JsonNode convertedNode = null;
 
 462               convertedNode = NodeUtils.convertJsonStrToJsonNode(txn.getOperationResult().getResult());
 
 464               final String parentEntityQueryString = determineEntityQueryString(txn.getEntityType(), convertedNode);
 
 466               List<String> extractedParentEntityAttributeValues = new ArrayList<String>();
 
 468               NodeUtils.extractFieldValuesFromObject(convertedNode,
 
 469                   cerDefinition.getReferenceAttributes(),
 
 470                   extractedParentEntityAttributeValues);
 
 472               List<JsonNode> nestedTargetEntityInstances = new ArrayList<JsonNode>();
 
 473               NodeUtils.extractObjectsByKey(convertedNode, cerDefinition.getTargetEntityType(),
 
 474                   nestedTargetEntityInstances);
 
 476               for (JsonNode targetEntityInstance : nestedTargetEntityInstances) {
 
 478                 if (cerDescriptor != null) {
 
 480                   String childEntityType = cerDefinition.getTargetEntityType();
 
 481                   OxmEntityDescriptor childDesciptor = oxmEntityLookup.getEntityDescriptors().get(childEntityType);
 
 483                   List<String> childPrimaryKeyNames = null;
 
 485                   if (childDesciptor != null) {
 
 486                     childPrimaryKeyNames = childDesciptor.getPrimaryKeyAttributeNames();
 
 488                     childPrimaryKeyNames = new ArrayList<String>();
 
 491                   List<String> childKeyValues = new ArrayList<String>();
 
 492                   NodeUtils.extractFieldValuesFromObject(targetEntityInstance, childPrimaryKeyNames, childKeyValues);
 
 494                   String childEntityQueryKeyString = childEntityType + "." + NodeUtils.concatArray(childPrimaryKeyNames,"/") + ":" + NodeUtils.concatArray(childKeyValues);
 
 497                    * Build generic-query to query child instance self-link from AAI
 
 499                   List<String> orderedQueryKeyParams = new ArrayList<String>();
 
 502                    * At present, there is an issue with resolving the self-link using the
 
 503                    * generic-query with nothing more than the service-instance identifier and the
 
 504                    * service-subscription. There is another level of detail we don't have access to
 
 505                    * unless we parse it out of the service-subscription self-link, which is a
 
 506                    * coupling I would like to avoid. Fortunately, there is a workaround, but only
 
 507                    * for service-instances, which is presently our only use-case for the
 
 508                    * cross-entity-reference in R1707. Going forwards hopefully there will be other
 
 509                    * ways to resolve a child self-link using parental embedded meta data that we
 
 510                    * don't currently have.
 
 512                    * The work-around with the service-instance entity-type is that it's possible to
 
 513                    * request the self-link using only the service-instance-id because of a
 
 514                    * historical AAI functional query requirement that it be possible to query a
 
 515                    * service-instance only by it's service-instance-id. This entity type is the only
 
 516                    * one in the system that can be queried this way which makes it a very limited
 
 517                    * workaround, but good enough for the current release.
 
 520                   if (SERVICE_INSTANCE.equals(childEntityType)) {
 
 521                     orderedQueryKeyParams.clear();
 
 522                     orderedQueryKeyParams.add(childEntityQueryKeyString);
 
 524                     orderedQueryKeyParams.add(parentEntityQueryString);
 
 525                     orderedQueryKeyParams.add(childEntityQueryKeyString);
 
 528                   String genericQueryStr = null;
 
 530                     genericQueryStr = aaiAdapter.getGenericQueryForSelfLink(childEntityType, orderedQueryKeyParams);
 
 532                     if (genericQueryStr != null) {
 
 533                       aaiWorkOnHand.incrementAndGet();
 
 535                       OperationResult aaiQueryResult = aaiAdapter.queryActiveInventoryWithRetries(
 
 536                           genericQueryStr, "application/json",
 
 537                           aaiAdapter.getEndpointConfig().getNumRequestRetries());
 
 539                       aaiWorkOnHand.decrementAndGet();
 
 541                       if (aaiQueryResult!= null && aaiQueryResult.wasSuccessful()) {
 
 543                         Collection<JsonNode> entityLinks = new ArrayList<JsonNode>();
 
 544                         JsonNode genericQueryResult = null;
 
 546                           genericQueryResult = NodeUtils.convertJsonStrToJsonNode(aaiQueryResult.getResult());
 
 548                           if ( genericQueryResult != null ) {
 
 550                             NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link", entityLinks);
 
 552                             String selfLink = null;
 
 554                             if (entityLinks.size() != 1) {
 
 556                                * an ambiguity exists where we can't reliably determine the self
 
 557                                * link, this should be a permanent error
 
 559                               LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_SELFLINK_AMBIGUITY, String.valueOf(entityLinks.size()));
 
 561                             selfLink = ((JsonNode) entityLinks.toArray()[0]).asText();
 
 564                             IndexableCrossEntityReference icer =
 
 565                                 getPopulatedDocument(targetEntityInstance, cerDescriptor);
 
 567                             for (String parentCrossEntityReferenceAttributeValue : extractedParentEntityAttributeValues) {
 
 568                               icer.addCrossEntityReferenceValue(
 
 569                                   parentCrossEntityReferenceAttributeValue);
 
 572                             icer.setLink(ActiveInventoryAdapter.extractResourcePath(selfLink));
 
 578                               link = elasticSearchAdapter
 
 579                                   .buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
 
 580                             } catch (Exception exc) {
 
 581                               LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY,
 
 582                                   exc.getLocalizedMessage());
 
 586                               NetworkTransaction n2 = new NetworkTransaction();
 
 588                               n2.setEntityType(txn.getEntityType());
 
 589                               n2.setDescriptor(txn.getDescriptor());
 
 590                               n2.setOperationType(HttpMethod.GET);
 
 592                               esWorkOnHand.incrementAndGet();
 
 595                                   new PerformElasticSearchRetrieval(n2, elasticSearchAdapter),
 
 596                                   esExecutor).whenComplete((result, error) -> {
 
 598                                     esWorkOnHand.decrementAndGet();
 
 601                                       LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED,
 
 602                                           error.getLocalizedMessage());
 
 604                                       updateElasticSearchCounters(result);
 
 605                                       performDocumentUpsert(result, icer);
 
 612                             LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DURING_AAI_RESPONSE_CONVERSION);
 
 615                         } catch (Exception exc) {
 
 616                           LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(), exc.getLocalizedMessage());
 
 620                         String result = aaiQueryResult != null ? aaiQueryResult.getResult() : "unknown";
 
 621                         String message = "Entity sync failed because AAI query failed with error " + result;
 
 622                         LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
 
 626                       String message = "Entity Sync failed because generic query str could not be determined.";
 
 627                       LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
 
 629                   } catch (Exception exc) {
 
 630                     String message = "Failed to sync entity because generation of generic query failed with error = " + exc.getMessage();
 
 631                     LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
 
 637             } catch (IOException ioe) {
 
 638               LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, ioe.getMessage());
 
 645       LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DESCRIPTOR_NOT_FOUND, txn.getEntityType());
 
 650    * Perform document upsert.
 
 652    * @param esGetResult the es get result
 
 653    * @param icer the icer
 
 655   protected void performDocumentUpsert(NetworkTransaction esGetResult,
 
 656       IndexableCrossEntityReference icer) {
 
 660      * As part of the response processing we need to do the following:
 
 661      * <li>1. Extract the version (if present), it will be the ETAG when we use the
 
 662      * Search-Abstraction-Service
 
 663      * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
 
 665      * <li>a) if version is null or RC=404, then standard put, no _update with version tag
 
 666      * <li>b) if version != null, do PUT with _update?version= (versionNumber) in the URI to elastic
 
 672       link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
 
 673     } catch (Exception exc) {
 
 674       LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
 
 678     boolean wasEntryDiscovered = false;
 
 679     String versionNumber = null;
 
 680     if (esGetResult.getOperationResult().getResultCode() == 404) {
 
 681       LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, icer.getEntityPrimaryKeyValue());
 
 682     } else if (esGetResult.getOperationResult().getResultCode() == 200) {
 
 683       wasEntryDiscovered = true;
 
 685         versionNumber = NodeUtils.extractFieldValueFromObject(
 
 686             NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
 
 688       } catch (IOException exc) {
 
 689         LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "version Number",
 
 690             icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
 
 695        * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
 
 698       LOG.info(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
 
 699           String.valueOf(esGetResult.getOperationResult().getResultCode()));
 
 704       String jsonPayload = null;
 
 705       if (wasEntryDiscovered) {
 
 707           ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
 
 708           NodeUtils.extractObjectsByKey(
 
 709               NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
 
 710               "_source", sourceObject);
 
 712           if (!sourceObject.isEmpty()) {
 
 713             String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
 
 714             MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
 
 715             ObjectReader updater = mapper.readerForUpdating(me);
 
 716             MergableEntity merged = updater.readValue(icer.getAsJson());
 
 717             jsonPayload = mapper.writeValueAsString(merged);
 
 719         } catch (IOException exc) {
 
 720           LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "source value",
 
 721               icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
 
 725         jsonPayload = icer.getAsJson();
 
 728       if (wasEntryDiscovered) {
 
 729         if (versionNumber != null && jsonPayload != null) {
 
 731           String requestPayload = elasticSearchAdapter.buildBulkImportOperationRequest(getIndexName(),
 
 732               "default", icer.getId(), versionNumber, jsonPayload);
 
 734           NetworkTransaction transactionTracker = new NetworkTransaction();
 
 735           transactionTracker.setEntityType(esGetResult.getEntityType());
 
 736           transactionTracker.setDescriptor(esGetResult.getDescriptor());
 
 737           transactionTracker.setOperationType(HttpMethod.PUT);
 
 739           esWorkOnHand.incrementAndGet();
 
 740           supplyAsync(new PerformElasticSearchUpdate(elasticSearchAdapter.getBulkUrl(),
 
 741               requestPayload, elasticSearchAdapter, transactionTracker), esPutExecutor)
 
 742                   .whenComplete((result, error) -> {
 
 744                     esWorkOnHand.decrementAndGet();
 
 747                       LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
 
 749                       updateElasticSearchCounters(result);
 
 750                       processStoreDocumentResult(result, esGetResult, icer);
 
 756         if (link != null && jsonPayload != null) {
 
 758           NetworkTransaction updateElasticTxn = new NetworkTransaction();
 
 759           updateElasticTxn.setLink(link);
 
 760           updateElasticTxn.setEntityType(esGetResult.getEntityType());
 
 761           updateElasticTxn.setDescriptor(esGetResult.getDescriptor());
 
 762           updateElasticTxn.setOperationType(HttpMethod.PUT);
 
 764           esWorkOnHand.incrementAndGet();
 
 765           supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, elasticSearchAdapter),
 
 766               esPutExecutor).whenComplete((result, error) -> {
 
 768                 esWorkOnHand.decrementAndGet();
 
 771                   LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
 
 773                   updateElasticSearchCounters(result);
 
 774                   processStoreDocumentResult(result, esGetResult, icer);
 
 779     } catch (Exception exc) {
 
 780       LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, exc.getLocalizedMessage());
 
 785    * Process store document result.
 
 787    * @param esPutResult the es put result
 
 788    * @param esGetResult the es get result
 
 789    * @param icer the icer
 
 791   private void processStoreDocumentResult(NetworkTransaction esPutResult,
 
 792       NetworkTransaction esGetResult, IndexableCrossEntityReference icer) {
 
 794     OperationResult or = esPutResult.getOperationResult();
 
 796     if (!or.wasSuccessful()) {
 
 797       if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
 
 799         if (shouldAllowRetry(icer.getId())) {
 
 801           esWorkOnHand.incrementAndGet();
 
 803           RetryCrossEntitySyncContainer rsc = new RetryCrossEntitySyncContainer(esGetResult, icer);
 
 804           retryQueue.push(rsc);
 
 806           LOG.warn(AaiUiMsgs.ES_CROSS_REF_SYNC_VERSION_CONFLICT);
 
 809         LOG.error(AaiUiMsgs.ES_CROSS_REF_SYNC_FAILURE, String.valueOf(or.getResultCode()),
 
 816    * Perform retry sync.
 
 818   private void performRetrySync() {
 
 819     while (retryQueue.peek() != null) {
 
 821       RetryCrossEntitySyncContainer rsc = retryQueue.poll();
 
 824         IndexableCrossEntityReference icer = rsc.getIndexableCrossEntityReference();
 
 825         NetworkTransaction txn = rsc.getNetworkTransaction();
 
 829           // In this retry flow the icer object has already
 
 830           // derived its fields
 
 831           link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), icer.getId());
 
 832         } catch (Exception exc) {
 
 833           LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
 
 837           NetworkTransaction retryTransaction = new NetworkTransaction();
 
 838           retryTransaction.setLink(link);
 
 839           retryTransaction.setEntityType(txn.getEntityType());
 
 840           retryTransaction.setDescriptor(txn.getDescriptor());
 
 841           retryTransaction.setOperationType(HttpMethod.GET);
 
 844            * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow and we did
 
 845            * that for this request already when queuing the failed PUT!
 
 848           supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, elasticSearchAdapter),
 
 849               esExecutor).whenComplete((result, error) -> {
 
 851                 esWorkOnHand.decrementAndGet();
 
 854                   LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
 
 856                   updateElasticSearchCounters(result);
 
 857                   performDocumentUpsert(result, icer);
 
 867    * Should allow retry.
 
 870    * @return true, if successful
 
 872   private boolean shouldAllowRetry(String id) {
 
 873     boolean isRetryAllowed = true;
 
 874     if (retryLimitTracker.get(id) != null) {
 
 875       Integer currentCount = retryLimitTracker.get(id);
 
 876       if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
 
 877         isRetryAllowed = false;
 
 878         LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_RESYNC_LIMIT, id);
 
 880         Integer newCount = new Integer(currentCount.intValue() + 1);
 
 881         retryLimitTracker.put(id, newCount);
 
 885       Integer firstRetryCount = new Integer(1);
 
 886       retryLimitTracker.put(id, firstRetryCount);
 
 889     return isRetryAllowed;
 
 893    * Gets the populated document.
 
 895    * @param entityNode the entity node
 
 896    * @param resultDescriptor the result descriptor
 
 897    * @return the populated document
 
 898    * @throws JsonProcessingException the json processing exception
 
 899    * @throws IOException Signals that an I/O exception has occurred.
 
 901   protected IndexableCrossEntityReference getPopulatedDocument(JsonNode entityNode,
 
 902       OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
 
 904     IndexableCrossEntityReference icer = new IndexableCrossEntityReference();
 
 906     icer.setEntityType(resultDescriptor.getEntityName());
 
 908     List<String> primaryKeyValues = new ArrayList<String>();
 
 909     String pkeyValue = null;
 
 911     for (String keyName : resultDescriptor.getPrimaryKeyAttributeNames()) {
 
 912       pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
 
 913       if (pkeyValue != null) {
 
 914         primaryKeyValues.add(pkeyValue);
 
 916         LOG.warn(AaiUiMsgs.ES_PKEYVALUE_NULL, resultDescriptor.getEntityName());
 
 920     final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
 
 921     icer.setEntityPrimaryKeyValue(primaryCompositeKeyValue);