changed the header license to new license
[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-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
29 import org.apache.camel.Exchange;
30 import org.apache.camel.component.restlet.RestletConstants;
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.search.filters.FilterQueryBuilder;
39 import org.onap.aai.sparky.search.filters.config.FiltersConfig;
40 import org.onap.aai.sparky.search.filters.entity.SearchFilter;
41 import org.onap.aai.sparky.viewandinspect.config.SparkyConstants;
42 import org.restlet.Request;
43 import org.restlet.Response;
44 import org.restlet.data.MediaType;
45 import org.restlet.data.Status;
46
47 public class AggregateSummaryProcessor {
48
49   private static final Logger LOG = LoggerFactory.getInstance().getLogger(AggregateSummaryProcessor.class);
50
51   private static final String KEY_FILTERS = "filters";
52
53   private ElasticSearchAdapter elasticSearchAdapter = null;
54   
55   private String vnfAggregationIndexName;
56   private FiltersConfig filtersConfig;
57   
58   public AggregateSummaryProcessor(ElasticSearchAdapter elasticSearchAdapter, FiltersConfig filtersConfig) {
59     this.elasticSearchAdapter = elasticSearchAdapter;
60     this.filtersConfig = filtersConfig;
61   }
62   
63   public void setVnfAggregationIndexName(String vnfAggregationIndexName) {
64     this.vnfAggregationIndexName = vnfAggregationIndexName;
65   }
66   
67   public void getFilteredAggregation(Exchange exchange) {
68     
69     Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);
70
71     Request request = exchange.getIn().getHeader(RestletConstants.RESTLET_REQUEST, Request.class);
72
73     /* Disables automatic Apache Camel Restlet component logging which prints out an undesirable log entry
74        which includes client (e.g. browser) information */
75     request.setLoggable(false);
76
77     try {
78       String payload = exchange.getIn().getBody(String.class);
79
80       if (payload == null || payload.isEmpty()) {
81
82         LOG.error(AaiUiMsgs.SEARCH_SERVLET_ERROR, "Request Payload is empty");
83
84         /*
85          * Don't throw back an error, just return an empty set
86          */
87
88       } else {
89
90         JSONObject parameters = new JSONObject(payload);
91
92         JSONArray requestFilters = null;
93         if (parameters.has(KEY_FILTERS)) {
94           requestFilters = parameters.getJSONArray(KEY_FILTERS);
95         } else {
96           
97           JSONObject zeroResponsePayload = new JSONObject();
98           zeroResponsePayload.put("count", 0);
99           response.setStatus(Status.SUCCESS_OK);
100           response.setEntity(zeroResponsePayload.toString(), MediaType.APPLICATION_JSON);
101           exchange.getOut().setBody(response);
102           
103           LOG.error(AaiUiMsgs.ERROR_FILTERS_NOT_FOUND);
104           return;
105         }
106       
107         if (requestFilters != null && requestFilters.length() > 0) {
108           List<JSONObject> filtersToQuery = new ArrayList<JSONObject>();
109           for(int i = 0; i < requestFilters.length(); i++) {
110             JSONObject filterEntry = requestFilters.getJSONObject(i);
111             filtersToQuery.add(filterEntry);
112           }
113           
114           String jsonResponsePayload = getVnfFilterAggregations(filtersToQuery);
115           response.setStatus(Status.SUCCESS_OK);
116           response.setEntity(jsonResponsePayload, MediaType.APPLICATION_JSON);
117           exchange.getOut().setBody(response);
118           
119         } else {
120           String emptyResponse = getEmptyAggResponse();
121           response.setStatus(Status.SUCCESS_OK);
122           response.setEntity(emptyResponse, MediaType.APPLICATION_JSON);
123           exchange.getOut().setBody(response);
124           LOG.error(AaiUiMsgs.ERROR_FILTERS_NOT_FOUND);
125         }
126       }
127     } catch (Exception exc) {
128       LOG.error(AaiUiMsgs.ERROR_GENERIC, "FilterProcessor failed to get filter list due to error = " + exc.getMessage());
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 static final String FILTER_ID_KEY = "filterId";
143   private static final String FILTER_VALUE_KEY = "filterValue";
144   private static final int DEFAULT_SHOULD_MATCH_SCORE = 1;
145   private static final String VNF_FILTER_AGGREGATION = "vnfFilterAggregation";
146
147   
148   private String getVnfFilterAggregations(List<JSONObject> filtersToQuery) throws IOException {
149     
150     List<SearchFilter> searchFilters = new ArrayList<SearchFilter>();
151     for(JSONObject filterEntry : filtersToQuery) {
152       
153       String filterId = filterEntry.getString(FILTER_ID_KEY);
154       if(filterId != null) {
155         SearchFilter filter = new SearchFilter();
156         filter.setFilterId(filterId);
157         
158         if(filterEntry.has(FILTER_VALUE_KEY)) {
159           String filterValue = filterEntry.getString(FILTER_VALUE_KEY);
160           filter.addValue(filterValue);
161         }
162         
163         searchFilters.add(filter);
164       }
165     }
166     
167     // Create query for summary by entity type
168     JsonObject vnfSearch = FilterQueryBuilder.createCombinedBoolAndAggQuery(filtersConfig, searchFilters, DEFAULT_SHOULD_MATCH_SCORE);
169
170     // Parse response for summary by entity type query
171     OperationResult opResult = elasticSearchAdapter.doPost(
172         elasticSearchAdapter.buildElasticSearchUrlForApi(vnfAggregationIndexName,
173             SparkyConstants.ES_SEARCH_API),
174         vnfSearch.toString(), javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE);
175     
176     return buildAggregateVnfResponseJson(opResult.getResult());
177     
178   }
179   
180   private String buildAggregateVnfResponseJson(String responseJsonStr) {
181     
182     JSONObject finalOutputToFe = new JSONObject();
183     JSONObject responseJson = new JSONObject(responseJsonStr);
184     
185     
186     JSONObject hits = responseJson.getJSONObject("hits");
187     int totalHits = hits.getInt("total");
188     finalOutputToFe.put("total", totalHits);
189     
190     JSONObject aggregations = responseJson.getJSONObject("aggregations");
191     String[] aggKeys = JSONObject.getNames(aggregations);
192     JSONObject aggregationsList = new JSONObject();
193     
194     for(String aggName : aggKeys) {
195       JSONObject aggregation = aggregations.getJSONObject(aggName);
196       JSONArray buckets = aggregation.getJSONArray("buckets");
197       aggregationsList.put(aggName, buckets);
198     }
199     
200     finalOutputToFe.put("aggregations", aggregationsList);
201
202     return finalOutputToFe.toString();
203   }
204 }