2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.onap.aai.sparky.aggregatevnf.search;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.List;
29 import javax.json.JsonObject;
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.elasticsearch.SearchAdapter;
39 import org.onap.aai.sparky.dataintegrity.config.DiUiConstants;
40 import org.onap.aai.sparky.logging.AaiUiMsgs;
41 import org.onap.aai.sparky.search.filters.FilterQueryBuilder;
42 import org.onap.aai.sparky.search.filters.entity.SearchFilter;
43 import org.onap.aai.sparky.viewandinspect.config.TierSupportUiConstants;
44 import org.restlet.Request;
45 import org.restlet.Response;
46 import org.restlet.data.MediaType;
47 import org.restlet.data.Status;
49 public class AggregateSummaryProcessor {
51 private static final Logger LOG =
52 LoggerFactory.getInstance().getLogger(AggregateSummaryProcessor.class);
54 private static final String KEY_FILTERS = "filters";
56 private SearchAdapter search = null;
58 private String vnfAggregationIndexName;
59 private String elasticSearchIp;
60 private String elatsticSearchPort;
62 public AggregateSummaryProcessor() {
65 search = new SearchAdapter();
67 } catch (Exception exc) {
68 LOG.error(AaiUiMsgs.ERROR_GENERIC,
69 "Failed to get elastic search configuration with error = " + exc.getMessage());
73 public void setVnfAggregationIndexName(String vnfAggregationIndexName) {
74 this.vnfAggregationIndexName = vnfAggregationIndexName;
77 public void setElasticSearchIp(String elasticSearchIp) {
78 this.elasticSearchIp = elasticSearchIp;
81 public void setElatsticSearchPort(String elatsticSearchPort) {
82 this.elatsticSearchPort = elatsticSearchPort;
85 public void getFilteredAggregation(Exchange exchange) {
88 exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);
90 Request request = exchange.getIn().getHeader(RestletConstants.RESTLET_REQUEST, Request.class);
93 * Disables automatic Apache Camel Restlet component logging which prints out an undesirable log
94 * entry which includes client (e.g. browser) information
96 request.setLoggable(false);
99 String payload = exchange.getIn().getBody(String.class);
101 if (payload == null || payload.isEmpty()) {
103 LOG.error(AaiUiMsgs.SEARCH_SERVLET_ERROR, "Request Payload is empty");
106 * Don't throw back an error, just return an empty set
111 JSONObject parameters = new JSONObject(payload);
113 JSONArray requestFilters = null;
114 if (parameters.has(KEY_FILTERS)) {
115 requestFilters = parameters.getJSONArray(KEY_FILTERS);
118 JSONObject zeroResponsePayload = new JSONObject();
119 zeroResponsePayload.put("count", 0);
120 response.setStatus(Status.SUCCESS_OK);
121 response.setEntity(zeroResponsePayload.toString(), MediaType.APPLICATION_JSON);
122 exchange.getOut().setBody(response);
124 LOG.error(AaiUiMsgs.ERROR_FILTERS_NOT_FOUND);
128 if (requestFilters != null && requestFilters.length() > 0) {
129 List<JSONObject> filtersToQuery = new ArrayList<JSONObject>();
130 for (int i = 0; i < requestFilters.length(); i++) {
131 JSONObject filterEntry = requestFilters.getJSONObject(i);
132 filtersToQuery.add(filterEntry);
135 String jsonResponsePayload = getVnfFilterAggregations(filtersToQuery);
136 response.setStatus(Status.SUCCESS_OK);
137 response.setEntity(jsonResponsePayload, MediaType.APPLICATION_JSON);
138 exchange.getOut().setBody(response);
141 String emptyResponse = getEmptyAggResponse();
142 response.setStatus(Status.SUCCESS_OK);
143 response.setEntity(emptyResponse, MediaType.APPLICATION_JSON);
144 exchange.getOut().setBody(response);
145 LOG.error(AaiUiMsgs.ERROR_FILTERS_NOT_FOUND);
148 } catch (Exception exc) {
149 LOG.error(AaiUiMsgs.ERROR_GENERIC,
150 "FilterProcessor failed to get filter list due to error = " + exc.getMessage());
154 private String getEmptyAggResponse() {
155 JSONObject aggPayload = new JSONObject();
156 aggPayload.put("totalChartHits", 0);
157 aggPayload.put("buckets", new JSONArray());
158 JSONObject payload = new JSONObject();
159 payload.append("groupby_aggregation", aggPayload);
161 return payload.toString();
164 private static final String FILTER_ID_KEY = "filterId";
165 private static final String FILTER_VALUE_KEY = "filterValue";
166 private static final int DEFAULT_SHOULD_MATCH_SCORE = 1;
167 private static final String VNF_FILTER_AGGREGATION = "vnfFilterAggregation";
170 private String getVnfFilterAggregations(List<JSONObject> filtersToQuery) throws IOException {
172 List<SearchFilter> searchFilters = new ArrayList<SearchFilter>();
173 for (JSONObject filterEntry : filtersToQuery) {
175 String filterId = filterEntry.getString(FILTER_ID_KEY);
176 if (filterId != null) {
177 SearchFilter filter = new SearchFilter();
178 filter.setFilterId(filterId);
180 if (filterEntry.has(FILTER_VALUE_KEY)) {
181 String filterValue = filterEntry.getString(FILTER_VALUE_KEY);
182 filter.addValue(filterValue);
185 searchFilters.add(filter);
189 // Create query for summary by entity type
190 JsonObject vnfSearch =
191 FilterQueryBuilder.createCombinedBoolAndAggQuery(searchFilters, DEFAULT_SHOULD_MATCH_SCORE);
193 // Parse response for summary by entity type query
194 OperationResult opResult =
195 search.doPost(getFullUrl(vnfAggregationIndexName, TierSupportUiConstants.ES_SEARCH_API),
196 vnfSearch.toString(), DiUiConstants.APP_JSON);
198 return buildAggregateVnfResponseJson(opResult.getResult());
203 * Get Full URL for search using elastic search configuration.
206 * @return the full url
208 private String getFullUrl(String indexName, String api) {
209 final String host = elasticSearchIp;
210 final String port = elatsticSearchPort;
211 return String.format("http://%s:%s/%s/%s", host, port, indexName, api);
214 private String buildAggregateVnfResponseJson(String responseJsonStr) {
216 JSONObject finalOutputToFe = new JSONObject();
217 JSONObject responseJson = new JSONObject(responseJsonStr);
220 JSONObject hits = responseJson.getJSONObject("hits");
221 int totalHits = hits.getInt("total");
222 finalOutputToFe.put("total", totalHits);
224 JSONObject aggregations = responseJson.getJSONObject("aggregations");
225 String[] aggKeys = JSONObject.getNames(aggregations);
226 JSONObject aggregationsList = new JSONObject();
228 for (String aggName : aggKeys) {
229 JSONObject aggregation = aggregations.getJSONObject(aggName);
230 JSONArray buckets = aggregation.getJSONArray("buckets");
231 aggregationsList.put(aggName, buckets);
234 finalOutputToFe.put("aggregations", aggregationsList);
236 return finalOutputToFe.toString();