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