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