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