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