Adding UI extensibility
[aai/sparky-be.git] / src / main / java / org / onap / aai / sparky / inventory / GeoVisualizationProcessor.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.inventory;
24
25 import java.io.IOException;
26
27 import org.apache.camel.Exchange;
28 import org.apache.camel.component.restlet.RestletConstants;
29 import org.json.JSONArray;
30 import org.json.JSONObject;
31 import org.onap.aai.cl.api.Logger;
32 import org.onap.aai.cl.eelf.LoggerFactory;
33 import org.onap.aai.cl.mdc.MdcContext;
34 import org.onap.aai.restclient.client.OperationResult;
35 import org.onap.aai.sparky.dal.elasticsearch.SearchAdapter;
36 import org.onap.aai.sparky.dal.elasticsearch.config.ElasticSearchConfig;
37 import org.onap.aai.sparky.logging.AaiUiMsgs;
38 import org.onap.aai.sparky.logging.util.ServletUtils;
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 SearchAdapter search = null;
61   private ElasticSearchConfig elasticConfig = null;
62
63   private static final String SEARCH_STRING = "_search";
64   private static final String SEARCH_PARAMETER =
65       "?filter_path=hits.hits._source&_source=location&size=5000&q=entityType:";
66   private static final String PARAMETER_KEY = "entity";
67
68   /**
69    * Instantiates a new geo visualization processor
70    */
71   public GeoVisualizationProcessor() {
72     this.mapper = new ObjectMapper();
73
74     try {
75       if (elasticConfig == null) {
76         elasticConfig = ElasticSearchConfig.getConfig();
77       }
78       if (search == null) {
79         search = new SearchAdapter();
80       }
81       this.mapper = new ObjectMapper();
82     } catch (Exception exc) {
83
84     }
85   }
86
87   public void setSearch(SearchAdapter search) {
88     this.search = search;
89   }
90
91   public void setElasticConfig(ElasticSearchConfig elasticConfig) {
92     this.elasticConfig = elasticConfig;
93   }
94
95   /**
96    * Gets the geo visualization results.
97    *
98    * @param response the response
99    * @param entityType the entity type
100    * @return the geo visualization results
101    * @throws Exception the exception
102    */
103   protected OperationResult getGeoVisualizationResults(Exchange exchange) throws Exception {
104     OperationResult operationResult = new OperationResult();
105
106
107     Object xTransactionId = exchange.getIn().getHeader("X-TransactionId");
108     if (xTransactionId == null) {
109       xTransactionId = NodeUtils.getRandomTxnId();
110     }
111
112     Object partnerName = exchange.getIn().getHeader("X-FromAppId");
113     if (partnerName == null) {
114       partnerName = "Browser";
115     }
116
117     Request request = exchange.getIn().getHeader(RestletConstants.RESTLET_REQUEST, Request.class);
118
119     /*
120      * Disables automatic Apache Camel Restlet component logging which prints out an undesirable log
121      * entry which includes client (e.g. browser) information
122      */
123     request.setLoggable(false);
124
125     ClientInfo clientInfo = request.getClientInfo();
126     MdcContext.initialize((String) xTransactionId, "AAI-UI", "", (String) partnerName,
127         clientInfo.getAddress() + ":" + clientInfo.getPort());
128
129     String entityType = "";
130
131     Form form = request.getResourceRef().getQueryAsForm();
132     for (Parameter parameter : form) {
133       if (PARAMETER_KEY.equals(parameter.getName())) {
134         entityType = parameter.getName();
135       }
136     }
137
138     String parameters = SEARCH_PARAMETER + entityType;
139     String requestString = String.format("/%s/%s/%s", elasticConfig.getTopographicalSearchIndex(),
140         SEARCH_STRING, parameters);
141
142     try {
143       final String fullUrlStr = ServletUtils.getFullUrl(elasticConfig, requestString);
144       OperationResult opResult = search.doGet(fullUrlStr, "application/json");
145
146       JSONObject finalOutputJson = formatOutput(opResult.getResult());
147
148       Response response =
149           exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);
150       response.setStatus(Status.SUCCESS_OK);
151       response.setEntity(String.valueOf(finalOutputJson), MediaType.APPLICATION_JSON);
152       exchange.getOut().setBody(response);
153
154     } catch (Exception exc) {
155       LOG.error(AaiUiMsgs.ERROR_GENERIC, "Error processing Geo Visualization request");
156     }
157
158     return operationResult;
159   }
160
161   /**
162    * Format output.
163    *
164    * @param results the results
165    * @return the JSON object
166    */
167   private JSONObject formatOutput(String results) {
168     JsonNode resultNode = null;
169     JSONObject finalResult = new JSONObject();
170     JSONArray entitiesArr = new JSONArray();
171
172     try {
173       resultNode = mapper.readTree(results);
174
175       final JsonNode hitsNode = resultNode.get("hits").get("hits");
176       if (hitsNode.isArray()) {
177
178         for (final JsonNode arrayNode : hitsNode) {
179           JsonNode sourceNode = arrayNode.get("_source");
180           if (sourceNode.get("location") != null) {
181             JsonNode locationNode = sourceNode.get("location");
182             if (NodeUtils.isNumeric(locationNode.get("lon").asText())
183                 && NodeUtils.isNumeric(locationNode.get("lat").asText())) {
184               JSONObject location = new JSONObject();
185               location.put("longitude", locationNode.get("lon").asText());
186               location.put("latitude", locationNode.get("lat").asText());
187
188               entitiesArr.put(location);
189             }
190
191           }
192         }
193       }
194       finalResult.put("plotPoints", entitiesArr);
195
196     } catch (IOException exc) {
197       LOG.warn(AaiUiMsgs.ERROR_BUILDING_SEARCH_RESPONSE, exc.getLocalizedMessage());
198     }
199
200     return finalResult;
201   }
202 }