enable suggestions to use search data service
[aai/sparky-be.git] / src / main / java / org / onap / aai / sparky / aggregatevnf / search / AggregateVnfSearchProvider.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23 package org.onap.aai.sparky.aggregatevnf.search;
24
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.List;
29
30 import org.onap.aai.cl.api.Logger;
31 import org.onap.aai.cl.eelf.LoggerFactory;
32 import org.onap.aai.restclient.client.OperationResult;
33 import org.onap.aai.sparky.common.search.CommonSearchSuggestion;
34 import org.onap.aai.sparky.logging.AaiUiMsgs;
35 import org.onap.aai.sparky.search.SearchServiceAdapter;
36 import org.onap.aai.sparky.search.api.SearchProvider;
37 import org.onap.aai.sparky.search.entity.QuerySearchEntity;
38 import org.onap.aai.sparky.search.entity.SearchSuggestion;
39 import org.onap.aai.sparky.search.filters.entity.UiFilterValueEntity;
40 import org.onap.aai.sparky.util.NodeUtils;
41
42 import com.fasterxml.jackson.databind.JsonNode;
43 import com.fasterxml.jackson.databind.ObjectMapper;
44 import com.fasterxml.jackson.databind.node.ArrayNode;
45
46 public class AggregateVnfSearchProvider implements SearchProvider {
47
48   private static final Logger LOG =
49       LoggerFactory.getInstance().getLogger(AggregateVnfSearchProvider.class);
50
51   private ObjectMapper mapper;
52   private SearchServiceAdapter searchServiceAdapter = null;
53   private String autoSuggestIndexName;
54   private String vnfSearchSuggestionRoute;
55
56   private static final String AUTO_SUGGEST_TEMPLATE = "{ " + "\"results-size\": %d,"
57       + "\"suggest-text\": \"%s\"," + "\"suggest-field\": \"%s\"" + "}";
58
59   private static final String KEY_SEARCH_RESULT = "searchResult";
60   private static final String KEY_HITS = "hits";
61   private static final String KEY_DOCUMENT = "document";
62   private static final String KEY_CONTENT = "content";
63   private static final String KEY_TEXT = "text";
64   private static final String KEY_FILTER_LIST = "filterList";
65
66   public AggregateVnfSearchProvider(SearchServiceAdapter searchServiceAdapter,
67       String autoSuggestIndexName, String vnfSearchSuggestionRoute) {
68     mapper = new ObjectMapper();
69     this.searchServiceAdapter = searchServiceAdapter;
70     this.autoSuggestIndexName = autoSuggestIndexName;
71     this.vnfSearchSuggestionRoute = vnfSearchSuggestionRoute;
72   }
73
74   public void setAutoSuggestIndexName(String autoSuggestIndexName) {
75     this.autoSuggestIndexName = autoSuggestIndexName;
76   }
77
78   @Override
79   public List<SearchSuggestion> search(QuerySearchEntity queryRequest) {
80
81     List<SearchSuggestion> returnList = new ArrayList<SearchSuggestion>();
82     try {
83
84       final String fullUrlStr =
85           searchServiceAdapter.buildSuggestServiceQueryUrl(autoSuggestIndexName);
86       String postBody =
87           String.format(AUTO_SUGGEST_TEMPLATE, Integer.parseInt(queryRequest.getMaxResults()),
88               queryRequest.getQueryStr(), "entity_suggest");
89       OperationResult opResult =
90           searchServiceAdapter.doPost(fullUrlStr, postBody, "application/json");
91       if (opResult.getResultCode() == 200) {
92         returnList = generateSuggestionsForSearchResponse(opResult.getResult());
93       } else {
94         LOG.error(AaiUiMsgs.ERROR_PARSING_JSON_PAYLOAD_VERBOSE, opResult.getResult());
95         return returnList;
96       }
97     } catch (Exception exc) {
98       LOG.error(AaiUiMsgs.ERROR_GENERIC, "Search failed due to error = " + exc.getMessage());
99     }
100
101     return returnList;
102   }
103
104   private List<SearchSuggestion> generateSuggestionsForSearchResponse(String operationResult) {
105
106     if (operationResult == null || operationResult.length() == 0) {
107       return null;
108     }
109
110     ObjectMapper mapper = new ObjectMapper();
111     JsonNode rootNode = null;
112     List<SearchSuggestion> suggestionEntityList = new ArrayList<SearchSuggestion>();
113
114     try {
115       rootNode = mapper.readTree(operationResult);
116       JsonNode hitsNode = rootNode.get(KEY_SEARCH_RESULT);
117       // Check if there are hits that are coming back
118       if (hitsNode.has(KEY_HITS)) {
119         ArrayNode hitsArray = (ArrayNode) hitsNode.get(KEY_HITS);
120
121         /*
122          * next we iterate over the values in the hit array elements
123          */
124         Iterator<JsonNode> nodeIterator = hitsArray.elements();
125         JsonNode entityNode = null;
126         CommonSearchSuggestion responseSuggestion = null;
127         JsonNode sourceNode = null;
128
129         while (nodeIterator.hasNext()) {
130           entityNode = nodeIterator.next();
131           String responseText = getValueFromNode(entityNode, KEY_TEXT);
132           // do the point transformation as we build the response?
133           responseSuggestion = new CommonSearchSuggestion();
134           responseSuggestion.setRoute(vnfSearchSuggestionRoute);
135           responseSuggestion.setText(responseText);
136           responseSuggestion.setHashId(NodeUtils.generateUniqueShaDigest(responseText));
137
138           sourceNode = entityNode.get(KEY_DOCUMENT).get(KEY_CONTENT);
139           if (sourceNode.has(KEY_FILTER_LIST)) {
140             ArrayNode filtersArray = (ArrayNode) sourceNode.get(KEY_FILTER_LIST);
141             for (int i = 0; i < filtersArray.size(); i++) {
142               String filterValueString = filtersArray.get(i).toString();
143               UiFilterValueEntity filterValue =
144                   mapper.readValue(filterValueString, UiFilterValueEntity.class);
145               responseSuggestion.getFilterValues().add(filterValue);
146             }
147           }
148           suggestionEntityList.add(responseSuggestion);
149         }
150       }
151     } catch (IOException exc) {
152       LOG.warn(AaiUiMsgs.SEARCH_RESPONSE_BUILDING_EXCEPTION, exc.getLocalizedMessage());
153     }
154     return suggestionEntityList;
155
156   }
157
158   private String getValueFromNode(JsonNode node, String fieldName) {
159
160     if (node == null || fieldName == null) {
161       return null;
162     }
163
164     JsonNode valueNode = node.get(fieldName);
165
166     if (valueNode != null) {
167       return valueNode.asText();
168     }
169
170     return null;
171
172   }
173
174 }