Initial commit for AAI-UI(sparky-backend)
[aai/sparky-be.git] / src / main / java / org / openecomp / sparky / inventory / servlet / GeoVisualizationServlet.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
26 package org.openecomp.sparky.inventory.servlet;
27
28 import org.openecomp.cl.mdc.MdcContext;
29 import com.fasterxml.jackson.core.JsonProcessingException;
30 import com.fasterxml.jackson.databind.JsonNode;
31 import com.fasterxml.jackson.databind.ObjectMapper;
32
33 import java.io.IOException;
34 import java.io.PrintWriter;
35 import java.nio.ByteBuffer;
36 import java.security.SecureRandom;
37
38 import javax.servlet.ServletException;
39 import javax.servlet.http.HttpServlet;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.servlet.http.HttpServletResponse;
42
43 import org.openecomp.cl.api.Logger;
44 import org.openecomp.cl.eelf.LoggerFactory;
45 import org.openecomp.sparky.logging.AaiUiMsgs;
46 import org.json.JSONArray;
47 import org.json.JSONObject;
48 import org.openecomp.sparky.dal.elasticsearch.SearchAdapter;
49 import org.openecomp.sparky.dal.elasticsearch.config.ElasticSearchConfig;
50 import org.openecomp.sparky.dal.rest.OperationResult;
51 import org.openecomp.sparky.dal.rest.RestClientBuilder;
52 import org.openecomp.sparky.util.NodeUtils;
53 import org.openecomp.sparky.util.ServletUtils;
54
55 /**
56  * The Class GeoVisualizationServlet.
57  */
58 public class GeoVisualizationServlet extends HttpServlet {
59
60   private static final Logger LOG =
61       LoggerFactory.getInstance().getLogger(GeoVisualizationServlet.class);
62
63   private static final long serialVersionUID = 1L;
64
65   private SearchAdapter search = null;
66   private ElasticSearchConfig elasticConfig = null;
67   private ObjectMapper mapper;
68
69   private static final String SEARCH_STRING = "_search";
70
71   private static final String SEARCH_PARAMETER =
72       "?filter_path=hits.hits._source&_source=location&size=5000&q=entityType:";
73
74   /**
75    * Instantiates a new geo visualization servlet.
76    *
77    * @throws ServletException the servlet exception
78    */
79   public GeoVisualizationServlet() throws ServletException {
80     init();
81   }
82
83   /* (non-Javadoc)
84    * @see javax.servlet.GenericServlet#init()
85    */
86   @Override
87   public void init() throws ServletException {
88     super.init();
89     try {
90       if (elasticConfig == null) {
91         elasticConfig = ElasticSearchConfig.getConfig();
92       }
93       if (search == null) {
94         search = new SearchAdapter();
95       }
96       this.mapper = new ObjectMapper();
97     } catch (Exception exc) {
98       new ServletException(
99           "Caught an exception while getting an instance of servlet configuration.", exc);
100     }
101   }
102
103   public void setSearch(SearchAdapter search) {
104     this.search = search;
105   }
106
107   public void setElasticConfig(ElasticSearchConfig elasticConfig) {
108     this.elasticConfig = elasticConfig;
109   }
110
111   /* (non-Javadoc)
112    * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
113    */
114   @Override
115   protected void doGet(HttpServletRequest request, HttpServletResponse response)
116       throws ServletException, IOException {
117           String txnID = request.getHeader("X-TransactionId");
118             if (txnID == null){
119               txnID = NodeUtils.getRandomTxnId();
120             }
121               
122           String partnerName = request.getHeader("X-FromAppId");
123           if ( partnerName == null)
124             partnerName = "Browser";
125                   
126           MdcContext.initialize(txnID, "AAI-UI", "", partnerName,
127                         request.getRemoteAddr());
128             
129     OperationResult operationResult = null;
130     try {
131       operationResult = getGeoVisualizationResults(response, request.getParameter("entity"));
132     } catch (Exception exc) {
133       LOG.error(AaiUiMsgs.ERROR_PROCESSING_REQUEST, exc);
134     }
135   }
136
137   /* (non-Javadoc)
138    * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
139    */
140   @Override
141   protected void doPost(HttpServletRequest request, HttpServletResponse response)
142       throws ServletException {
143
144   }
145
146   /**
147    * Gets the geo visualization results.
148    *
149    * @param response the response
150    * @param entityType the entity type
151    * @return the geo visualization results
152    * @throws Exception the exception
153    */
154   protected OperationResult getGeoVisualizationResults(HttpServletResponse response,
155       String entityType) throws Exception {
156     OperationResult operationResult = new OperationResult();
157
158     String parameters = SEARCH_PARAMETER + entityType;
159     String requestString = String.format("/%s/%s/%s", elasticConfig.getTopographicalSearchIndex(),
160         SEARCH_STRING, parameters);
161
162     try {
163       final String fullUrlStr = ServletUtils.getFullUrl(elasticConfig, requestString);
164       OperationResult opResult = ServletUtils.executeGetQuery(LOG, search, response, fullUrlStr);
165
166       JSONObject finalOutputJson = formatOutput(opResult.getResult());
167
168       if (finalOutputJson != null) {
169         response.setContentType("application/json");
170         PrintWriter out = response.getWriter();
171         out.println(finalOutputJson);
172         out.close();
173       }
174
175     } catch (JsonProcessingException exc) {
176       ServletUtils.handleSearchServletErrors(LOG, "Unable to map JSONpayload", exc, response);
177     }
178
179     return operationResult;
180   }
181
182   /**
183    * Format output.
184    *
185    * @param results the results
186    * @return the JSON object
187    */
188   private JSONObject formatOutput(String results) {
189     JsonNode resultNode = null;
190     JSONObject finalResult = new JSONObject();
191     JSONArray entitiesArr = new JSONArray();
192
193     try {
194       resultNode = mapper.readTree(results);
195
196       final JsonNode hitsNode = resultNode.get("hits").get("hits");
197       if (hitsNode.isArray()) {
198
199         for (final JsonNode arrayNode : hitsNode) {
200           JsonNode sourceNode = arrayNode.get("_source");
201           if (sourceNode.get("location") != null) {
202             JsonNode locationNode = sourceNode.get("location");
203             if (NodeUtils.isNumeric(locationNode.get("lon").asText())
204                 && NodeUtils.isNumeric(locationNode.get("lat").asText())) {
205               JSONObject location = new JSONObject();
206               location.put("longitude", locationNode.get("lon").asText());
207               location.put("latitude", locationNode.get("lat").asText());
208
209               entitiesArr.put(location);
210             }
211
212           }
213         }
214       }
215       finalResult.put("plotPoints", entitiesArr);
216
217     } catch (IOException exc) {
218       LOG.warn(AaiUiMsgs.ERROR_BUILDING_SEARCH_RESPONSE, exc.getLocalizedMessage());
219     }
220
221     return finalResult;
222   }
223 }