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