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