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