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