update sparky with configurable features
[aai/sparky-be.git] / sparkybe-onap-service / src / main / java / org / onap / aai / sparky / aggregation / sync / AggregationSynchronizer.java
index a438215..dc6bdc0 100644 (file)
@@ -1,26 +1,22 @@
 /**
- * ============LICENSE_START===================================================
- * SPARKY (AAI UI service)
- * ============================================================================
- * Copyright © 2017 AT&T Intellectual Property.
- * Copyright © 2017 Amdocs
- * All rights reserved.
- * ============================================================================
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright © 2017-2018 Amdocs
+ * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
- *      http://www.apache.org/licenses/LICENSE-2.0
+ *       http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
- * ============LICENSE_END=====================================================
- *
- * ECOMP and OpenECOMP are trademarks
- * and service marks of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
  */
 package org.onap.aai.sparky.aggregation.sync;
 
@@ -36,6 +32,7 @@ import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentLinkedDeque;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
 import java.util.function.Supplier;
 
 import org.onap.aai.cl.api.Logger;
@@ -59,9 +56,9 @@ import org.onap.aai.sparky.sync.entity.SelfLinkDescriptor;
 import org.onap.aai.sparky.sync.enumeration.OperationState;
 import org.onap.aai.sparky.sync.enumeration.SynchronizerState;
 import org.onap.aai.sparky.sync.task.PerformActiveInventoryRetrieval;
-import org.onap.aai.sparky.sync.task.PerformElasticSearchPut;
-import org.onap.aai.sparky.sync.task.PerformElasticSearchRetrieval;
-import org.onap.aai.sparky.sync.task.PerformElasticSearchUpdate;
+import org.onap.aai.sparky.sync.task.PerformSearchServicePut;
+import org.onap.aai.sparky.sync.task.PerformSearchServiceRetrieval;
+import org.onap.aai.sparky.sync.task.PerformSearchServiceUpdate;
 import org.onap.aai.sparky.util.NodeUtils;
 import org.slf4j.MDC;
 
@@ -122,7 +119,6 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer
   /**
    * Instantiates a new entity aggregation synchronizer.
    *
-   * @param indexName the index name
    * @throws Exception the exception
    */
   public AggregationSynchronizer(String entityType, ElasticSearchSchemaConfig schemaConfig,
@@ -237,46 +233,14 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer
         AggregationEntity ae = rsc.getAggregationEntity();
         NetworkTransaction txn = rsc.getNetworkTransaction();
 
-        String link = null;
-        try {
-          /*
-           * In this retry flow the se object has already derived its fields
-           */
-          link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), ae.getId());
-        } catch (Exception exc) {
-          LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
-        }
-
-        if (link != null) {
-          NetworkTransaction retryTransaction = new NetworkTransaction();
-          retryTransaction.setLink(link);
-          retryTransaction.setEntityType(txn.getEntityType());
-          retryTransaction.setDescriptor(txn.getDescriptor());
-          retryTransaction.setOperationType(HttpMethod.GET);
-
-          /*
-           * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow! We already
-           * called incrementAndGet when queuing the failed PUT!
-           */
-
-          supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, elasticSearchAdapter),
-              esExecutor).whenComplete((result, error) -> {
-
-                esWorkOnHand.decrementAndGet();
-
-                if (error != null) {
-                  LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
-                } else {
-                  updateElasticSearchCounters(result);
-                  performDocumentUpsert(result, ae);
-                }
-              });
-        }
+        final Consumer<NetworkTransaction> networkTransactionConsumer = (result) -> performDocumentUpsert(result, ae);
+        performRetrySync(ae.getId(), networkTransactionConsumer, txn);
 
       }
     }
   }
