Convert Sparky to Spring-Boot
[aai/sparky-be.git] / sparkybe-onap-service / src / main / java / org / onap / aai / sparky / inventory / GeoVisualizationProcessor.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.inventory;
26
27 import java.io.IOException;
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.cl.mdc.MdcContext;
36 import org.onap.aai.restclient.client.OperationResult;
37 import org.onap.aai.sparky.dal.ElasticSearchAdapter;
38 import org.onap.aai.sparky.logging.AaiUiMsgs;
39 import org.onap.aai.sparky.util.NodeUtils;
40 import org.restlet.Request;
41 import org.restlet.Response;
42 import org.restlet.data.ClientInfo;
43 import org.restlet.data.Form;
44 import org.restlet.data.MediaType;
45 import org.restlet.data.Parameter;
46 import org.restlet.data.Status;
47
48 import com.fasterxml.jackson.databind.JsonNode;
49 import com.fasterxml.jackson.databind.ObjectMapper;
50
51 /**
52  * The Class GeoVisualizationServlet.
53  */
54 public class GeoVisualizationProcessor {
55
56   private static final Logger LOG =
57       LoggerFactory.getInstance().getLogger(GeoVisualizationProcessor.class);
58
59   private ObjectMapper mapper;
60   private ElasticSearchAdapter elasticSearchAdapter = null;
61   private String topographicalSearchIndexName;
62
63   private static final String SEARCH_STRING = "_search";
64   private static final String SEARCH_PARAMETER = "?filter_path=hits.hits._source&_source=location&size=5000&q=entityType:";
65   private static final String PARAMETER_KEY = "entity";
66
67   /**
68    * Instantiates a new geo visualization processor
69    */
70   public GeoVisualizationProcessor(ElasticSearchAdapter elasticSearchAdapter, String topographicalSearchIndexName)  {
71     this.mapper = new ObjectMapper();
72     this.elasticSearchAdapter = elasticSearchAdapter;
73     this.topographicalSearchIndexName = topographicalSearchIndexName;
74   }
75
76   /**
77    * Gets the geo visualization results.
78    *
79    * @param response the response
80    * @param entityType the entity type
81    * @return the geo visualization results
82    * @throws Exception the exception
83    */
84   protected OperationResult getGeoVisualizationResults(Exchange exchange) throws Exception {
85     OperationResult operationResult = new OperationResult();
86
87     
88     Object xTransactionId = exchange.getIn().getHeader("X-TransactionId");
89     if (xTransactionId == null) {
90       xTransactionId = NodeUtils.getRandomTxnId();
91     }
92
93     Object partnerName = exchange.getIn().getHeader("X-FromAppId");
94     if (partnerName == null) {
95       partnerName = "Browser";
96     }
97
98     Request request = exchange.getIn().getHeader(RestletConstants.RESTLET_REQUEST, Request.class);
99
100     /* Disables automatic Apache Camel Restlet component logging which prints out an undesirable log entry
101        which includes client (e.g. browser) information */
102     request.setLoggable(false);
103
104     ClientInfo clientInfo = request.getClientInfo();
105     MdcContext.initialize((String) xTransactionId, "AAI-UI", "", (String) partnerName, clientInfo.getAddress() + ":" + clientInfo.getPort());
106     
107     String entityType = "";
108     
109     Form form = request.getResourceRef().getQueryAsForm();
110     for (Parameter parameter : form) {
111       if(PARAMETER_KEY.equals(parameter.getName())) {
112         entityType = parameter.getName();
113       }
114     }
115     
116     String api = SEARCH_STRING + SEARCH_PARAMETER + entityType;
117     
118     final String requestUrl = elasticSearchAdapter.buildElasticSearchUrlForApi(topographicalSearchIndexName, api);
119
120     try {
121       
122       OperationResult opResult =
123           elasticSearchAdapter.doGet(requestUrl, javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE);
124
125       JSONObject finalOutputJson = formatOutput(opResult.getResult());
126
127       Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);
128       response.setStatus(Status.SUCCESS_OK);
129       response.setEntity(String.valueOf(finalOutputJson), MediaType.APPLICATION_JSON);
130       exchange.getOut().setBody(response);
131
132     } catch (Exception exc) {
133       LOG.error(AaiUiMsgs.ERROR_GENERIC, "Error processing Geo Visualization request");
134     }
135
136     return operationResult;
137   }
138
139   /**
140    * Format output.
141    *
142    * @param results the results
143    * @return the JSON object
144    */
145   private JSONObject formatOutput(String results) {
146     JsonNode resultNode = null;
147     JSONObject finalResult = new JSONObject();
148     JSONArray entitiesArr = new JSONArray();
149
150     try {
151       resultNode = mapper.readTree(results);
152
153       final JsonNode hitsNode = resultNode.get("hits").get("hits");
154       if (hitsNode.isArray()) {
155
156         for (final JsonNode arrayNode : hitsNode) {
157           JsonNode sourceNode = arrayNode.get("_source");
158           if (sourceNode.get("location") != null) {
159             JsonNode locationNode = sourceNode.get("location");
160             if (NodeUtils.isNumeric(locationNode.get("lon").asText())
161                 && NodeUtils.isNumeric(locationNode.get("lat").asText())) {
162               JSONObject location = new JSONObject();
163               location.put("longitude", locationNode.get("lon").asText());
164               location.put("latitude", locationNode.get("lat").asText());
165
166               entitiesArr.put(location);
167             }
168
169           }
170         }
171       }
172       finalResult.put("plotPoints", entitiesArr);
173
174     } catch (IOException exc) {
175       LOG.warn(AaiUiMsgs.ERROR_BUILDING_SEARCH_RESPONSE, exc.getLocalizedMessage());
176     }
177
178     return finalResult;
179   }
180 }