enable suggestions to use search data service
[aai/sparky-be.git] / src / main / java / org / onap / aai / sparky / aggregatevnf / search / AggregateSummaryProcessor.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.List;
28
29 import javax.json.JsonObject;
30
31 import org.apache.camel.Exchange;
32 import org.apache.camel.component.restlet.RestletConstants;
33 import org.json.JSONArray;
34 import org.json.JSONObject;
35 import org.onap.aai.cl.api.Logger;
36 import org.onap.aai.cl.eelf.LoggerFactory;
37 import org.onap.aai.restclient.client.OperationResult;
38 import org.onap.aai.sparky.dal.ElasticSearchAdapter;
39 import org.onap.aai.sparky.logging.AaiUiMsgs;
40 import org.onap.aai.sparky.search.filters.FilterQueryBuilder;
41 import org.onap.aai.sparky.search.filters.config.FiltersConfig;
42 import org.onap.aai.sparky.search.filters.entity.SearchFilter;
43 import org.onap.aai.sparky.viewandinspect.config.SparkyConstants;
44 import org.restlet.Request;
45 import org.restlet.Response;
46 import org.restlet.data.MediaType;
47 import org.restlet.data.Status;
48
49 public class AggregateSummaryProcessor {
50
51   private static final Logger LOG =
52       LoggerFactory.getInstance().getLogger(AggregateSummaryProcessor.class);
53
54   private static final String KEY_FILTERS = "filters";
55
56   private ElasticSearchAdapter elasticSearchAdapter = null;
57
58   private String vnfAggregationIndexName;
59   private FiltersConfig filtersConfig;
60
61   public AggregateSummaryProcessor(ElasticSearchAdapter elasticSearchAdapter,
62       FiltersConfig filtersConfig) {
63     this.elasticSearchAdapter = elasticSearchAdapter;
64     this.filtersConfig = filtersConfig;
65   }
66
67   public void setVnfAggregationIndexName(String vnfAggregationIndexName) {
68     this.vnfAggregationIndexName = vnfAggregationIndexName;
69   }
70
71   public void getFilteredAggregation(Exchange exchange) {
72
73     Response response =
74         exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);
75
76     Request request = exchange.getIn().getHeader(RestletConstants.RESTLET_REQUEST, Request.class);
77
78     /*
79      * Disables automatic Apache Camel Restlet component logging which prints out an undesirable log
80      * entry which includes client (e.g. browser) information
81      */
82     request.setLoggable(false);
83
84     try {
85       String payload = exchange.getIn().getBody(String.class);
86
87       if (payload == null || payload.isEmpty()) {
88
89         LOG.error(AaiUiMsgs.SEARCH_SERVLET_ERROR, "Request Payload is empty");
90
91         /*
92          * Don't throw back an error, just return an empty set
93          */
94
95       } else {
96
97         JSONObject parameters = new JSONObject(payload);
98
99         JSONArray requestFilters = null;
100         if (parameters.has(KEY_FILTERS)) {
101           requestFilters = parameters.getJSONArray(KEY_FILTERS);
102         } else {
103
104           JSONObject zeroResponsePayload = new JSONObject();
105           zeroResponsePayload.put("count", 0);
106           response.setStatus(Status.SUCCESS_OK);
107           response.setEntity(zeroResponsePayload.toString(), MediaType.APPLICATION_JSON);
108           exchange.getOut().setBody(response);
109
110           LOG.error(AaiUiMsgs.ERROR_FILTERS_NOT_FOUND);
111           return;
112         }
113
114         if (requestFilters != null && requestFilters.length() > 0) {
115           List<JSONObject> filtersToQuery = new ArrayList<JSONObject>();
116           for (int i = 0; i < requestFilters.length(); i++) {
117             JSONObject filterEntry = requestFilters.getJSONObject(i);
118             filtersToQuery.add(filterEntry);
119           }
120
121           String jsonResponsePayload = getVnfFilterAggregations(filtersToQuery);
122           response.setStatus(Status.SUCCESS_OK);
123           response.setEntity(jsonResponsePayload, MediaType.APPLICATION_JSON);
124           exchange.getOut().setBody(response);
125
126         } else {
127           String emptyResponse = getEmptyAggResponse();
128           response.setStatus(Status.SUCCESS_OK);
129           response.setEntity(emptyResponse, MediaType.APPLICATION_JSON);
130           exchange.getOut().setBody(response);
131           LOG.error(AaiUiMsgs.ERROR_FILTERS_NOT_FOUND);
132         }
133       }
134     } catch (Exception exc) {
135       LOG.error(AaiUiMsgs.ERROR_GENERIC,
136           "FilterProcessor failed to get filter list due to error = " + exc.getMessage());
137     }
138   }
139
140   private String getEmptyAggResponse() {
141     JSONObject aggPayload = new JSONObject();
142     aggPayload.put("totalChartHits", 0);
143     aggPayload.put("buckets", new JSONArray());
144     JSONObject payload = new JSONObject();
145     payload.append("groupby_aggregation", aggPayload);
146
147     return payload.toString();
148   }
149
150   private static final String FILTER_ID_KEY = "filterId";
151   private static final String FILTER_VALUE_KEY = "filterValue";
152   private static final int DEFAULT_SHOULD_MATCH_SCORE = 1;
153   private static final String VNF_FILTER_AGGREGATION = "vnfFilterAggregation";
154
155   private String getVnfFilterAggregations(List<JSONObject> filtersToQuery) throws IOException {
156
157     List<SearchFilter> searchFilters = new ArrayList<SearchFilter>();
158     for (JSONObject filterEntry : filtersToQuery) {
159
160       String filterId = filterEntry.getString(FILTER_ID_KEY);
161       if (filterId != null) {
162         SearchFilter filter = new SearchFilter();
163         filter.setFilterId(filterId);
164
165         if (filterEntry.has(FILTER_VALUE_KEY)) {
166           String filterValue = filterEntry.getString(FILTER_VALUE_KEY);
167           filter.addValue(filterValue);
168         }
169
170         searchFilters.add(filter);
171       }
172     }
173
174     // Create query for summary by entity type
175     JsonObject vnfSearch = FilterQueryBuilder.createCombinedBoolAndAggQuery(filtersConfig,
176         searchFilters, DEFAULT_SHOULD_MATCH_SCORE);
177
178     // Parse response for summary by entity type query
179     OperationResult opResult = elasticSearchAdapter.doPost(
180         elasticSearchAdapter.buildElasticSearchUrlForApi(vnfAggregationIndexName,
181             SparkyConstants.ES_SEARCH_API),
182         vnfSearch.toString(), javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE);
183
184     return buildAggregateVnfResponseJson(opResult.getResult());
185
186   }
187
188   private String buildAggregateVnfResponseJson(String responseJsonStr) {
189
190     JSONObject finalOutputToFe = new JSONObject();
191     JSONObject responseJson = new JSONObject(responseJsonStr);
192
193     JSONObject hits = responseJson.getJSONObject("hits");
194     int totalHits = hits.getInt("total");
195     finalOutputToFe.put("total", totalHits);
196
197     JSONObject aggregations = responseJson.getJSONObject("aggregations");
198     String[] aggKeys = JSONObject.getNames(aggregations);
199     JSONObject aggregationsList = new JSONObject();
200
201     for (String aggName : aggKeys) {
202       JSONObject aggregation = aggregations.getJSONObject(aggName);
203       JSONArray buckets = aggregation.getJSONArray("buckets");
204       aggregationsList.put(aggName, buckets);
205     }
206
207     finalOutputToFe.put("aggregations", aggregationsList);
208
209     return finalOutputToFe.toString();
210   }
211 }