Fix potential null pointer places
[aai/sparky-be.git] / sparkybe-onap-service / src / main / java / org / onap / aai / sparky / viewinspect / sync / ViewInspectEntitySynchronizer.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
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 package org.onap.aai.sparky.viewinspect.sync;
22
23 import static java.util.concurrent.CompletableFuture.supplyAsync;
24
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Deque;
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.concurrent.ConcurrentHashMap;
33 import java.util.concurrent.ConcurrentLinkedDeque;
34 import java.util.concurrent.ExecutorService;
35 import java.util.function.Supplier;
36
37 import org.onap.aai.cl.api.Logger;
38 import org.onap.aai.cl.eelf.LoggerFactory;
39 import org.onap.aai.cl.mdc.MdcContext;
40 import org.onap.aai.restclient.client.OperationResult;
41 import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor;
42 import org.onap.aai.sparky.config.oxm.OxmEntityLookup;
43 import org.onap.aai.sparky.config.oxm.SearchableEntityLookup;
44 import org.onap.aai.sparky.config.oxm.SearchableOxmEntityDescriptor;
45 import org.onap.aai.sparky.dal.ActiveInventoryAdapter;
46 import org.onap.aai.sparky.dal.NetworkTransaction;
47 import org.onap.aai.sparky.dal.rest.HttpMethod;
48 import org.onap.aai.sparky.logging.AaiUiMsgs;
49 import org.onap.aai.sparky.sync.AbstractEntitySynchronizer;
50 import org.onap.aai.sparky.sync.IndexSynchronizer;
51 import org.onap.aai.sparky.sync.SynchronizerConstants;
52 import org.onap.aai.sparky.sync.config.ElasticSearchSchemaConfig;
53 import org.onap.aai.sparky.sync.config.NetworkStatisticsConfig;
54 import org.onap.aai.sparky.sync.entity.MergableEntity;
55 import org.onap.aai.sparky.sync.entity.SearchableEntity;
56 import org.onap.aai.sparky.sync.entity.SelfLinkDescriptor;
57 import org.onap.aai.sparky.sync.enumeration.OperationState;
58 import org.onap.aai.sparky.sync.enumeration.SynchronizerState;
59 import org.onap.aai.sparky.sync.task.PerformActiveInventoryRetrieval;
60 import org.onap.aai.sparky.sync.task.PerformElasticSearchPut;
61 import org.onap.aai.sparky.sync.task.PerformElasticSearchRetrieval;
62 import org.onap.aai.sparky.sync.task.PerformElasticSearchUpdate;
63 import org.onap.aai.sparky.util.NodeUtils;
64 import org.slf4j.MDC;
65
66 import com.fasterxml.jackson.core.JsonProcessingException;
67 import com.fasterxml.jackson.databind.JsonNode;
68 import com.fasterxml.jackson.databind.ObjectReader;
69 import com.fasterxml.jackson.databind.node.ArrayNode;
70
71 /**
72  * The Class SearchableEntitySynchronizer.
73  */
74 public class ViewInspectEntitySynchronizer extends AbstractEntitySynchronizer
75     implements IndexSynchronizer {
76
77   /**
78    * The Class RetrySearchableEntitySyncContainer.
79    */
80   private class RetrySearchableEntitySyncContainer {
81     NetworkTransaction txn;
82     SearchableEntity se;
83
84     /**
85      * Instantiates a new retry searchable entity sync container.
86      *
87      * @param txn the txn
88      * @param se the se
89      */
90     public RetrySearchableEntitySyncContainer(NetworkTransaction txn, SearchableEntity se) {
91       this.txn = txn;
92       this.se = se;
93     }
94
95     public NetworkTransaction getNetworkTransaction() {
96       return txn;
97     }
98
99     public SearchableEntity getSearchableEntity() {
100       return se;
101     }
102   }
103
104   private static final Logger LOG =
105       LoggerFactory.getInstance().getLogger(ViewInspectEntitySynchronizer.class);
106
107   private boolean allWorkEnumerated;
108   private Deque<SelfLinkDescriptor> selflinks;
109   private Deque<RetrySearchableEntitySyncContainer> retryQueue;
110   private Map<String, Integer> retryLimitTracker;
111   protected ExecutorService esPutExecutor;
112   private OxmEntityLookup oxmEntityLookup;
113   private SearchableEntityLookup searchableEntityLookup;
114
115   /**
116    * Instantiates a new searchable entity synchronizer.
117    *
118    * @throws Exception the exception
119    */
120   public ViewInspectEntitySynchronizer(ElasticSearchSchemaConfig schemaConfig,
121       int internalSyncWorkers, int aaiWorkers, int esWorkers, NetworkStatisticsConfig aaiStatConfig,
122       NetworkStatisticsConfig esStatConfig, OxmEntityLookup oxmEntityLookup,
123       SearchableEntityLookup searchableEntityLookup) throws Exception {
124     super(LOG, "SES", internalSyncWorkers, aaiWorkers, esWorkers, schemaConfig.getIndexName(),
125         aaiStatConfig, esStatConfig);
126     
127     this.oxmEntityLookup = oxmEntityLookup;
128     this.searchableEntityLookup = searchableEntityLookup;
129     this.allWorkEnumerated = false;
130     this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
131     this.retryQueue = new ConcurrentLinkedDeque<RetrySearchableEntitySyncContainer>();
132     this.retryLimitTracker = new ConcurrentHashMap<String, Integer>();
133     this.synchronizerName = "Searchable Entity Synchronizer";
134     this.esPutExecutor = NodeUtils.createNamedExecutor("SES-ES-PUT", 5, LOG);
135     this.aaiEntityStats.intializeEntityCounters(
136         searchableEntityLookup.getSearchableEntityDescriptors().keySet());
137     this.esEntityStats.intializeEntityCounters(
138         searchableEntityLookup.getSearchableEntityDescriptors().keySet());
139     this.syncDurationInMs = -1;
140   }
141
142   /**
143    * Collect all the work.
144    *
145    * @return the operation state
146    */
147   private OperationState collectAllTheWork() {
148     final Map<String, String> contextMap = MDC.getCopyOfContextMap();
149     Map<String, SearchableOxmEntityDescriptor> descriptorMap =
150         searchableEntityLookup.getSearchableEntityDescriptors();
151     
152     if (descriptorMap.isEmpty()) {
153       LOG.error(AaiUiMsgs.ERROR_LOADING_OXM_SEARCHABLE_ENTITIES);
154       LOG.info(AaiUiMsgs.ERROR_LOADING_OXM_SEARCHABLE_ENTITIES);
155       return OperationState.ERROR;
156     }
157
158     Collection<String> syncTypes = descriptorMap.keySet();
159
160     /*Collection<String> syncTypes = new ArrayList<String>();
161     syncTypes.add("service-instance");*/
162
163     try {
164
165       /*
166        * launch a parallel async thread to process the documents for each entity-type (to max the
167        * of the configured executor anyway)
168        */
169
170       aaiWorkOnHand.set(syncTypes.size());
171
172       for (String key : syncTypes) {
173
174         supplyAsync(new Supplier<Void>() {
175
176           @Override
177           public Void get() {
178             MDC.setContextMap(contextMap);
179             OperationResult typeLinksResult = null;
180             try {
181               typeLinksResult = aaiAdapter.getSelfLinksByEntityType(key);
182               System.out.println(typeLinksResult);
183               aaiWorkOnHand.decrementAndGet();
184               processEntityTypeSelfLinks(typeLinksResult);
185             } catch (Exception exc) {
186               // TODO -> LOG, what should be logged here?
187             }
188
189             return null;
190           }
191
192         }, aaiExecutor).whenComplete((result, error) -> {
193
194           if (error != null) {
195             LOG.error(AaiUiMsgs.ERROR_GENERIC,
196                 "An error occurred getting data from AAI. Error = " + error.getMessage());
197           }
198         });
199
200       }
201
202       while (aaiWorkOnHand.get() != 0) {
203
204         if (LOG.isDebugEnabled()) {
205           LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
206         }
207
208         Thread.sleep(1000);
209       }
210
211       aaiWorkOnHand.set(selflinks.size());
212       allWorkEnumerated = true;
213       syncEntityTypes();
214
215       while (!isSyncDone()) {
216         performRetrySync();
217         Thread.sleep(1000);
218       }
219
220       /*
221        * Make sure we don't hang on to retries that failed which could cause issues during future
222        * syncs
223        */
224       retryLimitTracker.clear();
225
226     } catch (Exception exc) {
227       // TODO -> LOG, waht should be logged here?
228     }
229
230     return OperationState.OK;
231   }
232
233   /* (non-Javadoc)
234    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
235    */
236   @Override
237   public OperationState doSync() {
238     this.syncDurationInMs = -1;
239     String txnID = NodeUtils.getRandomTxnId();
240     MdcContext.initialize(txnID, "SearchableEntitySynchronizer", "", "Sync", "");
241     
242     resetCounters();
243     this.allWorkEnumerated = false;
244     syncStartedTimeStampInMs = System.currentTimeMillis();
245     collectAllTheWork();
246
247     return OperationState.OK;
248   }
249
250   /**
251    * Process entity type self links.
252    *
253    * @param operationResult the operation result
254    */
255   private void processEntityTypeSelfLinks(OperationResult operationResult) {
256
257     final String jsonResult = operationResult.getResult();
258
259     if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) {
260
261       try {
262         JsonNode rootNode = mapper.readTree(jsonResult);
263         JsonNode resultData = rootNode.get("result-data");
264
265         if (resultData.isArray()) {
266           ArrayNode resultDataArrayNode = (ArrayNode) resultData;
267
268           Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
269
270           while (elementIterator.hasNext()) {
271             JsonNode element = elementIterator.next();
272
273             final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
274             final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
275
276             SearchableOxmEntityDescriptor descriptor = null;
277
278             if (resourceType != null && resourceLink != null) {
279
280               descriptor = searchableEntityLookup.getSearchableEntityDescriptors().get(resourceType);
281
282               if (descriptor == null) {
283                 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
284                 // go to next element in iterator
285                 continue;
286               }
287
288               if (descriptor.hasSearchableAttributes()) {
289                 selflinks.add(new SelfLinkDescriptor(resourceLink, SynchronizerConstants.NODES_ONLY_MODIFIER, resourceType));
290               }
291
292             }
293           }
294         }
295       } catch (IOException exc) {
296         String message =
297             "Could not deserialize JSON (representing operation result) as node tree. " +
298             "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage();
299         LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message);
300       }
301     }
302
303   }
304
305   /**
306    * Sync entity types.
307    */
308   private void syncEntityTypes() {
309
310     while (selflinks.peek() != null) {
311
312       SelfLinkDescriptor linkDescriptor = selflinks.poll();
313       aaiWorkOnHand.decrementAndGet();
314
315       OxmEntityDescriptor descriptor = null;
316
317       if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
318
319         descriptor = oxmEntityLookup.getEntityDescriptors().get(linkDescriptor.getEntityType());
320
321         if (descriptor == null) {
322           LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
323           // go to next element in iterator
324           continue;
325         }
326
327         NetworkTransaction txn = new NetworkTransaction();
328         txn.setDescriptor(descriptor);
329         txn.setLink(linkDescriptor.getSelfLink());
330         txn.setOperationType(HttpMethod.GET);
331         txn.setEntityType(linkDescriptor.getEntityType());
332
333         aaiWorkOnHand.incrementAndGet();
334
335         supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiAdapter), aaiExecutor)
336             .whenComplete((result, error) -> {
337
338               aaiWorkOnHand.decrementAndGet();
339
340               if (error != null) {
341                 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_GENERIC, error.getLocalizedMessage());
342               } else {
343                 if (result == null) {
344                   LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_FOR_SELF_LINK,
345                       linkDescriptor.getSelfLink());
346                 } else {
347                   updateActiveInventoryCounters(result);
348                   fetchDocumentForUpsert(result);
349                 }
350               }
351             });
352       }
353
354     }
355
356   }
357
358   /**
359    * Perform document upsert.
360    *
361    * @param esGetTxn the es get txn
362    * @param se the se
363    */
364   protected void performDocumentUpsert(NetworkTransaction esGetTxn, SearchableEntity se) {
365     /**
366      * <p>
367      * <ul>
368      * As part of the response processing we need to do the following:
369      * <li>1. Extract the version (if present), it will be the ETAG when we use the
370      * Search-Abstraction-Service
371      * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
372      * tag
373      * <li>a) if version is null or RC=404, then standard put, no _update with version tag
374      * <li>b) if version != null, do PUT with _update?version= versionNumber in the URI to elastic
375      * </ul>
376      * </p>
377      */
378     String link = null;
379     try {
380       link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), se.getId());
381     } catch (Exception exc) {
382       LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
383       return;
384     }
385
386     String versionNumber = null;
387     boolean wasEntryDiscovered = false;
388     if (esGetTxn.getOperationResult().getResultCode() == 404) {
389       LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, se.getEntityPrimaryKeyValue());
390     } else if (esGetTxn.getOperationResult().getResultCode() == 200) {
391       wasEntryDiscovered = true;
392       try {
393         versionNumber = NodeUtils.extractFieldValueFromObject(
394             NodeUtils.convertJsonStrToJsonNode(esGetTxn.getOperationResult().getResult()),
395             "_version");
396       } catch (IOException exc) {
397         String message =
398             "Error extracting version number from response, aborting searchable entity sync of "
399                 + se.getEntityPrimaryKeyValue() + ". Error - " + exc.getLocalizedMessage();
400         LOG.error(AaiUiMsgs.ERROR_EXTRACTING_FROM_RESPONSE, message);
401         return;
402       }
403     } else {
404       /*
405        * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
406        * return.
407        */
408       LOG.error(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
409           String.valueOf(esGetTxn.getOperationResult().getResultCode()));
410       return;
411     }
412
413     try {
414       String jsonPayload = null;
415       if (wasEntryDiscovered) {
416         try {
417           ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
418           NodeUtils.extractObjectsByKey(
419               NodeUtils.convertJsonStrToJsonNode(esGetTxn.getOperationResult().getResult()),
420               "_source", sourceObject);
421
422           if (!sourceObject.isEmpty()) {
423             String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
424             MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
425             ObjectReader updater = mapper.readerForUpdating(me);
426             MergableEntity merged = updater.readValue(NodeUtils.convertObjectToJson(se,false));
427             jsonPayload = mapper.writeValueAsString(merged);
428           }
429         } catch (IOException exc) {
430           String message =
431               "Error extracting source value from response, aborting searchable entity sync of "
432                   + se.getEntityPrimaryKeyValue() + ". Error - " + exc.getLocalizedMessage();
433           LOG.error(AaiUiMsgs.ERROR_EXTRACTING_FROM_RESPONSE, message);
434           return;
435         }
436       } else {
437           jsonPayload = se.getAsJson();
438       }
439
440       if (wasEntryDiscovered) {
441         if (versionNumber != null && jsonPayload != null) {
442
443           String requestPayload = elasticSearchAdapter.buildBulkImportOperationRequest(getIndexName(),
444               "default", se.getId(), versionNumber, jsonPayload);
445
446           NetworkTransaction transactionTracker = new NetworkTransaction();
447           transactionTracker.setEntityType(esGetTxn.getEntityType());
448           transactionTracker.setDescriptor(esGetTxn.getDescriptor());
449           transactionTracker.setOperationType(HttpMethod.PUT);
450
451           esWorkOnHand.incrementAndGet();
452           supplyAsync(new PerformElasticSearchUpdate(elasticSearchAdapter.getBulkUrl(),
453               requestPayload, elasticSearchAdapter, transactionTracker), esPutExecutor)
454                   .whenComplete((result, error) -> {
455
456                     esWorkOnHand.decrementAndGet();
457
458                     if (error != null) {
459                       String message = "Searchable entity sync UPDATE PUT error - "
460                           + error.getLocalizedMessage();
461                       LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
462                     } else {
463                       updateElasticSearchCounters(result);
464                       processStoreDocumentResult(result, esGetTxn, se);
465                     }
466                   });
467         }
468
469       } else {
470         
471         if (link != null && jsonPayload != null) {
472
473           NetworkTransaction updateElasticTxn = new NetworkTransaction();
474           updateElasticTxn.setLink(link);
475           updateElasticTxn.setEntityType(esGetTxn.getEntityType());
476           updateElasticTxn.setDescriptor(esGetTxn.getDescriptor());
477           updateElasticTxn.setOperationType(HttpMethod.PUT);
478
479           esWorkOnHand.incrementAndGet();
480           supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, elasticSearchAdapter),
481               esPutExecutor).whenComplete((result, error) -> {
482
483                 esWorkOnHand.decrementAndGet();
484
485                 if (error != null) {
486                   String message =
487                       "Searchable entity sync UPDATE PUT error - " + error.getLocalizedMessage();
488                   LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
489                 } else {
490                   updateElasticSearchCounters(result);
491                   processStoreDocumentResult(result, esGetTxn, se);
492                 }
493               });
494         }
495       }
496     } catch (Exception exc) {
497       String message = "Exception caught during searchable entity sync PUT operation. Message - "
498           + exc.getLocalizedMessage();
499       LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
500     }
501   }
502
503   /**
504    * Populate searchable entity document.
505    *
506    * @param doc the doc
507    * @param result the result
508    * @param resultDescriptor the result descriptor
509    * @throws JsonProcessingException the json processing exception
510    * @throws IOException Signals that an I/O exception has occurred.
511    */
512   protected void populateSearchableEntityDocument(SearchableEntity doc, String result,
513       OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
514
515     doc.setEntityType(resultDescriptor.getEntityName());
516
517     JsonNode entityNode = mapper.readTree(result);
518
519     List<String> primaryKeyValues = new ArrayList<String>();
520     String pkeyValue = null;
521
522     SearchableOxmEntityDescriptor searchableDescriptor = searchableEntityLookup.getSearchableEntityDescriptors().get(resultDescriptor.getEntityName());
523     
524     for (String keyName : searchableDescriptor.getPrimaryKeyAttributeNames()) {
525       pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
526       if (pkeyValue != null) {
527         primaryKeyValues.add(pkeyValue);
528       } else {
529         String message = "populateSearchableEntityDocument(), pKeyValue is null for entityType = "
530             + resultDescriptor.getEntityName();
531         LOG.warn(AaiUiMsgs.WARN_GENERIC, message);
532       }
533     }
534
535     final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
536     doc.setEntityPrimaryKeyValue(primaryCompositeKeyValue);
537
538     final List<String> searchTagFields = searchableDescriptor.getSearchableAttributes();
539
540     /*
541      * Based on configuration, use the configured field names for this entity-Type to build a
542      * multi-value collection of search tags for elastic search entity search criteria.
543      */
544     for (String searchTagField : searchTagFields) {
545       String searchTagValue = NodeUtils.getNodeFieldAsText(entityNode, searchTagField);
546       if (searchTagValue != null && !searchTagValue.isEmpty()) {
547         doc.addSearchTagWithKey(searchTagValue, searchTagField);
548       }
549     }
550   }
551
552   /**
553    * Fetch document for upsert.
554    *
555    * @param txn the txn
556    */
557   private void fetchDocumentForUpsert(NetworkTransaction txn) {
558     if (!txn.getOperationResult().wasSuccessful()) {
559       String message = "Self link failure. Result - " + txn.getOperationResult().getResult();
560       LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
561       return;
562     }
563
564     SearchableOxmEntityDescriptor searchableDescriptor = searchableEntityLookup
565         .getSearchableEntityDescriptors().get(txn.getDescriptor().getEntityName());
566     
567     try {
568       if (searchableDescriptor.hasSearchableAttributes()) {
569
570         final String jsonResult = txn.getOperationResult().getResult();
571         if (jsonResult != null && jsonResult.length() > 0) {
572
573           SearchableEntity se = new SearchableEntity();
574           se.setLink(ActiveInventoryAdapter.extractResourcePath(txn.getLink()));
575           populateSearchableEntityDocument(se, jsonResult, txn.getDescriptor());
576           se.deriveFields();
577
578           String link = null;
579           try {
580             link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), se.getId());
581           } catch (Exception exc) {
582             LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
583           }
584
585           if (link != null) {
586             NetworkTransaction n2 = new NetworkTransaction();
587             n2.setLink(link);
588             n2.setEntityType(txn.getEntityType());
589             n2.setDescriptor(txn.getDescriptor());
590             n2.setOperationType(HttpMethod.GET);
591
592             esWorkOnHand.incrementAndGet();
593
594             supplyAsync(new PerformElasticSearchRetrieval(n2, elasticSearchAdapter), esExecutor)
595                 .whenComplete((result, error) -> {
596
597                   esWorkOnHand.decrementAndGet();
598
599                   if (error != null) {
600                     LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage());
601                   } else {
602                     updateElasticSearchCounters(result);
603                     performDocumentUpsert(result, se);
604                   }
605                 });
606           }
607         }
608
609       }
610     } catch (JsonProcessingException exc) {
611       // TODO -> LOG, waht should be logged here?
612     } catch (IOException exc) {
613       // TODO -> LOG, waht should be logged here?
614     }
615   }
616
617   /**
618    * Process store document result.
619    *
620    * @param esPutResult the es put result
621    * @param esGetResult the es get result
622    * @param se the se
623    */
624   private void processStoreDocumentResult(NetworkTransaction esPutResult,
625       NetworkTransaction esGetResult, SearchableEntity se) {
626
627     OperationResult or = esPutResult.getOperationResult();
628
629     if (!or.wasSuccessful()) {
630       if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
631
632         if (shouldAllowRetry(se.getId())) {
633           esWorkOnHand.incrementAndGet();
634
635           RetrySearchableEntitySyncContainer rsc =
636               new RetrySearchableEntitySyncContainer(esGetResult, se);
637           retryQueue.push(rsc);
638
639           String message = "Store document failed during searchable entity synchronization"
640               + " due to version conflict. Entity will be re-synced.";
641           LOG.warn(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
642         }
643       } else {
644         String message =
645             "Store document failed during searchable entity synchronization with result code "
646                 + or.getResultCode() + " and result message " + or.getResult();
647         LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
648       }
649     }
650   }
651
652   /**
653    * Perform retry sync.
654    */
655   private void performRetrySync() {
656     while (retryQueue.peek() != null) {
657
658       RetrySearchableEntitySyncContainer rsc = retryQueue.poll();
659       if (rsc != null) {
660
661         SearchableEntity se = rsc.getSearchableEntity();
662         NetworkTransaction txn = rsc.getNetworkTransaction();
663
664         String link = null;
665         try {
666           /*
667            * In this retry flow the se object has already derived its fields
668            */
669           link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), se.getId());
670         } catch (Exception exc) {
671           LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
672         }
673
674         if (link != null) {
675           NetworkTransaction retryTransaction = new NetworkTransaction();
676           retryTransaction.setLink(link);
677           retryTransaction.setEntityType(txn.getEntityType());
678           retryTransaction.setDescriptor(txn.getDescriptor());
679           retryTransaction.setOperationType(HttpMethod.GET);
680
681           /*
682            * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow! We already
683            * called incrementAndGet when queuing the failed PUT!
684            */
685
686           supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, elasticSearchAdapter),
687               esExecutor).whenComplete((result, error) -> {
688
689                 esWorkOnHand.decrementAndGet();
690
691                 if (error != null) {
692                   LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
693                 } else {
694                   updateElasticSearchCounters(result);
695                   performDocumentUpsert(result, se);
696                 }
697               });
698         }
699
700       }
701     }
702   }
703
704   /**
705    * Should allow retry.
706    *
707    * @param id the id
708    * @return true, if successful
709    */
710   private boolean shouldAllowRetry(String id) {
711     boolean isRetryAllowed = true;
712     if (retryLimitTracker.get(id) != null) {
713       Integer currentCount = retryLimitTracker.get(id);
714       if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
715         isRetryAllowed = false;
716         String message = "Searchable entity re-sync limit reached for " + id
717             + ", re-sync will no longer be attempted for this entity";
718         LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
719       } else {
720         Integer newCount = new Integer(currentCount.intValue() + 1);
721         retryLimitTracker.put(id, newCount);
722       }
723     } else {
724       Integer firstRetryCount = new Integer(1);
725       retryLimitTracker.put(id, firstRetryCount);
726     }
727
728     return isRetryAllowed;
729   }
730
731   @Override
732   public SynchronizerState getState() {
733     if (!isSyncDone()) {
734       return SynchronizerState.PERFORMING_SYNCHRONIZATION;
735     }
736
737     return SynchronizerState.IDLE;
738
739   }
740
741   /* (non-Javadoc)
742    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
743    */
744   @Override
745   public String getStatReport(boolean showFinalReport) {
746     syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
747     return this.getStatReport(syncDurationInMs, showFinalReport);
748   }
749
750   /* (non-Javadoc)
751    * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
752    */
753   @Override
754   public void shutdown() {
755     this.shutdownExecutors();
756   }
757
758   @Override
759   protected boolean isSyncDone() {
760     int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
761
762     if (totalWorkOnHand > 0 || !allWorkEnumerated) {
763       return false;
764     }
765
766     return true;
767   }
768
769 }