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