Adding UI extensibility
[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.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;
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 SearchAdapter search = null;
57
58   private String vnfAggregationIndexName;
59   private String elasticSearchIp;
60   private String elatsticSearchPort;
61
62   public AggregateSummaryProcessor() {
63     try {
64       if (search == null) {
65         search = new SearchAdapter();
66       }
67     } catch (Exception exc) {
68       LOG.error(AaiUiMsgs.ERROR_GENERIC,
69           "Failed to get elastic search configuration with error = " + exc.getMessage());
70     }
71   }
72
73   public void setVnfAggregationIndexName(String vnfAggregationIndexName) {
74     this.vnfAggregationIndexName = vnfAggregationIndexName;
75   }
76
77   public void setElasticSearchIp(String elasticSearchIp) {
78     this.elasticSearchIp = elasticSearchIp;
79   }
80
81   public void setElatsticSearchPort(String elatsticSearchPort) {
82     this.elatsticSearchPort = elatsticSearchPort;
83   }
84
85   public void getFilteredAggregation(Exchange exchange) {
86
87     Response response =
88         exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);
89
90     Request request = exchange.getIn().getHeader(RestletConstants.RESTLET_REQUEST, Request.class);
91
92     /*
93      * Disables automatic Apache Camel Restlet component logging which prints out an undesirable log
94      * entry which includes client (e.g. browser) information
95      */
96     request.setLoggable(false);
97
98     try {
99       String payload = exchange.getIn().getBody(String.class);
100
101       if (payload == null || payload.isEmpty()) {
102
103         LOG.error(AaiUiMsgs.SEARCH_SERVLET_ERROR, "Request Payload is empty");
104
105         /*
106          * Don't throw back an error, just return an empty set
107          */
108
109       } else {
110
111         JSONObject parameters = new JSONObject(payload);
112
113         JSONArray requestFilters = null;
114         if (parameters.has(KEY_FILTERS)) {
115           requestFilters = parameters.getJSONArray(KEY_FILTERS);
116         } else {
117
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);
123
124           LOG.error(AaiUiMsgs.ERROR_FILTERS_NOT_FOUND);
125           return;
126         }
127
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);
133           }
134
135           String jsonResponsePayload = getVnfFilterAggregations(filtersToQuery);
136           response.setStatus(Status.SUCCESS_OK);
137           response.setEntity(jsonResponsePayload, MediaType.APPLICATION_JSON);
138           exchange.getOut().setBody(response);
139
140         } else {
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);
146         }
147       }
148     } catch (Exception exc) {
149       LOG.error(AaiUiMsgs.ERROR_GENERIC,
150           "FilterProcessor failed to get filter list due to error = " + exc.getMessage());
151     }
152   }
153
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);
160
161     return payload.toString();
162   }
163
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";
168
169
170   private String getVnfFilterAggregations(List<JSONObject> filtersToQuery) throws IOException {
171
172     List<SearchFilter> searchFilters = new ArrayList<SearchFilter>();
173     for (JSONObject filterEntry : filtersToQuery) {
174
175       String filterId = filterEntry.getString(FILTER_ID_KEY);
176       if (filterId != null) {
177         SearchFilter filter = new SearchFilter();
178         filter.setFilterId(filterId);
179
180         if (filterEntry.has(FILTER_VALUE_KEY)) {
181           String filterValue = filterEntry.getString(FILTER_VALUE_KEY);
182           filter.addValue(filterValue);
183         }
184
185         searchFilters.add(filter);
186       }
187     }
188
189     // Create query for summary by entity type
190     JsonObject vnfSearch =
191         FilterQueryBuilder.createCombinedBoolAndAggQuery(searchFilters, DEFAULT_SHOULD_MATCH_SCORE);
192
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);
197
198     return buildAggregateVnfResponseJson(opResult.getResult());
199
200   }
201
202   /**
203    * Get Full URL for search using elastic search configuration.
204    *
205    * @param api the api
206    * @return the full url
207    */
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);
212   }
213
214   private String buildAggregateVnfResponseJson(String responseJsonStr) {
215
216     JSONObject finalOutputToFe = new JSONObject();
217     JSONObject responseJson = new JSONObject(responseJsonStr);
218
219
220     JSONObject hits = responseJson.getJSONObject("hits");
221     int totalHits = hits.getInt("total");
222     finalOutputToFe.put("total", totalHits);
223
224     JSONObject aggregations = responseJson.getJSONObject("aggregations");
225     String[] aggKeys = JSONObject.getNames(aggregations);
226     JSONObject aggregationsList = new JSONObject();
227
228     for (String aggName : aggKeys) {
229       JSONObject aggregation = aggregations.getJSONObject(aggName);
230       JSONArray buckets = aggregation.getJSONArray("buckets");
231       aggregationsList.put(aggName, buckets);
232     }
233
234     finalOutputToFe.put("aggregations", aggregationsList);
235
236     return finalOutputToFe.toString();
237   }
238 }