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