summaryrefslogtreecommitdiffstats
path: root/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/crossentityreference/sync/CrossEntityReferenceSynchronizer.java
blob: 4b6b7a54bea5bb5aff431da3282e588d5a37a62d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
 * Copyright © 2017-2018 Amdocs
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */
package org.onap.aai.sparky.crossentityreference.sync;

import static java.util.concurrent.CompletableFuture.supplyAsync;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
import java.util.function.Supplier;

import org.onap.aai.cl.api.Logger;
import org.onap.aai.cl.eelf.LoggerFactory;
import org.onap.aai.cl.mdc.MdcContext;
import org.onap.aai.restclient.client.OperationResult;
import org.onap.aai.sparky.config.oxm.CrossEntityReference;
import org.onap.aai.sparky.config.oxm.CrossEntityReferenceDescriptor;
import org.onap.aai.sparky.config.oxm.CrossEntityReferenceLookup;
import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor;
import org.onap.aai.sparky.config.oxm.OxmEntityLookup;
import org.onap.aai.sparky.config.oxm.SearchableEntityLookup;
import org.onap.aai.sparky.dal.ActiveInventoryAdapter;
import org.onap.aai.sparky.dal.NetworkTransaction;
import org.onap.aai.sparky.dal.rest.HttpMethod;
import org.onap.aai.sparky.logging.AaiUiMsgs;
import org.onap.aai.sparky.sync.AbstractEntitySynchronizer;
import org.onap.aai.sparky.sync.IndexSynchronizer;
import org.onap.aai.sparky.sync.SynchronizerConstants;
import org.onap.aai.sparky.sync.config.ElasticSearchSchemaConfig;
import org.onap.aai.sparky.sync.config.NetworkStatisticsConfig;
import org.onap.aai.sparky.sync.entity.IndexableCrossEntityReference;
import org.onap.aai.sparky.sync.entity.MergableEntity;
import org.onap.aai.sparky.sync.entity.SelfLinkDescriptor;
import org.onap.aai.sparky.sync.enumeration.OperationState;
import org.onap.aai.sparky.sync.enumeration.SynchronizerState;
import org.onap.aai.sparky.sync.task.PerformActiveInventoryRetrieval;
import org.onap.aai.sparky.sync.task.PerformSearchServicePut;
import org.onap.aai.sparky.sync.task.PerformSearchServiceRetrieval;
import org.onap.aai.sparky.sync.task.PerformSearchServiceUpdate;
import org.onap.aai.sparky.util.NodeUtils;
import org.slf4j.MDC;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.node.ArrayNode;

/**
 * The Class CrossEntityReferenceSynchronizer.
 */
