2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.datarouter.policy;
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;
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;
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;
76 public class EntityEventPolicy implements Processor {
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;
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";
92 private static final List<String> SUPPORTED_ACTIONS =
93 Arrays.asList(ACTION_CREATE, ACTION_UPDATE, ACTION_DELETE);
95 Map<String, DynamicJAXBContext> oxmVersionContextMap = new HashMap<>();
96 private String oxmVersion = null;
98 /** Agent for communicating with the Search Service. */
99 private SearchServiceAgent searchAgent = null;
101 /** Search index name for storing AAI event entities. */
102 private String entitySearchIndex;
104 /** Search index name for storing topographical search data. */
105 private String topographicalSearchIndex;
107 /** Search index name for suggestive search data. */
108 private String aggregateGenericVnfIndex;
110 private String autosuggestIndex;
112 private String srcDomain;
114 private Logger logger;
115 private Logger metricsLogger;
117 public enum ResponseType {
118 SUCCESS, PARTIAL_SUCCESS, FAILURE;
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());
127 srcDomain = config.getSourceDomain();
129 // Populate the index names.
130 entitySearchIndex = config.getSearchEntitySearchIndex();
131 topographicalSearchIndex = config.getSearchTopographySearchIndex();
132 aggregateGenericVnfIndex = config.getSearchAggregationVnfIndex();
133 autosuggestIndex = config.getSearchEntityAutoSuggestIndex();
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(),
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();
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();
159 String version = pair.getKey().toString();
160 int versionNum = Integer.parseInt(version.substring(1, version.length()));
162 if (versionNum > latestVersion) {
163 latestVersion = versionNum;
164 oxmVersion = pair.getKey().toString();
167 logger.info(EntityEventPolicyMsgs.PROCESS_OXM_MODEL_FOUND, pair.getKey().toString());
170 logger.error(EntityEventPolicyMsgs.PROCESS_OXM_MODEL_MISSING, "");
174 public void startup() {
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);
180 logger.info(EntityEventPolicyMsgs.ENTITY_EVENT_POLICY_REGISTERED);
185 * Convert object to json.
187 * @param object the object
188 * @param pretty the pretty
190 * @throws JsonProcessingException the json processing exception
192 public static String convertObjectToJson(Object object, boolean pretty)
193 throws JsonProcessingException {
197 ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
200 ow = new ObjectMapper().writer();
203 return ow.writeValueAsString(object);
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);
213 public void process(Exchange exchange) throws Exception {
215 long startTime = System.currentTimeMillis();
217 String uebPayload = exchange.getIn().getBody().toString();
219 JsonNode uebAsJson = null;
220 ObjectMapper mapper = new ObjectMapper();
222 uebAsJson = mapper.readTree(uebPayload);
223 } catch (IOException e){
224 returnWithError(exchange, uebPayload, "Invalid Payload");
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);
235 JSONObject uebObjEntity = getUebContentAsJson(uebPayload, ENTITY_HEADER);
236 if (uebObjEntity == null) {
237 returnWithError(exchange, uebPayload, "Payload is missing " + ENTITY_HEADER);
241 UebEventHeader eventHeader;
242 eventHeader = initializeUebEventHeader(uebObjHeader.toString());
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 + "'");
252 setResponse(exchange, ResponseType.SUCCESS, additionalInfo);
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",
262 setResponse(exchange, ResponseType.FAILURE, additionalInfo);
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 + "'");
273 setResponse(exchange, ResponseType.FAILURE, additionalInfo);
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");
284 setResponse(exchange, ResponseType.FAILURE, additionalInfo);
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");
295 setResponse(exchange, ResponseType.FAILURE, additionalInfo);
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");
306 setResponse(exchange, ResponseType.FAILURE, additionalInfo);
310 // log the fact that all data are in good shape
311 logger.info(EntityEventPolicyMsgs.PROCESS_ENTITY_EVENT_POLICY_NONVERBOSE, action,
313 logger.debug(EntityEventPolicyMsgs.PROCESS_ENTITY_EVENT_POLICY_VERBOSE, action, entityType,
317 // Process for building AaiEventEntity object
318 String oxmEntityType = new OxmEntityTypeConverter().convert(entityType);
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 + "'",
329 setResponse(exchange, ResponseType.FAILURE, additionalInfo);
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);
342 setResponse(exchange, ResponseType.FAILURE, additionalInfo);
346 AaiEventEntity aaiEventEntity = new AaiEventEntity();
349 * Use the OXM Model to determine the primary key field name based on the entity-type
352 aaiEventEntity.setEntityPrimaryKeyName(entityPrimaryKeyFieldName);
353 aaiEventEntity.setEntityPrimaryKeyValue(entityPrimaryKeyFieldValue);
354 aaiEventEntity.setEntityType(entityType);
355 aaiEventEntity.setLink(entityLink);
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);
363 setResponse(exchange, ResponseType.FAILURE, additionalInfo);
369 aaiEventEntity.deriveFields();
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);
377 setResponse(exchange, ResponseType.FAILURE, additionalInfo);
381 handleSearchServiceOperation(aaiEventEntity, action, entitySearchIndex);
383 handleTopographicalData(uebPayload, action, entityType, oxmEntityType, oxmJaxbContext,
384 entityPrimaryKeyFieldName, entityPrimaryKeyFieldValue);
387 * Use the versioned OXM Entity class to get access to cross-entity reference helper collections
389 VersionedOxmEntities oxmEntities =
390 EntityOxmReferenceHelper.getInstance().getVersionedOxmEntities(Version.valueOf(oxmVersion.toLowerCase()));
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.
403 if (!action.equalsIgnoreCase(ACTION_DELETE) && oxmEntities != null
404 && oxmEntities.entityModelContainsCrossEntityReference(topEntityType)) {
406 // We know the model "can" contain a CER reference definition, let's process a bit more
408 HashMap<String, CrossEntityReference> crossEntityRefMap =
409 oxmEntities.getCrossEntityReferences();
411 JSONObject entityJsonObject = getUebEntity(uebPayload);
413 JsonNode entityJsonNode = convertToJsonNode(entityJsonObject.toString());
415 String parentEntityType = entityType;
417 String targetEntityUrl = entityLink;
419 for (Map.Entry<String, CrossEntityReference> entry : crossEntityRefMap.entrySet()) {
422 * if we know service-subscription is in the tree, then we can pull our all instances and
423 * process from there.
426 String key = entry.getKey();
427 CrossEntityReference cerDescriptor = entry.getValue();
429 ArrayList<JsonNode> foundNodes = new ArrayList<>();
431 RouterServiceUtil.extractObjectsByKey(entityJsonNode, key, foundNodes);
433 if (!foundNodes.isEmpty()) {
435 for (JsonNode n : foundNodes) {
436 if ("customer".equalsIgnoreCase(parentEntityType)){
439 * 1. prepare to hand-create url for service-instance
440 * 2. this will break if the URL structure for service-instance changes
442 if (n.has("service-type")){
443 targetEntityUrl += "/service-subscriptions/service-subscription/"
444 + RouterServiceUtil.getNodeFieldAsText(n, "service-type")
445 + "/service-instances/service-instance/";
450 List<String> extractedParentEntityAttributeValues = new ArrayList<>();
452 RouterServiceUtil.extractFieldValuesFromObject(n, cerDescriptor.getAttributeNames(),
453 extractedParentEntityAttributeValues);
455 List<JsonNode> nestedTargetEntityInstances = new ArrayList<>();
456 RouterServiceUtil.extractObjectsByKey(n, cerDescriptor.getTargetEntityType(),
457 nestedTargetEntityInstances);
459 for (JsonNode targetEntityInstance : nestedTargetEntityInstances) {
462 * 1. build the AAIEntityType (IndexDocument) based on the extract entity
463 * 2. Get data from ES
465 * 4. Merge ES Doc + AAIEntityType + Extracted Parent Cross-Entity-Reference Values
466 * 5. Put data into ES with ETAG + updated doc
469 // Get the complete URL for target entity
470 if (targetEntityInstance.has("link")) { // nested SI has url mentioned
471 targetEntityUrl = RouterServiceUtil.getNodeFieldAsText(targetEntityInstance,
473 } else if ("customer".equalsIgnoreCase(parentEntityType) &&
474 targetEntityInstance.has("service-instance-id")){
475 targetEntityUrl += RouterServiceUtil.getNodeFieldAsText(targetEntityInstance,
476 "service-instance-id");
479 OxmEntityDescriptor searchableDescriptor =
480 oxmEntities.getSearchableEntityDescriptor(cerDescriptor.getTargetEntityType());
482 if (searchableDescriptor != null) {
484 if (!searchableDescriptor.getSearchableAttributes().isEmpty()) {
486 AaiEventEntity entityToSync = null;
490 entityToSync = getPopulatedEntity(targetEntityInstance, searchableDescriptor);
493 * Ready to do some ElasticSearch ops
496 for (String parentCrossEntityReferenceAttributeValue : extractedParentEntityAttributeValues) {
498 .addCrossEntityReferenceValue(parentCrossEntityReferenceAttributeValue);
501 entityToSync.setLink(targetEntityUrl);
502 entityToSync.deriveFields();
504 updateCerInEntity(entityToSync);
506 } catch (NoSuchAlgorithmException e) {
507 logger.debug(e.getMessage());
511 logger.debug(EntityEventPolicyMsgs.CROSS_ENTITY_REFERENCE_SYNC,
512 "failure to find searchable descriptor for type "
513 + cerDescriptor.getTargetEntityType());
520 logger.debug(EntityEventPolicyMsgs.CROSS_ENTITY_REFERENCE_SYNC,
521 "failed to find 0 instances of cross-entity-reference with entity " + key);
527 logger.info(EntityEventPolicyMsgs.CROSS_ENTITY_REFERENCE_SYNC, "skipped due to OXM model for "
528 + topEntityType + " does not contain a cross-entity-reference entity");
532 * Process for autosuggestable entities
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);
548 if (suggestibleAttrInPayload.isEmpty()) {
552 List<String> suggestionAliases = extractAliasForSuggestableEntity(oxmEntities, entityType);
553 AggregationEntity ae = new AggregationEntity();
554 ae.setLink(entityLink);
555 ae.deriveFields(uebAsJson);
557 handleSearchServiceOperation(ae, action, aggregateGenericVnfIndex);
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.
563 if (!ACTION_DELETE.equalsIgnoreCase(action)) {
564 List<ArrayList<String>> listOfValidPowerSetElements =
565 SearchSuggestionPermutation.getNonEmptyUniqueLists(suggestibleAttrInPayload);
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());
579 if (suggestionSearchEntity.isSuggestableDoc()) {
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());
588 handleSearchServiceOperation(suggestionSearchEntity, action, autosuggestIndex);
595 long stopTime = System.currentTimeMillis();
597 metricsLogger.info(EntityEventPolicyMsgs.OPERATION_RESULT_NO_ERRORS, PROCESS_AAI_EVENT,
598 String.valueOf(stopTime - startTime));
600 setResponse(exchange, ResponseType.SUCCESS, additionalInfo);
604 public List<String> extractSuggestableAttr(VersionedOxmEntities oxmEntities, String entityType) {
605 // Extract suggestable attributeshandleTopographicalData
606 Map<String, OxmEntityDescriptor> rootDescriptor = oxmEntities.getSuggestableEntityDescriptors();
608 if (rootDescriptor == null) {
609 return Collections.emptyList();
612 OxmEntityDescriptor desc = rootDescriptor.get(entityType);
615 return Collections.emptyList();
618 return desc.getSuggestableAttributes();
621 public List<String> extractAliasForSuggestableEntity(VersionedOxmEntities oxmEntities,
625 Map<String, OxmEntityDescriptor> rootDescriptor = oxmEntities.getEntityAliasDescriptors();
627 if (rootDescriptor == null) {
628 return Collections.emptyList();
631 OxmEntityDescriptor desc = rootDescriptor.get(entityType);
632 return desc.getAlias();
635 private void setResponse(Exchange exchange, ResponseType responseType, String additionalInfo) {
637 exchange.getOut().setHeader("ResponseType", responseType.toString());
638 exchange.getOut().setBody(additionalInfo);
641 public void extractDetailsForAutosuggestion(VersionedOxmEntities oxmEntities, String entityType,
642 List<String> suggestableAttr, List<String> alias) {
644 // Extract suggestable attributes
645 Map<String, OxmEntityDescriptor> rootDescriptor = oxmEntities.getSuggestableEntityDescriptors();
647 OxmEntityDescriptor desc = rootDescriptor.get(entityType);
648 suggestableAttr = desc.getSuggestableAttributes();
651 rootDescriptor = oxmEntities.getEntityAliasDescriptors();
652 desc = rootDescriptor.get(entityType);
653 alias = desc.getAlias();
657 * Load the UEB JSON payload, any errors would result to a failure case response.
659 private JSONObject getUebContentAsJson(String payload, String contentKey) {
661 JSONObject uebJsonObj;
662 JSONObject uebObjContent;
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);
672 if (uebJsonObj.has(contentKey)) {
673 uebObjContent = uebJsonObj.getJSONObject(contentKey);
675 logger.debug(EntityEventPolicyMsgs.UEB_FAILED_TO_PARSE_PAYLOAD, contentKey);
676 logger.error(EntityEventPolicyMsgs.UEB_FAILED_TO_PARSE_PAYLOAD, contentKey);
680 return uebObjContent;
684 private UebEventHeader initializeUebEventHeader(String payload) {
686 UebEventHeader eventHeader = null;
687 ObjectMapper mapper = new ObjectMapper();
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);
697 // Marshal the supplied string into a UebEventHeader object.
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());
706 if (eventHeader != null) {
707 logger.debug(EntityEventPolicyMsgs.UEB_EVENT_HEADER_PARSED, eventHeader.toString());
715 private String getEntityPrimaryKeyFieldName(DynamicJAXBContext oxmJaxbContext, String payload,
716 String oxmEntityType, String entityType) {
718 DynamicType entity = oxmJaxbContext.getDynamicType(oxmEntityType);
719 if (entity == null) {
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('/'));
732 private String lookupValueUsingKey(String payload, String key) throws JSONException {
733 JsonNode jsonNode = convertToJsonNode(payload);
734 return RouterServiceUtil.recursivelyLookupJsonPayload(jsonNode, key);
737 private JsonNode convertToJsonNode(String payload) {
739 ObjectMapper mapper = new ObjectMapper();
740 JsonNode jsonNode = null;
742 jsonNode = mapper.readTree(mapper.getJsonFactory().createJsonParser(payload));
743 } catch (IOException e) {
744 logger.debug(EntityEventPolicyMsgs.FAILED_TO_PARSE_UEB_PAYLOAD, ENTITY_HEADER + " missing",
746 logger.error(EntityEventPolicyMsgs.FAILED_TO_PARSE_UEB_PAYLOAD, ENTITY_HEADER + " missing",
753 private boolean getSearchTags(AaiEventEntity aaiEventEntity, List<String> searchableAttr,
754 String payload, String action) {
756 boolean hasSearchableAttr = false;
757 for (String searchTagField : searchableAttr) {
758 String searchTagValue;
759 if (searchTagField.equalsIgnoreCase(aaiEventEntity.getEntityPrimaryKeyName())) {
760 searchTagValue = aaiEventEntity.getEntityPrimaryKeyValue();
762 searchTagValue = this.lookupValueUsingKey(payload, searchTagField);
765 if (searchTagValue != null && !searchTagValue.isEmpty()) {
766 hasSearchableAttr = true;
767 aaiEventEntity.addSearchTagWithKey(searchTagValue, searchTagField);
770 return hasSearchableAttr;
774 * Check if OXM version is available. If available, load it.
776 private DynamicJAXBContext loadOxmContext(String version) {
777 if (version == null) {
778 logger.error(EntityEventPolicyMsgs.FAILED_TO_FIND_OXM_VERSION, version);
782 return oxmVersionContextMap.get(version);
785 private List<String> getOxmAttributes(String payload, DynamicJAXBContext oxmJaxbContext,
786 String oxmEntityType, String entityType, String fieldName) {
788 DynamicType entity = (DynamicType) oxmJaxbContext.getDynamicType(oxmEntityType);
789 if (entity == null) {
794 * Check for searchable XML tag
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(","));
808 private JSONObject getUebEntity(String payload) {
809 JSONObject uebJsonObj;
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");
821 if (uebJsonObj.has(ENTITY_HEADER)) {
822 return uebJsonObj.getJSONObject(ENTITY_HEADER);
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");
830 protected AaiEventEntity getPopulatedEntity(JsonNode entityNode,
831 OxmEntityDescriptor resultDescriptor) {
832 AaiEventEntity d = new AaiEventEntity();
834 d.setEntityType(resultDescriptor.getEntityName());
836 List<String> primaryKeyValues = new ArrayList<>();
837 List<String> primaryKeyNames = new ArrayList<>();
840 for (String keyName : resultDescriptor.getPrimaryKeyAttributeName()) {
841 pkeyValue = RouterServiceUtil.getNodeFieldAsText(entityNode, keyName);
842 if (pkeyValue != null) {
843 primaryKeyValues.add(pkeyValue);
844 primaryKeyNames.add(keyName);
846 logger.error(EntityEventPolicyMsgs.PRIMARY_KEY_NULL_FOR_ENTITY_TYPE,
847 resultDescriptor.getEntityName());
851 final String primaryCompositeKeyValue = RouterServiceUtil.concatArray(primaryKeyValues, "/");
852 d.setEntityPrimaryKeyValue(primaryCompositeKeyValue);
853 final String primaryCompositeKeyName = RouterServiceUtil.concatArray(primaryKeyNames, "/");
854 d.setEntityPrimaryKeyName(primaryCompositeKeyName);
856 final List<String> searchTagFields = resultDescriptor.getSearchableAttributes();
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.
864 for (String searchTagField : searchTagFields) {
865 String searchTagValue = RouterServiceUtil.getNodeFieldAsText(entityNode, searchTagField);
866 if (searchTagValue != null && !searchTagValue.isEmpty()) {
867 d.addSearchTagWithKey(searchTagValue, searchTagField);
874 private void updateCerInEntity(AaiEventEntity aaiEventEntity) {
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)));
880 String entityId = aaiEventEntity.getId();
883 // Run the GET to retrieve the ETAG from the search service
884 OperationResult storedEntity = searchAgent.getDocument(entitySearchIndex, entityId);
886 if (HttpUtil.isHttpResponseClassSuccess(storedEntity.getResultCode())) {
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).
893 List<String> etag = storedEntity.getHeaders().get(Headers.ETAG);
895 if (etag != null && !etag.isEmpty()) {
896 headers.put(Headers.IF_MATCH, etag);
898 logger.error(EntityEventPolicyMsgs.NO_ETAG_AVAILABLE_FAILURE,
899 entitySearchIndex, entityId);
902 ArrayList<JsonNode> sourceObject = new ArrayList<>();
903 NodeUtils.extractObjectsByKey(
904 NodeUtils.convertJsonStrToJsonNode(storedEntity.getResult()),
905 "content", sourceObject);
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;
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);
930 if (storedEntity.getResultCode() == 404) {
931 // entity not found, so attempt to do a PUT
932 searchAgent.putDocument(entitySearchIndex, entityId, aaiEventEntity.getAsJson(), headers);
934 logger.error(EntityEventPolicyMsgs.FAILED_TO_UPDATE_ENTITY_IN_DOCSTORE,
935 aaiEventEntity.getId(), "SYNC_ENTITY");
938 } catch (IOException e) {
939 logger.error(EntityEventPolicyMsgs.FAILED_TO_UPDATE_ENTITY_IN_DOCSTORE,
940 aaiEventEntity.getId(), "SYNC_ENTITY");
945 * Perform create, read, update or delete (CRUD) operation on search engine's suggestive search
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
953 protected void handleSearchServiceOperation(DocumentStoreDataEntity eventEntity,
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)));
962 String entityId = eventEntity.getId();
964 if ((action.equalsIgnoreCase(ACTION_CREATE) && entityId != null)
965 || action.equalsIgnoreCase(ACTION_UPDATE)) {
967 // Run the GET to retrieve the ETAG from the search service
968 OperationResult storedEntity = searchAgent.getDocument(index, entityId);
970 if (HttpUtil.isHttpResponseClassSuccess(storedEntity.getResultCode())) {
971 List<String> etag = storedEntity.getHeaders().get(Headers.ETAG);
973 if (etag != null && !etag.isEmpty()) {
974 headers.put(Headers.IF_MATCH, etag);
976 logger.error(EntityEventPolicyMsgs.NO_ETAG_AVAILABLE_FAILURE, index,
981 // Write the entity to the search service.
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);
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);
992 if (HttpUtil.isHttpResponseClassSuccess(storedEntity.getResultCode())) {
993 List<String> etag = storedEntity.getHeaders().get(Headers.ETAG);
995 if (etag != null && !etag.isEmpty()) {
996 headers.put(Headers.IF_MATCH, etag);
998 logger.error(EntityEventPolicyMsgs.NO_ETAG_AVAILABLE_FAILURE, index,
1003 * The Spring-Boot version of the search-data-service rejects the DELETE operation unless
1004 * we specify a Content-Type.
1007 headers.put("Content-Type", Arrays.asList(MediaType.APPLICATION_JSON.getMediaType()));
1009 searchAgent.deleteDocument(index, eventEntity.getId(), headers);
1011 logger.error(EntityEventPolicyMsgs.NO_ETAG_AVAILABLE_FAILURE, index,
1015 logger.error(EntityEventPolicyMsgs.ENTITY_OPERATION_NOT_SUPPORTED, action);
1017 } catch (IOException e) {
1018 logger.error(EntityEventPolicyMsgs.FAILED_TO_UPDATE_ENTITY_IN_DOCSTORE, eventEntity.getId(),
1023 private void handleTopographicalData(String payload, String action, String entityType,
1024 String oxmEntityType, DynamicJAXBContext oxmJaxbContext, String entityPrimaryKeyFieldName,
1025 String entityPrimaryKeyFieldValue) {
1027 Map<String, String> topoData = new HashMap<>();
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 + "'",
1038 entityLink = lookupValueUsingKey(payload, "entity-link");
1039 for (String topoAttr : topographicalAttr) {
1040 topoData.put(topoAttr, lookupValueUsingKey(payload, topoAttr));
1042 updateTopographicalSearchDb(topoData, entityType, action, entityPrimaryKeyFieldName,
1043 entityPrimaryKeyFieldValue, entityLink);
1048 private void updateTopographicalSearchDb(Map<String, String> topoData, String entityType,
1049 String action, String entityPrimaryKeyName, String entityPrimaryKeyValue, String entityLink) {
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);
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.");
1066 this.handleSearchServiceOperation(topoEntity, action, topographicalSearchIndex);
1070 // put this here until we find a better spot
1072 * Helper utility to concatenate substrings of a URI together to form a proper URI.
1074 * @param suburis the list of substrings to concatenate together
1075 * @return the concatenated list of substrings
1077 public static String concatSubUri(String... suburis) {
1078 String finalUri = "";
1080 for (String suburi : suburis) {
1082 if (suburi != null) {
1083 // Remove any leading / since we only want to append /
1084 suburi = suburi.replaceFirst("^/*", "");
1086 // Add a trailing / if one isn't already there
1087 finalUri += suburi.endsWith("/") ? suburi : suburi + "/";