Changing the license and trademark
[aai/sparky-be.git] / src / main / java / org / openecomp / sparky / synchronizer / CrossEntityReferenceSynchronizer.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
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
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  *
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23 package org.openecomp.sparky.synchronizer;
24
25 import static java.util.concurrent.CompletableFuture.supplyAsync;
26
27 import java.io.IOException;
28 import java.net.InetAddress;
29 import java.net.UnknownHostException;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Deque;
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.concurrent.ConcurrentHashMap;
37 import java.util.concurrent.ConcurrentLinkedDeque;
38 import java.util.concurrent.ExecutorService;
39 import java.util.function.Supplier;
40
41 import org.openecomp.cl.api.Logger;
42 import org.openecomp.cl.eelf.LoggerFactory;
43 import org.openecomp.sparky.config.oxm.CrossEntityReference;
44 import org.openecomp.sparky.config.oxm.OxmEntityDescriptor;
45 import org.openecomp.sparky.dal.NetworkTransaction;
46 import org.openecomp.sparky.dal.aai.config.ActiveInventoryConfig;
47 import org.openecomp.sparky.dal.elasticsearch.config.ElasticSearchConfig;
48 import org.openecomp.sparky.dal.rest.HttpMethod;
49 import org.openecomp.sparky.dal.rest.OperationResult;
50 import org.openecomp.sparky.logging.AaiUiMsgs;
51 import org.openecomp.sparky.synchronizer.config.SynchronizerConfiguration;
52 import org.openecomp.sparky.synchronizer.entity.IndexableCrossEntityReference;
53 import org.openecomp.sparky.synchronizer.entity.MergableEntity;
54 import org.openecomp.sparky.synchronizer.entity.SelfLinkDescriptor;
55 import org.openecomp.sparky.synchronizer.enumeration.OperationState;
56 import org.openecomp.sparky.synchronizer.enumeration.SynchronizerState;
57 import org.openecomp.sparky.synchronizer.task.PerformActiveInventoryRetrieval;
58 import org.openecomp.sparky.synchronizer.task.PerformElasticSearchPut;
59 import org.openecomp.sparky.synchronizer.task.PerformElasticSearchRetrieval;
60 import org.openecomp.sparky.synchronizer.task.PerformElasticSearchUpdate;
61 import org.openecomp.sparky.util.NodeUtils;
62 import org.slf4j.MDC;
63
64 import org.openecomp.cl.mdc.MdcContext;
65 import com.fasterxml.jackson.core.JsonProcessingException;
66 import com.fasterxml.jackson.databind.JsonNode;
67 import com.fasterxml.jackson.databind.ObjectReader;
68 import com.fasterxml.jackson.databind.node.ArrayNode;
69
70 /**
71  * The Class CrossEntityReferenceSynchronizer.
72  */
73 public class CrossEntityReferenceSynchronizer extends AbstractEntitySynchronizer
74     implements IndexSynchronizer {
75
76   /**
77    * The Class RetryCrossEntitySyncContainer.
78    */
79   private class RetryCrossEntitySyncContainer {
80     NetworkTransaction txn;
81     IndexableCrossEntityReference icer;
82
83     /**
84      * Instantiates a new retry cross entity sync container.
85      *
86      * @param txn the txn
87      * @param icer the icer
88      */
89     public RetryCrossEntitySyncContainer(NetworkTransaction txn,
90         IndexableCrossEntityReference icer) {
91       this.txn = txn;
92       this.icer = icer;
93     }
94
95     public NetworkTransaction getNetworkTransaction() {
96       return txn;
97     }
98
99     public IndexableCrossEntityReference getIndexableCrossEntityReference() {
100       return icer;
101     }
102   }
103
104   private static final Logger LOG =
105       LoggerFactory.getInstance().getLogger(CrossEntityReferenceSynchronizer.class);
106   
107   private static final String SERVICE_INSTANCE = "service-instance";
108   private Deque<SelfLinkDescriptor> selflinks;
109   private Deque<RetryCrossEntitySyncContainer> retryQueue;
110   private Map<String, Integer> retryLimitTracker;
111   private boolean isAllWorkEnumerated;
112   protected ExecutorService esPutExecutor;
113   protected ActiveInventoryConfig aaiConfig;
114
115   /**
116    * Instantiates a new cross entity reference synchronizer.
117    *
118    * @param indexName the index name
119    * @throws Exception the exception
120    */
121   public CrossEntityReferenceSynchronizer(String indexName, ActiveInventoryConfig aaiConfig) throws Exception {
122     super(LOG, "CERS", 2, 5, 5, indexName);
123     this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
124     this.retryQueue = new ConcurrentLinkedDeque<RetryCrossEntitySyncContainer>();
125     this.retryLimitTracker = new ConcurrentHashMap<String, Integer>();
126     this.synchronizerName = "Cross Reference Entity Synchronizer";
127     this.isAllWorkEnumerated = false;
128     this.esPutExecutor = NodeUtils.createNamedExecutor("CERS-ES-PUT", 5, LOG);
129     this.aaiEntityStats.initializeCountersFromOxmEntityDescriptors(
130         oxmModelLoader.getCrossReferenceEntityDescriptors());
131     this.esEntityStats.initializeCountersFromOxmEntityDescriptors(
132         oxmModelLoader.getCrossReferenceEntityDescriptors());
133     this.aaiConfig = aaiConfig;
134     this.syncDurationInMs = -1;
135   }
136
137   /* (non-Javadoc)
138    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
139    */
140   @Override
141   public OperationState doSync() {
142         this.syncDurationInMs = -1;
143         String txnID = NodeUtils.getRandomTxnId();
144     MdcContext.initialize(txnID, "CrossEntitySynchronizer", "", "Sync", "");
145         
146     resetCounters();
147     syncStartedTimeStampInMs = System.currentTimeMillis();
148     launchSyncFlow();
149     return OperationState.OK;
150   }
151
152   @Override
153   public SynchronizerState getState() {
154     if (!isSyncDone()) {
155       return SynchronizerState.PERFORMING_SYNCHRONIZATION;
156     }
157
158     return SynchronizerState.IDLE;
159   }
160
161   /* (non-Javadoc)
162    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
163    */
164   @Override
165   public String getStatReport(boolean showFinalReport) {
166           syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
167           return getStatReport(syncDurationInMs, showFinalReport);
168   }
169
170   /* (non-Javadoc)
171    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
172    */
173   @Override
174   public void shutdown() {
175     this.shutdownExecutors();
176   }
177
178   @Override
179   protected boolean isSyncDone() {
180     int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
181
182     if (totalWorkOnHand > 0 || !isAllWorkEnumerated) {
183       return false;
184     }
185
186     return true;
187   }
188
189   /**
190    * Launch sync flow.
191    *
192    * @return the operation state
193    */
194   private OperationState launchSyncFlow() {
195         final Map<String,String> contextMap = MDC.getCopyOfContextMap();
196     Map<String, OxmEntityDescriptor> descriptorMap =
197         oxmModelLoader.getCrossReferenceEntityDescriptors();
198
199     if (descriptorMap.isEmpty()) {
200       LOG.error(AaiUiMsgs.ERROR_LOADING_OXM);
201
202       return OperationState.ERROR;
203     }
204
205     Collection<String> syncTypes = descriptorMap.keySet();
206
207     try {
208
209       /*
210        * launch a parallel async thread to process the documents for each entity-type (to max the of
211        * the configured executor anyway)
212        */
213
214       aaiWorkOnHand.set(syncTypes.size());
215
216       for (String key : syncTypes) {
217
218         supplyAsync(new Supplier<Void>() {
219
220           @Override
221           public Void get() {
222                 MDC.setContextMap(contextMap);
223             OperationResult typeLinksResult = null;
224             try {
225               typeLinksResult = aaiDataProvider.getSelfLinksByEntityType(key);
226               aaiWorkOnHand.decrementAndGet();
227               processEntityTypeSelfLinks(typeLinksResult);
228             } catch (Exception exc) {
229               // TODO -> LOG, what should be logged here?
230             }
231
232             return null;
233           }
234
235         }, aaiExecutor).whenComplete((result, error) -> {
236           if (error != null) {
237             LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, error.getMessage());
238           }
239         });
240       }
241
242       while (aaiWorkOnHand.get() != 0) {
243
244         if (LOG.isDebugEnabled()) {
245           LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
246         }
247
248         Thread.sleep(1000);
249       }
250
251       aaiWorkOnHand.set(selflinks.size());
252       isAllWorkEnumerated = true;
253       performSync();
254
255       while (!isSyncDone()) {
256         performRetrySync();
257         Thread.sleep(1000);
258       }
259
260       /*
261        * Make sure we don't hang on to retries that failed which could cause issues during future
262        * syncs
263        */
264       retryLimitTracker.clear();
265
266     } catch (Exception exc) {
267       // TODO -> LOG, waht should be logged here?
268     }
269
270     return OperationState.OK;
271   }
272
273   /**
274    * Perform sync.
275    */
276   private void performSync() {
277     while (selflinks.peek() != null) {
278
279       SelfLinkDescriptor linkDescriptor = selflinks.poll();
280       aaiWorkOnHand.decrementAndGet();
281
282       OxmEntityDescriptor descriptor = null;
283
284       if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
285
286         descriptor = oxmModelLoader.getEntityDescriptor(linkDescriptor.getEntityType());
287
288         if (descriptor == null) {
289           LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
290           // go to next element in iterator
291           continue;
292         }
293
294         if (descriptor.hasCrossEntityReferences()) {
295
296           NetworkTransaction txn = new NetworkTransaction();
297           txn.setDescriptor(descriptor);
298           txn.setLink(linkDescriptor.getSelfLink() + linkDescriptor.getDepthModifier());
299           txn.setOperationType(HttpMethod.GET);
300           txn.setEntityType(linkDescriptor.getEntityType());
301
302           aaiWorkOnHand.incrementAndGet();
303
304           supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiDataProvider), aaiExecutor)
305               .whenComplete((result, error) -> {
306
307                 aaiWorkOnHand.decrementAndGet();
308
309                 if (error != null) {
310                   LOG.error(AaiUiMsgs.SELF_LINK_GET, error.getLocalizedMessage());
311                 } else {
312                   if (result == null) {
313                     LOG.error(AaiUiMsgs.SELF_LINK_CROSS_REF_SYNC);
314                   } else {
315                     updateActiveInventoryCounters(result);
316                     fetchDocumentForUpsert(result);
317                   }
318                 }
319               });
320         }
321       }
322     }
323   }
324
325   /**
326    * Process entity type self links.
327    *
328    * @param operationResult the operation result
329    */
330   private void processEntityTypeSelfLinks(OperationResult operationResult) {
331
332     JsonNode rootNode = null;
333
334     final String jsonResult = operationResult.getResult();
335
336     if (jsonResult != null && jsonResult.length() > 0) {
337
338       try {
339         rootNode = mapper.readTree(jsonResult);
340       } catch (IOException exc) {
341         // TODO // TODO -> LOG, waht should be logged here?
342       }
343
344       JsonNode resultData = rootNode.get("result-data");
345       ArrayNode resultDataArrayNode = null;
346
347       if (resultData.isArray()) {
348         resultDataArrayNode = (ArrayNode) resultData;
349
350         Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
351         JsonNode element = null;
352
353         while (elementIterator.hasNext()) {
354           element = elementIterator.next();
355
356           final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
357           final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
358
359           OxmEntityDescriptor descriptor = null;
360
361           if (resourceType != null && resourceLink != null) {
362             descriptor = oxmModelLoader.getEntityDescriptor(resourceType);
363
364             if (descriptor == null) {
365               LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
366               // go to next element in iterator
367               continue;
368             }
369             if (descriptor.hasCrossEntityReferences()) {
370               selflinks.add(new SelfLinkDescriptor(
371                   resourceLink,SynchronizerConfiguration.DEPTH_ALL_MODIFIER, resourceType));
372             }
373           }
374         }
375       }
376     }
377   }
378
379   
380   
381   /**
382    * By providing the entity type and a json node for the entity, determine the
383    * primary key name(s) + primary key value(s) sufficient to build an entity query string
384    * of the following format:
385    * 
386    *      <entityType>.<primaryKeyNames>:<primaryKeyValues>
387    * 
388    * @return - a composite string in the above format or null
389    */
390   private String determineEntityQueryString(String entityType, JsonNode entityJsonNode) {
391     
392     OxmEntityDescriptor entityDescriptor =
393         oxmModelLoader.getEntityDescriptor(entityType);
394     
395     String queryString = null;
396     
397     if ( entityDescriptor != null ) {
398
399       final List<String> primaryKeyNames = entityDescriptor.getPrimaryKeyAttributeName();
400       final List<String> keyValues = new ArrayList<String>();
401       NodeUtils.extractFieldValuesFromObject(entityJsonNode, primaryKeyNames, keyValues);
402
403       queryString = entityType + "." + NodeUtils.concatArray(primaryKeyNames,"/") + ":" + NodeUtils.concatArray(keyValues);
404
405     } 
406     
407     return queryString;
408
409     
410   }
411   
412   /**
413    * Fetch document for upsert.
414    *
415    * @param txn the txn
416    */
417   private void fetchDocumentForUpsert(NetworkTransaction txn) {
418     
419     if (!txn.getOperationResult().wasSuccessful()) {
420       LOG.error(AaiUiMsgs.SELF_LINK_GET, txn.getOperationResult().getResult());
421       return;
422     }
423
424     if (txn.getDescriptor().hasCrossEntityReferences()) {
425
426       final String jsonResult = txn.getOperationResult().getResult();
427       
428       if (jsonResult != null && jsonResult.length() > 0) {
429         
430         /**
431          * Here's what we are going to do:
432          * 
433          * <li>Extract primary key name and value from the parent type.
434          * <li>Extract the primary key and value from the nested child instance.
435          * <li>Build a generic query to discover the self-link for the nested-child-instance using
436          * parent and child.
437          * <li>Set the self-link on the child.
438          * <li>Generate the id that will allow the elastic-search upsert to work.
439          * <li>Rinse and repeat.
440          */
441
442         OxmEntityDescriptor parentEntityDescriptor =
443             oxmModelLoader.getEntityDescriptor(txn.getEntityType());
444         
445         if ( parentEntityDescriptor != null ) {
446           
447           CrossEntityReference cerDefinition = parentEntityDescriptor.getCrossEntityReference();
448
449           if (cerDefinition != null) {
450             JsonNode convertedNode = null;
451             try {
452               convertedNode = NodeUtils.convertJsonStrToJsonNode(txn.getOperationResult().getResult());
453               
454               final String parentEntityQueryString = determineEntityQueryString(txn.getEntityType(), convertedNode);
455               
456               List<String> extractedParentEntityAttributeValues = new ArrayList<String>();
457
458               NodeUtils.extractFieldValuesFromObject(convertedNode,
459                   cerDefinition.getReferenceAttributes(),
460                   extractedParentEntityAttributeValues);
461
462               List<JsonNode> nestedTargetEntityInstances = new ArrayList<JsonNode>();
463               NodeUtils.extractObjectsByKey(convertedNode, cerDefinition.getTargetEntityType(),
464                   nestedTargetEntityInstances);
465
466               for (JsonNode targetEntityInstance : nestedTargetEntityInstances) {
467
468                 OxmEntityDescriptor cerDescriptor =
469                     oxmModelLoader.getSearchableEntityDescriptor(cerDefinition.getTargetEntityType());
470
471                 if (cerDescriptor != null) {
472                   
473                   String childEntityType = cerDefinition.getTargetEntityType();
474                   
475                   List<String> childPrimaryKeyNames = cerDescriptor.getPrimaryKeyAttributeName();
476                   
477                   List<String> childKeyValues = new ArrayList<String>();
478                   NodeUtils.extractFieldValuesFromObject(targetEntityInstance, childPrimaryKeyNames, childKeyValues);
479                   
480                   String childEntityQueryKeyString = childEntityType + "." + NodeUtils.concatArray(childPrimaryKeyNames,"/") + ":" + NodeUtils.concatArray(childKeyValues);
481                   
482                   /**
483                    * Build generic-query to query child instance self-link from AAI
484                    */
485                   List<String> orderedQueryKeyParams = new ArrayList<String>();
486                   if (SERVICE_INSTANCE.equals(childEntityType)) {
487                       orderedQueryKeyParams.clear();
488                       orderedQueryKeyParams.add(childEntityQueryKeyString);
489                     } else {
490                       orderedQueryKeyParams.add(parentEntityQueryString);
491                       orderedQueryKeyParams.add(childEntityQueryKeyString);
492                     }
493                   String genericQueryStr = null;
494                   try {
495                     genericQueryStr = aaiDataProvider.getGenericQueryForSelfLink(childEntityType, orderedQueryKeyParams);
496                     
497                     if (genericQueryStr != null) {
498                       aaiWorkOnHand.incrementAndGet();
499                       OperationResult aaiQueryResult = aaiDataProvider.queryActiveInventoryWithRetries(
500                           genericQueryStr, "application/json",
501                           aaiConfig.getAaiRestConfig().getNumRequestRetries());
502                       aaiWorkOnHand.decrementAndGet();
503                       if (aaiQueryResult!= null && aaiQueryResult.wasSuccessful()) {
504                         
505                         Collection<JsonNode> entityLinks = new ArrayList<JsonNode>();
506                         JsonNode genericQueryResult = null;
507                         try {
508                           genericQueryResult = NodeUtils.convertJsonStrToJsonNode(aaiQueryResult.getResult());
509                           
510                           if ( genericQueryResult != null ) {
511                             
512                             NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link", entityLinks);
513
514                             String selfLink = null;
515
516                             if (entityLinks.size() != 1) {
517                               /**
518                                * an ambiguity exists where we can't reliably determine the self
519                                * link, this should be a permanent error
520                                */
521                               LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_SELFLINK_AMBIGUITY, String.valueOf(entityLinks.size()));
522                             } else {
523                               selfLink = ((JsonNode) entityLinks.toArray()[0]).asText();
524                               
525                               if (!cerDescriptor.getSearchableAttributes().isEmpty()) {
526
527                                 IndexableCrossEntityReference icer =
528                                     getPopulatedDocument(targetEntityInstance, cerDescriptor);
529
530                                 for (String parentCrossEntityReferenceAttributeValue : extractedParentEntityAttributeValues) {
531                                   icer.addCrossEntityReferenceValue(
532                                       parentCrossEntityReferenceAttributeValue);
533                                 }
534                                 
535                                 icer.setLink(ActiveInventoryConfig.extractResourcePath(selfLink));
536
537                                 icer.deriveFields();
538
539                                 String link = null;
540                                 try {
541                                   link = getElasticFullUrl("/" + icer.getId(), getIndexName());
542                                 } catch (Exception exc) {
543                                   LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
544                                 }
545
546                                 if (link != null) {
547                                   NetworkTransaction n2 = new NetworkTransaction();
548                                   n2.setLink(link);
549                                   n2.setEntityType(txn.getEntityType());
550                                   n2.setDescriptor(txn.getDescriptor());
551                                   n2.setOperationType(HttpMethod.GET);
552
553                                   esWorkOnHand.incrementAndGet();
554
555                                   supplyAsync(new PerformElasticSearchRetrieval(n2, esDataProvider),
556                                       esExecutor).whenComplete((result, error) -> {
557
558                                         esWorkOnHand.decrementAndGet();
559
560                                         if (error != null) {
561                                           LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage());
562                                         } else {
563                                           updateElasticSearchCounters(result);
564                                           performDocumentUpsert(result, icer);
565                                         }
566                                       });
567                                 }
568                               }
569                             }
570                           } else {
571                             LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DURING_AAI_RESPONSE_CONVERSION);
572                           }
573
574                         } catch (Exception exc) {
575                           LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(), exc.getLocalizedMessage());
576                         }
577                         
578                       } else {
579                         String message = "Entity sync failed because AAI query failed with error " + aaiQueryResult.getResult(); 
580                         LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
581                       }
582                       
583                     } else {
584                       String message = "Entity Sync failed because generic query str could not be determined.";
585                       LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
586                     }
587                   } catch (Exception exc) {
588                     String message = "Failed to sync entity because generation of generic query failed with error = " + exc.getMessage();
589                     LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_QUERY_ERROR, message);
590                   }
591                   
592                 }
593               }
594               
595             } catch (IOException ioe) {
596               LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, ioe.getMessage());
597             }
598           }
599           
600         } else {
601           LOG.error(AaiUiMsgs.ENTITY_SYNC_FAILED_DESCRIPTOR_NOT_FOUND, txn.getEntityType());
602         }
603       }
604     }
605   }
606
607   /**
608    * Perform document upsert.
609    *
610    * @param esGetResult the es get result
611    * @param icer the icer
612    */
613   protected void performDocumentUpsert(NetworkTransaction esGetResult,
614       IndexableCrossEntityReference icer) {
615     /**
616      * <p>
617      * <ul>
618      * As part of the response processing we need to do the following:
619      * <li>1. Extract the version (if present), it will be the ETAG when we use the
620      * Search-Abstraction-Service
621      * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
622      * tag
623      * <li>a) if version is null or RC=404, then standard put, no _update with version tag
624      * <li>b) if version != null, do PUT with _update?version= (versionNumber) in the URI to elastic
625      * </ul>
626      * </p>
627      */
628     String link = null;
629     try {
630       link = getElasticFullUrl("/" + icer.getId(), getIndexName());
631     } catch (Exception exc) {
632       LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
633       return;
634     }
635
636     boolean wasEntryDiscovered = false;
637     String versionNumber = null;
638     if (esGetResult.getOperationResult().getResultCode() == 404) {
639       LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, icer.getEntityPrimaryKeyValue());
640     } else if (esGetResult.getOperationResult().getResultCode() == 200) {
641       wasEntryDiscovered = true;
642       try {
643         versionNumber = NodeUtils.extractFieldValueFromObject(
644             NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
645             "_version");
646       } catch (IOException exc) {
647         LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "version Number",
648             icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
649         return;
650       }
651     } else {
652       /*
653        * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
654        * return.
655        */
656       LOG.info(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
657           String.valueOf(esGetResult.getOperationResult().getResultCode()));
658       return;
659     }
660
661     try {
662       String jsonPayload = null;
663       if (wasEntryDiscovered) {
664         try {
665           ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
666           NodeUtils.extractObjectsByKey(
667               NodeUtils.convertJsonStrToJsonNode(esGetResult.getOperationResult().getResult()),
668               "_source", sourceObject);
669
670           if (!sourceObject.isEmpty()) {
671             String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
672             MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
673             ObjectReader updater = mapper.readerForUpdating(me);
674             MergableEntity merged = updater.readValue(icer.getIndexDocumentJson());
675             jsonPayload = mapper.writeValueAsString(merged);
676           }
677         } catch (IOException exc) {
678           LOG.error(AaiUiMsgs.ES_ABORT_CROSS_ENTITY_REF_SYNC, "source value",
679               icer.getEntityPrimaryKeyValue(), exc.getLocalizedMessage());
680           return;
681         }
682       } else {
683         jsonPayload = icer.getIndexDocumentJson();
684       }
685
686       if (wasEntryDiscovered) {
687         if (versionNumber != null && jsonPayload != null) {
688
689           String requestPayload = esDataProvider.buildBulkImportOperationRequest(getIndexName(),
690               ElasticSearchConfig.getConfig().getType(), icer.getId(), versionNumber, jsonPayload);
691
692           NetworkTransaction transactionTracker = new NetworkTransaction();
693           transactionTracker.setEntityType(esGetResult.getEntityType());
694           transactionTracker.setDescriptor(esGetResult.getDescriptor());
695           transactionTracker.setOperationType(HttpMethod.PUT);
696
697           esWorkOnHand.incrementAndGet();
698           supplyAsync(new PerformElasticSearchUpdate(ElasticSearchConfig.getConfig().getBulkUrl(),
699               requestPayload, esDataProvider, transactionTracker), esPutExecutor)
700                   .whenComplete((result, error) -> {
701
702                     esWorkOnHand.decrementAndGet();
703
704                     if (error != null) {
705                       LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
706                     } else {
707                       updateElasticSearchCounters(result);
708                       processStoreDocumentResult(result, esGetResult, icer);
709                     }
710                   });
711         }
712
713       } else {
714         if (link != null && jsonPayload != null) {
715
716           NetworkTransaction updateElasticTxn = new NetworkTransaction();
717           updateElasticTxn.setLink(link);
718           updateElasticTxn.setEntityType(esGetResult.getEntityType());
719           updateElasticTxn.setDescriptor(esGetResult.getDescriptor());
720           updateElasticTxn.setOperationType(HttpMethod.PUT);
721
722           esWorkOnHand.incrementAndGet();
723           supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, esDataProvider),
724               esPutExecutor).whenComplete((result, error) -> {
725
726                 esWorkOnHand.decrementAndGet();
727
728                 if (error != null) {
729                   LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, error.getLocalizedMessage());
730                 } else {
731                   updateElasticSearchCounters(result);
732                   processStoreDocumentResult(result, esGetResult, icer);
733                 }
734               });
735         }
736       }
737     } catch (Exception exc) {
738       LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_REF_PUT, exc.getLocalizedMessage());
739     }
740   }
741
742   /**
743    * Process store document result.
744    *
745    * @param esPutResult the es put result
746    * @param esGetResult the es get result
747    * @param icer the icer
748    */
749   private void processStoreDocumentResult(NetworkTransaction esPutResult,
750       NetworkTransaction esGetResult, IndexableCrossEntityReference icer) {
751
752     OperationResult or = esPutResult.getOperationResult();
753
754     if (!or.wasSuccessful()) {
755       if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
756
757         if (shouldAllowRetry(icer.getId())) {
758
759           esWorkOnHand.incrementAndGet();
760
761           RetryCrossEntitySyncContainer rsc = new RetryCrossEntitySyncContainer(esGetResult, icer);
762           retryQueue.push(rsc);
763
764           LOG.warn(AaiUiMsgs.ES_CROSS_REF_SYNC_VERSION_CONFLICT);
765         }
766       } else {
767         LOG.error(AaiUiMsgs.ES_CROSS_REF_SYNC_FAILURE, String.valueOf(or.getResultCode()),
768             or.getResult());
769       }
770     }
771   }
772
773   /**
774    * Perform retry sync.
775    */
776   private void performRetrySync() {
777     while (retryQueue.peek() != null) {
778
779       RetryCrossEntitySyncContainer rsc = retryQueue.poll();
780       if (rsc != null) {
781
782         IndexableCrossEntityReference icer = rsc.getIndexableCrossEntityReference();
783         NetworkTransaction txn = rsc.getNetworkTransaction();
784
785         String link = null;
786         try {
787           // In this retry flow the icer object has already
788           // derived its fields
789           link = getElasticFullUrl("/" + icer.getId(), getIndexName());
790         } catch (Exception exc) {
791           LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
792         }
793
794         if (link != null) {
795           NetworkTransaction retryTransaction = new NetworkTransaction();
796           retryTransaction.setLink(link);
797           retryTransaction.setEntityType(txn.getEntityType());
798           retryTransaction.setDescriptor(txn.getDescriptor());
799           retryTransaction.setOperationType(HttpMethod.GET);
800
801           /*
802            * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow and we did
803            * that for this request already when queuing the failed PUT!
804            */
805
806           supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, esDataProvider),
807               esExecutor).whenComplete((result, error) -> {
808
809                 esWorkOnHand.decrementAndGet();
810
811                 if (error != null) {
812                   LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
813                 } else {
814                   updateElasticSearchCounters(result);
815                   performDocumentUpsert(result, icer);
816                 }
817               });
818         }
819
820       }
821     }
822   }
823
824   /**
825    * Should allow retry.
826    *
827    * @param id the id
828    * @return true, if successful
829    */
830   private boolean shouldAllowRetry(String id) {
831     boolean isRetryAllowed = true;
832     if (retryLimitTracker.get(id) != null) {
833       Integer currentCount = retryLimitTracker.get(id);
834       if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
835         isRetryAllowed = false;
836         LOG.error(AaiUiMsgs.ES_CROSS_ENTITY_RESYNC_LIMIT, id);
837       } else {
838         Integer newCount = new Integer(currentCount.intValue() + 1);
839         retryLimitTracker.put(id, newCount);
840       }
841
842     } else {
843       Integer firstRetryCount = new Integer(1);
844       retryLimitTracker.put(id, firstRetryCount);
845     }
846
847     return isRetryAllowed;
848   }
849
850   /**
851    * Gets the populated document.
852    *
853    * @param entityNode the entity node
854    * @param resultDescriptor the result descriptor
855    * @return the populated document
856    * @throws JsonProcessingException the json processing exception
857    * @throws IOException Signals that an I/O exception has occurred.
858    */
859   protected IndexableCrossEntityReference getPopulatedDocument(JsonNode entityNode,
860       OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
861
862     IndexableCrossEntityReference icer = new IndexableCrossEntityReference(oxmModelLoader);
863
864     icer.setEntityType(resultDescriptor.getEntityName());
865
866     List<String> primaryKeyValues = new ArrayList<String>();
867     String pkeyValue = null;
868
869     for (String keyName : resultDescriptor.getPrimaryKeyAttributeName()) {
870       pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
871       if (pkeyValue != null) {
872         primaryKeyValues.add(pkeyValue);
873       } else {
874         LOG.warn(AaiUiMsgs.ES_PKEYVALUE_NULL, resultDescriptor.getEntityName());
875       }
876     }
877
878     final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
879     icer.setEntityPrimaryKeyValue(primaryCompositeKeyValue);
880
881     return icer;
882
883   }
884 }