Renaming openecomp to onap
[aai/sparky-be.git] / src / main / java / org / onap / aai / sparky / viewandinspect / servlet / VisualizationServlet.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.viewandinspect.servlet;
24
25 import java.io.IOException;
26 import java.io.PrintWriter;
27
28 import javax.servlet.FilterConfig;
29 import javax.servlet.ServletException;
30 import javax.servlet.http.HttpServlet;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.servlet.http.HttpServletResponse;
33
34 import org.apache.commons.io.IOUtils;
35 import org.onap.aai.sparky.config.oxm.OxmModelLoader;
36 import org.onap.aai.sparky.dal.rest.OperationResult;
37 import org.onap.aai.sparky.dal.servlet.ResettableStreamHttpServletRequest;
38 import org.onap.aai.sparky.logging.AaiUiMsgs;
39 import org.onap.aai.sparky.util.NodeUtils;
40 import org.onap.aai.sparky.viewandinspect.entity.QueryRequest;
41 import org.onap.aai.sparky.viewandinspect.services.VisualizationService;
42 import org.onap.aai.cl.api.Logger;
43 import org.onap.aai.cl.eelf.LoggerFactory;
44 import org.onap.aai.cl.mdc.MdcContext;
45
46 /**
47  * A dedicated servlet for handling Front-End Visualization Requests and performing feats of magic
48  * to execute the right model/type/config driven queries to build the D3 visualization output JSON
49  * back to the FE.
50  * 
51  * @author DAVEA
52  *
53  */
54 public class VisualizationServlet extends HttpServlet {
55
56   /**
57    * 
58    */
59   private static final long serialVersionUID = 4678831934652478571L;
60   private static final Logger LOG =
61       LoggerFactory.getInstance().getLogger(VisualizationServlet.class);
62   private static final String VISUALIZATION_API_ENDPOINT = "prepareVisualization"; 
63   private final VisualizationService visualizationService;
64   /**
65    * Instantiates a new visualization servlet.
66    *
67    * @throws Exception the exception
68    */
69   public VisualizationServlet() throws Exception {
70     this.visualizationService = new VisualizationService(OxmModelLoader.getInstance());
71   }
72
73   /**
74    * Inits the.
75    *
76    * @param filterConfig the filter config
77    * @throws ServletException the servlet exception
78    */
79   public void init(FilterConfig filterConfig) throws ServletException {
80     LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "init()");
81   }
82
83   /**
84    * Gets the request body.
85    *
86    * @param request the request
87    * @return the request body
88    */
89   private String getRequestBody(HttpServletRequest request) {
90
91     ResettableStreamHttpServletRequest requestWrapper =
92         new ResettableStreamHttpServletRequest(request);
93
94     String body = null;
95     try {
96       body = IOUtils.toString(requestWrapper.getRequestBody());
97     } catch (IOException exc) {
98       LOG.error(AaiUiMsgs.EXCEPTION_CAUGHT, "Trying to get body from request",
99           exc.getLocalizedMessage());
100     }
101
102     return body;
103   }
104
105   /*
106    * (non-Javadoc)
107    * 
108    * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
109    * javax.servlet.http.HttpServletResponse)
110    */
111   @Override
112   protected void doGet(HttpServletRequest request, HttpServletResponse response)
113       throws ServletException, IOException {
114     doPost(request, response);
115   }
116
117   /*
118    * (non-Javadoc)
119    * 
120    * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
121    * javax.servlet.http.HttpServletResponse)
122    */
123   @Override
124   protected void doPost(HttpServletRequest request, HttpServletResponse response)
125       throws ServletException, IOException {
126     String txnID = request.getHeader("X-TransactionId");
127     if (txnID == null) {
128       txnID = NodeUtils.getRandomTxnId();
129     }
130
131     String partnerName = request.getHeader("X-FromAppId");
132     if (partnerName == null) {
133       partnerName = "Browser";
134     }
135
136     MdcContext.initialize(txnID, "AAI-UI", "", partnerName, request.getRemoteAddr());
137
138     String postRequestBody = getRequestBody(request);
139
140     String requestUri = request.getRequestURI();
141     OperationResult operationResult = null;
142
143     /*
144      * For now we only have a single API call but there could be more in the future
145      */
146     if (requestUri.endsWith(VISUALIZATION_API_ENDPOINT)) {
147
148       /*
149        * Work our magic and determine the best way to interrogate AAI to get the stuff we are
150        * interested in. Perhaps it should be an edge-tag-query or perhaps it is a straight up
151        * derived self-link query.
152        */
153
154       /*
155        * Map request body to an interpreted API PoJo object
156        */
157       QueryRequest queryRequest = visualizationService.analyzeQueryRequestBody(postRequestBody);
158
159       if (queryRequest != null) {
160         operationResult = visualizationService.buildVisualizationUsingGenericQuery(queryRequest);
161       } else {
162         LOG.error(AaiUiMsgs.FAILED_TO_ANALYZE,
163             String.format("Failed to analyze post request query body = '%s'", postRequestBody));
164
165         operationResult = new OperationResult();
166         operationResult.setResult(500,
167             String.format("Failed to analyze post request query body = '%s'", postRequestBody));
168
169       }
170
171     } else {
172       // unhandled type
173       LOG.error(AaiUiMsgs.UNKNOWN_SERVER_ERROR, "Unhandled requestUri - " + requestUri);
174       operationResult = new OperationResult();
175       operationResult.setResult(500, "Unknown Server Error: Unhandled requestUri = " + requestUri);
176     }
177
178     PrintWriter out = response.getWriter();
179     response.addHeader("Content-Type", "application/xml");
180
181     response.setStatus(operationResult.getResultCode());
182
183     if (operationResult.getResultCode() == 200) {
184       response.setContentLength(operationResult.getResult().length());
185       out.print(operationResult.getResult());
186       out.print("\n");
187     } else {
188       response.setContentLength(operationResult.getResult().length());
189       out.print(operationResult.getResult());
190       out.print("\n");
191     }
192   }
193   
194   @Override
195   public void destroy() {
196       super.destroy();
197       visualizationService.shutdown();
198   }
199 }