Sonar fixes - AggregateVnfSearchProvider
[aai/sparky-be.git] / sparkybe-onap-service / 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  * Copyright © 2019 IBM
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *       http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22 package org.onap.aai.sparky.aggregatevnf.search;
23
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.Iterator;
27 import java.util.List;
28
29 import org.onap.aai.cl.api.Logger;
30 import org.onap.aai.cl.eelf.LoggerFactory;
31 import org.onap.aai.restclient.client.OperationResult;
32 import org.onap.aai.sparky.common.search.CommonSearchSuggestion;
33 import org.onap.aai.sparky.logging.AaiUiMsgs;
34 import org.onap.aai.sparky.search.SearchServiceAdapter;
35 import org.onap.aai.sparky.search.api.SearchProvider;
36 import org.onap.aai.sparky.search.entity.QuerySearchEntity;
37 import org.onap.aai.sparky.search.entity.SearchSuggestion;
38 import org.onap.aai.sparky.search.filters.entity.UiFilterValueEntity;
39 import org.onap.aai.sparky.util.NodeUtils;
40
41 import com.fasterxml.jackson.databind.JsonNode;
42 import com.fasterxml.jackson.databind.ObjectMapper;
43 import com.fasterxml.jackson.databind.node.ArrayNode;
44
45 public class AggregateVnfSearchProvider implements SearchProvider {
46
47   private static final Logger LOG =
48       LoggerFactory.getInstance().getLogger(AggregateVnfSearchProvider.class);
49
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     this.searchServiceAdapter = searchServiceAdapter;
67     this.autoSuggestIndexName = autoSuggestIndexName;
68     this.vnfSearchSuggestionRoute = vnfSearchSuggestionRoute;
69   }
70
71   public void setAutoSuggestIndexName(String autoSuggestIndexName) {
72     this.autoSuggestIndexName = autoSuggestIndexName;
73   }
74
75   @Override
76   public List<SearchSuggestion> search(QuerySearchEntity queryRequest) {
77
78     List<SearchSuggestion> returnList = new ArrayList<>();
79     try {
80
81       final String fullUrlStr =
82           searchServiceAdapter.buildSuggestServiceQueryUrl(autoSuggestIndexName);
83       String postBody =
84           String.format(AUTO_SUGGEST_TEMPLATE, Integer.parseInt(queryRequest.getMaxResults()),
85               queryRequest.getQueryStr(), "entity_suggest");
86       OperationResult opResult =
87           searchServiceAdapter.doPost(fullUrlStr, postBody);
88       if (opResult.getResultCode() == 200) {
89         returnList = generateSuggestionsForSearchResponse(opResult.getResult());
90       } else {
91         LOG.error(AaiUiMsgs.ERROR_PARSING_JSON_PAYLOAD_VERBOSE, opResult.getResult());
92         return returnList;
93       }
94     } catch (Exception exc) {
95       LOG.error(AaiUiMsgs.ERROR_GENERIC, "Search failed due to error = " + exc.getMessage());
96     }
97
98     return returnList;
99   }
100
101   private List<SearchSuggestion> generateSuggestionsForSearchResponse(String operationResult) {
102
103     if (operationResult == null || operationResult.length() == 0) {
104       return null;
105     }
106
107     ObjectMapper mapper = new ObjectMapper();
108     List<SearchSuggestion> suggestionEntityList = new ArrayList<>();
109
110     try {
111       JsonNode rootNode = mapper.readTree(operationResult);
112       JsonNode hitsNode = rootNode.get(KEY_SEARCH_RESULT);
113       // Check if there are hits that are coming back
114       if (hitsNode.has(KEY_HITS)) {
115         ArrayNode hitsArray = (ArrayNode) hitsNode.get(KEY_HITS);
116
117         /*
118          * next we iterate over the values in the hit array elements
119          */
120         Iterator<JsonNode> nodeIterator = hitsArray.elements();
121         while (nodeIterator.hasNext()) {
122           JsonNode entityNode = nodeIterator.next();
123           if(entityNode != null) {
124             String responseText = getValueFromNode(entityNode, KEY_TEXT);
125
126             CommonSearchSuggestion responseSuggestion = createCommonSearchSuggestion(mapper, entityNode, responseText);
127             suggestionEntityList.add(responseSuggestion);
128           }
129         }
130       }
131     } catch (IOException exc) {
132       LOG.warn(AaiUiMsgs.SEARCH_RESPONSE_BUILDING_EXCEPTION, exc.getLocalizedMessage());
133     }
134     return suggestionEntityList;
135
136   }
137
138   private CommonSearchSuggestion createCommonSearchSuggestion(ObjectMapper mapper, JsonNode entityNode, String responseText) throws IOException {
139     // do the point transformation as we build the response?
140     CommonSearchSuggestion responseSuggestion = new CommonSearchSuggestion();
141     responseSuggestion.setRoute(vnfSearchSuggestionRoute);
142     responseSuggestion.setText(responseText);
143     responseSuggestion.setHashId(NodeUtils.generateUniqueShaDigest(responseText));
144
145     JsonNode keyDocument = entityNode.get(KEY_DOCUMENT);
146     JsonNode sourceNode = keyDocument.get(KEY_CONTENT);
147     if (sourceNode.has(KEY_FILTER_LIST)) {
148       ArrayNode filtersArray = (ArrayNode) sourceNode.get(KEY_FILTER_LIST);
149       for (int i = 0; i < filtersArray.size(); i++) {
150         String filterValueString = filtersArray.get(i).toString();
151         UiFilterValueEntity filterValue =
152             mapper.readValue(filterValueString, UiFilterValueEntity.class);
153         responseSuggestion.getFilterValues().add(filterValue);
154       }
155     }
156     return responseSuggestion;
157   }
158
159   private String getValueFromNode(JsonNode node, String fieldName) {
160
161     if (fieldName == null) {
162       return null;
163     }
164
165     JsonNode valueNode = node.get(fieldName);
166
167     if (valueNode != null) {
168       return valueNode.asText();
169     }
170
171     return null;
172
173   }
174
175 }