-  
+
+
   /**
    * Perform document upsert.
    *
@@ -299,7 +263,7 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer
      */
     String link = null;
     try {
-      link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), ae.getId()); 
+      link = searchServiceAdapter.buildSearchServiceDocUrl(getIndexName(), ae.getId()); 
     } catch (Exception exc) {
       LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
       return;
@@ -362,9 +326,9 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer
       if (wasEntryDiscovered) {
         if (versionNumber != null && jsonPayload != null) {
 
-          String requestPayload =
-              elasticSearchAdapter.buildBulkImportOperationRequest(schemaConfig.getIndexName(),
-                  schemaConfig.getIndexDocType(), ae.getId(), versionNumber, jsonPayload);
+               String requestPayload =
+                         searchServiceAdapter.buildBulkImportOperationRequest(schemaConfig.getIndexName(),
+                       ae.getId(),jsonPayload);
 
           NetworkTransaction transactionTracker = new NetworkTransaction();
           transactionTracker.setEntityType(esGetTxn.getEntityType());
@@ -372,9 +336,9 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer
           transactionTracker.setOperationType(HttpMethod.PUT);
 
           esWorkOnHand.incrementAndGet();
-          supplyAsync(new PerformElasticSearchUpdate(elasticSearchAdapter.getBulkUrl(),
-              requestPayload, elasticSearchAdapter, transactionTracker), esPutExecutor)
-                  .whenComplete((result, error) -> {
+          supplyAsync(new PerformSearchServiceUpdate(searchServiceAdapter.buildSearchServiceBulkUrl(),
+                  requestPayload, searchServiceAdapter, transactionTracker), esPutExecutor)
+          .whenComplete((result, error) -> {
 
                     esWorkOnHand.decrementAndGet();
 
@@ -399,8 +363,8 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer
           updateElasticTxn.setOperationType(HttpMethod.PUT);
 
           esWorkOnHand.incrementAndGet();
-          supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, elasticSearchAdapter),
-              esPutExecutor).whenComplete((result, error) -> {
+          supplyAsync(new PerformSearchServicePut(jsonPayload, updateElasticTxn, searchServiceAdapter),
+                  esPutExecutor).whenComplete((result, error) -> {
 
                 esWorkOnHand.decrementAndGet();
 
@@ -514,7 +478,7 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer
 
         aaiWorkOnHand.incrementAndGet();
 
-        supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiAdapter), aaiExecutor)
+        supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiAdapter,"sync"), aaiExecutor)
             .whenComplete((result, error) -> {
 
               aaiWorkOnHand.decrementAndGet();
@@ -561,7 +525,7 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer
 
           String link = null;
           try {
-            link = elasticSearchAdapter.buildElasticSearchGetDocUrl(getIndexName(), ae.getId());
+            link = searchServiceAdapter.buildSearchServiceDocUrl(getIndexName(), ae.getId());
           } catch (Exception exc) {
             LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
           }
@@ -575,8 +539,8 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer
 
             esWorkOnHand.incrementAndGet();
 
-            supplyAsync(new PerformElasticSearchRetrieval(n2, elasticSearchAdapter), esExecutor)
-                .whenComplete((result, error) -> {
+            supplyAsync(new PerformSearchServiceRetrieval(n2, searchServiceAdapter), esExecutor)
+            .whenComplete((result, error) -> {
 
                   esWorkOnHand.decrementAndGet();
 
@@ -617,7 +581,7 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer
     Map<String, Object> map = mapper.convertValue(entityNode, Map.class);
     doc.copyAttributeKeyValuePair(map);
   }
-  
+
   /**
    * Process entity type self links.
    *
@@ -625,10 +589,8 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer
    */
   private void processEntityTypeSelfLinks(OperationResult operationResult) {
 
-    JsonNode rootNode = null;
-    
-    if ( operationResult == null ) {
-       return;
+    if (operationResult == null) {
+      return;
     }
 
     final String jsonResult = operationResult.getResult();
@@ -636,46 +598,41 @@ public class AggregationSynchronizer extends AbstractEntitySynchronizer
     if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) {
 
       try {
-        rootNode = mapper.readTree(jsonResult);
-      } catch (IOException exc) {
-        String message =
-            "Could not deserialize JSON (representing operation result) as node tree. " +
-            "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage();
-        LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message);
-      }
-
-      JsonNode resultData = rootNode.get("result-data");
-      ArrayNode resultDataArrayNode = null;
+        JsonNode rootNode = mapper.readTree(jsonResult);
 
-      if (resultData.isArray()) {
-        resultDataArrayNode = (ArrayNode) resultData;
+        JsonNode resultData = rootNode.get("result-data");
 
-        Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
-        JsonNode element = null;
+        if (resultData.isArray()) {
+          ArrayNode resultDataArrayNode = (ArrayNode) resultData;
 
-        while (elementIterator.hasNext()) {
-          element = elementIterator.next();
+          Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
 
-          final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
-          final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
+          while (elementIterator.hasNext()) {
+            JsonNode element = elementIterator.next();
 
-          OxmEntityDescriptor descriptor = null;
+            final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
+            final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
 
-          if (resourceType != null && resourceLink != null) {
+            if (resourceType != null && resourceLink != null) {
 
-            descriptor = oxmEntityLookup.getEntityDescriptors().get(resourceType);
+              OxmEntityDescriptor descriptor = oxmEntityLookup.getEntityDescriptors().get(resourceType);
 
-            if (descriptor == null) {
-              LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
-              // go to next element in iterator
-              continue;
-            }
+              if (descriptor == null) {
+                LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
+                // go to next element in iterator
+                continue;
+              }
 
-            selflinks.add(new SelfLinkDescriptor(resourceLink, SynchronizerConstants.NODES_ONLY_MODIFIER, resourceType));
-            
+              selflinks.add(new SelfLinkDescriptor(resourceLink, SynchronizerConstants.NODES_ONLY_MODIFIER, resourceType));
 
+            }
           }
         }
+      } catch (IOException exc) {
+        String message =
+                "Could not deserialize JSON (representing operation result) as node tree. " +
+                        "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage();
+        LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message);
       }
     }