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