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