Adding interfaces in documentation
[aai/sparky-be.git] / sparkybe-onap-service / src / main / java / org / onap / aai / sparky / aggregatevnf / search / AggregateSummaryProcessor.java
1 /**
2  * ============LICENSE_START===================================================
3  * SPARKY (AAI UI service)
4  * ============================================================================
5  * Copyright © 2017 AT&T Intellectual Property.
6  * Copyright © 2017 Amdocs
7  * All rights reserved.
8  * ============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=====================================================
21  *
22  * ECOMP and OpenECOMP are trademarks
23  * and service marks of AT&T Intellectual Property.
24  */
25 package org.onap.aai.sparky.aggregatevnf.search;
26
27 import java.io.IOException;
28 import java.util.ArrayList;
29 import java.util.List;
30
31 import javax.json.JsonObject;
32 import javax.servlet.http.HttpServletRequest;
33
34 import org.apache.camel.Exchange;
35 import org.json.JSONArray;
36 import org.json.JSONObject;
37 import org.onap.aai.cl.api.Logger;
38 import org.onap.aai.cl.eelf.LoggerFactory;
39 import org.onap.aai.restclient.client.OperationResult;
40 import org.onap.aai.sparky.dal.ElasticSearchAdapter;
41 import org.onap.aai.sparky.logging.AaiUiMsgs;
42 import org.onap.aai.sparky.logging.util.ServletUtils;
43 import org.onap.aai.sparky.search.filters.FilterQueryBuilder;
44 import org.onap.aai.sparky.search.filters.config.FiltersConfig;
45 import org.onap.aai.sparky.search.filters.entity.SearchFilter;
46 import org.onap.aai.sparky.viewandinspect.config.SparkyConstants;
47
48 public class AggregateSummaryProcessor {
49
50   private static final Logger LOG = 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, FiltersConfig filtersConfig) {
60     this.elasticSearchAdapter = elasticSearchAdapter;
61     this.filtersConfig = filtersConfig;
62   }
63   
64   public void setVnfAggregationIndexName(String vnfAggregationIndexName) {
65     this.vnfAggregationIndexName = vnfAggregationIndexName;
66   }
67   
68   public void getFilteredAggregation(Exchange exchange) {
69
70     HttpServletRequest request = exchange.getIn().getBody(HttpServletRequest.class);
71     ServletUtils.setUpMdcContext(exchange, request);
72     
73
74     try {
75       String payload = exchange.getIn().getBody(String.class);
76
77       if (payload == null || payload.isEmpty()) {
78
79         LOG.error(AaiUiMsgs.SEARCH_SERVLET_ERROR, "Request Payload is empty");
80
81         /*
82          * Don't throw back an error, just return an empty set
83          */
84
85       } else {
86
87         JSONObject parameters = new JSONObject(payload);
88
89         JSONArray requestFilters = null;
90         if (parameters.has(KEY_FILTERS)) {
91           requestFilters = parameters.getJSONArray(KEY_FILTERS);
92         } else {
93           
94           JSONObject zeroResponsePayload = new JSONObject();
95           zeroResponsePayload.put("count", 0);
96           //response.setStatus(Status.SUCCESS_OK);
97           //response.setEntity(zeroResponsePayload.toString(), MediaType.APPLICATION_JSON);
98           exchange.getOut().setBody(zeroResponsePayload.toString());
99           
100           LOG.error(AaiUiMsgs.ERROR_FILTERS_NOT_FOUND);
101           return;
102         }
103       
104         if (requestFilters != null && requestFilters.length() > 0) {
105           List<JSONObject> filtersToQuery = new ArrayList<JSONObject>();
106           for(int i = 0; i < requestFilters.length(); i++) {
107             JSONObject filterEntry = requestFilters.getJSONObject(i);
108             filtersToQuery.add(filterEntry);
109           }
110           
111           String jsonResponsePayload = getVnfFilterAggregations(filtersToQuery);
112           exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, 200);
113           exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "application/json");
114           exchange.getOut().setBody(jsonResponsePayload);
115           
116         } else {
117           String emptyResponse = getEmptyAggResponse();
118           exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, 200);
119           exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "application/json");
120           exchange.getOut().setBody(emptyResponse);
121           LOG.error(AaiUiMsgs.ERROR_FILTERS_NOT_FOUND);
122         }
123       }
124     } catch (Exception exc) {
125       LOG.error(AaiUiMsgs.ERROR_GENERIC, "FilterProcessor failed to get filter list due to error = " + exc.getMessage());
126     }
127   }
128   
129   private String getEmptyAggResponse() {
130     JSONObject aggPayload = new JSONObject();
131     aggPayload.put("totalChartHits", 0);
132     aggPayload.put("buckets", new JSONArray());
133     JSONObject payload = new JSONObject();
134     payload.append("groupby_aggregation", aggPayload);
135
136     return payload.toString();
137   }  
138   
139   private static final String FILTER_ID_KEY = "filterId";
140   private static final String FILTER_VALUE_KEY = "filterValue";
141   private static final int DEFAULT_SHOULD_MATCH_SCORE = 1;
142   private static final String VNF_FILTER_AGGREGATION = "vnfFilterAggregation";
143
144   
145   private String getVnfFilterAggregations(List<JSONObject> filtersToQuery) throws IOException {
146     
147     List<SearchFilter> searchFilters = new ArrayList<SearchFilter>();
148     for(JSONObject filterEntry : filtersToQuery) {
149       
150       String filterId = filterEntry.getString(FILTER_ID_KEY);
151       if(filterId != null) {
152         SearchFilter filter = new SearchFilter();
153         filter.setFilterId(filterId);
154         
155         if(filterEntry.has(FILTER_VALUE_KEY)) {
156           String filterValue = filterEntry.getString(FILTER_VALUE_KEY);
157           filter.addValue(filterValue);
158         }
159         
160         searchFilters.add(filter);
161       }
162     }
163     
164     // Create query for summary by entity type
165     JsonObject vnfSearch = FilterQueryBuilder.createCombinedBoolAndAggQuery(filtersConfig, 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 }