public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer
    implements IndexSynchronizer {

  /**
   * The Class RetryCrossEntitySyncContainer.
   */
  private class RetryCrossEntitySyncContainer {
    NetworkTransaction txn;
    IndexableCrossEntityReference icer;

    /**
     * Instantiates a new retry cross entity sync container.
     *
     * @param txn the txn
     * @param icer the icer
     */
    public RetryCrossEntitySyncContainer(NetworkTransaction txn,
        IndexableCrossEntityReference icer) {
      this.txn = txn;
      this.icer = icer;
    }

    public NetworkTransaction getNetworkTransaction() {
      return txn;
    }

    public IndexableCrossEntityReference getIndexableCrossEntityReference() {
      return icer;
    }
  }

  private static final Logger LOG =
      LoggerFactory.getInstance().getLogger(CrossEntityReferenceSynchronizer.class);

  private static final String SERVICE_INSTANCE = "service-instance";

  private Deque<SelfLinkDescriptor> selflinks;
  private Deque<RetryCrossEntitySyncContainer> retryQueue;
  private Map<String, Integer> retryLimitTracker;
  private boolean isAllWorkEnumerated;
  protected ExecutorService esPutExecutor;
  private CrossEntityReferenceLookup crossEntityReferenceLookup;
  private OxmEntityLookup oxmEntityLookup;
  private SearchableEntityLookup searchableEntityLookup;
  

  /**
   * Instantiates a new cross entity reference synchronizer.
   *
   * @throws Exception the exception
   */
  public CrossEntityReferenceSynchronizer(ElasticSearchSchemaConfig schemaConfig,
      int internalSyncWorkers, int aaiWorkers, int esWorkers, NetworkStatisticsConfig aaiStatConfig,
      NetworkStatisticsConfig esStatConfig, CrossEntityReferenceLookup crossEntityReferenceLookup,
      OxmEntityLookup oxmEntityLookup, SearchableEntityLookup searchableEntityLookup) throws Exception {
    super(LOG, "CERS", internalSyncWorkers, aaiWorkers, esWorkers, schemaConfig.getIndexName(),
        aaiStatConfig, esStatConfig);
    this.crossEntityReferenceLookup = crossEntityReferenceLookup;
    this.oxmEntityLookup = oxmEntityLookup;
    this.searchableEntityLookup = searchableEntityLookup;
    this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
    this.retryQueue = new ConcurrentLinkedDeque<RetryCrossEntitySyncContainer>();
    this.retryLimitTracker = new ConcurrentHashMap<String, Integer>();
    this.synchronizerName = "Cross Reference Entity Synchronizer";
    this.isAllWorkEnumerated = false;
    this.esPutExecutor = NodeUtils.createNamedExecutor("CERS-ES-PUT", 5, LOG);
    this.aaiEntityStats.intializeEntityCounters(
        crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().keySet());

    this.esEntityStats.intializeEntityCounters(
        crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().keySet());
    this.syncDurationInMs = -1;
  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
   */
  @Override
  public OperationState doSync() {
    this.syncDurationInMs = -1;
	String txnID = NodeUtils.getRandomTxnId();
    MdcContext.initialize(txnID, "CrossEntitySynchronizer", "", "Sync", "");
	
    resetCounters();
    syncStartedTimeStampInMs = System.currentTimeMillis();
    launchSyncFlow();
    return OperationState.OK;
  }

  @Override
  public SynchronizerState getState() {
    if (!isSyncDone()) {
      return SynchronizerState.PERFORMING_SYNCHRONIZATION;
    }

    return SynchronizerState.IDLE;
  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
   */
  @Override
  public String getStatReport(boolean showFinalReport) {
    syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
    return getStatReport(syncDurationInMs, showFinalReport);
  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
   */
  @Override
  public void shutdown() {
    this.shutdownExecutors();
  }

  @Override
  protected boolean isSyncDone() {
    int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();

    if (totalWorkOnHand > 0 || !isAllWorkEnumerated) {
      return false;
    }

    return true;
  }

  /**
   * Launch sync flow.
   *
   * @return the operation state
   */
  private OperationState launchSyncFlow() {
	final Map<String,String> contextMap = MDC.getCopyOfContextMap();
    Map<String, CrossEntityReferenceDescriptor> descriptorMap =
        crossEntityReferenceLookup.getCrossReferenceEntityDescriptors();

    if (descriptorMap.isEmpty()) {
      LOG.error(AaiUiMsgs.ERROR_LOADING_OXM);

      return OperationState.ERROR;
    }

    Collection<String> syncTypes = descriptorMap.keySet();

    try {

      /*
       * launch a parallel async thread to process the documents for each entity-type (to max the of
       * the configured executor anyway)
       */

      aaiWorkOnHand.set(syncTypes.size());

      for (String key : syncTypes) {

        supplyAsync(new Supplier<Void>() {

          @Override
          public Void get() {
        	MDC.setContextMap(contextMap);
            OperationResult typeLinksResult = null;
            try {
              typeLinksResult = aaiAdapter.getSelfLinksByEntityType(key);
              aaiWorkOnHand.decrementAndGet();
              processEntityTypeSelfLinks(typeLinksResult);
            } catch (Exception exc) {
              LOG.error(AaiUiMsgs.ERROR_GENERIC,
                  "An error occurred processing entity selflinks. Error: " + exc.getMessage());
            }

            return null;
          }

        }, aaiExecutor).whenComplete((result, error) -> {
          if (error != null) {
            LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, error.getMessage());
          }
        });
      }

      while (aaiWorkOnHand.get() != 0) {

        if (LOG.isDebugEnabled()) {
          LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
        }

        Thread.sleep(1000);
      }

      aaiWorkOnHand.set(selflinks.size());
      isAllWorkEnumerated = true;
      performSync();

      while (!isSyncDone()) {
        performRetrySync();
        Thread.sleep(1000);
      }

      /*
       * Make sure we don't hang on to retries that failed which could cause issues during future
       * syncs
       */
      retryLimitTracker.clear();

    } catch (Exception exc) {
      LOG.error(AaiUiMsgs.ERROR_GENERIC,
          "An error occurred during entity synchronization. Error: " + exc.getMessage());

    }

    return OperationState.OK;
  }

  /**
   * Perform sync.
   */
  private void performSync() {
    while (selflinks.peek() != null) {

      SelfLinkDescriptor linkDescriptor = selflinks.poll();
      aaiWorkOnHand.decrementAndGet();

      CrossEntityReferenceDescriptor descriptor = null;

      if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {

        descriptor = crossEntityReferenceLookup.getCrossReferenceEntityDescriptors()
            .get(linkDescriptor.getEntityType());

        if (descriptor == null) {
          LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
          // go to next element in iterator
          continue;
        }

        if (descriptor.hasCrossEntityReferences()) {

          NetworkTransaction txn = new NetworkTransaction();
          txn.setDescriptor(descriptor);
          txn.setLink(linkDescriptor.getSelfLink());
          txn.setQueryParameters(linkDescriptor.getDepthModifier());
          txn.setOperationType(HttpMethod.GET);
          txn.setEntityType(linkDescriptor.getEntityType());

          aaiWorkOnHand.incrementAndGet();

          supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiAdapter,"sync"), aaiExecutor)
              .whenComplete((result, error) -> {

                aaiWorkOnHand.decrementAndGet();

                if (error != null) {
                  LOG.error(AaiUiMsgs.SELF_LINK_GET, error.getLocalizedMessage());
                } else {
                  if (result == null) {
                    LOG.error(AaiUiMsgs.SELF_LINK_CROSS_REF_SYNC);
                  } else {
                    updateActiveInventoryCounters(result);
                    fetchDocumentForUpsert(result);
                  }
                }
              });
        }
      }
    }
  }

  /**
   * Process entity type self links.
   *
   * @param operationResult the operation result
   */
  private void processEntityTypeSelfLinks(OperationResult operationResult) {

    final String jsonResult = operationResult.getResult();

    if (jsonResult != null && jsonResult.length() > 0) {

      try {
        JsonNode rootNode = mapper.readTree(jsonResult);
        JsonNode resultData = rootNode.get("result-data");

        if (resultData.isArray()) {
          ArrayNode resultDataArrayNode = (ArrayNode) resultData;

          Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();

          while (elementIterator.hasNext()) {
            JsonNode element = elementIterator.next();

            final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
            final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");

            if (resourceType != null && resourceLink != null) {
              CrossEntityReferenceDescriptor descriptor = crossEntityReferenceLookup.getCrossReferenceEntityDescriptors().get(resourceType);

              if (descriptor == null) {
                LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
                // go to next element in iterator
                continue;
              }
              if (descriptor.hasCrossEntityReferences()) {
                selflinks.add(new SelfLinkDescriptor(
                        resourceLink, SynchronizerConstants.DEPTH_ALL_MODIFIER, resourceType));
              }
            }
          }
        }
      } catch (IOException exc) {
        // TODO // TODO -> LOG, waht should be logged here?
      }
    }
  }

  
  
  /**
   * By providing the entity type and a json node for the entity, determine the
   * primary key name(s) + primary key value(s) sufficient to build an entity query string
   * of the following format:
   * 
   *      <entityType>.<primaryKeyNames>:<primaryKeyValues>
   * 
   * @return - a composite string in the above format or null
   */
  private String determineEntityQueryString(String entityType, JsonNode entityJsonNode) {
    
    OxmEntityDescriptor entityDescriptor =
        oxmEntityLookup.getEntityDescriptors().get(entityType);
    
    String queryString = null;
    
    if ( entityDescriptor != null ) {

      final List<String> primaryKeyNames = entityDescriptor.getPrimaryKeyAttributeNames();
      final List<String> keyValues = new ArrayList<String>();
      NodeUtils.extractFieldValuesFromObject(entityJsonNode, primaryKeyNames, keyValues);

      queryString = entityType + "." + NodeUtils.concatArray(primaryKeyNames,"/") + ":" + NodeUtils.concatArray(keyValues);

    } 
    
    return queryString;

    
  }
  
  /**
   * Fetch document for upsert.
   *
   * @param txn the txn
   */
  private void fetchDocumentForUpsert(NetworkTransaction txn) {
    
    if (!txn.getOperationResult().wasSuccessful()) {
      LOG.error(AaiUiMsgs.SELF_LINK_GET, txn.getOperationResult().getResult());
      return;
    }

    CrossEntityReferenceDescriptor cerDescriptor = crossEntityReferenceLookup
        .getCrossReferenceEntityDescriptors().get(txn.getDescriptor().getEntityName());
    
    if (cerDescriptor != null && cerDescriptor.hasCrossEntityReferences()) {

      final String jsonResult = txn.getOperationResult().getResult();
      
      if (jsonResult != null && jsonResult.length() > 0) {
        
        /**
         * Here's what we are going to do:
         * 
         * <li>Extract primary key name and value from the parent type.
         * <li>Extract the primary key and value from the nested child instance.
         * <li>Build a generic query to discover the self-link for the nested-child-instance using
         * parent and child.
         * <li>Set the self-link on the child.
         * <li>Generate the id that will allow the elastic-search upsert to work.
         * <li>Rinse and repeat.
         */
          
          CrossEntityReference cerDefinition = cerDescriptor.getCrossEntityReference();

          if (cerDefinition != null) {
            JsonNode convertedNode = null;
            try {
              convertedNode = NodeUtils.convertJsonStrToJsonNode(txn.getOperationResult().getResult());
              
              final String parentEntityQueryString = determineEntityQueryString(txn.getEntityType(), convertedNode);
              
              List<String> extractedParentEntityAttributeValues = new ArrayList<String>();

              NodeUtils.extractFieldValuesFromObject(convertedNode,
                  cerDefinition.getReferenceAttributes(),
                  extractedParentEntityAttributeValues);

              List<JsonNode> nestedTargetEntityInstances = new ArrayList<JsonNode>();
              NodeUtils.extractObjectsByKey(convertedNode, cerDefinition.getTargetEntityType(),
                  nestedTargetEntityInstances);

              for (JsonNode targetEntityInstance : nestedTargetEntityInstances) {

                if (cerDescriptor != null) {
                  
                  String childEntityType = cerDefinition.getTargetEntityType();
                  OxmEntityDescriptor childDesciptor = oxmEntityLookup.getEntityDescriptors().get(childEntityType);
                  
                  List<String> childPrimaryKeyNames = null;
                  
                  if (childDesciptor != null) {
                    childPrimaryKeyNames = childDesciptor.getPrimaryKeyAttributeNames();
                  } else {
                    childPrimaryKeyNames = new ArrayList<String>();
                  }
                                
                  List<String> childKeyValues = new ArrayList<String>();
                  NodeUtils.extractFieldValuesFromObject(targetEntityInstance, childPrimaryKeyNames, childKeyValues);
                  
                  String childEntityQueryKeyString = childEntityType + "." + NodeUtils.concatArray(childPrimaryKeyNames,"/") + ":" + NodeUtils.concatArray(childKeyValues);
                  
                  /**
                   * Build generic-query to query child instance self-link from AAI
                   */
                  List<String> orderedQueryKeyParams = new ArrayList<String>();

                  /**
                   * At present, there is an issue with resolving the self-link using the
                   * generic-query with nothing more than the service-instance identifier and the
                   * service-subscription. There is another level of detail we don't have access to
                   * unless we parse it out of the service-subscription self-link, which is a
                   * coupling I would like to avoid. Fortunately, there is a workaround, but only
                   * for service-instances, which is presently our only use-case for the
                   * cross-entity-reference in R1707. Going forwards hopefully there will be other
                   * ways to resolve a child self-link using parental embedded meta data that we
                   * don't currently have.
                   * 
                   * The work-around with the service-instance entity-type is that it's possible to
                   * request the self-link using only the service-instance-id because of a
                   * historical AAI functional query requirement that it be possible to query a
                   * service-instance only by it's service-instance-id. This entity type is the only
                   * one in the system that can be queried this way which makes it a very limited
                   * workaround, but good enough for the current release.
                   */

                  if (SERVICE_INSTANCE.equals(childEntityType)) {
                    orderedQueryKeyParams.clear();
                    orderedQueryKeyParams.add(childEntityQueryKeyString);
                  } else {
                    orderedQueryKeyParams.add(parentEntityQueryString);
                    orderedQueryKeyParams.add(childEntityQueryKeyString);
                  }

                  String genericQueryStr = null;
                  try {
                    genericQueryStr = aaiAdapter.getGenericQueryForSelfLink(childEntityType, orderedQueryKeyParams);
                    
                    if (genericQueryStr != null) {
                      aaiWorkOnHand.incrementAndGet();

                      OperationResult aaiQueryResult = aaiAdapter.queryActiveInventoryWithRetries(
                          genericQueryStr, "application/json",
                          aaiAdapter.getEndpointConfig().getNumRequestRetries(),"sync");

                      aaiWorkOnHand.decrementAndGet();

                      if (aaiQueryResult!= null && aaiQueryResult.wasSuccessful()) {
                        
                        Collection<JsonNode> entityLinks = new ArrayList<JsonNode>();
                        JsonNode genericQueryResult = null;
                        try {
                          genericQueryResult = NodeUtils.convertJsonStrToJsonNode(aaiQueryResult.getResult());
                          
                          if ( genericQueryResult != null ) {
                            
                            NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link", entityLinks);

                            String selfLink = null;

                            if (entityLinks.size() != 1) {
                              /**
                               * an ambiguity exists where we can't reliably determine the self
                               * link, this should be a permanent error
                               */
                              LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_SELFLINK_AMBIGUITY, String.valueOf(entityLinks.size()));
                          } else {
                            selfLink = ((JsonNode) entityLinks.toArray()[0]).asText();


                            IndexableCrossEntityReference icer =
                                getPopulatedDocument(targetEntityInstance, cerDescriptor);

                            for (String parentCrossEntityReferenceAttributeValue : extractedParentEntityAttributeValues) {
                              icer.addCrossEntityReferenceValue(
                                  parentCrossEntityReferenceAttributeValue);
                            }

                            icer.setLink(ActiveInventoryAdapter.extractResourcePath(selfLink));

                            icer.deriveFields();

                            String link = null;
                            try {
                              link = searchServiceAdapter
                                  .buildSearchServiceDocUrl(getIndexName(), icer.getId());
                            } catch (Exception exc) {
                              LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY,
                                  exc.getLocalizedMessage());
                            }

                            if (link != null) {
                              NetworkTransaction n2 = new NetworkTransaction();
                              n2.setLink(link);
                              n2.setEntityType(txn.getEntityType());
                              n2.setDescriptor(txn.getDescriptor());
                              n2.setOperationType(HttpMethod.GET);

                              esWorkOnHand.incrementAndGet();

                              supplyAsync(
                                      new PerformSearchServiceRetrieval(n2, searchServiceAdapter),
                                      esExecutor).whenComplete((result, error) -> {

                                    esWorkOnHand.decrementAndGet();

                                    if (error != null) {
                                      LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED,
                                          error.getLocalizedMessage());
                                    } else {
                                      updateElasticSearchCounters(result);
                                      performDocumentUpsert(result, icer);
                                    }
                                  });
                            }

                          }
                          } else {
                            LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DURING_AAI_RESPONSE_CONVERSION);
                          }

                        } catch (Exception exc) {
                          LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(), exc.getLocalizedMessage());
                        }
                        
                      } else {
                        String result = aaiQueryResult != null ? aaiQueryResult.getResult() : "unknown";
                        String message = "Entity sync failed because AAI query failed with error " + result;
                        LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
                      }
                      
                    } else {
                      String message = "Entity Sync failed because generic query str could not be determined.";
                      LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
                    }
                  } catch (Exception exc) {
                    String message = "Failed to sync entity because generation of generic query failed with error = " + exc.getMessage();
                    LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
                  }
                  
                }
              }
              
            } catch (IOException ioe) {
              LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, ioe.getMessage());
            }
          }
          
        } 
      
    } else {
      LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DESCRIPTOR_NOT_FOUND, txn.getEntityType());
    }
  }

  /**
   * Perform document upsert.
   *
   * @param esGetResult the es get result
   * @param icer the icer
   */
  protected void performDocumentUpsert(NetworkTransaction esGetResult,
      IndexableCrossEntityReference icer) {
    /**
     * <p>
     * <ul>
     * As part of the response processing we need to do the following:
     * <li>1. Extract the version (if present), it will be the ETAG when we use the
     * Search-Abstraction-Service
     * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
     * tag
     * <li>a) if version is null or RC=404, then standard put, no _update with version tag
     * <li>b) if version != null, do PUT with _update?version= (versionNumber) in the URI to elastic
     * </ul>
     * </p>
     */
    String link = null;
    try {
      link = searchServiceAdapter.buildSearchServiceDocUrl(getIndexName(), icer.getId());
    } catch (Exception exc) {
      LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
      return;
    }

    boolean wasEntryDiscovered = false;
    String versionNumber = null;
    if (esGetResult.getOperationResult().getResultCode() == 404) {
      LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, icer.getEntityPrimaryKeyValue());
    } else if (esGetResult.getOperationResult().getResultCode() == 200) {
      wasEntryDiscovered = true;
      try {
        versionNumber = NodeUtils.extractFieldValueFromObject(
            NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
            "etag");
      } catch (IOException exc) {
        LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "version Number",
            icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
        return;
      }
    } else {
      /*
       * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
       * return.
       */
      LOG.info(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
          String.valueOf(esGetResult.getOperationResult().getResultCode()));
      return;
    }

    try {
      String jsonPayload = null;
      if (wasEntryDiscovered) {
        try {
          ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
          NodeUtils.extractObjectsByKey(
              NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
              "content", sourceObject);

          if (!sourceObject.isEmpty()) {
            String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
            MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
            ObjectReader updater = mapper.readerForUpdating(me);
            MergableEntity merged = updater.readValue(icer.getAsJson());
            jsonPayload = mapper.writeValueAsString(merged);
          }
        } catch (IOException exc) {
          LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "source value",
              icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
          return;
        }
      } else {
        jsonPayload = icer.getAsJson();
      }

      if (wasEntryDiscovered) {
        if (versionNumber != null && jsonPayload != null) {

        	String requestPayload = searchServiceAdapter.buildBulkImportOperationRequest(getIndexName(),
              icer.getId(), versionNumber, jsonPayload);

          NetworkTransaction transactionTracker = new NetworkTransaction();
          transactionTracker.setEntityType(esGetResult.getEntityType());
          transactionTracker.setDescriptor(esGetResult.getDescriptor());
          transactionTracker.setOperationType(HttpMethod.PUT);

          esWorkOnHand.incrementAndGet();
          supplyAsync(new PerformSearchServiceUpdate(searchServiceAdapter.buildSearchServiceBulkUrl(),
                  requestPayload, searchServiceAdapter, transactionTracker), esPutExecutor)
                      .whenComplete((result, error) -> {

                    esWorkOnHand.decrementAndGet();

                    if (error != null) {
                       LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage()); 
                    } else {
                      updateElasticSearchCounters(result);
                      processStoreDocumentResult(result, esGetResult, icer);
                    }
                  });
        }

      } else {
        if (link != null && jsonPayload != null) {

          NetworkTransaction updateElasticTxn = new NetworkTransaction();
          updateElasticTxn.setLink(link);
          updateElasticTxn.setEntityType(esGetResult.getEntityType());
          updateElasticTxn.setDescriptor(esGetResult.getDescriptor());
          updateElasticTxn.setOperationType(HttpMethod.PUT);

          esWorkOnHand.incrementAndGet();
          supplyAsync(new PerformSearchServicePut(jsonPayload, updateElasticTxn, searchServiceAdapter),
                  esPutExecutor).whenComplete((result, error) -> {

                esWorkOnHand.decrementAndGet();

                if (error != null) {
                  LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
                } else {
                  updateElasticSearchCounters(result);
                  processStoreDocumentResult(result, esGetResult, icer);
                }
              });
        }
      }
    } catch (Exception exc) {
      LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, exc.getLocalizedMessage());
    }
  }

  /**
   * Process store document result.
   *
   * @param esPutResult the es put result
   * @param esGetResult the es get result
   * @param icer the icer
   */
  private void processStoreDocumentResult(NetworkTransaction esPutResult,
      NetworkTransaction esGetResult, IndexableCrossEntityReference icer) {

    OperationResult or = esPutResult.getOperationResult();

    if (!or.wasSuccessful()) {
      if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {

        if (shouldAllowRetry(icer.getId())) {

          esWorkOnHand.incrementAndGet();

          RetryCrossEntitySyncContainer rsc = new RetryCrossEntitySyncContainer(esGetResult, icer);
          retryQueue.push(rsc);

          LOG.warn(AaiUiMsgs.ES_CROSS_REF_SYNC_VERSION_CONFLICT);
        }
      } else {
        LOG.error(AaiUiMsgs.ES_CROSS_REF_SYNC_FAILURE, String.valueOf(or.getResultCode()),
            or.getResult());
      }
    }
  }

  /**
   * Perform retry sync.
   */
  private void performRetrySync() {
    while (retryQueue.peek() != null) {

      RetryCrossEntitySyncContainer rsc = retryQueue.poll();
      if (rsc != null) {

        IndexableCrossEntityReference icer = rsc.getIndexableCrossEntityReference();
        NetworkTransaction txn = rsc.getNetworkTransaction();

        final Consumer<NetworkTransaction> networkTransactionConsumer = (result) -> performDocumentUpsert(result,icer);
        performRetrySync(icer.getId(), networkTransactionConsumer, txn);

      }
    }
  }

  /**
   * Should allow retry.
   *
   * @param id the id
   * @return true, if successful
   */
  private boolean shouldAllowRetry(String id) {
    boolean isRetryAllowed = true;
    if (retryLimitTracker.get(id) != null) {
      Integer currentCount = retryLimitTracker.get(id);
      if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
        isRetryAllowed = false;
        LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_RESYNC_LIMIT, id);
      } else {
        Integer newCount = new Integer(currentCount.intValue() + 1);
        retryLimitTracker.put(id, newCount);
      }

    } else {
      Integer firstRetryCount = new Integer(1);
      retryLimitTracker.put(id, firstRetryCount);
    }

    return isRetryAllowed;
  }

  /**
   * Gets the populated document.
   *
   * @param entityNode the entity node
   * @param resultDescriptor the result descriptor
   * @return the populated document
   * @throws JsonProcessingException the json processing exception
   * @throws IOException Signals that an I/O exception has occurred.
   */
  protected IndexableCrossEntityReference getPopulatedDocument(JsonNode entityNode,
      OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {

    IndexableCrossEntityReference icer = new IndexableCrossEntityReference();

    return icer;

  }
}