Adding UI extensibility
[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.util.ArrayList;
26 import java.util.List;
27
28 import javax.json.JsonObject;
29
30 import org.json.JSONArray;
31 import org.json.JSONObject;
32 import org.onap.aai.cl.api.Logger;
33 import org.onap.aai.cl.eelf.LoggerFactory;
34 import org.onap.aai.restclient.client.OperationResult;
35 import org.onap.aai.sparky.common.search.CommonSearchSuggestion;
36 import org.onap.aai.sparky.dal.elasticsearch.SearchAdapter;
37 import org.onap.aai.sparky.dataintegrity.config.DiUiConstants;
38 import org.onap.aai.sparky.logging.AaiUiMsgs;
39 import org.onap.aai.sparky.search.api.SearchProvider;
40 import org.onap.aai.sparky.search.entity.QuerySearchEntity;
41 import org.onap.aai.sparky.search.entity.SearchSuggestion;
42 import org.onap.aai.sparky.search.filters.entity.UiFilterValueEntity;
43 import org.onap.aai.sparky.util.NodeUtils;
44 import org.onap.aai.sparky.viewandinspect.config.TierSupportUiConstants;
45
46 import com.fasterxml.jackson.databind.ObjectMapper;
47
48 public class AggregateVnfSearchProvider implements SearchProvider {
49
50   private static final Logger LOG =
51       LoggerFactory.getInstance().getLogger(AggregateVnfSearchProvider.class);
52
53   private ObjectMapper mapper;
54   private static SearchAdapter search = null;
55
56   private String autoSuggestIndexName;
57   private String elasticSearchIp;
58   private String elatsticSearchPort;
59
60   public AggregateVnfSearchProvider() {
61
62     mapper = new ObjectMapper();
63
64     try {
65       if (search == null) {
66         search = new SearchAdapter();
67       }
68     } catch (Exception exc) {
69       LOG.error(AaiUiMsgs.CONFIGURATION_ERROR,
70           "Search Configuration Error.  Error = " + exc.getMessage());
71     }
72   }
73
74   public void setAutoSuggestIndexName(String autoSuggestIndexName) {
75     this.autoSuggestIndexName = autoSuggestIndexName;
76   }
77
78   public void setElasticSearchIp(String elasticSearchIp) {
79     this.elasticSearchIp = elasticSearchIp;
80   }
81
82   public void setElatsticSearchPort(String elatsticSearchPort) {
83     this.elatsticSearchPort = elatsticSearchPort;
84   }
85
86   /**
87    * Get Full URL for search using elastic search configuration.
88    *
89    * @param api the api
90    * @return the full url
91    */
92   private String getFullUrl(String indexName, String api) {
93     final String host = elasticSearchIp;
94     final String port = elatsticSearchPort;
95     return String.format("http://%s:%s/%s/%s", host, port, indexName, api);
96   }
97
98   @Override
99   public List<SearchSuggestion> search(QuerySearchEntity queryRequest) {
100
101     List<SearchSuggestion> returnList = new ArrayList<SearchSuggestion>();
102
103     try {
104
105       /* Create suggestions query */
106       JsonObject vnfSearch = VnfSearchQueryBuilder.createSuggestionsQuery(
107           String.valueOf(queryRequest.getMaxResults()), queryRequest.getQueryStr());
108
109       /* Parse suggestions response */
110       OperationResult opResult =
111           search.doPost(getFullUrl(autoSuggestIndexName, TierSupportUiConstants.ES_SUGGEST_API),
112               vnfSearch.toString(), DiUiConstants.APP_JSON);
113
114       String result = opResult.getResult();
115
116       if (!opResult.wasSuccessful()) {
117         LOG.error(AaiUiMsgs.ERROR_PARSING_JSON_PAYLOAD_VERBOSE, result);
118         return returnList;
119       }
120
121       JSONObject responseJson = new JSONObject(result);
122       String suggestionsKey = "vnfs";
123       JSONArray suggestionsArray = new JSONArray();
124       JSONArray suggestions = responseJson.getJSONArray(suggestionsKey);
125       if (suggestions.length() > 0) {
126         suggestionsArray = suggestions.getJSONObject(0).getJSONArray("options");
127         for (int i = 0; i < suggestionsArray.length(); i++) {
128           JSONObject querySuggestion = suggestionsArray.getJSONObject(i);
129           if (querySuggestion != null) {
130             CommonSearchSuggestion responseSuggestion = new CommonSearchSuggestion();
131             responseSuggestion.setText(querySuggestion.getString("text"));
132             responseSuggestion.setRoute("vnfSearch"); // TODO -> Read route from
133                                                       // suggestive-search.properties instead of
134                                                       // hard coding
135             responseSuggestion
136                 .setHashId(NodeUtils.generateUniqueShaDigest(querySuggestion.getString("text")));
137
138             // Extract filter list from JSON and add to response suggestion
139             JSONObject payload = querySuggestion.getJSONObject("payload");
140             if (payload.length() > 0) {
141               JSONArray filterList = payload.getJSONArray("filterList");
142               for (int filter = 0; filter < filterList.length(); filter++) {
143                 String filterValueString = filterList.getJSONObject(filter).toString();
144                 UiFilterValueEntity filterValue =
145                     mapper.readValue(filterValueString, UiFilterValueEntity.class);
146                 responseSuggestion.getFilterValues().add(filterValue);
147               }
148             }
149             returnList.add(responseSuggestion);
150           }
151         }
152       }
153     } catch (Exception exc) {
154       LOG.error(AaiUiMsgs.ERROR_GENERIC, "Search failed due to error = " + exc.getMessage());
155     }
156
157     return returnList;
158   }
159
160 }