Adding back-end support for UI filters
[aai/sparky-be.git] / src / main / java / org / onap / aai / sparky / search / filters / FilterElasticSearchAdapter.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.search.filters;
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.dal.elasticsearch.SearchAdapter;
36 import org.onap.aai.sparky.dal.elasticsearch.config.ElasticSearchConfig;
37 import org.onap.aai.sparky.logging.AaiUiMsgs;
38 import org.onap.aai.sparky.search.filters.config.UiFilterDataSourceConfig;
39 import org.onap.aai.sparky.search.filters.entity.UiFilterEntity;
40 import org.onap.aai.sparky.viewandinspect.config.TierSupportUiConstants;
41
42
43 /**
44  * Performs all Elasticsearch related queries for filters related to the Sparky-FE.
45  */
46 public class FilterElasticSearchAdapter {
47
48   private static ElasticSearchConfig esConfig = null;
49   private static SearchAdapter search = null;
50   private static final String ES_SEARCH_API = TierSupportUiConstants.ES_SEARCH_API;
51   private static final String APP_JSON = "application/json";
52   private static final Logger LOG =
53       LoggerFactory.getInstance().getLogger(FilterElasticSearchAdapter.class);
54   private static final String AGGS = "aggregations";
55   private static final String CONTAINER = "default";
56   private static final String BUCKETS = "buckets";
57   private static final String FILTER_VALUE_KEY = "key";
58
59
60   public FilterElasticSearchAdapter() {
61     try {
62       if (esConfig == null) {
63         esConfig = ElasticSearchConfig.getConfig();
64       }
65       if (search == null) {
66         search = new SearchAdapter();
67       }
68     } catch (Exception exc) {
69       LOG.error(AaiUiMsgs.CONFIGURATION_ERROR, "Search");
70     }
71   }
72
73   /**
74    * Get Full URL for search using elastic search configuration.
75    *
76    * @param api the api
77    * @return the full url
78    */
79   private String getFullUrl(String indexName, String api) {
80     final String host = esConfig.getIpAddress();
81     final String port = esConfig.getHttpPort();
82     return String.format("http://%s:%s/%s/%s", host, port, indexName, api);
83   }
84
85   /**
86    * For a given UiFilterEntity, will attempt to contact an Elasticsearch instance and fetch all
87    * possible values for filter's field name.
88    * 
89    * @param filter - Filter object against which the search will take place.
90    * @param sourceData - If present, contains the index name and field value to search against.
91    * @return - A List of strings if results were found, else empty list.
92    */
93   public List<String> fetchValuesForFilter(UiFilterEntity filter,
94       UiFilterDataSourceConfig dataSourceConfig) {
95     ArrayList<String> filterValues = new ArrayList<String>();
96
97     if (dataSourceConfig != null) {
98       JsonObject filterValueQuery = null;
99       if (dataSourceConfig.getPathToField() != null) {
100         filterValueQuery = FilterQueryBuilder.createNestedFilterValueQueryObject(
101             dataSourceConfig.getFieldName(), dataSourceConfig.getPathToField());
102       } else {
103         filterValueQuery =
104             FilterQueryBuilder.createFilterValueQueryObject(dataSourceConfig.getFieldName());
105       }
106
107       org.onap.aai.sparky.dal.rest.OperationResult opResult =
108           search.doPost(getFullUrl(dataSourceConfig.getIndexName(), ES_SEARCH_API),
109               filterValueQuery.toString(), APP_JSON);
110
111       String result = opResult.getResult();
112       if (opResult.wasSuccessful() && result != null) {
113         JSONObject responseJson = new JSONObject(result);
114         JSONObject aggJson = responseJson.getJSONObject(AGGS);
115
116         JSONObject containerJson = null;
117         if (dataSourceConfig.getPathToField() != null) {
118           JSONObject nestedContainer = aggJson.getJSONObject(dataSourceConfig.getPathToField());
119           containerJson = nestedContainer.getJSONObject(dataSourceConfig.getFieldName());
120         } else {
121           containerJson = aggJson.getJSONObject(CONTAINER);
122         }
123
124         JSONArray buckets = containerJson.getJSONArray(BUCKETS);
125
126         int bucketLength = buckets.length();
127         for (int i = 0; i < bucketLength; i++) {
128           JSONObject filterBucket = buckets.getJSONObject(i);
129
130           String filterValue = filterBucket.getString(FILTER_VALUE_KEY);
131           if (filterValue != null && !filterValue.isEmpty()) {
132             filterValues.add(filterValue);
133           }
134         }
135       } else {
136         LOG.error(AaiUiMsgs.ERROR_FETCHING_FILTER_VALUES, String.valueOf(opResult.getResultCode()),
137             filter.getFilterName());
138       }
139     }
140     filterValues.sort(String::compareToIgnoreCase);
141     return filterValues;
142   }
143 }