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