8165801cdd9293863a67c7733e519882e17fccd4
[portal/sdk.git] /
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal SDK
4  * ===================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software 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  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 package org.onap.portalsdk.analytics.system.fusion.web;
39
40 import java.io.IOException;
41 import java.io.OutputStreamWriter;
42 import java.io.PrintWriter;
43 import java.io.StringWriter;
44 import java.io.Writer;
45 import java.lang.reflect.InvocationTargetException;
46 import java.lang.reflect.Method;
47 import java.util.ArrayList;
48 import java.util.Enumeration;
49 import java.util.HashMap;
50 import java.util.HashSet;
51 import java.util.Iterator;
52 import java.util.List;
53 import java.util.Map;
54 import java.util.Vector;
55
56 import javax.servlet.ServletContext;
57 import javax.servlet.http.HttpServletRequest;
58 import javax.servlet.http.HttpServletResponse;
59 import javax.servlet.http.HttpSession;
60
61 import org.onap.portalsdk.analytics.controller.Action;
62 import org.onap.portalsdk.analytics.controller.ErrorHandler;
63 import org.onap.portalsdk.analytics.controller.WizardSequence;
64 import org.onap.portalsdk.analytics.error.RaptorException;
65 import org.onap.portalsdk.analytics.error.RaptorRuntimeException;
66 import org.onap.portalsdk.analytics.error.ReportSQLException;
67 import org.onap.portalsdk.analytics.model.DataCache;
68 import org.onap.portalsdk.analytics.model.ReportHandler;
69 import org.onap.portalsdk.analytics.model.base.IdNameValue;
70 import org.onap.portalsdk.analytics.model.base.ReportUserRole;
71 import org.onap.portalsdk.analytics.model.definition.ReportDefinition;
72 import org.onap.portalsdk.analytics.model.definition.SecurityEntry;
73 import org.onap.portalsdk.analytics.model.definition.wizard.ColumnEditJSON;
74 import org.onap.portalsdk.analytics.model.definition.wizard.ColumnJSON;
75 import org.onap.portalsdk.analytics.model.definition.wizard.DefinitionJSON;
76 import org.onap.portalsdk.analytics.model.definition.wizard.FormEditJSON;
77 import org.onap.portalsdk.analytics.model.definition.wizard.IdNameBooleanJSON;
78 import org.onap.portalsdk.analytics.model.definition.wizard.ImportJSON;
79 import org.onap.portalsdk.analytics.model.definition.wizard.MessageJSON;
80 import org.onap.portalsdk.analytics.model.definition.wizard.NameBooleanJSON;
81 import org.onap.portalsdk.analytics.model.definition.wizard.QueryJSON;
82 import org.onap.portalsdk.analytics.model.definition.wizard.QueryResultJSON;
83 import org.onap.portalsdk.analytics.model.definition.wizard.RaptorResponse;
84 import org.onap.portalsdk.analytics.model.definition.wizard.SearchFieldJSON;
85 import org.onap.portalsdk.analytics.model.pdf.PdfReportHandler;
86 import org.onap.portalsdk.analytics.model.runtime.CategoryAxisJSON;
87 import org.onap.portalsdk.analytics.model.runtime.ChartJSON;
88 import org.onap.portalsdk.analytics.model.runtime.ErrorJSONRuntime;
89 import org.onap.portalsdk.analytics.model.runtime.FormField;
90 import org.onap.portalsdk.analytics.model.runtime.RangeAxisJSON;
91 import org.onap.portalsdk.analytics.model.runtime.ReportFormFields;
92 import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
93 import org.onap.portalsdk.analytics.system.AppUtils;
94 import org.onap.portalsdk.analytics.system.ConnectionUtils;
95 import org.onap.portalsdk.analytics.system.Globals;
96 import org.onap.portalsdk.analytics.util.AppConstants;
97 import org.onap.portalsdk.analytics.util.DataSet;
98 import org.onap.portalsdk.analytics.util.Utils;
99 import org.onap.portalsdk.analytics.util.XSSFilter;
100 import org.onap.portalsdk.analytics.view.ReportData;
101 import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
102 import org.onap.portalsdk.analytics.xmlobj.FormFieldType;
103 import org.onap.portalsdk.analytics.xmlobj.ObjectFactory;
104 import org.onap.portalsdk.analytics.xmlobj.PredefinedValueList;
105 import org.onap.portalsdk.core.controller.RestrictedBaseController;
106 import org.onap.portalsdk.core.domain.User;
107 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
108 import org.onap.portalsdk.core.web.support.UserUtils;
109 import org.springframework.stereotype.Controller;
110 import org.springframework.web.bind.annotation.PathVariable;
111 import org.springframework.web.bind.annotation.RequestBody;
112 import org.springframework.web.bind.annotation.RequestMapping;
113 import org.springframework.web.bind.annotation.RequestMethod;
114 import org.springframework.web.bind.annotation.ResponseBody;
115
116 import com.fasterxml.jackson.databind.DeserializationFeature;
117 import com.fasterxml.jackson.databind.ObjectMapper;
118 import com.fasterxml.jackson.databind.SerializationFeature;
119
120 @Controller
121 @RequestMapping("/")
122 public class RaptorControllerAsync extends RestrictedBaseController {
123
124         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RaptorControllerAsync.class);
125
126         private String viewName;
127
128         @RequestMapping(value = { "/raptor.htm" }, method = RequestMethod.GET)
129         public void RaptorSearch(HttpServletRequest request, HttpServletResponse response)
130                         throws IOException, RaptorException {
131
132                 viewName = "";
133                 String actionKey = nvl(request.getParameter(AppConstants.RI_ACTION), request.getParameter("action"));
134                 actionKey = nvl(actionKey, "report.run");
135
136                 HttpSession session = request.getSession();
137                 User user = UserUtils.getUserSession(request);
138
139                 if (actionKey.equals("report.download.excel2007.session") || actionKey.equals("report.download.csv.session")
140                                 || actionKey.equals("report.download.excel.session")
141                                 || actionKey.equals("report.download.pdf.session")) {
142                         if (session != null && user != null) {
143                                 ServletContext servletContext = request.getSession().getServletContext();
144                                 if (!Globals.isSystemInitialized()) {
145                                         Globals.initializeSystem(servletContext);
146                                 }
147                                 ReportRuntime rr = null;
148                                 ReportData rd = null;
149                                 String parent = "";
150                                 int parentFlag = 0;
151                                 if (!nvl(request.getParameter("parent"), "").equals("N"))
152                                         parent = nvl(request.getParameter("parent"), "");
153                                 if (parent.startsWith("parent_"))
154                                         parentFlag = 1;
155                                 if (parentFlag == 1) {
156                                         rr = (ReportRuntime) request.getSession().getAttribute(parent + "_rr");
157                                         rd = (ReportData) request.getSession().getAttribute(parent + "_rd");
158                                 }
159
160                                 boolean isEmbedded = false;
161                                 Object temp = request.getSession().getAttribute("isEmbedded");
162                                 if (temp != null) {
163                                         isEmbedded = (boolean) temp;
164                                 }
165                                 if (isEmbedded) {
166                                         String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
167                                         if (rr == null)
168                                                 rr = (ReportRuntime) ((HashMap) request.getSession()
169                                                                 .getAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP)).get(reportID);
170                                         if (rd == null)
171                                                 rd = (ReportData) ((HashMap) request.getSession()
172                                                                 .getAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP)).get(reportID);
173                                 } else {
174                                         if (rr == null)
175                                                 rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
176                                         if (rd == null)
177                                                 rd = (ReportData) request.getSession().getAttribute(AppConstants.RI_REPORT_DATA);
178                                 }
179                                 String user_id = AppUtils.getUserID(request);
180                                 int downloadLimit = 0;
181                                 if (rr != null)
182                                         downloadLimit = (rr.getMaxRowsInExcelDownload() > 0) ? rr.getMaxRowsInExcelDownload()
183                                                         : Globals.getDownloadLimit();
184                                 if (actionKey.equals("report.csv.download"))
185                                         downloadLimit = Globals.getCSVDownloadLimit();
186                                 String sql_whole = rr.getReportDataSQL(user_id, downloadLimit, request);
187                                 request.setAttribute(AppConstants.RI_REPORT_SQL_WHOLE, sql_whole);
188                                 try {
189                                         OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream());
190
191                                         if (actionKey.equals("report.download.pdf.session")) {
192                                                 new PdfReportHandler().createPdfFileContent(request, response, 3);
193                                         } else if (actionKey.equals("report.download.csv.session")) {
194                                                 (new ReportHandler()).createCSVFileContent(out, rd, rr, request, response);
195                                         } else if (actionKey.equals("report.download.excel.session")) {
196                                                 new ReportHandler().createExcelFileContent(out, rd, rr, request, response, user_id, 3); // 3
197                                                                                                                                                                                                                                 // whole
198                                         } else {
199
200                                                 new ReportHandler().createExcel2007FileContent(out, rd, rr, request, response, user_id, 3); // 3
201                                                                                                                                                                                                                                         // whole
202                                         }
203                                 } catch (Exception e) {
204                                         logger.error(EELFLoggerDelegate.errorLogger,
205                                                         "[Controller.processRequest]Invalid raptor action [" + actionKey + "].", e);
206                                 }
207                         } else {
208                                 response.sendRedirect("login.htm");
209                         }
210                 } else {
211                         if (session != null && user != null) {
212                                 Action action = null;
213                                 ServletContext servletContext = request.getSession().getServletContext();
214                                 if (!Globals.isSystemInitialized()) {
215                                         Globals.initializeSystem(servletContext);
216                                 }
217                                 try {
218                                         action = Globals.getRaptorActionMapping().getAction(actionKey);
219                                         if (action == null)
220                                                 throw new RaptorRuntimeException("Action not found");
221                                 } catch (RaptorException e) {
222                                         logger.error(EELFLoggerDelegate.errorLogger,
223                                                         "[Controller.processRequest]Invalid raptor action [" + actionKey + "].", e);
224
225                                         viewName = (new ErrorHandler()).processFatalErrorJSON(request,
226                                                         new RaptorRuntimeException("[Controller.processRequest]Invalid raptor action [" + actionKey
227                                                                         + "]. Exception: " + e.getMessage()));
228                                 }
229
230                                 try {
231                                         Class[] paramTypes = new Class[2];
232                                         paramTypes[0] = Class.forName("javax.servlet.http.HttpServletRequest");
233                                         paramTypes[1] = Class.forName("java.lang.String");
234
235                                         Class handlerClass = Class.forName(action.getControllerClass());
236                                         Object handler = handlerClass.newInstance();
237                                         Method handlerMethod = handlerClass.getMethod(action.getControllerMethod(), paramTypes);
238
239                                         Object[] paramValues = new Object[2];
240                                         paramValues[0] = request;
241                                         paramValues[1] = action.getJspName();
242                                         ;
243
244                                         viewName = (String) handlerMethod.invoke(handler, paramValues);
245                                         if (!actionKey.equals("chart.run"))
246                                                 response.setContentType("application/json");
247                                         else
248                                                 response.setContentType("text/html");
249
250                                 } catch (ClassNotFoundException e) {
251                                         logger.debug(EELFLoggerDelegate.debugLogger, ("[Controller.processRequest]Invalid raptor action ["
252                                                         + actionKey + "]. ClassNotFoundException: " + e.getMessage()));
253                                         viewName = (new ErrorHandler()).processFatalErrorJSON(request,
254                                                         new RaptorRuntimeException(
255                                                                         "[Controller.processRequest] Unable to instantiate and invoke action handler. Exception: "
256                                                                                         + e.getMessage()));
257                                 } catch (IllegalAccessException e) {
258                                         logger.debug(EELFLoggerDelegate.debugLogger, ("[Controller.processRequest]Invalid raptor action ["
259                                                         + actionKey + "]. IllegalAccessException: " + e.getMessage()));
260                                         viewName = (new ErrorHandler()).processFatalErrorJSON(request,
261                                                         new RaptorRuntimeException(
262                                                                         "[Controller.processRequest] Unable to instantiate and invoke action handler. Exception: "
263                                                                                         + e.getMessage()));
264                                 } catch (InstantiationException e) {
265                                         logger.debug(EELFLoggerDelegate.debugLogger, ("[Controller.processRequest]Invalid raptor action ["
266                                                         + actionKey + "]. InstantiationException: " + e.getMessage()));
267                                         viewName = (new ErrorHandler()).processFatalErrorJSON(request,
268                                                         new RaptorRuntimeException(
269                                                                         "[Controller.processRequest] Unable to instantiate and invoke action handler. Exception: "
270                                                                                         + e.getMessage()));
271                                 } catch (NoSuchMethodException e) {
272                                         logger.debug(EELFLoggerDelegate.debugLogger, ("[Controller.processRequest]Invalid raptor action ["
273                                                         + actionKey + "]. NoSuchMethodException: " + e.getMessage()));
274                                         viewName = (new ErrorHandler()).processFatalErrorJSON(request,
275                                                         new RaptorRuntimeException(
276                                                                         "[Controller.processRequest] Unable to instantiate and invoke action handler. Exception: "
277                                                                                         + e.getMessage()));
278                                 } catch (InvocationTargetException e) {
279                                         logger.debug(EELFLoggerDelegate.debugLogger, ("[Controller.processRequest]Invalid raptor action ["
280                                                         + actionKey + "]. InvocationTargetException: " + e.getMessage()));
281                                         viewName = (new ErrorHandler()).processFatalErrorJSON(request,
282                                                         new RaptorRuntimeException(
283                                                                         "[Controller.processRequest] Unable to instantiate and invoke action handler. Exception: "
284                                                                                         + e.getMessage()));
285                                 } finally {
286                                         PrintWriter out = response.getWriter();
287                                         out.write(viewName);
288                                 }
289                         } else {
290                                 PrintWriter out = response.getWriter();
291                                 out.write("session has timed out for user");
292                         }
293
294                 }
295         }
296
297         @RequestMapping(value = "/report/wizard/list_columns", method = RequestMethod.GET, produces = "application/json")
298         public @ResponseBody ArrayList<ColumnJSON> listColumns(HttpServletRequest request, HttpServletResponse response)
299                         throws IOException, RaptorException {
300                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
301                 List<DataColumnType> reportColumnList = rdef.getAllColumns();
302                 ArrayList<ColumnJSON> listJSON = new ArrayList<ColumnJSON>();
303                 ColumnJSON columnJSON = new ColumnJSON();
304
305                 for (DataColumnType reportColumnType : reportColumnList) {
306                         columnJSON = new ColumnJSON();
307                         columnJSON.setId(reportColumnType.getColId());
308                         columnJSON.setName(reportColumnType.getColName());
309                         listJSON.add(columnJSON);
310                 }
311                 return listJSON;
312         }
313
314         @RequestMapping(value = "/report/wizard/list_drilldown_reports", method = RequestMethod.GET, produces = "application/json")
315         public @ResponseBody ArrayList<ColumnJSON> list_drilldown_reports(HttpServletRequest request,
316                         HttpServletResponse response) throws IOException, RaptorException {
317                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
318                 Vector<IdNameValue> publicReportIdNames = DataCache.getPublicReportIdNames();
319                 Vector groupReportIdNames = DataCache.getGroupAccessibleReportIdNames(AppUtils.getUserID(request),
320                                 AppUtils.getUserRoles(request));
321                 Vector privateReportIdNames = DataCache.getPrivateAccessibleReportIdNames(AppUtils.getUserID(request),
322                                 AppUtils.getUserRoles(request));
323
324                 ArrayList<ColumnJSON> listJSON = new ArrayList<ColumnJSON>();
325                 ColumnJSON columnJSON = new ColumnJSON();
326
327                 ServletContext servletContext = request.getSession().getServletContext();
328                 if (!Globals.isSystemInitialized()) {
329                         Globals.initializeSystem(servletContext);
330                 }
331
332                 for (int i = 0; i < publicReportIdNames.size(); i++) {
333                         IdNameValue reportIdName = (IdNameValue) publicReportIdNames.get(i);
334                         columnJSON = new ColumnJSON();
335                         columnJSON.setId(reportIdName.getId());
336                         columnJSON.setName("Public Report: " + reportIdName.getName());
337                         if (!rdef.getReportID().equals(reportIdName.getId()))
338                                 listJSON.add(columnJSON);
339                 }
340
341                 for (int i = 0; i < groupReportIdNames.size(); i++) {
342                         IdNameValue reportIdName = (IdNameValue) groupReportIdNames.get(i);
343                         columnJSON = new ColumnJSON();
344                         columnJSON.setId(reportIdName.getId());
345                         columnJSON.setName("Group Report: " + reportIdName.getName());
346                         if (!rdef.getReportID().equals(reportIdName.getId()))
347                                 listJSON.add(columnJSON);
348                 }
349
350                 for (int i = 0; i < privateReportIdNames.size(); i++) {
351                         IdNameValue reportIdName = (IdNameValue) privateReportIdNames.get(i);
352                         columnJSON = new ColumnJSON();
353                         columnJSON.setId(reportIdName.getId());
354                         columnJSON.setName("Private Report: " + reportIdName.getName());
355                         if (!rdef.getReportID().equals(reportIdName.getId()))
356                                 listJSON.add(columnJSON);
357                 }
358
359                 return listJSON;
360         }
361
362         @RequestMapping(value = "/report/wizard/list_formfields", method = RequestMethod.GET, produces = "application/json")
363         public @ResponseBody ArrayList<SearchFieldJSON> listFormFields(HttpServletRequest request,
364                         HttpServletResponse response) throws IOException, RaptorException {
365                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
366                 ArrayList<SearchFieldJSON> listJSON = new ArrayList<SearchFieldJSON>();
367                 SearchFieldJSON fieldJSON = new SearchFieldJSON();
368                 if (rdef.getFormFieldList() != null) {
369                         for (Iterator iter = rdef.getFormFieldList().getFormField().iterator(); iter.hasNext();) {
370                                 fieldJSON = new SearchFieldJSON();
371                                 FormFieldType fft = (FormFieldType) iter.next();
372                                 String fieldId = fft.getFieldId();
373                                 String fieldDisplay = fft.getFieldName();
374                                 fieldJSON.setId(fieldId);
375                                 fieldJSON.setName(fieldDisplay);
376                                 listJSON.add(fieldJSON);
377                         }
378                 }
379
380                 return listJSON;
381         }
382
383         @RequestMapping(value = "/report/wizard/list_child_report_col/{reportID}", method = RequestMethod.GET, produces = "application/json")
384         public @ResponseBody ArrayList<ColumnJSON> listChildReportCols(@PathVariable("reportID") String reportID,
385                         HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
386                 ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, reportID, false);
387
388                 List<DataColumnType> reportColumnList = ddRr.getAllColumns();
389                 ArrayList<ColumnJSON> listJSON = new ArrayList<ColumnJSON>();
390                 ColumnJSON columnJSON = new ColumnJSON();
391
392                 for (DataColumnType reportColumnType : reportColumnList) {
393                         columnJSON = new ColumnJSON();
394                         columnJSON.setId(reportColumnType.getColId());
395                         columnJSON.setName(reportColumnType.getColName());
396                         listJSON.add(columnJSON);
397                 }
398                 return listJSON;
399         }
400
401         @RequestMapping(value = "/report/wizard/list_child_report_ff/{reportID}", method = RequestMethod.GET, produces = "application/json")
402         public @ResponseBody ArrayList<SearchFieldJSON> listChildReportFormFields(@PathVariable("reportID") String reportID,
403                         HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
404                 ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, reportID, false);
405                 ArrayList<SearchFieldJSON> listJSON = new ArrayList<SearchFieldJSON>();
406                 SearchFieldJSON fieldJSON = new SearchFieldJSON();
407
408                 ReportFormFields ddReportFormFields = ddRr.getReportFormFields();
409                 if (ddReportFormFields != null) {
410                         for (ddReportFormFields.resetNext(); ddReportFormFields.hasNext();) {
411                                 FormField ff = ddReportFormFields.getNext();
412                                 if (!ff.getFieldType().equals(FormField.FFT_BLANK)) {
413                                         fieldJSON = new SearchFieldJSON();
414                                         fieldJSON.setId(ff.getFieldName());
415                                         fieldJSON.setName(ff.getFieldDisplayName());
416                                         listJSON.add(fieldJSON);
417                                 }
418                         }
419                 }
420                 return listJSON;
421         }
422
423         @RequestMapping(value = "report/wizard/copy_report/{reportID}", method = RequestMethod.GET, produces = "application/json")
424         public @ResponseBody MessageJSON copyReport(@PathVariable("reportID") String reportID, HttpServletRequest request,
425                         HttpServletResponse response) throws IOException, RaptorException {
426                 MessageJSON messageJSON = new MessageJSON();
427                 try {
428
429                         ReportHandler rh = new ReportHandler();
430                         ReportDefinition rdef = rh.loadReportDefinition(request, reportID);
431                         rdef.setAsCopy(request);
432                         request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
433                         messageJSON.setMessage("Success- Report Copied.");
434                         messageJSON.setAnyStacktrace(rdef.getReportID() + " is Modified and added to session and DB.");
435
436                 } catch (RaptorException e) {
437                         request.setAttribute("error_extra_msg", "While copying report " + reportID);
438                         messageJSON.setMessage("Failed - While copying report " + reportID);
439                         messageJSON.setAnyStacktrace(getStackTrace(e));
440                         logger.debug(EELFLoggerDelegate.debugLogger,
441                                         ("[Controller.processRequest]Invalid raptor action [copyReport]. RaptorException: "
442                                                         + e.getMessage()));
443                         return messageJSON;
444                 }
445
446                 return messageJSON;
447         }
448
449         @RequestMapping(value = "report/wizard/import_report", method = RequestMethod.POST, consumes = "application/json")
450         public @ResponseBody MessageJSON importReport(@RequestBody ImportJSON importJSON, HttpServletRequest request,
451                         HttpServletResponse response) throws IOException, RaptorException {
452                 MessageJSON messageJSON = new MessageJSON();
453                 try {
454                         String reportXML = importJSON.getReportXML();
455
456                         ReportHandler rh = new ReportHandler();
457                         ReportDefinition rdef = rh.createReportDefinition(request, "-1", reportXML);
458                         rdef.updateReportDefType();
459                         rdef.generateWizardSequence(request);
460                         rdef.setReportName("Import: " + rdef.getReportName());
461                         rdef.clearAllDrillDowns();
462
463                         request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
464
465                         messageJSON.setMessage("Success- Report imported.");
466                         messageJSON.setAnyStacktrace(rdef.getReportID() + " is Modified and added to session and DB.");
467
468                 } catch (RaptorException e) {
469                         request.setAttribute("error_extra_msg", "Unable to parse XML. Nested error: ");
470                         messageJSON.setMessage("Unable to parse XML. Nested error: ");
471                         messageJSON.setAnyStacktrace(getStackTrace(e));
472
473                         return messageJSON;
474                 }
475
476                 return messageJSON;
477
478         }
479
480         @RequestMapping(value = "report/wizard/save_formfield_tab_data", method = RequestMethod.POST)
481         public @ResponseBody MessageJSON saveFFTabWiseData(@RequestBody FormEditJSON formEditJSON,
482                         HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
483                 ReportDefinition rdef = null;
484                 rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
485
486                 MessageJSON messageJSON = new MessageJSON();
487                 try {
488                         if (rdef != null) {
489
490                                 String fieldId = formEditJSON.getFieldId();
491
492                                 if (rdef.getFormFieldList() != null) {
493                                         for (FormFieldType fft : rdef.getFormFieldList().getFormField()) {
494                                                 if (fft.getFieldId().equals(fieldId)) {
495                                                         fft.setFieldName(formEditJSON.getFieldName());
496                                                         fft.setFieldType(formEditJSON.getFieldType());
497                                                         fft.setVisible(formEditJSON.isVisible() ? "Y" : "N");
498                                                         fft.setDefaultValue(formEditJSON.getDefaultValue());
499                                                         fft.setFieldDefaultSQL(formEditJSON.getFieldDefaultSQL());
500                                                         fft.setFieldSQL(formEditJSON.getFieldSQL());
501                                                         fft.setValidationType(formEditJSON.getValidationType());
502
503                                                         // clear predefined value
504                                                         if (fft.getPredefinedValueList() != null) {
505                                                                 for (Iterator<String> iter = fft.getPredefinedValueList().getPredefinedValue()
506                                                                                 .iterator(); iter.hasNext();)
507                                                                         iter.remove();
508                                                         }
509
510                                                         List<IdNameBooleanJSON> predefList = formEditJSON.getPredefinedValueList();
511                                                         if (predefList != null && predefList.size() > 0) {
512                                                                 for (IdNameBooleanJSON item : predefList) {
513                                                                         PredefinedValueList predefinedValueList = new ObjectFactory()
514                                                                                         .createPredefinedValueList();
515                                                                         fft.setPredefinedValueList(predefinedValueList);
516                                                                         fft.getPredefinedValueList().getPredefinedValue().add(item.getId());
517                                                                 }
518                                                         }
519
520                                                 }
521                                         }
522                                 }
523
524                                 persistReportDefinition(request, rdef);
525                                 messageJSON.setMessage("Success formfield Details of given report is saved in session.");
526                                 messageJSON.setAnyStacktrace(rdef.getReportID() + " is Modified and added to session and DB.");
527
528                         } else {
529                                 messageJSON.setMessage("Report Definition is not in session");
530                                 messageJSON.setAnyStacktrace("Report Definition is not in session");
531
532                         }
533                 } catch (Exception ex) {
534                         messageJSON.setMessage("Error occured while formfield details Tab");
535                         messageJSON.setAnyStacktrace(getStackTrace(ex));
536                         return messageJSON;
537                 }
538
539                 return messageJSON;
540         }
541
542         @RequestMapping(value = "report/wizard/save_col_tab_data", method = RequestMethod.POST)
543         public @ResponseBody MessageJSON saveColTabWiseData(@RequestBody ColumnEditJSON columnEditJSON,
544                         HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
545                 ReportDefinition rdef = null;
546                 rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
547
548                 MessageJSON messageJSON = new MessageJSON();
549
550                 try {
551                         if (rdef != null) {
552                                 String colId = columnEditJSON.getColId();
553                                 List<DataColumnType> reportColumnList = rdef.getAllColumns();
554
555                                 for (DataColumnType reportColumnType : reportColumnList) {
556                                         // columnJSON = new ColumnJSON();
557                                         if (reportColumnType.getColId().equals(colId)) {
558                                                 reportColumnType.setColName(columnEditJSON.getColName());
559                                                 reportColumnType.setDisplayAlignment(columnEditJSON.getDisplayAlignment());
560                                                 reportColumnType.setDisplayHeaderAlignment(columnEditJSON.getDisplayHeaderAlignment());
561                                                 reportColumnType.setIsSortable(columnEditJSON.isSortable());
562                                                 reportColumnType.setVisible(columnEditJSON.isVisible());
563                                                 reportColumnType.setDrillDownURL(columnEditJSON.getDrilldownURL());
564                                                 reportColumnType.setDrillDownParams(columnEditJSON.getDrilldownParams());
565                                                 reportColumnType.setDrillDownType(columnEditJSON.getDrilldownType());
566
567                                         }
568
569                                 }
570                                 persistReportDefinition(request, rdef);
571                                 messageJSON.setMessage("Success Column Details of given report is saved in session.");
572                                 messageJSON.setAnyStacktrace(rdef.getReportID() + " is Modified and added to session and DB.");
573
574                         } else {
575                                 messageJSON.setMessage("Report Definition is not in session");
576                                 messageJSON.setAnyStacktrace("");
577
578                         }
579                 } catch (Exception ex) {
580                         messageJSON.setMessage("Error occured while saving column details Tab");
581                         messageJSON.setAnyStacktrace(getStackTrace(ex));
582
583                         return messageJSON;
584                 }
585
586                 return messageJSON;
587         }
588
589         @RequestMapping(value = "report/wizard/save_def_tab_data/{id}", method = RequestMethod.POST)
590         public @ResponseBody MessageJSON saveDefTabWiseData(@PathVariable("id") String id,
591                         @RequestBody DefinitionJSON definitionJSON, HttpServletRequest request, HttpServletResponse response)
592                         throws IOException, RaptorException {
593                 ReportDefinition rdef = null;
594                 ReportRuntime rr = null;
595                 boolean newReport = false;
596                 MessageJSON messageJSON = new MessageJSON();
597
598                 try {
599                         if (id.equals("InSession")) {
600                                 rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
601                                 newReport = false;
602
603                         } else if (id.equals("Create")) {
604                                 removeVariablesFromSession(request);
605                                 rdef = (new ReportHandler()).loadReportDefinition(request, "-1");
606                                 newReport = true;
607                                 System.out.println("&&&&&&&&&&&&&&&&&&&&&& CHECK Report Type "
608                                                 + (AppUtils.nvl(rdef.getReportType()).length() <= 0));
609                                 if (AppUtils.nvl(rdef.getReportType()).length() <= 0) {
610                                         rdef.setReportType(AppConstants.RT_LINEAR);
611                                         System.out.println("&&&&&&&&&&&&&&&&&&&&&& ADDED Report Type in session ");
612                                 }
613
614                         } else if (AppUtils.nvl(id).length() > 0) {
615                                 rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
616                                 rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
617
618                                 if (rdef != null && !rdef.getReportID().equals(id)) {
619                                         request.getSession().removeAttribute(AppConstants.SI_REPORT_DEFINITION);
620                                         removeVariablesFromSession(request);
621                                         rdef = (new ReportHandler()).loadReportDefinition(request, id);
622                                 } else if (rr != null && !rr.getReportID().equals(id)) {
623                                         request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);
624                                         removeVariablesFromSession(request);
625                                         rdef = (new ReportHandler()).loadReportDefinition(request, id);
626                                 } else if (rdef == null) {
627                                         rdef = (new ReportHandler()).loadReportDefinition(request, id);
628                                 }
629                                 newReport = false;
630
631                         } else {
632                                 rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
633                                 newReport = true;
634                         }
635                         // }
636
637                         if (rdef != null) {
638                                 String reportName = definitionJSON.getReportName();
639                                 String errorString = "";
640                                 if (AppUtils.nvl(reportName).length() <= 0)
641                                         errorString = "ReportName cannot be null;";
642                                 rdef.setReportName(reportName);
643
644                                 String reportDescr = definitionJSON.getReportDescr();
645                                 rdef.setReportDescr(reportDescr);
646
647                                 String formHelpText = definitionJSON.getFormHelpText();
648                                 rdef.setFormHelpText(formHelpText);
649
650                                 Integer pageSize = definitionJSON.getPageSize();
651                                 rdef.setPageSize(pageSize);
652
653                                 List<IdNameBooleanJSON> menuIds = definitionJSON.getDisplayArea();
654                                 for (IdNameBooleanJSON menuId : menuIds) {
655                                         if (menuId.isSelected()) {
656                                                 rdef.setMenuID(menuId.getName());
657                                         }
658
659                                 }
660
661                                 Boolean hideFormFieldsAfterRun = definitionJSON.getHideFormFieldsAfterRun();
662                                 rdef.setHideFormFieldAfterRun(hideFormFieldsAfterRun);
663                                 Integer maxRowsInExcelCSVDownload = definitionJSON.getMaxRowsInExcelCSVDownload();
664                                 rdef.setMaxRowsInExcelDownload(maxRowsInExcelCSVDownload);
665                                 Integer frozenColumns = definitionJSON.getFrozenColumns();
666                                 rdef.setFrozenColumns(frozenColumns);
667                                 String dataGridAlign = definitionJSON.getDataGridAlign();
668                                 rdef.setDataGridAlign(dataGridAlign);
669                                 String emptyMessage = definitionJSON.getEmptyMessage();
670                                 rdef.setEmptyMessage(emptyMessage);
671                                 String dataContainerHeight = definitionJSON.getDataContainerHeight();
672                                 rdef.setDataContainerHeight(dataContainerHeight);
673                                 String dataContainerWidth = definitionJSON.getDataContainerWidth();
674                                 rdef.setDataContainerWidth(dataContainerWidth);
675                                 boolean runtimeColSortDisabled = definitionJSON.getRuntimeColSortDisabled();
676                                 rdef.setRuntimeColSortDisabled(runtimeColSortDisabled);
677                                 Integer numFormCols = definitionJSON.getNumFormCols();
678                                 rdef.setNumFormCols(Integer.toString(numFormCols));
679                                 String reportTitle = definitionJSON.getReportTitle();
680                                 rdef.setReportTitle(reportTitle);
681                                 String reportSubTitle = definitionJSON.getReportSubTitle();
682                                 rdef.setReportSubTitle(reportSubTitle);
683
684                                 List<NameBooleanJSON> displayOptions = definitionJSON.getDisplayOptions();
685                                 StringBuffer displayOptionStr = new StringBuffer("NNNNNNN");
686                                 for (NameBooleanJSON displayOption : displayOptions) {
687                                         if (displayOption.isSelected()) {
688                                                 if (displayOption.getName().equals("HideFormFields")) {
689                                                         displayOptionStr.setCharAt(0, 'Y');
690                                                 } else if (displayOption.getName().equals("HideChart")) {
691                                                         displayOptionStr.setCharAt(1, 'Y');
692                                                 } else if (displayOption.getName().equals("HideReportData")) {
693                                                         displayOptionStr.setCharAt(2, 'Y');
694                                                 } else if (displayOption.getName().equals("HideExcel")) {
695                                                         displayOptionStr.setCharAt(5, 'Y');
696                                                 } else if (displayOption.getName().equals("HidePdf")) {
697                                                         displayOptionStr.setCharAt(6, 'Y');
698                                                 }
699                                         }
700
701                                 }
702
703                                 rdef.setDisplayOptions(displayOptionStr.toString());
704                         }
705                         if (id.equals("Create")) {
706                                 rdef.persistReport(request);
707                         } else
708                                 persistReportDefinition(request, rdef);
709                         messageJSON.setMessage("Success Definition of given report is saved in session.");
710                         messageJSON.setAnyStacktrace((newReport ? " New Report info is added to Session "
711                                         : rdef.getReportID() + " is Modified and added to session and DB."));
712
713                 } catch (Exception ex) {
714                         messageJSON.setMessage("Error occured while saving definition Tab");
715                         messageJSON.setAnyStacktrace(getStackTrace(ex));
716                         logger.error(EELFLoggerDelegate.errorLogger,
717                                         "[Controller.processRequest]Invalid raptor action [retrieveTabWiseData].", ex);
718                         return messageJSON;
719                 }
720
721                 return messageJSON;
722         }
723
724         @RequestMapping(value = { "/report/wizard/retrieve_form_tab_wise_data/{id}",
725                         "/report/wizard/retrieve_form_tab_wise_data/{id}/{action}" }, method = RequestMethod.GET)
726         public @ResponseBody FormEditJSON retrieveFormTabWiseData(@PathVariable Map<String, String> pathVariables,
727                         HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
728                 ReportDefinition rdef = null;
729                 String id = "";
730                 String action = "";
731                 String detailId = "";
732                 FormEditJSON wizardJSON = new FormEditJSON();
733                 rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
734
735                 if (pathVariables.containsKey("id")) {
736                         id = pathVariables.get("id");
737                 }
738                 if (pathVariables.containsKey("action")) {
739                         action = pathVariables.get("action");
740                 }
741
742                 ServletContext servletContext = request.getSession().getServletContext();
743                 if (!Globals.isSystemInitialized()) {
744                         Globals.initializeSystem(servletContext);
745                 }
746                 wizardJSON.setTabId("FormEdit");
747                 wizardJSON.setTabName("Form Edit");
748                 FormFieldType currField = null;
749                 try {
750                         if (id.equals("add")) {
751
752                                 currField = rdef.addFormFieldType(new ObjectFactory(), "", "", "", "", "", "", "", "", null, null, "",
753                                                 "");
754                                 wizardJSON.setFieldId(currField.getFieldId());
755                                 wizardJSON.setFieldName(currField.getFieldName());
756                                 wizardJSON.setFieldType(currField.getFieldType());
757                                 wizardJSON.setVisible(AppUtils.nvls(currField.getVisible(), "Y").toUpperCase().startsWith("Y"));
758                                 wizardJSON.setDefaultValue(currField.getDefaultValue());
759                                 wizardJSON.setFieldDefaultSQL(currField.getFieldDefaultSQL());
760                                 wizardJSON.setFieldSQL(currField.getFieldSQL());
761                                 wizardJSON.setValidationType(currField.getValidationType());
762                                 persistReportDefinition(request, rdef);
763
764                         } else if (action.equals("delete")) {
765                                 rdef.deleteFormField(id);
766                                 persistReportDefinition(request, rdef);
767                                 wizardJSON.setMessage("Formfield " + detailId + " Deleted");
768                         }
769                         if (rdef.getFormFieldList() != null) {
770                                 for (FormFieldType fft : rdef.getFormFieldList().getFormField()) {
771                                         if (fft.getFieldId().equals(id)) {
772                                                 wizardJSON.setFieldId(fft.getFieldId());
773                                                 wizardJSON.setFieldName(fft.getFieldName());
774                                                 wizardJSON.setFieldType(fft.getFieldType());
775                                                 wizardJSON.setVisible(fft.getVisible().toUpperCase().startsWith("Y"));
776                                                 wizardJSON.setDefaultValue(fft.getDefaultValue());
777                                                 wizardJSON.setFieldDefaultSQL(fft.getFieldDefaultSQL());
778                                                 wizardJSON.setFieldSQL(fft.getFieldSQL());
779                                                 wizardJSON.setValidationType(fft.getValidationType());
780
781                                                 PredefinedValueList preDefined = fft.getPredefinedValueList();
782
783                                                 if (preDefined != null) {
784                                                         List<IdNameBooleanJSON> preDefinedList = new ArrayList<IdNameBooleanJSON>();
785                                                         IdNameBooleanJSON idNameBooleanJSON = new IdNameBooleanJSON();
786
787                                                         for (String v : preDefined.getPredefinedValue()) {
788                                                                 idNameBooleanJSON = new IdNameBooleanJSON();
789                                                                 idNameBooleanJSON.setId(v);
790                                                                 idNameBooleanJSON.setName(v);
791                                                                 preDefinedList.add(idNameBooleanJSON);
792                                                         }
793                                                         wizardJSON.setPredefinedValueList(preDefinedList);
794                                                 }
795                                         }
796                                 }
797                         }
798                 } catch (Exception ex) {
799                         logger.error(EELFLoggerDelegate.errorLogger,
800                                         "[Controller.processRequest]Invalid raptor action [retrieveFormTabWiseData].", ex);
801                         ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
802                         errorJSONRuntime.setErrormessage("Error occured while retreiving formedit definition Tab");
803                         errorJSONRuntime.setStacktrace(getStackTrace(ex));
804                         wizardJSON.setErrorMessage("Error occured while retreiving formedit definition Tab");
805                         wizardJSON.setErrorStackTrace(getStackTrace(ex));
806
807                 }
808
809                 return wizardJSON;
810         }
811
812         @RequestMapping(value = { "/report/wizard/retrieve_col_tab_wise_data/{id}" }, method = RequestMethod.GET)
813         public @ResponseBody ColumnEditJSON retrieveColTabWiseData(@PathVariable Map<String, String> pathVariables,
814                         HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
815                 ReportDefinition rdef = null;
816                 String id = "";
817                 ColumnEditJSON wizardJSON = new ColumnEditJSON();
818                 rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
819
820                 if (pathVariables.containsKey("id")) {
821                         id = pathVariables.get("id");
822                 }
823                 ServletContext servletContext = request.getSession().getServletContext();
824                 if (!Globals.isSystemInitialized()) {
825                         Globals.initializeSystem(servletContext);
826                 }
827                 if (rdef != null) {
828                         wizardJSON.setTabId("ColEdit");
829                         wizardJSON.setTabName("Column Edit");
830
831                         List<DataColumnType> reportColumnList = rdef.getAllColumns();
832
833                         for (DataColumnType reportColumnType : reportColumnList) {
834                                 if (reportColumnType.getColId().equals(id)) {
835                                         wizardJSON.setColId(reportColumnType.getColId());
836                                         wizardJSON.setColName(reportColumnType.getColName());
837                                         wizardJSON.setDisplayAlignment(reportColumnType.getDisplayAlignment());
838                                         wizardJSON.setDisplayHeaderAlignment(reportColumnType.getDisplayHeaderAlignment());
839                                         wizardJSON.setSortable(
840                                                         reportColumnType.isIsSortable() == null ? false : reportColumnType.isIsSortable());
841                                         wizardJSON.setVisible(reportColumnType.isVisible());
842                                         wizardJSON.setDrilldownURL(
843                                                         reportColumnType.getDrillDownURL() == null ? "" : reportColumnType.getDrillDownURL());
844                                         wizardJSON.setDrilldownParams(
845                                                         reportColumnType.getDrillDownParams() == null ? "" : reportColumnType.getDrillDownParams());
846                                         wizardJSON.setDrilldownType(
847                                                         reportColumnType.getDrillDownType() == null ? "" : reportColumnType.getDrillDownType());
848
849                                 }
850                         }
851                 } else {
852                         wizardJSON.setErrorMessage("Report is not in session");
853                 }
854
855                 return wizardJSON;
856         }
857
858         @RequestMapping(value = { "/report/wizard/retrieve_sql_tab_wise_data/{id}",
859                         "/report/wizard/retrieve_sql_tab_wise_data/" }, method = RequestMethod.GET)
860         public @ResponseBody QueryJSON retrieveSqlTabWiseData(@PathVariable Map<String, String> pathVariables,
861                         HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
862                 ReportDefinition rdef = null;
863                 ReportRuntime rr = null;
864                 String id = "";
865                 String detailId = "";
866                 QueryJSON wizardJSON = new QueryJSON();
867
868                 if (pathVariables.containsKey("id")) {
869                         id = pathVariables.get("id");
870                 }
871                 if (pathVariables.containsKey("detailId")) {
872                         detailId = pathVariables.get("detailId");
873                 }
874                 ServletContext servletContext = request.getSession().getServletContext();
875                 if (!Globals.isSystemInitialized()) {
876                         Globals.initializeSystem(servletContext);
877                 }
878                 if (id.equals("InSession") || AppUtils.nvl(id).length() <= 0) {
879                         rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
880                 } else if (AppUtils.nvl(id).length() > 0) {
881                         rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
882                         rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
883
884                         if (rdef != null && !rdef.getReportID().equals(id)) {
885                                 request.getSession().removeAttribute(AppConstants.SI_REPORT_DEFINITION);
886                                 removeVariablesFromSession(request);
887                                 rdef = (new ReportHandler()).loadReportDefinition(request, id);
888                         } else if (rr != null && !rr.getReportID().equals(id)) {
889                                 request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);
890                                 removeVariablesFromSession(request);
891                                 rdef = (new ReportHandler()).loadReportDefinition(request, id);
892                         } else if (rdef == null) {
893                                 rdef = (new ReportHandler()).loadReportDefinition(request, id);
894                         }
895                 }
896
897                 if (rdef != null) {
898
899                         wizardJSON.setTabId("Sql");
900                         wizardJSON.setTabName("Sql");
901                         wizardJSON.setQuery(rdef.getReportSQL());
902                 }
903                 return wizardJSON;
904         }
905
906         @RequestMapping(value = { "/report/wizard/security/retrieveReportUserList" }, method = RequestMethod.GET)
907         public @ResponseBody List<SecurityEntry> getReportUserList(HttpServletRequest request)
908                         throws IOException, RaptorException {
909                         List<SecurityEntry> reportUserList = new ArrayList<SecurityEntry>();
910                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
911                         Vector reportUsers = rdef.getReportUsers(request);
912                         for(Iterator iter=reportUsers.iterator(); iter.hasNext();) { 
913                                 SecurityEntry rUser = (SecurityEntry) iter.next(); 
914                                 reportUserList.add(rUser);
915                         }
916                         return reportUserList;
917         };
918         
919         @RequestMapping(value = { "/report/wizard/security/retrieveReportRoleList" }, method = RequestMethod.GET)
920         public @ResponseBody List<IdNameValue> getReportRoleList(HttpServletRequest request)
921                         throws IOException, RaptorException {
922                         List<IdNameValue> reportRoleList = new ArrayList<IdNameValue>();
923                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
924                         Vector reportRoles = rdef.getReportRoles(request);
925                         Vector remainingRoles = Utils.getRolesNotInList(reportRoles,request); 
926                         for(int i=0; i<remainingRoles.size(); i++) {
927                                 IdNameValue role = (IdNameValue) remainingRoles.get(i);
928                                 reportRoleList.add(role);
929                         }
930                         return reportRoleList;
931                 };
932                 
933                 @RequestMapping(value = { "/report/wizard/security/retrieveReportUserList_query" }, method = RequestMethod.GET)
934                 public @ResponseBody List<Map<String, String>> getReportUserListQuery(HttpServletRequest request)
935                                 throws IOException, RaptorException {                           
936                                 List<Map<String, String>> reportUserList = new ArrayList();
937                                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
938                                 String reportId = rdef.getReportID();
939                                 Map<String, Object> params = new HashMap<String, Object>();
940                         params.put("report_id", new Long(reportId));    
941                         List<ReportUserRole> queriedUserList = getDataAccessService().executeNamedQuery("getReportSecurityUsers", params, null);
942                         for (int i=0; i<queriedUserList.size();i++){
943                                 Map<String, String> reportUser = new HashMap<String, String>();
944                                 Object tmp = queriedUserList.get(i);
945                                 reportUser.put("rep_id", queriedUserList.get(i).toString());
946                                 reportUser.put("order_no", queriedUserList.get(i).getOrderNo().toString());
947                                 reportUser.put("user_id", queriedUserList.get(i).getUserId().toString());                               
948                                 reportUser.put("role_id", queriedUserList.get(i).getRoleId().toString());                                                               
949                                 reportUser.put("read_only_yn", queriedUserList.get(i).getReadOnlyYn());                                                         
950                                 reportUserList.add(reportUser);
951                         }                       
952                                 return reportUserList;
953                         };
954
955
956
957                         @RequestMapping(value = "/report/security/addReportUser", method = RequestMethod.POST)
958                         public @ResponseBody Map<String,String> addSelectedReportUser(
959                                         @RequestBody String userIdToAdd, HttpServletRequest request, HttpServletResponse response)
960                                         throws IOException, RaptorException {
961                                         Map<String, String> JsonResponse = new HashMap<String, String>();
962                                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
963                                         try {
964                                                 JsonResponse.put("status","success");
965                                                 JsonResponse.put("userId",userIdToAdd);
966                                                 String action = "Add User";
967                                                 rdef.getReportSecurity().addUserAccess(userIdToAdd, "Y");
968                                                 WizardSequence ws = rdef.getWizardSequence();
969                                                 ws.performAction(action,rdef);
970                                                 return JsonResponse;
971                                         } catch (Exception ex) {
972                                                 logger.error(EELFLoggerDelegate.errorLogger,
973                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
974                                                 return null;
975                                         }                               
976                                 }
977
978                         @RequestMapping(value = "/report/security/removeReportUser", method = RequestMethod.POST)
979                         public @ResponseBody Map<String,String> removeSelectedReportUser(
980                                         @RequestBody String userIdToRemove, HttpServletRequest request, HttpServletResponse response)
981                                         throws IOException, RaptorException {
982                                                 Map<String, String> JsonResponse = new HashMap<String, String>();
983                                                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
984                                                 try {
985                                                         JsonResponse.put("status","success");
986                                                         JsonResponse.put("userId",userIdToRemove);
987                                                         String action = "Delete User";                          
988                                                         rdef.getReportSecurity().removeUserAccess(userIdToRemove);
989                                                         rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
990                                                         WizardSequence ws = rdef.getWizardSequence();
991                                                         ws.performAction(action,rdef);
992                                                         return JsonResponse;                                                    
993                                                 } catch (Exception ex) {
994                                                         logger.error(EELFLoggerDelegate.errorLogger,
995                                                                         "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
996                                                         return null;
997                                                 }                               
998                                         }
999                         
1000                         @RequestMapping(value = "/report/security/addReportRole", method = RequestMethod.POST)
1001                         public @ResponseBody Map<String,String> addSelectedReportRole(
1002                                         @RequestBody String roleIdToAdd, HttpServletRequest request, HttpServletResponse response)
1003                                         throws IOException, RaptorException {
1004                                         Map<String, String> JsonResponse = new HashMap<String, String>();
1005                                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1006                                         try {
1007                                                 JsonResponse.put("status","success");
1008                                                 JsonResponse.put("roleId",roleIdToAdd);
1009                                                 String action = "Add Role";
1010                                                 rdef.getReportSecurity().addRoleAccess(roleIdToAdd, "Y");
1011                                                 WizardSequence ws = rdef.getWizardSequence();
1012                                                 ws.performAction(action,rdef);
1013                                                 return JsonResponse;
1014                                         } catch (Exception ex) {
1015                                                 logger.error(EELFLoggerDelegate.errorLogger,
1016                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
1017                                                 return null;
1018                                         }                               
1019                                 }
1020
1021                         @RequestMapping(value = "/report/security/removeReportRole", method = RequestMethod.POST)
1022                         public @ResponseBody Map<String,String> removeSelectedReportRole(
1023                                         @RequestBody String roleIdToRemove, HttpServletRequest request, HttpServletResponse response)
1024                                         throws IOException, RaptorException {
1025                                         Map<String, String> JsonResponse = new HashMap<String, String>();
1026                                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1027                                         try {
1028                                                 JsonResponse.put("status","success");
1029                                                 JsonResponse.put("roleId",roleIdToRemove);
1030                                                 String action = "Delete Role";
1031                                                 rdef.getReportSecurity().removeRoleAccess(roleIdToRemove);
1032                                                 WizardSequence ws = rdef.getWizardSequence();
1033                                                 ws.performAction(action,rdef);
1034                                                 return JsonResponse;
1035                                         } catch (Exception ex) {
1036                                                 logger.error(EELFLoggerDelegate.errorLogger,
1037                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
1038                                                 return null;
1039                                         }                               
1040                                 }                       
1041
1042                         @RequestMapping(value = "/report/security/updateReportSecurityInfo", method = RequestMethod.POST)
1043                         public @ResponseBody Map<String,String> updateReportSecurityInfo(
1044                                         @RequestBody Map<String,String> securityInfo, HttpServletRequest request, HttpServletResponse response)
1045                                         throws IOException, RaptorException {
1046
1047                                         Map<String, String> JsonResponse = new HashMap<String, String>();
1048                                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1049                                         try {
1050                                                 JsonResponse.put("status","success");
1051                                                 String OwnerUserId = securityInfo.get("userId");
1052                                                 String isPublic = securityInfo.get("isPublic");
1053                                                 boolean rPublic = isPublic.equals("true"); 
1054                                                 rdef.getReportSecurity().setOwnerID(OwnerUserId);
1055                                                 rdef.setPublic(rPublic);
1056                                                 persistReportDefinition(request, rdef);
1057                                                 return JsonResponse;
1058                                                 
1059                                         } catch (Exception ex) {
1060                                                 logger.error(EELFLoggerDelegate.errorLogger,
1061                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
1062                                                 return null;
1063                                         }                               
1064                                 }
1065
1066                         @RequestMapping(value = "/report/security/toggleUserEditAccess/{userID}", method = RequestMethod.POST)
1067                         public @ResponseBody Map<String,String> toggleUserEditAccess(
1068                                         @PathVariable("userID") String userId,
1069                                         @RequestBody String readOnly, HttpServletRequest request, HttpServletResponse response)
1070                                         throws IOException, RaptorException {
1071                                         Map<String, String> JsonResponse = new HashMap<String, String>();
1072                                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1073                                         try {
1074                                                 String action ="";
1075                                                 JsonResponse.put("status","success");
1076                                                 if (readOnly.equals("N")) {
1077                                                         action = "Grant User Access";
1078                                                 }  else {
1079                                                         action = "Revoke User Access";                                                  
1080                                                 }                                               
1081                                                 rdef.getReportSecurity().updateUserAccess(userId, readOnly);
1082                                                 WizardSequence ws = rdef.getWizardSequence();
1083                                                 ws.performAction(action,rdef);
1084                                                 
1085                                                 return JsonResponse;
1086                                         } catch (Exception ex) {
1087                                                 logger.error(EELFLoggerDelegate.errorLogger,
1088                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
1089                                                 return null;
1090                                         }                               
1091                                 };                      
1092
1093                                 @RequestMapping(value = "/report/security/toggleRoleEditAccess/{roleID}", method = RequestMethod.POST)
1094                                 public @ResponseBody Map<String,String> toggleRoleEditAccess(
1095                                                 @PathVariable("roleID") String roleId,
1096                                                 @RequestBody String readOnly, HttpServletRequest request, HttpServletResponse response)
1097                                                 throws IOException, RaptorException {
1098                                                 Map<String, String> JsonResponse = new HashMap<String, String>();
1099                                                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1100                                                 try {
1101                                                         String action ="";
1102                                                         JsonResponse.put("status","success");
1103                                                         if (readOnly.equals("N")) {
1104                                                                 action = "Grant Role Access";
1105                                                         }  else {
1106                                                                 action = "Revoke Role Access";                                                  
1107                                                         }                                               
1108                                                         rdef.getReportSecurity().updateRoleAccess(roleId, readOnly);
1109                                                         WizardSequence ws = rdef.getWizardSequence();
1110                                                         ws.performAction(action,rdef);
1111                                                         
1112                                                         return JsonResponse;
1113                                                 } catch (Exception ex) {
1114                                                         logger.error(EELFLoggerDelegate.errorLogger,
1115                                                                         "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
1116                                                         return null;
1117                                                 }                               
1118                                         };                      
1119                                 
1120         @RequestMapping(value = { "/report/wizard/security/retrieveReportOwner" }, method = RequestMethod.GET)
1121         public @ResponseBody List<IdNameValue> getReportOwnerInList(HttpServletRequest request)
1122                         throws IOException, RaptorException {
1123                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1124
1125                 List<IdNameValue> UserList = new ArrayList<IdNameValue>();
1126                 List excludeValues = new java.util.ArrayList();
1127                 HttpSession session = request.getSession();
1128                 String query = Globals.getCustomizedScheduleQueryForUsers();
1129                 session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
1130                 String userId = AppUtils.getUserID(request);
1131                 session.setAttribute("LOGGED_USERID", userId);
1132                 String[] sessionParameters = Globals.getSessionParams().split(",");
1133                 String param = "";
1134                 for (int i = 0; i < sessionParameters.length; i++) {
1135                         param = (String) session.getAttribute(sessionParameters[0]);
1136                         query = Utils.replaceInString(query, "[" + sessionParameters[i].toUpperCase() + "]",
1137                                         (String) session.getAttribute(sessionParameters[i]));
1138                 }
1139                 boolean isAdmin = AppUtils.isAdminUser(request);
1140                 Vector allUsers = AppUtils.getAllUsers(query, param, isAdmin);
1141                 Vector result = new Vector(allUsers.size());
1142
1143                 for (Iterator iter = allUsers.iterator(); iter.hasNext();) {
1144                         IdNameValue value = (IdNameValue) iter.next();
1145
1146                         boolean exclude = false;
1147                         for (Iterator iterE = excludeValues.iterator(); iterE.hasNext();)
1148                                 if (((IdNameValue) iterE.next()).getId().equals(value.getId())) {
1149                                         exclude = true;
1150                                         break;
1151                                 } // if
1152
1153                         if (!exclude)
1154                                 UserList.add(value);
1155                 } // for
1156                 return UserList;
1157         }
1158
1159         
1160         @RequestMapping(value = { "/report/wizard/security/getReportSecurityInfo" }, method = RequestMethod.GET)
1161         public @ResponseBody Map<String,String> getReportSecurityInfo(HttpServletRequest request)
1162                         throws IOException, RaptorException {
1163                 Map<String, String> securityInfoMap = new HashMap<String,String>();
1164                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1165                 String isPublic = Boolean.toString(rdef.isPublic()); 
1166                 String createUser = AppUtils.getUserName(rdef.getCreateID());
1167                 String createDate = rdef.getCreateDate();
1168                 String updateUser = AppUtils.getUserName(rdef.getUpdateID());
1169                 String updateDate = rdef.getUpdateDate();
1170                 String ownerId = rdef.getOwnerID();
1171                 
1172                 securityInfoMap.put("isPublic",isPublic);
1173                 securityInfoMap.put("createdUser",createUser);          
1174                 securityInfoMap.put("createdDate",createDate);          
1175                 securityInfoMap.put("updateUser",updateUser);
1176                 securityInfoMap.put("updatedDate",updateDate);
1177                 securityInfoMap.put("ownerId",ownerId);
1178                 
1179                 return securityInfoMap;
1180         }       
1181         
1182         @RequestMapping(value = { "/report/wizard/security/getReportSecurityUsers" }, method = RequestMethod.GET)
1183         public @ResponseBody List<SecurityEntry> getReportSecurityUsers(HttpServletRequest request)
1184                         throws IOException, RaptorException {
1185                 
1186                 List<SecurityEntry> reportUserMapList = new ArrayList<SecurityEntry>();
1187                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1188                 Vector reportUsers = rdef.getReportUsers(request);
1189                 int iCount = 0;
1190                 
1191                 for(Iterator iter=reportUsers.iterator(); iter.hasNext(); iCount++) { 
1192                         Map<String, String> reportUserMap = new HashMap<String,String>();
1193                         SecurityEntry rUser = (SecurityEntry) iter.next();
1194                         reportUserMapList.add(rUser);
1195                 }
1196                 
1197                 return reportUserMapList;
1198         }               
1199         
1200         
1201         @RequestMapping(value = { "/report/wizard/security/getReportSecurityRoles" }, method = RequestMethod.GET)
1202         public @ResponseBody List<SecurityEntry> getReportSecurityRoles(HttpServletRequest request)
1203                         throws IOException, RaptorException {
1204                 
1205                 List<SecurityEntry> reportRoleList = new ArrayList<SecurityEntry>();
1206                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1207                 Vector reportRoles = rdef.getReportRoles(request);
1208                 int iCount = 0;
1209                 
1210                 for(Iterator iter=reportRoles.iterator(); iter.hasNext(); iCount++) { 
1211                         SecurityEntry rRole = (SecurityEntry) iter.next(); 
1212                         reportRoleList.add(rRole);
1213                 }
1214                 
1215                 return reportRoleList;
1216         }               
1217         
1218         
1219         @RequestMapping(value = { "/report/wizard/retrieve_def_tab_wise_data/{id}",
1220                         "/report/wizard/retrieve_def_tab_wise_data/{id}/{detailId}" }, method = RequestMethod.GET)
1221         public @ResponseBody DefinitionJSON retrieveDefTabWiseData(@PathVariable Map<String, String> pathVariables,
1222                         HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
1223                 ReportDefinition rdef = null;
1224                 ReportRuntime rr = null;
1225                 boolean newReport = false;
1226                 String tabId = "Def";
1227                 String id = "";
1228
1229                 if (pathVariables.containsKey("id")) {
1230                         id = pathVariables.get("id");
1231                 }
1232                 String detailId = "";
1233                 if (pathVariables.containsKey("detailId")) {
1234                         detailId = pathVariables.get("detailId");
1235                 }
1236
1237                 ServletContext servletContext = request.getSession().getServletContext();
1238                 if (!Globals.isSystemInitialized()) {
1239                         Globals.initializeSystem(servletContext);
1240                 }
1241
1242                 if (tabId.equals("Def") && id.equals("InSession")) {
1243                         rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1244                         newReport = false;
1245
1246                 } else if (tabId.equals("Def") && id.equals("Create")) {
1247                         removeVariablesFromSession(request);
1248                         rdef = (new ReportHandler()).loadReportDefinition(request, "-1");
1249                         rdef.setReportType(AppConstants.RT_LINEAR);
1250                         newReport = true;
1251
1252                 } else if (tabId.equals("Def") && AppUtils.nvl(id).length() > 0) {
1253                         rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1254                         rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
1255
1256                         if (rdef != null && !rdef.getReportID().equals(id)) {
1257                                 request.getSession().removeAttribute(AppConstants.SI_REPORT_DEFINITION);
1258                                 removeVariablesFromSession(request);
1259                                 rdef = (new ReportHandler()).loadReportDefinition(request, id);
1260                                 request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
1261                         } else if (rr != null && !rr.getReportID().equals(id)) {
1262                                 request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);
1263                                 removeVariablesFromSession(request);
1264                                 rdef = (new ReportHandler()).loadReportDefinition(request, id);
1265                                 request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
1266                         } else if (rdef == null) {
1267                                 rdef = (new ReportHandler()).loadReportDefinition(request, id);
1268                                 request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
1269                         }
1270                         newReport = false;
1271
1272                 } else {
1273                         rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1274                 }
1275                 DefinitionJSON wizardJSON = new DefinitionJSON();
1276                 if (tabId.equals("Def")) {
1277                         wizardJSON.setTabId("Def");
1278                         wizardJSON.setTabName("Definition");
1279
1280                         wizardJSON.setReportId((rdef != null) ? rdef.getReportID() + "" : "");
1281                         wizardJSON.setReportName((rdef != null) ? rdef.getReportName() : "");
1282                         wizardJSON.setReportDescr((rdef != null) ? rdef.getReportDescr() : "");
1283                         wizardJSON.setReportType((rdef != null) ? rdef.getReportType() : AppConstants.RT_LINEAR);
1284                         wizardJSON.setDbInfo((rdef != null) ? rdef.getDBInfo() : "");
1285                         wizardJSON.setFormHelpText((rdef != null) ? rdef.getFormHelpText() : "");
1286                         wizardJSON.setPageSize((rdef != null) ? rdef.getPageSize() : 50);
1287                         List<IdNameBooleanJSON> displayArea = new ArrayList<IdNameBooleanJSON>();
1288                         IdNameBooleanJSON idNameJSON = new IdNameBooleanJSON();
1289                         String qMenu = "";
1290                         for (int i = 0; i < AppUtils.getQuickLinksMenuIDs().size(); i++) {
1291                                 idNameJSON = new IdNameBooleanJSON();
1292                                 qMenu = (String) AppUtils.getQuickLinksMenuIDs().get(i);
1293                                 idNameJSON.setId(qMenu);
1294                                 idNameJSON.setName(qMenu);
1295                                 if (rdef != null && (rdef.getMenuID().equals(qMenu))) {
1296                                         idNameJSON.setSelected(true);
1297                                 }
1298                                 displayArea.add(idNameJSON);
1299                         }
1300                         wizardJSON.setDisplayArea(displayArea);
1301                         wizardJSON.setHideFormFieldsAfterRun((rdef != null) ? rdef.isHideFormFieldAfterRun() : false);
1302                         wizardJSON.setMaxRowsInExcelCSVDownload((rdef != null) ? rdef.getMaxRowsInExcelDownload() : 500);
1303                         wizardJSON.setFrozenColumns((rdef != null) ? rdef.getFrozenColumns() : 0);
1304                         wizardJSON.setDataGridAlign((rdef != null) ? rdef.getDataGridAlign() : "left");
1305                         wizardJSON.setEmptyMessage((rdef != null) ? rdef.getEmptyMessage() : "No records found");
1306                         wizardJSON.setDataContainerHeight((rdef != null) ? rdef.getDataContainerHeight() : "600");
1307                         wizardJSON.setDataContainerWidth((rdef != null) ? rdef.getDataContainerWidth() : "900");
1308                         List<NameBooleanJSON> displayOptions = new ArrayList<NameBooleanJSON>();
1309                         NameBooleanJSON nameBooleanJSON = new NameBooleanJSON();
1310                         nameBooleanJSON.setName("HideFormFields");
1311                         nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideForm() : false);
1312                         displayOptions.add(nameBooleanJSON);
1313
1314                         nameBooleanJSON = new NameBooleanJSON();
1315                         nameBooleanJSON.setName("HideChart");
1316                         nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideChart() : false);
1317                         displayOptions.add(nameBooleanJSON);
1318
1319                         nameBooleanJSON = new NameBooleanJSON();
1320                         nameBooleanJSON.setName("HideReportData");
1321                         nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideData() : false);
1322                         displayOptions.add(nameBooleanJSON);
1323
1324                         nameBooleanJSON = new NameBooleanJSON();
1325                         nameBooleanJSON.setName("HideExcel");
1326                         nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideExcelIcons() : false);
1327                         displayOptions.add(nameBooleanJSON);
1328
1329                         nameBooleanJSON = new NameBooleanJSON();
1330                         nameBooleanJSON.setName("HidePdf");
1331                         nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHidePDFIcons() : false);
1332                         displayOptions.add(nameBooleanJSON);
1333
1334                         wizardJSON.setDisplayOptions(displayOptions);
1335
1336                         wizardJSON.setRuntimeColSortDisabled((rdef != null) ? rdef.isRuntimeColSortDisabled() : false);
1337                         wizardJSON.setNumFormCols((rdef != null) ? rdef.getNumFormColsAsInt() : 1);
1338                         wizardJSON.setReportTitle((rdef != null) ? rdef.getReportTitle() : "");
1339                         wizardJSON.setReportSubTitle((rdef != null) ? rdef.getReportSubTitle() : "");
1340
1341                 }
1342
1343                 ObjectMapper mapper = new ObjectMapper();
1344                 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
1345                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1346
1347                 return wizardJSON;
1348
1349         }
1350
1351         @RequestMapping(value = "/report/wizard/retrieve_data/{validate}", method = RequestMethod.POST)
1352         public @ResponseBody RaptorResponse retrieveDataForGivenQuery(@PathVariable("validate") boolean validate,
1353                         @RequestBody QueryJSON queryJSON, HttpServletRequest request, HttpServletResponse response)
1354                         throws IOException, RaptorException {
1355                 RaptorResponse raptorResponse = new RaptorResponse();
1356                 String sql = queryJSON.getQuery();
1357                 String jsonInString = "";
1358
1359                 ServletContext servletContext = request.getSession().getServletContext();
1360                 if (!Globals.isSystemInitialized()) {
1361                         Globals.initializeSystem(servletContext);
1362                 }
1363
1364                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1365                 if (rdef == null) {
1366                         ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
1367                         errorJSONRuntime.setErrormessage("Report Definition is not in session;");
1368                         errorJSONRuntime.setStacktrace("");
1369
1370                         ObjectMapper mapper = new ObjectMapper();
1371                         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
1372                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1373
1374                         try {
1375                                 jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
1376                                 raptorResponse.data().put("elements", jsonInString);
1377                                 return raptorResponse;
1378                         } catch (Exception ex1) {
1379                                 logger.error(EELFLoggerDelegate.errorLogger,
1380                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex1);
1381                         }
1382                 } else {
1383                         if (!sql.trim().toUpperCase().startsWith("SELECT")) {
1384                                 ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
1385                                 errorJSONRuntime.setErrormessage("Invalid statement - the SQL must start with the keyword SELECT");
1386                                 errorJSONRuntime.setStacktrace("SQL Error");
1387                                 ObjectMapper mapper = new ObjectMapper();
1388                                 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
1389                                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1390
1391                                 try {
1392                                         jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
1393                                         raptorResponse.data().put("elements", jsonInString);
1394                                         return raptorResponse;
1395
1396                                 } catch (Exception ex) {
1397                                         logger.error(EELFLoggerDelegate.errorLogger,
1398                                                         "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
1399                                 }
1400                         } else {
1401                                 DataSet ds = null;
1402                                 String remoteDb = request.getParameter("remoteDbPrefix");
1403                                 // comment below two lines to test
1404                                 String remoteDbPrefix = (remoteDb != null && !remoteDb.equalsIgnoreCase("null")) ? remoteDb
1405                                                 : rdef.getDBInfo();
1406                                 String userId = AppUtils.getUserID(request);
1407                                 // String userId = "1";
1408                                 sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId);
1409                                 sql = Utils.replaceInString(sql, "[USERID]", userId);
1410                                 String[] reqParameters = Globals.getRequestParams().split(",");
1411                                 String[] sessionParameters = Globals.getSessionParams().split(",");
1412                                 javax.servlet.http.HttpSession session = request.getSession();
1413                                 logger.debug(EELFLoggerDelegate.debugLogger, ("B4 testRunSQL " + sql));
1414                                 if (request != null) {
1415                                         for (int i = 0; i < reqParameters.length; i++) {
1416                                                 if (!reqParameters[i].startsWith("ff"))
1417                                                         sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase() + "]",
1418                                                                         request.getParameter(reqParameters[i].toUpperCase()));
1419                                                 else
1420                                                         sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase() + "]",
1421                                                                         request.getParameter(reqParameters[i]));
1422                                         }
1423                                 }
1424                                 if (session != null) {
1425                                         for (int i = 0; i < sessionParameters.length; i++) {
1426                                                 logger.debug(EELFLoggerDelegate.debugLogger, (" Session " + " sessionParameters[i] "
1427                                                                 + sessionParameters[i] + " " + (String) session.getAttribute(sessionParameters[i])));
1428                                                 sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase() + "]",
1429                                                                 (String) session.getAttribute(sessionParameters[i]));
1430                                         }
1431                                 }
1432                                 logger.debug(EELFLoggerDelegate.debugLogger, ("After testRunSQL " + sql));
1433                                 try {
1434
1435                                         response.setContentType("application/json");
1436                                         ds = ConnectionUtils.getDataSet(sql, "local", true);
1437
1438                                         QueryResultJSON queryResultJSON = new QueryResultJSON();
1439                                         queryResultJSON.setQuery(queryJSON.getQuery());
1440                                         String query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
1441                                         rdef.parseReportSQL(query);
1442                                         queryResultJSON.setQuery(query);
1443
1444                                         int numColumns = ds.getColumnCount();
1445                                         queryResultJSON.setTotalRows(ds.getRowCount());
1446
1447                                         int count = 0;
1448                                         Map<String, String> dvJSON = null;
1449                                         ArrayList<String> colList = new ArrayList<String>();
1450                                         ArrayList<Map<String, String>> reportDataRows = new ArrayList<Map<String, String>>();
1451                                         if (!ds.isEmpty()) {
1452                                                 count = 0;
1453
1454                                                 for (int i = 0; i < ds.getColumnCount(); i++) {
1455                                                         colList.add(ds.getColumnName(i));
1456                                                 }
1457                                                 queryResultJSON.setReportDataColumns(colList);
1458                                                 if (queryResultJSON.getTotalRows() > 0) {
1459                                                         count = 0;
1460                                                         dvJSON = new HashMap<String, String>();
1461                                                         for (int r = 0; r < Math.min(ds.getRowCount(), 100); r++) {
1462                                                                 dvJSON = new HashMap<String, String>();
1463                                                                 for (int c = 0; c < ds.getColumnCount(); c++) {
1464                                                                         try {
1465                                                                                 dvJSON.put(ds.getColumnName(c), ds.getString(r, c));
1466                                                                         } catch (Exception ex) {
1467                                                                                 logger.error(EELFLoggerDelegate.errorLogger,
1468                                                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].",
1469                                                                                                 ex);
1470                                                                         }
1471                                                                 }
1472                                                                 reportDataRows.add(dvJSON);
1473
1474                                                         }
1475                                                 }
1476
1477                                         }
1478                                         queryResultJSON.setReportDataRows(reportDataRows);
1479                                         ObjectMapper mapper = new ObjectMapper();
1480                                         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
1481                                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1482                                         if (validate) {
1483                                                 query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
1484                                                 request.setAttribute("sqlValidated", "N");
1485                                                 rdef.parseReportSQL(query);
1486                                                 request.setAttribute("sqlValidated", "Y");
1487                                                 persistReportDefinition(request, rdef);
1488
1489                                         }
1490                                         try {
1491                                                 jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(queryResultJSON);
1492                                                 raptorResponse.data().put("elements", jsonInString);
1493                                                 return raptorResponse;
1494
1495                                         } catch (Exception ex) {
1496                                                 logger.error(EELFLoggerDelegate.errorLogger,
1497                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery]. RaptorException: ",
1498                                                                 ex);
1499                                         }
1500                                 } catch (ReportSQLException ex) {
1501                                         ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
1502                                         if (sql.contains("[")) {
1503                                                 errorJSONRuntime.setErrormessage(
1504                                                                 "Formfield information is present in the query, hence couldn't execute");
1505                                                 errorJSONRuntime
1506                                                                 .setStacktrace("Formfield information is present in the query, hence couldn't execute");
1507                                                 if (validate) {
1508                                                         String query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
1509                                                         request.setAttribute("sqlValidated", "N");
1510                                                         rdef.parseReportSQL(query);
1511                                                         request.setAttribute("sqlValidated", "Y");
1512                                                         persistReportDefinition(request, rdef);
1513
1514                                                 }
1515
1516                                         } else {
1517                                                 errorJSONRuntime.setErrormessage(ex.getMessage());
1518                                                 errorJSONRuntime.setStacktrace(getStackTrace(ex));
1519                                         }
1520                                         ObjectMapper mapper = new ObjectMapper();
1521                                         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
1522                                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1523
1524                                         try {
1525                                                 jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
1526                                                 raptorResponse.data().put("elements", jsonInString);
1527                                                 return raptorResponse;
1528
1529                                         } catch (Exception ex1) {
1530                                                 logger.error(EELFLoggerDelegate.errorLogger,
1531                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex1);
1532                                         }
1533                                 }
1534                                 if (validate) {
1535                                         String query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
1536                                         request.setAttribute("sqlValidated", "N");
1537                                         rdef.parseReportSQL(query);
1538                                         request.setAttribute("sqlValidated", "Y");
1539                                         persistReportDefinition(request, rdef);
1540
1541                                 }
1542
1543                         }
1544                 }
1545                 raptorResponse.data().put("elements", jsonInString);
1546                 return raptorResponse;
1547
1548         }
1549
1550         @RequestMapping(value = "save_chart", method = RequestMethod.POST)
1551         public void reportChartReceive(@RequestBody ChartJSON chartJSON, HttpServletRequest request,
1552                         HttpServletResponse response) throws IOException {
1553                 ReportRuntime reportRuntime;
1554                 reportRuntime = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); // changing
1555                                                                                                                                                                                                                         // session
1556                                                                                                                                                                                                                         // to
1557                                                                                                                                                                                                                         // request
1558                 String reportID = request.getParameter("c_master");
1559                 if (reportRuntime == null && AppUtils.nvl(reportID).length() > 0) {
1560                         try {
1561                                 ReportHandler rh = new ReportHandler();
1562                                 reportRuntime = rh.loadReportRuntime(request, reportID);
1563                         } catch (RaptorException ex) {
1564                                 logger.error(EELFLoggerDelegate.errorLogger,
1565                                                 "[Controller.processRequest]Invalid raptor action [reportChartReceive].", ex);
1566                         }
1567                 }
1568
1569                 if (reportRuntime != null) {
1570                         String chartType = chartJSON.getChartType();
1571                         reportRuntime.setChartType(chartJSON.getChartType());
1572                         reportRuntime.setChartAnimate(chartJSON.isAnimation());
1573                         reportRuntime.setChartWidth(chartJSON.getWidth());
1574                         reportRuntime.setChartHeight(chartJSON.getHeight());
1575                         reportRuntime.setShowChartTitle(chartJSON.isShowTitle());
1576
1577                         String domainAxis = null;
1578                         domainAxis = chartJSON.getDomainAxis();
1579
1580                         List<DataColumnType> reportCols = reportRuntime.getAllColumns();
1581
1582                         for (Iterator<DataColumnType> iter = reportCols.iterator(); iter.hasNext();) {
1583                                 DataColumnType dct = (DataColumnType) iter.next();
1584                                 if (dct.getColId().equals(domainAxis)) {
1585                                         dct.setColOnChart(AppConstants.GC_LEGEND);
1586                                 } else {
1587                                         dct.setColOnChart(null);
1588                                 }
1589                         }
1590
1591                         CategoryAxisJSON categoryAxisJSON = chartJSON.getCategoryAxisJSON();
1592                         String categoryAxis = null;
1593
1594                         categoryAxis = (categoryAxisJSON != null ? categoryAxisJSON.getValue() : "");
1595
1596                         reportCols = reportRuntime.getAllColumns();
1597
1598                         for (Iterator<DataColumnType> iter = reportCols.iterator(); iter.hasNext();) {
1599                                 DataColumnType dct = (DataColumnType) iter.next();
1600                                 if (dct.getColId().equals(categoryAxis)) {
1601                                         dct.setChartSeries(true);
1602                                 } else {
1603                                         dct.setChartSeries(false);
1604                                 }
1605                         }
1606
1607                         ArrayList<RangeAxisJSON> rangeAxisList = chartJSON.getRangeAxisList();
1608                         int r = 0;
1609                         HashSet<String> removeRangeAxisMap = new HashSet<>();
1610                         for(RangeAxisJSON rangeAxis:chartJSON.getRangeAxisRemoveList()){                                
1611                                 removeRangeAxisMap.add(rangeAxis.getRangeAxis());
1612                         }
1613                         for (int i = 0; i < rangeAxisList.size(); i++) {
1614                                 RangeAxisJSON rangeAxisJSON = rangeAxisList.get(i);
1615                                 String rangeAxis = rangeAxisJSON.getRangeAxis();
1616                                 String rangeYAxis = AppUtils.nvl(rangeAxisJSON.getRangeYAxis());
1617                                 String rangeChartGroup = AppUtils.nvl(rangeAxisJSON.getRangeChartGroup());
1618                                 String rangeColor = AppUtils.nvl(rangeAxisJSON.getRangeColor());
1619                                 String rangeLineType = AppUtils.nvl(rangeAxisJSON.getRangeLineType());
1620
1621                                 rangefor: for (Iterator<DataColumnType> iterator = reportCols.iterator(); iterator.hasNext();) {
1622                                         DataColumnType dct = (DataColumnType) iterator.next();
1623                                         if (dct.getColId().equals(rangeAxis)) {
1624                                                 if(removeRangeAxisMap.contains(rangeAxis))
1625                                                         dct.setChartSeq(-1); // if we set it to -1, means this range axis will not be included
1626                                                 else
1627                                                         dct.setChartSeq(++r);
1628                                                 dct.setColOnChart("0");
1629                                                 dct.setYAxis(rangeYAxis); // +"|"+dct.getColId());
1630                                                 dct.setChartGroup(rangeChartGroup); // +"|"+dct.getColId());
1631                                                 dct.setChartColor(rangeColor);
1632                                                 dct.setChartLineType(rangeLineType);
1633
1634                                                 if (chartType.equals(AppConstants.GT_ANNOTATION_CHART)
1635                                                                 || chartType.equals(AppConstants.GT_FLEX_TIME_CHARTS)) {
1636                                                         if (rangeAxisJSON.isShowAsArea()) {
1637                                                                 dct.setIsRangeAxisFilled(true);
1638                                                         } else {
1639                                                                 dct.setIsRangeAxisFilled(false);
1640                                                         }
1641                                                 }
1642                                                 break rangefor;
1643                                         }
1644                                 }
1645
1646                         }
1647
1648                         reportRuntime.setChartLeftAxisLabel(chartJSON.getPrimaryAxisLabel());
1649                         reportRuntime.setChartRightAxisLabel(chartJSON.getSecondaryAxisLabel());
1650
1651                         reportRuntime.setRangeAxisLowerLimit(chartJSON.getMinRange());
1652                         reportRuntime.setRangeAxisUpperLimit(chartJSON.getMaxRange());
1653
1654                         if (chartType.equals(AppConstants.GT_ANNOTATION_CHART)
1655                                         || chartType.equals(AppConstants.GT_FLEX_TIME_CHARTS)) {
1656                                 if (chartJSON.getFlexTimeSeriesChartOptions() != null) {
1657                                         reportRuntime.setZoomIn(chartJSON.getFlexTimeSeriesChartOptions().getZoomIn());
1658                                         reportRuntime.setTimeAxisType(chartJSON.getFlexTimeSeriesChartOptions().getTimeAxisType());
1659                                 }
1660
1661                         }
1662
1663                         if (chartType.equals(AppConstants.GT_TIME_SERIES)) {
1664                                 if (chartJSON.getTimeSeriesChartOptions() != null) {
1665                                         reportRuntime.setTimeSeriesRender(chartJSON.getTimeSeriesChartOptions().getLineChartRenderer());
1666                                         reportRuntime.setShowXAxisLabel(chartJSON.getTimeSeriesChartOptions().isShowXAxisLabel());
1667                                         reportRuntime.setAddXAxisTickers(chartJSON.getTimeSeriesChartOptions().isAddXAxisTicker());
1668                                         reportRuntime.setTimeAxis(chartJSON.getTimeSeriesChartOptions().isNonTimeAxis());
1669                                         reportRuntime.setMultiSeries(chartJSON.getTimeSeriesChartOptions().isMultiSeries());
1670                                 }
1671
1672                         }
1673
1674                         if (chartType.equals(AppConstants.GT_BAR_3D)) {
1675                                 if (chartJSON.getBarChartOptions() != null) {
1676                                         reportRuntime.setChartOrientation(
1677                                                         chartJSON.getBarChartOptions().isVerticalOrientation() ? "vertical" : "horizontal");
1678                                         reportRuntime.setChartStacked(chartJSON.getBarChartOptions().isStackedChart());
1679                                         reportRuntime.setBarControls(chartJSON.getBarChartOptions().isDisplayBarControls());
1680                                         reportRuntime.setXAxisDateType(chartJSON.getBarChartOptions().isxAxisDateType());
1681                                         reportRuntime.setLessXaxisTickers(chartJSON.getBarChartOptions().isMinimizeXAxisTickers());
1682                                         reportRuntime.setTimeAxis(chartJSON.getBarChartOptions().isTimeAxis());
1683                                         reportRuntime.setLogScale(chartJSON.getBarChartOptions().isyAxisLogScale());
1684                                 }
1685                         }
1686
1687                         reportRuntime.setLegendLabelAngle(chartJSON.getCommonChartOptions().getLegendLabelAngle());
1688                         reportRuntime.setLegendPosition(chartJSON.getCommonChartOptions().getLegendPosition());
1689                         reportRuntime.setChartLegendDisplay(chartJSON.getCommonChartOptions().isHideLegend() ? "Y" : "N");
1690                         reportRuntime.setAnimateAnimatedChart(chartJSON.getCommonChartOptions().isAnimateAnimatedChart());
1691
1692                         reportRuntime.setTopMargin(chartJSON.getCommonChartOptions().getTopMargin());
1693                         reportRuntime.setBottomMargin(chartJSON.getCommonChartOptions().getBottomMargin());
1694                         reportRuntime.setLeftMargin(chartJSON.getCommonChartOptions().getLeftMargin());
1695                         reportRuntime.setRightMargin(chartJSON.getCommonChartOptions().getRightMargin());
1696
1697                         for (Iterator<DataColumnType> iterator = reportCols.iterator(); iterator.hasNext();) {
1698                                 DataColumnType dct = (DataColumnType) iterator.next();
1699                                 if (!(AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND)
1700                                                 || (dct.getChartSeq() != null && dct.getChartSeq() > 0) || dct.isChartSeries())) {
1701                                         dct.setChartSeq(-1);
1702                                         dct.setChartColor(null);
1703                                         dct.setColOnChart(null);
1704                                         dct.setCreateInNewChart(false);
1705                                         dct.setChartGroup(null);
1706                                         dct.setYAxis(null);
1707                                 }
1708                         }
1709
1710                         try {
1711                                 reportRuntime.persistLinearReport(request);
1712                         } catch (Exception ex) {
1713                                 logger.error(EELFLoggerDelegate.errorLogger,
1714                                                 "[Controller.processRequest]Invalid raptor action [reportChartReceive].", ex);
1715                         }
1716                 }
1717
1718         }
1719
1720         public String getViewName() {
1721                 return viewName;
1722         }
1723
1724         public void setViewName(String viewName) {
1725                 this.viewName = viewName;
1726         }
1727
1728         public String nvl(String s) {
1729                 return (s == null) ? "" : s;
1730         }
1731
1732         public String nvl(String s, String sDefault) {
1733                 return nvl(s).equals("") ? sDefault : s;
1734         }
1735
1736         public static String getStackTrace(Throwable aThrowable) {
1737                 Writer result = new StringWriter();
1738                 PrintWriter printWriter = new PrintWriter(result);
1739                 aThrowable.printStackTrace(printWriter);
1740                 return result.toString();
1741         }
1742
1743         public void persistReportDefinition(HttpServletRequest request, ReportDefinition rdef) throws RaptorException {
1744                 ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
1745                 if (rr != null && rr.getReportID().equals(rdef.getReportID()))
1746                         request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);
1747                 rdef.persistReport(request);
1748         } // persistReportDefinition
1749
1750         // Remove from session
1751         private void removeVariablesFromSession(HttpServletRequest request) {
1752                 HttpSession session = request.getSession();
1753                 session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST);
1754                 session.removeAttribute(AppConstants.DRILLDOWN_INDEX);
1755                 session.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX);
1756                 session.removeAttribute(AppConstants.SI_BACKUP_FOR_REP_ID);
1757                 session.removeAttribute(AppConstants.SI_COLUMN_LOOKUP);
1758                 session.removeAttribute(AppConstants.SI_DASHBOARD_REP_ID);
1759                 session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP);
1760                 session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME);
1761                 session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP);
1762                 session.removeAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP);
1763                 session.removeAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP);
1764                 session.removeAttribute(AppConstants.SI_DATA_SIZE_FOR_TEXTFIELD_POPUP);
1765                 session.removeAttribute(AppConstants.SI_MAP);
1766                 session.removeAttribute(AppConstants.SI_MAP_OBJECT);
1767                 session.removeAttribute(AppConstants.SI_REPORT_DEFINITION);
1768                 session.removeAttribute(AppConstants.SI_REPORT_RUNTIME);
1769                 session.removeAttribute(AppConstants.SI_REPORT_RUN_BACKUP);
1770                 session.removeAttribute(AppConstants.SI_REPORT_SCHEDULE);
1771                 session.removeAttribute(AppConstants.RI_REPORT_DATA);
1772                 session.removeAttribute(AppConstants.RI_CHART_DATA);
1773                 session.removeAttribute(AppConstants.SI_FORMFIELD_INFO);
1774                 session.removeAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO);
1775                 session.removeAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP);
1776                 session.removeAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP);
1777                 Enumeration<String> enum1 = session.getAttributeNames();
1778                 String attributeName = "";
1779                 while (enum1.hasMoreElements()) {
1780                         attributeName = enum1.nextElement();
1781                         if (attributeName.startsWith("parent_")) {
1782                                 session.removeAttribute(attributeName);
1783                         }
1784                 }
1785         }
1786
1787 }