Fixed a typo in a name
[aai/data-router.git] / src / main / java / org / onap / aai / datarouter / policy / EntityEventPolicy.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.datarouter.policy;
22
23 import java.io.FileNotFoundException;
24 import java.io.IOException;
25 import java.security.NoSuchAlgorithmException;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.List;
33 import java.util.Map;
34
35 import org.apache.camel.Exchange;
36 import org.apache.camel.Processor;
37 import org.eclipse.persistence.dynamic.DynamicType;
38 import org.eclipse.persistence.internal.helper.DatabaseField;
39 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
40 import org.eclipse.persistence.oxm.MediaType;
41 import org.json.JSONException;
42 import org.json.JSONObject;
43 import org.onap.aai.datarouter.entity.AaiEventEntity;
44 import org.onap.aai.datarouter.entity.AggregationEntity;
45 import org.onap.aai.datarouter.entity.DocumentStoreDataEntity;
46 import org.onap.aai.datarouter.entity.SuggestionSearchEntity;
47 import org.onap.aai.datarouter.entity.TopographicalEntity;
48 import org.onap.aai.datarouter.entity.UebEventHeader;
49 import org.onap.aai.datarouter.logging.EntityEventPolicyMsgs;
50 import org.onap.aai.datarouter.util.NodeUtils;
51 import org.onap.aai.datarouter.util.RouterServiceUtil;
52 import org.onap.aai.datarouter.util.SearchServiceAgent;
53 import org.onap.aai.datarouter.util.SearchSuggestionPermutation;
54 import org.onap.aai.entity.OxmEntityDescriptor;
55 import org.onap.aai.util.CrossEntityReference;
56 import org.onap.aai.util.EntityOxmReferenceHelper;
57 import org.onap.aai.util.ExternalOxmModelProcessor;
58 import org.onap.aai.schema.OxmModelLoader;
59 import org.onap.aai.setup.SchemaVersions;
60 import org.onap.aai.util.Version;
61 import org.onap.aai.util.VersionedOxmEntities;
62 import org.onap.aai.cl.api.Logger;
63 import org.onap.aai.cl.eelf.LoggerFactory;
64 import org.onap.aai.cl.mdc.MdcContext;
65 import org.onap.aai.restclient.client.Headers;
66 import org.onap.aai.restclient.client.OperationResult;
67 import org.onap.aai.restclient.rest.HttpUtil;
68 import org.slf4j.MDC;
69
70 import com.fasterxml.jackson.core.JsonProcessingException;
71 import com.fasterxml.jackson.databind.JsonNode;
72 import com.fasterxml.jackson.databind.ObjectMapper;
73 import com.fasterxml.jackson.databind.ObjectWriter;
74 import com.fasterxml.jackson.databind.node.ObjectNode;
75
76 public class EntityEventPolicy implements Processor {
77
78   public static final String additionalInfo = "Response of AAIEntityEventPolicy";
79   private static final String ENTITY_SEARCH_SCHEMA = "entitysearch_schema.json";
80   private static final String TOPOGRAPHICAL_SEARCH_SCHEMA = "topographysearch_schema.json";
81   private Collection<ExternalOxmModelProcessor> externalOxmModelProcessors;
82
83   private static final String EVENT_HEADER = "event-header";
84   private static final String ENTITY_HEADER = "entity";
85   private static final String ACTION_CREATE = "create";
86   private static final String ACTION_DELETE = "delete";
87   private static final String ACTION_UPDATE = "update";
88   private static final String PROCESS_AAI_EVENT = "Process AAI Event";
89   private static final String TOPO_LAT = "latitude";
90   private static final String TOPO_LONG = "longitude";
91
92   private static final List<String> SUPPORTED_ACTIONS =
93       Arrays.asList(ACTION_CREATE, ACTION_UPDATE, ACTION_DELETE);
94
95   Map<String, DynamicJAXBContext> oxmVersionContextMap = new HashMap<>();
96   private String oxmVersion = null;
97
98   /** Agent for communicating with the Search Service. */
99   private SearchServiceAgent searchAgent = null;
100   
101   /** Search index name for storing AAI event entities. */
102   private String entitySearchIndex;
103
104   /** Search index name for storing topographical search data. */
105   private String topographicalSearchIndex;
106   
107   /** Search index name for suggestive search data. */
108   private String aggregateGenericVnfIndex;
109   
110   private String autosuggestIndex;
111
112   private String srcDomain;
113
114   private Logger logger;
115   private Logger metricsLogger;
116
117   public enum ResponseType {
118     SUCCESS, PARTIAL_SUCCESS, FAILURE;
119   };
120
121   public EntityEventPolicy(EntityEventPolicyConfig config) throws FileNotFoundException {
122     LoggerFactory loggerFactoryInstance = LoggerFactory.getInstance();
123     logger = loggerFactoryInstance.getLogger(EntityEventPolicy.class.getName());
124     metricsLogger = loggerFactoryInstance.getMetricsLogger(EntityEventPolicy.class.getName());
125
126
127     srcDomain = config.getSourceDomain();
128
129     // Populate the index names.
130     entitySearchIndex        = config.getSearchEntitySearchIndex();
131     topographicalSearchIndex = config.getSearchTopographySearchIndex();
132     aggregateGenericVnfIndex = config.getSearchAggregationVnfIndex();
133     autosuggestIndex             = config.getSearchEntityAutoSuggestIndex();
134        
135     // Instantiate the agent that we will use for interacting with the Search Service.
136     searchAgent = new SearchServiceAgent(config.getSearchCertName(),
137                                          config.getSearchKeystore(),
138                                          config.getSearchKeystorePwd(),
139                                          EntityEventPolicy.concatSubUri(config.getSearchBaseUrl(),
140                                                                         config.getSearchEndpoint()),
141                                          config.getSearchEndpointDocuments(),
142                                          logger);
143
144     this.externalOxmModelProcessors = new ArrayList<>();
145     this.externalOxmModelProcessors.add(EntityOxmReferenceHelper.getInstance());
146     OxmModelLoader.registerExternalOxmModelProcessors(externalOxmModelProcessors);
147     OxmModelLoader.loadModels(config.getSchemaVersions(), config.getSchemaLocationsBean());
148     oxmVersionContextMap = OxmModelLoader.getVersionContextMap();
149     parseLatestOxmVersion();
150   }
151
152   private void parseLatestOxmVersion() {
153     int latestVersion = -1;
154     if (oxmVersionContextMap != null) {
155       Iterator it = oxmVersionContextMap.entrySet().iterator();
156       while (it.hasNext()) {
157         Map.Entry pair = (Map.Entry) it.next();
158
159         String version = pair.getKey().toString();
160         int versionNum = Integer.parseInt(version.substring(1, version.length()));
161
162         if (versionNum > latestVersion) {
163           latestVersion = versionNum;
164           oxmVersion = pair.getKey().toString();
165         }
166
167         logger.info(EntityEventPolicyMsgs.PROCESS_OXM_MODEL_FOUND, pair.getKey().toString());
168       }
169     } else {
170       logger.error(EntityEventPolicyMsgs.PROCESS_OXM_MODEL_MISSING, "");
171     }
172   }
173
174   public void startup() {
175     
176     // Create the indexes in the search service if they do not already exist.
177     searchAgent.createSearchIndex(entitySearchIndex, ENTITY_SEARCH_SCHEMA);
178     searchAgent.createSearchIndex(topographicalSearchIndex, TOPOGRAPHICAL_SEARCH_SCHEMA);
179     
180     logger.info(EntityEventPolicyMsgs.ENTITY_EVENT_POLICY_REGISTERED);
181   }
182
183
184   /**
185    * Convert object to json.
186    *
187    * @param object the object
188    * @param pretty the pretty
189    * @return the string
190    * @throws JsonProcessingException the json processing exception
191    */
192   public static String convertObjectToJson(Object object, boolean pretty)
193       throws JsonProcessingException {
194     ObjectWriter ow;
195
196     if (pretty) {
197       ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
198
199     } else {
200       ow = new ObjectMapper().writer();
201     }
202
203     return ow.writeValueAsString(object);
204   }
205
206   public void returnWithError(Exchange exchange, String payload, String errorMsg){
207     logger.error(EntityEventPolicyMsgs.DISCARD_EVENT_NONVERBOSE, errorMsg);
208     logger.debug(EntityEventPolicyMsgs.DISCARD_EVENT_VERBOSE, errorMsg, payload);
209     setResponse(exchange, ResponseType.FAILURE, additionalInfo);
210   }
211   
212   @Override
213   public void process(Exchange exchange) throws Exception {
214
215     long startTime = System.currentTimeMillis();
216
217     String uebPayload = exchange.getIn().getBody().toString();
218
219     JsonNode uebAsJson = null;
220     ObjectMapper mapper = new ObjectMapper();
221     try{
222       uebAsJson = mapper.readTree(uebPayload);
223     } catch (IOException e){
224       returnWithError(exchange, uebPayload, "Invalid Payload");
225       return;
226     }
227
228     // Load the UEB payload data, any errors will result in a failure and discard
229     JSONObject uebObjHeader = getUebContentAsJson(uebPayload, EVENT_HEADER);
230     if (uebObjHeader == null) {
231       returnWithError(exchange, uebPayload, "Payload is missing " + EVENT_HEADER);
232       return;
233     }
234     
235     JSONObject uebObjEntity = getUebContentAsJson(uebPayload, ENTITY_HEADER);
236     if (uebObjEntity == null) {
237       returnWithError(exchange, uebPayload, "Payload is missing " + ENTITY_HEADER);
238       return;
239     }
240
241     UebEventHeader eventHeader;
242     eventHeader = initializeUebEventHeader(uebObjHeader.toString());
243
244     // Get src domain from header; discard event if not originated from same domain
245     String payloadSrcDomain = eventHeader.getDomain();
246     if (payloadSrcDomain == null || !payloadSrcDomain.equalsIgnoreCase(this.srcDomain)) {
247       logger.debug(EntityEventPolicyMsgs.DISCARD_EVENT_VERBOSE,
248           "Unrecognized source domain '" + payloadSrcDomain + "'", uebPayload);
249       logger.error(EntityEventPolicyMsgs.DISCARD_EVENT_NONVERBOSE,
250           "Unrecognized source domain '" + payloadSrcDomain + "'");
251
252       setResponse(exchange, ResponseType.SUCCESS, additionalInfo);
253       return;
254     }
255
256     DynamicJAXBContext oxmJaxbContext = loadOxmContext(oxmVersion);
257     if (oxmJaxbContext == null) {
258       logger.error(EntityEventPolicyMsgs.OXM_VERSION_NOT_SUPPORTED, oxmVersion);
259       logger.debug(EntityEventPolicyMsgs.DISCARD_EVENT_VERBOSE, "OXM version mismatch",
260           uebPayload);
261
262       setResponse(exchange, ResponseType.FAILURE, additionalInfo);
263       return;
264     }
265
266     String action = eventHeader.getAction();
267     if (action == null || !SUPPORTED_ACTIONS.contains(action.toLowerCase())) {
268       logger.debug(EntityEventPolicyMsgs.DISCARD_EVENT_VERBOSE,
269           "Unrecognized action '" + action + "'", uebPayload);
270       logger.error(EntityEventPolicyMsgs.DISCARD_EVENT_NONVERBOSE,
271           "Unrecognized action '" + action + "'");
272
273       setResponse(exchange, ResponseType.FAILURE, additionalInfo);
274       return;
275     }
276
277     String entityType = eventHeader.getEntityType();
278     if (entityType == null) {
279       logger.debug(EntityEventPolicyMsgs.DISCARD_EVENT_VERBOSE,
280           "Payload header missing entity type", uebPayload);
281       logger.error(EntityEventPolicyMsgs.DISCARD_EVENT_NONVERBOSE,
282           "Payload header missing entity type");
283
284       setResponse(exchange, ResponseType.FAILURE, additionalInfo);
285       return;
286     }
287
288     String topEntityType = eventHeader.getTopEntityType();
289     if (topEntityType == null) {
290       logger.debug(EntityEventPolicyMsgs.DISCARD_EVENT_VERBOSE,
291           "Payload header missing top entity type", uebPayload);
292       logger.error(EntityEventPolicyMsgs.DISCARD_EVENT_NONVERBOSE,
293           "Payload header top missing entity type");
294
295       setResponse(exchange, ResponseType.FAILURE, additionalInfo);
296       return;
297     }
298
299     String entityLink = eventHeader.getEntityLink();
300     if (entityLink == null) {
301       logger.debug(EntityEventPolicyMsgs.DISCARD_EVENT_VERBOSE,
302           "Payload header missing entity link", uebPayload);
303       logger.error(EntityEventPolicyMsgs.DISCARD_EVENT_NONVERBOSE,
304           "Payload header missing entity link");
305
306       setResponse(exchange, ResponseType.FAILURE, additionalInfo);
307       return;
308     }
309
310     // log the fact that all data are in good shape
311     logger.info(EntityEventPolicyMsgs.PROCESS_ENTITY_EVENT_POLICY_NONVERBOSE, action,
312         entityType);
313     logger.debug(EntityEventPolicyMsgs.PROCESS_ENTITY_EVENT_POLICY_VERBOSE, action, entityType,
314         uebPayload);
315
316
317     // Process for building AaiEventEntity object
318     String oxmEntityType = new OxmEntityTypeConverter().convert(entityType);
319
320     List<String> searchableAttr =
321         getOxmAttributes(uebPayload, oxmJaxbContext, oxmEntityType, entityType, "searchable");
322     if (searchableAttr == null) {
323       logger.error(EntityEventPolicyMsgs.DISCARD_EVENT_NONVERBOSE,
324           "Searchable attribute not found for payload entity type '" + entityType + "'");
325       logger.debug(EntityEventPolicyMsgs.DISCARD_EVENT_VERBOSE,
326           "Searchable attribute not found for payload entity type '" + entityType + "'",
327           uebPayload);
328
329       setResponse(exchange, ResponseType.FAILURE, additionalInfo);
330       return;
331     }
332
333     String entityPrimaryKeyFieldName =
334         getEntityPrimaryKeyFieldName(oxmJaxbContext, uebPayload, oxmEntityType, entityType);
335     String entityPrimaryKeyFieldValue = lookupValueUsingKey(uebPayload, entityPrimaryKeyFieldName);
336     if (entityPrimaryKeyFieldValue == null || entityPrimaryKeyFieldValue.isEmpty()) {
337       logger.error(EntityEventPolicyMsgs.DISCARD_EVENT_NONVERBOSE,
338           "Payload missing primary key attribute");
339       logger.debug(EntityEventPolicyMsgs.DISCARD_EVENT_VERBOSE,
340           "Payload missing primary key attribute", uebPayload);
341
342       setResponse(exchange, ResponseType.FAILURE, additionalInfo);
343       return;
344     }
345
346     AaiEventEntity aaiEventEntity = new AaiEventEntity();
347
348     /*
349      * Use the OXM Model to determine the primary key field name based on the entity-type
350      */
351
352     aaiEventEntity.setEntityPrimaryKeyName(entityPrimaryKeyFieldName);
353     aaiEventEntity.setEntityPrimaryKeyValue(entityPrimaryKeyFieldValue);
354     aaiEventEntity.setEntityType(entityType);
355     aaiEventEntity.setLink(entityLink);
356
357     if (!getSearchTags(aaiEventEntity, searchableAttr, uebPayload, action)) {
358       logger.error(EntityEventPolicyMsgs.DISCARD_EVENT_NONVERBOSE,
359           "Payload missing searchable attribute for entity type '" + entityType + "'");
360       logger.debug(EntityEventPolicyMsgs.DISCARD_EVENT_VERBOSE,
361           "Payload missing searchable attribute for entity type '" + entityType + "'", uebPayload);
362
363       setResponse(exchange, ResponseType.FAILURE, additionalInfo);
364       return;
365
366     }
367
368     try {
369       aaiEventEntity.deriveFields();
370
371     } catch (NoSuchAlgorithmException e) {
372       logger.error(EntityEventPolicyMsgs.DISCARD_EVENT_VERBOSE,
373           "Cannot create unique SHA digest");
374       logger.debug(EntityEventPolicyMsgs.DISCARD_EVENT_VERBOSE,
375           "Cannot create unique SHA digest", uebPayload);
376
377       setResponse(exchange, ResponseType.FAILURE, additionalInfo);
378       return;
379     }
380
381     handleSearchServiceOperation(aaiEventEntity, action, entitySearchIndex);
382
383     handleTopographicalData(uebPayload, action, entityType, oxmEntityType, oxmJaxbContext,
384         entityPrimaryKeyFieldName, entityPrimaryKeyFieldValue);
385
386     /*
387      * Use the versioned OXM Entity class to get access to cross-entity reference helper collections
388      */
389     VersionedOxmEntities oxmEntities =
390         EntityOxmReferenceHelper.getInstance().getVersionedOxmEntities(Version.valueOf(oxmVersion.toLowerCase()));
391
392     /**
393      * NOTES:
394      * 1. If the entity type is "customer", the below check will return true if any nested entityType
395      * in that model could contain a CER based on the OXM model version that has been loaded.
396      * 2. For a DELETE operation on outer/parent entity (handled by the regular flow: 
397      * handleSearchServiceOperation()), ignore processing for cross-entity-reference under the
398      * assumption that AAI will push down all required cascade-deletes for nested entities as well
399      * 3. Handling the case where UEB events arrive out of order: CREATE customer is received before
400      *  CREATE service-instance.
401      */
402
403     if (!action.equalsIgnoreCase(ACTION_DELETE) && oxmEntities != null 
404         && oxmEntities.entityModelContainsCrossEntityReference(topEntityType)) {
405
406       // We know the model "can" contain a CER reference definition, let's process a bit more
407
408       HashMap<String, CrossEntityReference> crossEntityRefMap =
409           oxmEntities.getCrossEntityReferences();
410
411       JSONObject entityJsonObject = getUebEntity(uebPayload);
412
413       JsonNode entityJsonNode = convertToJsonNode(entityJsonObject.toString());
414       
415       String parentEntityType = entityType;
416       
417       String targetEntityUrl = entityLink;
418
419       for (Map.Entry<String, CrossEntityReference> entry : crossEntityRefMap.entrySet()) {
420
421         /*
422          * if we know service-subscription is in the tree, then we can pull our all instances and
423          * process from there.
424          */
425
426         String key = entry.getKey();
427         CrossEntityReference cerDescriptor = entry.getValue();
428
429         ArrayList<JsonNode> foundNodes = new ArrayList<>();
430
431         RouterServiceUtil.extractObjectsByKey(entityJsonNode, key, foundNodes);
432
433         if (!foundNodes.isEmpty()) {
434
435           for (JsonNode n : foundNodes) {
436             if ("customer".equalsIgnoreCase(parentEntityType)){  
437               /*
438                * NOTES:
439                * 1. prepare to hand-create url for service-instance
440                * 2. this will break if the URL structure for service-instance changes
441                */
442               if (n.has("service-type")){
443                 targetEntityUrl += "/service-subscriptions/service-subscription/" 
444                     + RouterServiceUtil.getNodeFieldAsText(n, "service-type") 
445                     + "/service-instances/service-instance/";
446               }
447               
448             }
449
450             List<String> extractedParentEntityAttributeValues = new ArrayList<>();
451
452             RouterServiceUtil.extractFieldValuesFromObject(n, cerDescriptor.getAttributeNames(),
453                 extractedParentEntityAttributeValues);
454
455             List<JsonNode> nestedTargetEntityInstances = new ArrayList<>();
456             RouterServiceUtil.extractObjectsByKey(n, cerDescriptor.getTargetEntityType(),
457                 nestedTargetEntityInstances);
458
459             for (JsonNode targetEntityInstance : nestedTargetEntityInstances) {
460               /*
461                * Now: 
462                * 1. build the AAIEntityType (IndexDocument) based on the extract entity 
463                * 2. Get data from ES
464                * 3. Extract ETAG 
465                * 4. Merge ES Doc + AAIEntityType + Extracted Parent Cross-Entity-Reference Values
466                * 5. Put data into ES with ETAG + updated doc 
467                */
468
469               // Get the complete URL for target entity
470               if (targetEntityInstance.has("link")) {   // nested SI has url mentioned
471                 targetEntityUrl = RouterServiceUtil.getNodeFieldAsText(targetEntityInstance, 
472                     "link");
473               } else if ("customer".equalsIgnoreCase(parentEntityType) && 
474                   targetEntityInstance.has("service-instance-id")){
475                 targetEntityUrl += RouterServiceUtil.getNodeFieldAsText(targetEntityInstance, 
476                     "service-instance-id");
477               }
478                     
479               OxmEntityDescriptor searchableDescriptor =
480                   oxmEntities.getSearchableEntityDescriptor(cerDescriptor.getTargetEntityType());
481
482               if (searchableDescriptor != null) {
483
484                 if (!searchableDescriptor.getSearchableAttributes().isEmpty()) {
485
486                   AaiEventEntity entityToSync = null;
487
488                   try {
489
490                     entityToSync = getPopulatedEntity(targetEntityInstance, searchableDescriptor);
491
492                     /*
493                      * Ready to do some ElasticSearch ops
494                      */
495
496                     for (String parentCrossEntityReferenceAttributeValue : extractedParentEntityAttributeValues) {
497                       entityToSync
498                           .addCrossEntityReferenceValue(parentCrossEntityReferenceAttributeValue);
499                     }
500
501                     entityToSync.setLink(targetEntityUrl);
502                     entityToSync.deriveFields();
503
504                     updateCerInEntity(entityToSync);
505
506                   } catch (NoSuchAlgorithmException e) {
507                     logger.debug(e.getMessage());
508                   }
509                 }
510               } else {
511                 logger.debug(EntityEventPolicyMsgs.CROSS_ENTITY_REFERENCE_SYNC,
512                     "failure to find searchable descriptor for type "
513                         + cerDescriptor.getTargetEntityType());
514               }
515             }
516
517           }
518
519         } else {
520           logger.debug(EntityEventPolicyMsgs.CROSS_ENTITY_REFERENCE_SYNC,
521               "failed to find 0 instances of cross-entity-reference with entity " + key);
522         }
523
524       }
525
526     } else {
527       logger.info(EntityEventPolicyMsgs.CROSS_ENTITY_REFERENCE_SYNC, "skipped due to OXM model for "
528           + topEntityType + " does not contain a cross-entity-reference entity");
529     }
530
531     /*
532      * Process for autosuggestable entities
533      */
534     if (oxmEntities != null) {
535       Map<String, OxmEntityDescriptor> rootDescriptor =
536           oxmEntities.getSuggestableEntityDescriptors();
537       if (!rootDescriptor.isEmpty()) {
538         List<String> suggestibleAttrInPayload = new ArrayList<>();
539         List<String> suggestibleAttrInOxm = extractSuggestableAttr(oxmEntities, entityType);
540         if (suggestibleAttrInOxm != null) {
541           for (String attr: suggestibleAttrInOxm){
542             if ( uebObjEntity.has(attr) ){
543               suggestibleAttrInPayload.add(attr);
544             }
545           }
546         }
547
548         if (suggestibleAttrInPayload.isEmpty()) {
549           return;
550         }
551
552         List<String> suggestionAliases = extractAliasForSuggestableEntity(oxmEntities, entityType);
553         AggregationEntity ae = new AggregationEntity();
554         ae.setLink(entityLink);
555         ae.deriveFields(uebAsJson);
556
557         handleSearchServiceOperation(ae, action, aggregateGenericVnfIndex);
558
559         /*
560          * It was decided to silently ignore DELETE requests for resources we don't allow to be
561          * deleted. e.g. auto-suggestion deletion is not allowed while aggregation deletion is.
562          */
563         if (!ACTION_DELETE.equalsIgnoreCase(action)) {
564           List<ArrayList<String>> listOfValidPowerSetElements =
565               SearchSuggestionPermutation.getNonEmptyUniqueLists(suggestibleAttrInPayload);
566
567           // Now we have a list containing the power-set (minus empty element) for the status that are
568           // available in the payload. Try inserting a document for every combination.
569           for (ArrayList<String> list : listOfValidPowerSetElements) {
570             SuggestionSearchEntity suggestionSearchEntity = new SuggestionSearchEntity();
571             suggestionSearchEntity.setEntityType(entityType);
572             suggestionSearchEntity.setSuggestableAttr(list);
573             suggestionSearchEntity.setEntityTypeAliases(suggestionAliases);
574             suggestionSearchEntity.setFilterBasedPayloadFromResponse(uebAsJson.get("entity"),
575                 suggestibleAttrInOxm, list);
576             suggestionSearchEntity.setSuggestionInputPermutations(
577                 suggestionSearchEntity.generateSuggestionInputPermutations());
578
579             if (suggestionSearchEntity.isSuggestableDoc()) {
580               try {
581                 suggestionSearchEntity.generateSearchSuggestionDisplayStringAndId();
582               } catch (NoSuchAlgorithmException e) {
583                 logger.error(EntityEventPolicyMsgs.DISCARD_UPDATING_SEARCH_SUGGESTION_DATA,
584                     "Cannot create unique SHA digest for search suggestion data. Exception: "
585                         + e.getLocalizedMessage());
586               }
587
588               handleSearchServiceOperation(suggestionSearchEntity, action, autosuggestIndex);
589             }
590           }
591         }
592       }
593     }
594
595     long stopTime = System.currentTimeMillis();
596
597     metricsLogger.info(EntityEventPolicyMsgs.OPERATION_RESULT_NO_ERRORS, PROCESS_AAI_EVENT,
598         String.valueOf(stopTime - startTime));
599
600     setResponse(exchange, ResponseType.SUCCESS, additionalInfo);
601     return;
602   }
603
604   public List<String> extractSuggestableAttr(VersionedOxmEntities oxmEntities, String entityType) {
605     // Extract suggestable attributeshandleTopographicalData
606     Map<String, OxmEntityDescriptor> rootDescriptor = oxmEntities.getSuggestableEntityDescriptors();
607
608     if (rootDescriptor == null) {
609       return Collections.emptyList();
610     }
611
612     OxmEntityDescriptor desc = rootDescriptor.get(entityType);
613     
614     if (desc == null) {
615       return Collections.emptyList();
616     }
617
618     return desc.getSuggestableAttributes();
619   }
620
621   public List<String> extractAliasForSuggestableEntity(VersionedOxmEntities oxmEntities,
622       String entityType) {
623
624     // Extract alias
625     Map<String, OxmEntityDescriptor> rootDescriptor = oxmEntities.getEntityAliasDescriptors();
626
627     if (rootDescriptor == null) {
628       return Collections.emptyList();
629     }
630
631     OxmEntityDescriptor desc = rootDescriptor.get(entityType);
632     return desc.getAlias();
633   }
634
635   private void setResponse(Exchange exchange, ResponseType responseType, String additionalInfo) {
636
637     exchange.getOut().setHeader("ResponseType", responseType.toString());
638     exchange.getOut().setBody(additionalInfo);
639   }
640
641   public void extractDetailsForAutosuggestion(VersionedOxmEntities oxmEntities, String entityType,
642       List<String> suggestableAttr, List<String> alias) {
643
644     // Extract suggestable attributes
645     Map<String, OxmEntityDescriptor> rootDescriptor = oxmEntities.getSuggestableEntityDescriptors();
646
647     OxmEntityDescriptor desc = rootDescriptor.get(entityType);
648     suggestableAttr = desc.getSuggestableAttributes();
649
650     // Extract alias
651     rootDescriptor = oxmEntities.getEntityAliasDescriptors();
652     desc = rootDescriptor.get(entityType);
653     alias = desc.getAlias();
654   }
655
656   /*
657    * Load the UEB JSON payload, any errors would result to a failure case response.
658    */
659   private JSONObject getUebContentAsJson(String payload, String contentKey) {
660
661     JSONObject uebJsonObj;
662     JSONObject uebObjContent;
663
664     try {
665       uebJsonObj = new JSONObject(payload);
666     } catch (JSONException e) {
667       logger.debug(EntityEventPolicyMsgs.UEB_INVALID_PAYLOAD_JSON_FORMAT, payload);
668       logger.error(EntityEventPolicyMsgs.UEB_INVALID_PAYLOAD_JSON_FORMAT, payload);
669       return null;
670     }
671
672     if (uebJsonObj.has(contentKey)) {
673       uebObjContent = uebJsonObj.getJSONObject(contentKey);
674     } else {
675       logger.debug(EntityEventPolicyMsgs.UEB_FAILED_TO_PARSE_PAYLOAD, contentKey);
676       logger.error(EntityEventPolicyMsgs.UEB_FAILED_TO_PARSE_PAYLOAD, contentKey);
677       return null;
678     }
679
680     return uebObjContent;
681   }
682
683
684   private UebEventHeader initializeUebEventHeader(String payload) {
685
686     UebEventHeader eventHeader = null;
687     ObjectMapper mapper = new ObjectMapper();
688
689     // Make sure that were were actually passed in a valid string.
690     if (payload == null || payload.isEmpty()) {
691       logger.debug(EntityEventPolicyMsgs.UEB_FAILED_TO_PARSE_PAYLOAD, EVENT_HEADER);
692       logger.error(EntityEventPolicyMsgs.UEB_FAILED_TO_PARSE_PAYLOAD, EVENT_HEADER);
693
694       return eventHeader;
695     }
696
697     // Marshal the supplied string into a UebEventHeader object.
698     try {
699       eventHeader = mapper.readValue(payload, UebEventHeader.class);
700     } catch (JsonProcessingException e) {
701       logger.error(EntityEventPolicyMsgs.UEB_FAILED_UEBEVENTHEADER_CONVERSION, e.toString());
702     } catch (Exception e) {
703       logger.error(EntityEventPolicyMsgs.UEB_FAILED_UEBEVENTHEADER_CONVERSION, e.toString());
704     }
705
706     if (eventHeader != null) {
707       logger.debug(EntityEventPolicyMsgs.UEB_EVENT_HEADER_PARSED, eventHeader.toString());
708     }
709
710     return eventHeader;
711
712   }
713
714
715   private String getEntityPrimaryKeyFieldName(DynamicJAXBContext oxmJaxbContext, String payload,
716       String oxmEntityType, String entityType) {
717
718     DynamicType entity = oxmJaxbContext.getDynamicType(oxmEntityType);
719     if (entity == null) {
720       return null;
721     }
722
723     List<DatabaseField> list = entity.getDescriptor().getPrimaryKeyFields();
724     if (list != null && !list.isEmpty()) {
725       String keyName = list.get(0).getName();
726       return keyName.substring(0, keyName.indexOf('/'));
727     }
728
729     return "";
730   }
731
732   private String lookupValueUsingKey(String payload, String key) throws JSONException {
733     JsonNode jsonNode = convertToJsonNode(payload);
734     return RouterServiceUtil.recursivelyLookupJsonPayload(jsonNode, key);
735   }
736
737   private JsonNode convertToJsonNode(String payload) {
738
739     ObjectMapper mapper = new ObjectMapper();
740     JsonNode jsonNode = null;
741     try {
742       jsonNode = mapper.readTree(mapper.getJsonFactory().createJsonParser(payload));
743     } catch (IOException e) {
744       logger.debug(EntityEventPolicyMsgs.FAILED_TO_PARSE_UEB_PAYLOAD, ENTITY_HEADER + " missing",
745           payload);
746       logger.error(EntityEventPolicyMsgs.FAILED_TO_PARSE_UEB_PAYLOAD, ENTITY_HEADER + " missing",
747           "");
748     }
749
750     return jsonNode;
751   }
752
753   private boolean getSearchTags(AaiEventEntity aaiEventEntity, List<String> searchableAttr,
754       String payload, String action) {
755
756     boolean hasSearchableAttr = false;
757     for (String searchTagField : searchableAttr) {
758       String searchTagValue;
759       if (searchTagField.equalsIgnoreCase(aaiEventEntity.getEntityPrimaryKeyName())) {
760         searchTagValue = aaiEventEntity.getEntityPrimaryKeyValue();
761       } else {
762         searchTagValue = this.lookupValueUsingKey(payload, searchTagField);
763       }
764
765       if (searchTagValue != null && !searchTagValue.isEmpty()) {
766         hasSearchableAttr = true;
767         aaiEventEntity.addSearchTagWithKey(searchTagValue, searchTagField);
768       }
769     }
770     return hasSearchableAttr;
771   }
772
773   /*
774    * Check if OXM version is available. If available, load it.
775    */
776   private DynamicJAXBContext loadOxmContext(String version) {
777     if (version == null) {
778       logger.error(EntityEventPolicyMsgs.FAILED_TO_FIND_OXM_VERSION, version);
779       return null;
780     }
781
782     return oxmVersionContextMap.get(version);
783   }
784
785   private List<String> getOxmAttributes(String payload, DynamicJAXBContext oxmJaxbContext,
786       String oxmEntityType, String entityType, String fieldName) {
787
788     DynamicType entity = (DynamicType) oxmJaxbContext.getDynamicType(oxmEntityType);
789     if (entity == null) {
790       return null;
791     }
792
793     /*
794      * Check for searchable XML tag
795      */
796     List<String> fieldValues = null;
797     Map<String, String> properties = entity.getDescriptor().getProperties();
798     for (Map.Entry<String, String> entry : properties.entrySet()) {
799       if (entry.getKey().equalsIgnoreCase(fieldName)) {
800         fieldValues = Arrays.asList(entry.getValue().split(","));
801         break;
802       }
803     }
804
805     return fieldValues;
806   }
807
808   private JSONObject getUebEntity(String payload) {
809     JSONObject uebJsonObj;
810
811     try {
812       uebJsonObj = new JSONObject(payload);
813     } catch (JSONException e) {
814       logger.debug(EntityEventPolicyMsgs.DISCARD_EVENT_VERBOSE,
815           "Payload has invalid JSON Format", payload);
816       logger.error(EntityEventPolicyMsgs.DISCARD_EVENT_NONVERBOSE,
817           "Payload has invalid JSON Format");
818       return null;
819     }
820
821     if (uebJsonObj.has(ENTITY_HEADER)) {
822       return uebJsonObj.getJSONObject(ENTITY_HEADER);
823     } else {
824       logger.debug(EntityEventPolicyMsgs.FAILED_TO_PARSE_UEB_PAYLOAD, ENTITY_HEADER + " missing", payload);
825       logger.error(EntityEventPolicyMsgs.FAILED_TO_PARSE_UEB_PAYLOAD, ENTITY_HEADER + " missing");
826       return null;
827     }
828   }
829
830   protected AaiEventEntity getPopulatedEntity(JsonNode entityNode,
831       OxmEntityDescriptor resultDescriptor) {
832     AaiEventEntity d = new AaiEventEntity();
833
834     d.setEntityType(resultDescriptor.getEntityName());
835
836     List<String> primaryKeyValues = new ArrayList<>();
837     List<String> primaryKeyNames = new ArrayList<>();
838     String pkeyValue;
839
840     for (String keyName : resultDescriptor.getPrimaryKeyAttributeName()) {
841       pkeyValue = RouterServiceUtil.getNodeFieldAsText(entityNode, keyName);
842       if (pkeyValue != null) {
843         primaryKeyValues.add(pkeyValue);
844         primaryKeyNames.add(keyName);
845       } else {
846         logger.error(EntityEventPolicyMsgs.PRIMARY_KEY_NULL_FOR_ENTITY_TYPE,
847             resultDescriptor.getEntityName());
848       }
849     }
850
851     final String primaryCompositeKeyValue = RouterServiceUtil.concatArray(primaryKeyValues, "/");
852     d.setEntityPrimaryKeyValue(primaryCompositeKeyValue);
853     final String primaryCompositeKeyName = RouterServiceUtil.concatArray(primaryKeyNames, "/");
854     d.setEntityPrimaryKeyName(primaryCompositeKeyName);
855
856     final List<String> searchTagFields = resultDescriptor.getSearchableAttributes();
857
858     /*
859      * Based on configuration, use the configured field names for this entity-Type to build a
860      * multi-value collection of search tags for elastic search entity search criteria.
861      */
862
863
864     for (String searchTagField : searchTagFields) {
865       String searchTagValue = RouterServiceUtil.getNodeFieldAsText(entityNode, searchTagField);
866       if (searchTagValue != null && !searchTagValue.isEmpty()) {
867         d.addSearchTagWithKey(searchTagValue, searchTagField);
868       }
869     }
870
871     return d;
872   }
873
874   private void updateCerInEntity(AaiEventEntity aaiEventEntity) {
875     try {
876       Map<String, List<String>> headers = new HashMap<>();
877       headers.put(Headers.FROM_APP_ID, Arrays.asList("Data Router"));
878       headers.put(Headers.TRANSACTION_ID, Arrays.asList(MDC.get(MdcContext.MDC_REQUEST_ID)));
879
880       String entityId = aaiEventEntity.getId();
881       String jsonPayload;
882
883       // Run the GET to retrieve the ETAG from the search service
884       OperationResult storedEntity = searchAgent.getDocument(entitySearchIndex, entityId);
885
886       if (HttpUtil.isHttpResponseClassSuccess(storedEntity.getResultCode())) {
887         /*
888          * NOTES: aaiEventEntity (ie the nested entity) may contain a subset of properties of 
889          * the pre-existing object, 
890          * so all we want to do is update the CER on the pre-existing object (if needed).
891          */
892         
893         List<String> etag = storedEntity.getHeaders().get(Headers.ETAG);
894
895         if (etag != null && !etag.isEmpty()) {
896           headers.put(Headers.IF_MATCH, etag);
897         } else {
898           logger.error(EntityEventPolicyMsgs.NO_ETAG_AVAILABLE_FAILURE,
899                   entitySearchIndex, entityId);
900         }
901         
902         ArrayList<JsonNode> sourceObject = new ArrayList<>();
903         NodeUtils.extractObjectsByKey(
904             NodeUtils.convertJsonStrToJsonNode(storedEntity.getResult()),
905             "content", sourceObject);
906
907         if (!sourceObject.isEmpty()) {
908           JsonNode node = sourceObject.get(0);
909           final String sourceCer = NodeUtils.extractFieldValueFromObject(node, 
910               "crossReferenceEntityValues");
911           String newCer = aaiEventEntity.getCrossReferenceEntityValues();
912           boolean hasNewCer = true;
913           if (sourceCer != null && sourceCer.length() > 0){ // already has CER
914             if ( !sourceCer.contains(newCer)){//don't re-add
915               newCer = sourceCer + ";" + newCer;
916             } else {
917               hasNewCer = false;
918             }
919           }
920           
921           if (hasNewCer){
922             // Do the PUT with new CER
923             ((ObjectNode)node).put("crossReferenceEntityValues", newCer);
924             jsonPayload = NodeUtils.convertObjectToJson(node, false);
925             searchAgent.putDocument(entitySearchIndex, entityId, jsonPayload, headers);
926           }
927          }
928       } else {
929
930         if (storedEntity.getResultCode() == 404) {
931           // entity not found, so attempt to do a PUT
932           searchAgent.putDocument(entitySearchIndex, entityId, aaiEventEntity.getAsJson(), headers);
933         } else {
934           logger.error(EntityEventPolicyMsgs.FAILED_TO_UPDATE_ENTITY_IN_DOCSTORE,
935               aaiEventEntity.getId(), "SYNC_ENTITY");
936         }
937       }
938     } catch (IOException e) {
939       logger.error(EntityEventPolicyMsgs.FAILED_TO_UPDATE_ENTITY_IN_DOCSTORE,
940           aaiEventEntity.getId(), "SYNC_ENTITY");
941     }
942   }
943
944   /**
945    * Perform create, read, update or delete (CRUD) operation on search engine's suggestive search
946    * index
947    * 
948    * @param eventEntity Entity/data to use in operation
949    * @param action The operation to perform
950    * @param target Resource to perform the operation on
951    * @param allowDeleteEvent Allow delete operation to be performed on resource
952    */
953   protected void handleSearchServiceOperation(DocumentStoreDataEntity eventEntity, 
954                                             String                  action,
955                                             String                  index) {
956     try {
957
958       Map<String, List<String>> headers = new HashMap<>();
959       headers.put(Headers.FROM_APP_ID, Arrays.asList("DataLayer"));
960       headers.put(Headers.TRANSACTION_ID, Arrays.asList(MDC.get(MdcContext.MDC_REQUEST_ID)));
961
962       String entityId = eventEntity.getId();
963
964       if ((action.equalsIgnoreCase(ACTION_CREATE) && entityId != null)
965           || action.equalsIgnoreCase(ACTION_UPDATE)) {
966
967         // Run the GET to retrieve the ETAG from the search service
968         OperationResult storedEntity = searchAgent.getDocument(index, entityId);
969
970         if (HttpUtil.isHttpResponseClassSuccess(storedEntity.getResultCode())) {
971           List<String> etag = storedEntity.getHeaders().get(Headers.ETAG);
972
973           if (etag != null && !etag.isEmpty()) {
974             headers.put(Headers.IF_MATCH, etag);
975           } else {
976             logger.error(EntityEventPolicyMsgs.NO_ETAG_AVAILABLE_FAILURE, index,
977                 entityId);
978           }
979         }
980
981         // Write the entity to the search service.
982         // PUT
983         searchAgent.putDocument(index, entityId, eventEntity.getAsJson(), headers);
984       } else if (action.equalsIgnoreCase(ACTION_CREATE)) {
985         // Write the entry to the search service.
986         searchAgent.postDocument(index, eventEntity.getAsJson(), headers);
987         
988       } else if (action.equalsIgnoreCase(ACTION_DELETE)) {
989         // Run the GET to retrieve the ETAG from the search service
990         OperationResult storedEntity = searchAgent.getDocument(index, entityId);
991
992         if (HttpUtil.isHttpResponseClassSuccess(storedEntity.getResultCode())) {
993           List<String> etag = storedEntity.getHeaders().get(Headers.ETAG);
994
995           if (etag != null && !etag.isEmpty()) {
996             headers.put(Headers.IF_MATCH, etag);
997           } else {
998             logger.error(EntityEventPolicyMsgs.NO_ETAG_AVAILABLE_FAILURE, index,
999                 entityId);
1000           }
1001           
1002           /*
1003            * The Spring-Boot version of the search-data-service rejects the DELETE operation unless
1004            * we specify a Content-Type.
1005            */
1006
1007           headers.put("Content-Type", Arrays.asList(MediaType.APPLICATION_JSON.getMediaType()));
1008
1009           searchAgent.deleteDocument(index, eventEntity.getId(), headers);
1010         } else {
1011           logger.error(EntityEventPolicyMsgs.NO_ETAG_AVAILABLE_FAILURE, index,
1012               entityId);
1013         }
1014       } else {
1015         logger.error(EntityEventPolicyMsgs.ENTITY_OPERATION_NOT_SUPPORTED, action);
1016       }
1017     } catch (IOException e) {
1018       logger.error(EntityEventPolicyMsgs.FAILED_TO_UPDATE_ENTITY_IN_DOCSTORE, eventEntity.getId(),
1019           action);
1020     }
1021   }
1022
1023   private void handleTopographicalData(String payload, String action, String entityType,
1024       String oxmEntityType, DynamicJAXBContext oxmJaxbContext, String entityPrimaryKeyFieldName,
1025       String entityPrimaryKeyFieldValue) {
1026
1027     Map<String, String> topoData = new HashMap<>();
1028     String entityLink;
1029     List<String> topographicalAttr =
1030         getOxmAttributes(payload, oxmJaxbContext, oxmEntityType, entityType, "geoProps");
1031     if (topographicalAttr == null) {
1032       logger.error(EntityEventPolicyMsgs.DISCARD_UPDATING_TOPOGRAPHY_DATA_NONVERBOSE,
1033           "Topograhical attribute not found for payload entity type '" + entityType + "'");
1034       logger.debug(EntityEventPolicyMsgs.DISCARD_UPDATING_TOPOGRAPHY_DATA_VERBOSE,
1035           "Topograhical attribute not found for payload entity type '" + entityType + "'",
1036           payload);
1037     } else {
1038       entityLink = lookupValueUsingKey(payload, "entity-link");
1039       for (String topoAttr : topographicalAttr) {
1040         topoData.put(topoAttr, lookupValueUsingKey(payload, topoAttr));
1041       }
1042       updateTopographicalSearchDb(topoData, entityType, action, entityPrimaryKeyFieldName,
1043           entityPrimaryKeyFieldValue, entityLink);
1044     }
1045
1046   }
1047
1048   private void updateTopographicalSearchDb(Map<String, String> topoData, String entityType,
1049       String action, String entityPrimaryKeyName, String entityPrimaryKeyValue, String entityLink) {
1050
1051     TopographicalEntity topoEntity = new TopographicalEntity();
1052     topoEntity.setEntityPrimaryKeyName(entityPrimaryKeyName);
1053     topoEntity.setEntityPrimaryKeyValue(entityPrimaryKeyValue);
1054     topoEntity.setEntityType(entityType);
1055     topoEntity.setLatitude(topoData.get(TOPO_LAT));
1056     topoEntity.setLongitude(topoData.get(TOPO_LONG));
1057     topoEntity.setSelfLink(entityLink);
1058     try {
1059       topoEntity.setId(TopographicalEntity.generateUniqueShaDigest(entityType, entityPrimaryKeyName,
1060           entityPrimaryKeyValue));
1061     } catch (NoSuchAlgorithmException e) {
1062       logger.error(EntityEventPolicyMsgs.DISCARD_UPDATING_TOPOGRAPHY_DATA_VERBOSE,
1063           "Cannot create unique SHA digest for topographical data.");
1064     }
1065
1066     this.handleSearchServiceOperation(topoEntity, action, topographicalSearchIndex);
1067   }
1068
1069
1070   // put this here until we find a better spot
1071   /**
1072    * Helper utility to concatenate substrings of a URI together to form a proper URI.
1073    * 
1074    * @param suburis the list of substrings to concatenate together
1075    * @return the concatenated list of substrings
1076    */
1077   public static String concatSubUri(String... suburis) {
1078     String finalUri = "";
1079
1080     for (String suburi : suburis) {
1081
1082       if (suburi != null) {
1083         // Remove any leading / since we only want to append /
1084         suburi = suburi.replaceFirst("^/*", "");
1085
1086         // Add a trailing / if one isn't already there
1087         finalUri += suburi.endsWith("/") ? suburi : suburi + "/";
1088       }
1089     }
1090
1091     return finalUri;
1092   }
1093 }