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