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