Fix aggregate-vnf search index population
[aai/data-router.git] / src / main / java / org / onap / aai / datarouter / policy / SpikeAutosuggestIndexProcessor.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.security.NoSuchAlgorithmException;
25 import java.util.ArrayList;
26 import java.util.Collections;
27 import java.util.List;
28 import java.util.Map;
29
30 import org.apache.camel.Exchange;
31 import org.onap.aai.datarouter.entity.SpikeEventMeta;
32 import org.onap.aai.datarouter.entity.SuggestionSearchEntity;
33 import org.onap.aai.datarouter.logging.EntityEventPolicyMsgs;
34 import org.onap.aai.datarouter.util.SearchSuggestionPermutation;
35 import org.onap.aai.entity.OxmEntityDescriptor;
36 import org.onap.aai.util.EntityOxmReferenceHelper;
37 import org.onap.aai.util.Version;
38 import org.onap.aai.util.VersionedOxmEntities;
39
40 import com.fasterxml.jackson.databind.JsonNode;
41
42 public class SpikeAutosuggestIndexProcessor extends AbstractSpikeEntityEventProcessor {
43
44   public static final String additionalInfo = "Response of SpikeEntityEventPolicy";
45
46   private static final String PROCESS_SPIKE_EVENT = "Process Spike Event";
47
48   
49   /** Agent for communicating with the Search Service. */
50
51   public SpikeAutosuggestIndexProcessor(SpikeEventPolicyConfig config)
52       throws FileNotFoundException {
53     super(config);
54   }
55
56   @Override
57   protected void startup() {
58     // Create the indexes in the search service if they do not already exist.
59     searchAgent.createSearchIndex(searchIndexName, searchIndexSchema, createIndexUrl);
60     logger.info(EntityEventPolicyMsgs.ENTITY_EVENT_POLICY_REGISTERED);
61   }
62
63   @Override
64   public void process(Exchange exchange) throws Exception {
65    
66   long startTime = System.currentTimeMillis();
67     
68     SpikeEventMeta meta = processSpikeEvent(exchange);
69     
70     if ( meta == null ) {
71       return;
72     }
73  
74     /*
75      * Use the versioned OXM Entity class to get access to cross-entity reference helper collections
76      */
77     VersionedOxmEntities oxmEntities =
78         EntityOxmReferenceHelper.getInstance().getVersionedOxmEntities(Version.valueOf(oxmVersion.toLowerCase()));
79     
80     if (oxmEntities != null) {
81       Map<String, OxmEntityDescriptor> rootDescriptor =
82           oxmEntities.getSuggestableEntityDescriptors();
83       if (!rootDescriptor.isEmpty()) {
84         List<String> suggestibleAttrInPayload = new ArrayList<>();
85         List<String> suggestibleAttrInOxm =
86             extractSuggestableAttr(oxmEntities, meta.getSpikeEventVertex().getType());
87         if (suggestibleAttrInOxm != null) {
88           for (String attr : suggestibleAttrInOxm) {
89             if (meta.getVertexProperties().has(attr)) {
90               suggestibleAttrInPayload.add(attr);
91             }
92           }
93         }
94
95         if (suggestibleAttrInPayload.isEmpty()) {
96           return;
97         }
98         List<String> suggestionAliases = extractAliasForSuggestableEntity(oxmEntities,  meta.getSpikeEventVertex().getType());       
99
100         /*
101          * It was decided to silently ignore DELETE requests for resources we don't allow to be
102          * deleted. e.g. auto-suggestion deletion is not allowed while aggregation deletion is.
103          */
104         if (!DELETE.equalsIgnoreCase(meta.getBodyOperationType())) {
105           List<ArrayList<String>> listOfValidPowerSetElements =
106               SearchSuggestionPermutation.getNonEmptyUniqueLists(suggestibleAttrInPayload);
107           
108           JsonNode propertiesNode = mapper.readValue(meta.getVertexProperties().toString(), JsonNode.class);
109           
110           // Now we have a list containing the power-set (minus empty element) for the status that are
111           // available in the payload. Try inserting a document for every combination.
112           for (ArrayList<String> list : listOfValidPowerSetElements) {
113             SuggestionSearchEntity suggestionSearchEntity = new SuggestionSearchEntity();
114             suggestionSearchEntity.setEntityType(meta.getSpikeEventVertex().getType());
115             suggestionSearchEntity.setSuggestableAttr(list);
116             suggestionSearchEntity.setEntityTypeAliases(suggestionAliases);
117             suggestionSearchEntity.setFilterBasedPayloadFromResponse(propertiesNode,
118                 suggestibleAttrInOxm, list);
119             suggestionSearchEntity.setSuggestionInputPermutations(
120                 suggestionSearchEntity.generateSuggestionInputPermutations());
121
122             if (suggestionSearchEntity.isSuggestableDoc()) {
123               try {
124                 suggestionSearchEntity.generateSearchSuggestionDisplayStringAndId();
125               } catch (NoSuchAlgorithmException e) {
126                 logger.error(EntityEventPolicyMsgs.DISCARD_UPDATING_SEARCH_SUGGESTION_DATA,
127                     "Cannot create unique SHA digest for search suggestion data. Exception: "
128                         + e.getLocalizedMessage());
129               }
130
131               handleSearchServiceOperation(suggestionSearchEntity, meta.getBodyOperationType(), searchIndexName);
132             }
133           }
134         }
135       }
136     }
137     long stopTime = System.currentTimeMillis();
138     metricsLogger.info(EntityEventPolicyMsgs.OPERATION_RESULT_NO_ERRORS, PROCESS_SPIKE_EVENT,
139         String.valueOf(stopTime - startTime));
140     setResponse(exchange, ResponseType.SUCCESS, additionalInfo);
141     return;
142   }
143  
144
145   public List<String> extractAliasForSuggestableEntity(VersionedOxmEntities oxmEntities,
146       String entityType) {
147
148     // Extract alias
149     Map<String, OxmEntityDescriptor> rootDescriptor = oxmEntities.getEntityAliasDescriptors();
150
151     if (rootDescriptor == null) {
152       return Collections.emptyList();
153     }
154
155     OxmEntityDescriptor desc = rootDescriptor.get(entityType);
156     return desc.getAlias();
157   }
158
159 }