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