517d26721207bcb6089e547c5626450519652186
[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
136         private String viewName;
137
138         @RequestMapping(value = { "/raptor.htm" }, method = RequestMethod.GET)
139         public void RaptorSearch(HttpServletRequest request, HttpServletResponse response)
140                         throws IOException, RaptorException {
141
142                 viewName = "";
143                 String actionKey = nvl(request.getParameter(AppConstants.RI_ACTION), request.getParameter("action"));
144                 actionKey = nvl(actionKey, "report.run");
145
146                 HttpSession session = request.getSession();
147                 User user = UserUtils.getUserSession(request);
148
149                 if ("report.download.excel2007.session".equals(actionKey) || "report.download.csv.session".equals(actionKey)
150                                 || "report.download.excel.session".equals(actionKey)
151                                 || "report.download.pdf.session".equals(actionKey)) {
152                         if (session != null && user != null) {
153                                 ServletContext servletContext = request.getSession().getServletContext();
154                                 if (!Globals.isSystemInitialized()) {
155                                         Globals.initializeSystem(servletContext);
156                                 }
157                                 ReportRuntime rr = null;
158                                 ReportData rd = null;
159                                 String parent = "";
160                                 int parentFlag = 0;
161                                 if (!"N".equals(nvl(request.getParameter("parent"), "")))
162                                         parent = nvl(request.getParameter("parent"), "");
163                                 if (parent.startsWith("parent_"))
164                                         parentFlag = 1;
165                                 if (parentFlag == 1) {
166                                         rr = (ReportRuntime) request.getSession().getAttribute(parent + "_rr");
167                                         rd = (ReportData) request.getSession().getAttribute(parent + "_rd");
168                                 }
169
170                                 boolean isEmbedded = false;
171                                 Object temp = request.getSession().getAttribute("isEmbedded");
172                                 if (temp != null) {
173                                         isEmbedded = (boolean) temp;
174                                 }
175                                 if (isEmbedded) {
176                                         String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
177                                         if (rr == null)
178                                                 rr = (ReportRuntime) ((HashMap) request.getSession()
179                                                                 .getAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP)).get(reportID);
180                                         if (rd == null)
181                                                 rd = (ReportData) ((HashMap) request.getSession()
182                                                                 .getAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP)).get(reportID);
183                                 } else {
184                                         if (rr == null)
185                                                 rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
186                                         if (rd == null)
187                                                 rd = (ReportData) request.getSession().getAttribute(AppConstants.RI_REPORT_DATA);
188                                 }
189                                 String userId = AppUtils.getUserID(request);
190                                 int downloadLimit = 0;
191                                 if (rr != null)
192                                         downloadLimit = (rr.getMaxRowsInExcelDownload() > 0) ? rr.getMaxRowsInExcelDownload()
193                                                         : Globals.getDownloadLimit();
194                                 if ("report.csv.download".equals(actionKey))
195                                         downloadLimit = Globals.getCSVDownloadLimit();
196                                 if(rr != null) {
197                                         String sqlWhole = rr.getReportDataSQL(userId, downloadLimit, request);
198                                         request.setAttribute(AppConstants.RI_REPORT_SQL_WHOLE, sqlWhole);
199                                 }
200                                 try {
201                                         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.getMessage()));
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.getMessage()));
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.getMessage()));
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.getMessage()));
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.getMessage()));
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.size() > 0) {
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().size()==0)
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                         messageJSON.setMessage("Success Definition of given report is saved in session.");
899                         messageJSON.setAnyStacktrace((newReport ? " New Report info is added to Session "
900                                         : rdef.getReportID() + "- is Modified and added to session and DB."));
901
902                 } catch (Exception ex) {
903                         messageJSON.setMessage("Error occured while saving definition Tab");
904                         messageJSON.setAnyStacktrace(getStackTrace(ex));
905                         logger.error(EELFLoggerDelegate.errorLogger,
906                                         "[Controller.processRequest]Invalid raptor action [retrieveTabWiseData].", ex);
907                         return messageJSON;
908                 }
909
910                 return messageJSON;
911         }
912
913         @RequestMapping(value = { "/report/wizard/retrieve_form_tab_wise_data/{id}",
914                         "/report/wizard/retrieve_form_tab_wise_data/{id}/{action}" }, method = RequestMethod.GET)
915         public @ResponseBody FormEditJSON retrieveFormTabWiseData(@PathVariable Map<String, String> pathVariables,
916                         HttpServletRequest request, HttpServletResponse response) {
917                 ReportDefinition rdef;
918                 String id = "";
919                 String action = "";
920                 String detailId = "";
921                 FormEditJSON wizardJSON = new FormEditJSON();
922                 rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
923
924                 if (pathVariables.containsKey("id")) {
925                         id = pathVariables.get("id");
926                 }
927                 if (pathVariables.containsKey("action")) {
928                         action = pathVariables.get("action");
929                 }
930
931                 ServletContext servletContext = request.getSession().getServletContext();
932                 if (!Globals.isSystemInitialized()) {
933                         Globals.initializeSystem(servletContext);
934                 }
935                 wizardJSON.setTabId("FormEdit");
936                 wizardJSON.setTabName("Form Edit");
937                 FormFieldType currField = null;
938                 try {
939                         if (id.equals("add")) {
940
941                                 currField = rdef.addFormFieldType(new ObjectFactory(), "", "", "", "", "", "", "", "", null, null, "",
942                                                 "");
943                                 wizardJSON.setFieldId(currField.getFieldId());
944                                 wizardJSON.setFieldName(currField.getFieldName());
945                                 wizardJSON.setFieldType(currField.getFieldType());
946                                 wizardJSON.setVisible(AppUtils.nvls(currField.getVisible(), "Y").toUpperCase().startsWith("Y"));
947                                 wizardJSON.setDefaultValue(currField.getDefaultValue());
948                                 wizardJSON.setFieldDefaultSQL(currField.getFieldDefaultSQL());
949                                 wizardJSON.setFieldSQL(currField.getFieldSQL());
950                                 wizardJSON.setValidationType(currField.getValidationType());
951                                 persistReportDefinition(request, rdef);
952
953                         } else if (action.equals("delete")) {
954                                 rdef.deleteFormField(id);
955                                 persistReportDefinition(request, rdef);
956                                 wizardJSON.setMessage("Formfield " + detailId + " Deleted");
957                         }
958                         if (rdef.getFormFieldList() != null) {
959                                 for (FormFieldType fft : rdef.getFormFieldList().getFormField()) {
960                                         if (fft.getFieldId().equals(id)) {
961                                                 wizardJSON.setFieldId(fft.getFieldId());
962                                                 wizardJSON.setFieldName(fft.getFieldName());
963                                                 wizardJSON.setFieldType(fft.getFieldType());
964                                                 wizardJSON.setVisible(fft.getVisible().toUpperCase().startsWith("Y"));
965                                                 wizardJSON.setDefaultValue(fft.getDefaultValue());
966                                                 wizardJSON.setFieldDefaultSQL(fft.getFieldDefaultSQL());
967                                                 wizardJSON.setFieldSQL(fft.getFieldSQL());
968                                                 wizardJSON.setValidationType(fft.getValidationType());
969                                                 wizardJSON.setGroupFormField(fft.isGroupFormField());
970                                                 wizardJSON.setOrderSeq(fft.getOrderBySeq());
971                                                 PredefinedValueList preDefined = fft.getPredefinedValueList();
972
973                                                 if (preDefined != null) {
974                                                         List<IdNameBooleanJSON> preDefinedList = new ArrayList<>();
975                                                         IdNameBooleanJSON idNameBooleanJSON;
976
977                                                         for (String v : preDefined.getPredefinedValue()) {
978                                                                 idNameBooleanJSON = new IdNameBooleanJSON();
979                                                                 idNameBooleanJSON.setId(v);
980                                                                 idNameBooleanJSON.setName(v);
981                                                                 preDefinedList.add(idNameBooleanJSON);
982                                                         }
983                                                         wizardJSON.setPredefinedValueList(preDefinedList);
984                                                 }
985                                         }
986                                 }
987                         }
988                 } catch (Exception ex) {
989                         logger.error(EELFLoggerDelegate.errorLogger,
990                                         "[Controller.processRequest]Invalid raptor action [retrieveFormTabWiseData].", ex);
991                         ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
992                         errorJSONRuntime.setErrormessage("Error occured while retreiving formedit definition Tab");
993                         errorJSONRuntime.setStacktrace(getStackTrace(ex));
994                         wizardJSON.setErrorMessage("Error occured while retreiving formedit definition Tab");
995                         wizardJSON.setErrorStackTrace(getStackTrace(ex));
996
997                 }
998
999                 return wizardJSON;
1000         }
1001
1002         @RequestMapping(value = { "/report/wizard/retrieve_col_tab_wise_data/{id}" }, method = RequestMethod.GET)
1003         public @ResponseBody ColumnEditJSON retrieveColTabWiseData(@PathVariable Map<String, String> pathVariables,
1004                         HttpServletRequest request, HttpServletResponse response) {
1005                 ReportDefinition rdef;
1006                 String id = "";
1007                 ColumnEditJSON wizardJSON = new ColumnEditJSON();
1008                 rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1009
1010                 if (pathVariables.containsKey("id")) {
1011                         id = pathVariables.get("id");
1012                 }
1013                 ServletContext servletContext = request.getSession().getServletContext();
1014                 if (!Globals.isSystemInitialized()) {
1015                         Globals.initializeSystem(servletContext);
1016                 }
1017                 if (rdef != null) {
1018                         wizardJSON.setTabId("ColEdit");
1019                         wizardJSON.setTabName("Column Edit");
1020
1021                         List<DataColumnType> reportColumnList = rdef.getAllColumns();
1022
1023                         for (DataColumnType reportColumnType : reportColumnList) {
1024                                 if (reportColumnType.getColId().equals(id)) {
1025                                         wizardJSON.setColId(reportColumnType.getColId());
1026                                         wizardJSON.setColName(reportColumnType.getColName());
1027                                         wizardJSON.setDisplayAlignment(reportColumnType.getDisplayAlignment());
1028                                         wizardJSON.setDisplayHeaderAlignment(reportColumnType.getDisplayHeaderAlignment());
1029                                         wizardJSON.setSortable(
1030                                                         reportColumnType.isIsSortable() == null ? false : reportColumnType.isIsSortable());
1031                                         wizardJSON.setVisible(reportColumnType.isVisible());
1032                                         wizardJSON.setDrilldownURL(
1033                                                         reportColumnType.getDrillDownURL() == null ? "" : reportColumnType.getDrillDownURL());
1034                                         wizardJSON.setDrilldownParams(
1035                                                         reportColumnType.getDrillDownParams() == null ? "" : reportColumnType.getDrillDownParams());
1036                                         wizardJSON.setDrilldownType(
1037                                                         reportColumnType.getDrillDownType() == null ? "" : reportColumnType.getDrillDownType());
1038                                         wizardJSON.setDataType(reportColumnType.getDbColType() == null ? "" :reportColumnType.getDbColType());
1039                                         wizardJSON.setGroupByPos(reportColumnType.getGroupByPos());
1040                                         wizardJSON.setLevel(reportColumnType.getLevel());
1041                                         wizardJSON.setDisplayWidth(reportColumnType.getDisplayWidth());
1042                                         wizardJSON.setNoWrap(reportColumnType.getNowrap() == null ? "" : reportColumnType.getNowrap());
1043                                         wizardJSON.setIndentation(reportColumnType.getIndentation());           
1044                                                         
1045                                         wizardJSON.setDepeondsOnForField(reportColumnType.getDependsOnFormField() ==null?"":reportColumnType.getDependsOnFormField());
1046                                         wizardJSON.setSubTotalCustomText(reportColumnType.getSubTotalCustomText()==null?"":reportColumnType.getSubTotalCustomText());
1047                                         
1048                                         wizardJSON.setHideRepeatedKey(reportColumnType.isHideRepeatedKey()==null?false:reportColumnType.isHideRepeatedKey());
1049                                         wizardJSON.setColspan(reportColumnType.getColspan()==null?null:reportColumnType.getColspan());
1050                                         wizardJSON.setDisplayName(reportColumnType.getDisplayName());
1051                                         wizardJSON.setDisplayTotal(reportColumnType.getDisplayTotal());
1052                                 }
1053                         }
1054                 } else {
1055                         wizardJSON.setErrorMessage("Report is not in session");
1056                 }
1057
1058                 return wizardJSON;
1059         }
1060
1061         @RequestMapping(value = { "/report/wizard/retrieve_sql_tab_wise_data/{id}",
1062                         "/report/wizard/retrieve_sql_tab_wise_data/" }, method = RequestMethod.GET)
1063         public @ResponseBody QueryJSON retrieveSqlTabWiseData(@PathVariable Map<String, String> pathVariables,
1064                         HttpServletRequest request, HttpServletResponse response) throws RaptorException {
1065                 ReportDefinition rdef = null;
1066                 ReportRuntime rr;
1067                 String id = "";
1068                 QueryJSON wizardJSON = new QueryJSON();
1069
1070                 if (pathVariables.containsKey("id")) {
1071                         id = pathVariables.get("id");
1072                 }
1073                 ServletContext servletContext = request.getSession().getServletContext();
1074                 if (!Globals.isSystemInitialized()) {
1075                         Globals.initializeSystem(servletContext);
1076                 }
1077                 if (id.equals("InSession") || AppUtils.nvl(id).length() <= 0) {
1078                         rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1079                 } else if (AppUtils.nvl(id).length() > 0) {
1080                         rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1081                         rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
1082
1083                         if (rdef != null && !rdef.getReportID().equals(id)) {
1084                                 request.getSession().removeAttribute(AppConstants.SI_REPORT_DEFINITION);
1085                                 removeVariablesFromSession(request);
1086                                 rdef = (new ReportHandler()).loadReportDefinition(request, id);
1087                         } else if (rr != null && !rr.getReportID().equals(id)) {
1088                                 request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);
1089                                 removeVariablesFromSession(request);
1090                                 rdef = (new ReportHandler()).loadReportDefinition(request, id);
1091                         } else if (rdef == null) {
1092                                 rdef = (new ReportHandler()).loadReportDefinition(request, id);
1093                         }
1094                 }
1095
1096                 if (rdef != null) {
1097
1098                         wizardJSON.setTabId("Sql");
1099                         wizardJSON.setTabName("Sql");
1100                         wizardJSON.setQuery(rdef.getReportSQL());
1101                 }
1102                 return wizardJSON;
1103         }
1104
1105         @RequestMapping(value = { "/report/wizard/retrieveTotalForTheColList" }, method = RequestMethod.GET)
1106         public @ResponseBody List<IdNameValue> getTotalForTheCol(HttpServletRequest request)
1107         {
1108             IdNameList idNameList = AppConstants.TOTAL_FUNCTIONS;
1109             List<IdNameValue> list = new ArrayList<>();
1110             for(int i=0; i<idNameList.getCount(); i++) 
1111                 list.add(idNameList.getValue(i));
1112
1113                 return list;
1114         }
1115         
1116         @RequestMapping(value = { "/report/wizard/security/retrieveReportUserList" }, method = RequestMethod.GET)
1117         public @ResponseBody List<SecurityEntry> getReportUserList(HttpServletRequest request)
1118                         throws RaptorException {
1119                         List<SecurityEntry> reportUserList = new ArrayList<>();
1120                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1121                         Vector reportUsers = rdef.getReportUsers(request);
1122                         for(Iterator iter=reportUsers.iterator(); iter.hasNext();) { 
1123                                 SecurityEntry rUser = (SecurityEntry) iter.next(); 
1124                                 reportUserList.add(rUser);
1125                         }
1126                         return reportUserList;
1127         };
1128         
1129         @RequestMapping(value = { "/report/wizard/security/retrieveReportRoleList" }, method = RequestMethod.GET)
1130         public @ResponseBody List<IdNameValue> getReportRoleList(HttpServletRequest request)
1131                         throws RaptorException {
1132                         List<IdNameValue> reportRoleList = new ArrayList<>();
1133                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1134                         Vector reportRoles = rdef.getReportRoles(request);
1135                         Vector remainingRoles = Utils.getRolesNotInList(reportRoles,request); 
1136                         for(int i=0; i<remainingRoles.size(); i++) {
1137                                 IdNameValue role = (IdNameValue) remainingRoles.get(i);
1138                                 reportRoleList.add(role);
1139                         }
1140                         return reportRoleList;
1141                 };
1142                 
1143                 @RequestMapping(value = { "/report/wizard/security/retrieveReportUserList_query" }, method = RequestMethod.GET)
1144                 public @ResponseBody List<Map<String, String>> getReportUserListQuery(HttpServletRequest request)
1145                 {
1146                                 List<Map<String, String>> reportUserList = new ArrayList();
1147                                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1148                                 String reportId = rdef.getReportID();
1149                                 Map<String, Object> params = new HashMap<>();
1150                         params.put("report_id", new Long(reportId));    
1151                         List<ReportUserRole> queriedUserList = getDataAccessService().executeNamedQuery("getReportSecurityUsers", params, null);
1152                         for (int i=0; i<queriedUserList.size();i++){
1153                                 Map<String, String> reportUser = new HashMap<>();
1154                                 reportUser.put("rep_id", queriedUserList.get(i).toString());
1155                                 reportUser.put("order_no", queriedUserList.get(i).getOrderNo().toString());
1156                                 reportUser.put("user_id", queriedUserList.get(i).getUserId().toString());                               
1157                                 reportUser.put("role_id", queriedUserList.get(i).getRoleId().toString());                                                               
1158                                 reportUser.put("read_only_yn", queriedUserList.get(i).getReadOnlyYn());                                                         
1159                                 reportUserList.add(reportUser);
1160                         }                       
1161                                 return reportUserList;
1162                         };
1163
1164
1165
1166                         @RequestMapping(value = "/report/security/addReportUser", method = RequestMethod.POST)
1167                         public @ResponseBody Map<String,String> addSelectedReportUser(
1168                                         @RequestBody String userIdToAdd, HttpServletRequest request, HttpServletResponse response)
1169                         {
1170                                         Map<String, String> JsonResponse = new HashMap<>();
1171                                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1172                                         try {
1173                                                 JsonResponse.put("status","success");
1174                                                 JsonResponse.put("userId",userIdToAdd);
1175                                                 String action = "Add User";
1176                                                 rdef.getReportSecurity().addUserAccess(userIdToAdd, "Y");
1177                                                 WizardSequence ws = rdef.getWizardSequence();
1178                                                 ws.performAction(action,rdef);
1179                                                 return JsonResponse;
1180                                         } catch (Exception ex) {
1181                                                 logger.error(EELFLoggerDelegate.errorLogger,
1182                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
1183                                                 return null;
1184                                         }                               
1185                                 }
1186
1187                         @RequestMapping(value = "/report/security/removeReportUser", method = RequestMethod.POST)
1188                         public @ResponseBody Map<String,String> removeSelectedReportUser(
1189                                         @RequestBody String userIdToRemove, HttpServletRequest request, HttpServletResponse response)
1190                         {
1191                                                 Map<String, String> JsonResponse = new HashMap<>();
1192                                                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1193                                                 try {
1194                                                         JsonResponse.put("status","success");
1195                                                         JsonResponse.put("userId",userIdToRemove);
1196                                                         String action = "Delete User";                          
1197                                                         rdef.getReportSecurity().removeUserAccess(userIdToRemove);
1198                                                         rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1199                                                         WizardSequence ws = rdef.getWizardSequence();
1200                                                         ws.performAction(action,rdef);
1201                                                         return JsonResponse;                                                    
1202                                                 } catch (Exception ex) {
1203                                                         logger.error(EELFLoggerDelegate.errorLogger,
1204                                                                         "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
1205                                                         return null;
1206                                                 }                               
1207                                         }
1208                         
1209                         @RequestMapping(value = "/report/security/addReportRole", method = RequestMethod.POST)
1210                         public @ResponseBody Map<String,String> addSelectedReportRole(
1211                                         @RequestBody String roleIdToAdd, HttpServletRequest request, HttpServletResponse response) {
1212                                         Map<String, String> JsonResponse = new HashMap<>();
1213                                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1214                                         try {
1215                                                 JsonResponse.put("status","success");
1216                                                 JsonResponse.put("roleId",roleIdToAdd);
1217                                                 String action = "Add Role";
1218                                                 rdef.getReportSecurity().addRoleAccess(roleIdToAdd, "Y");
1219                                                 WizardSequence ws = rdef.getWizardSequence();
1220                                                 ws.performAction(action,rdef);
1221                                                 return JsonResponse;
1222                                         } catch (Exception ex) {
1223                                                 logger.error(EELFLoggerDelegate.errorLogger,
1224                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
1225                                                 return null;
1226                                         }                               
1227                                 }
1228
1229                         @RequestMapping(value = "/report/security/removeReportRole", method = RequestMethod.POST)
1230                         public @ResponseBody Map<String,String> removeSelectedReportRole(
1231                                         @RequestBody String roleIdToRemove, HttpServletRequest request, HttpServletResponse response)
1232                         {
1233                                         Map<String, String> JsonResponse = new HashMap<String, String>();
1234                                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1235                                         try {
1236                                                 JsonResponse.put("status","success");
1237                                                 JsonResponse.put("roleId",roleIdToRemove);
1238                                                 String action = "Delete Role";
1239                                                 rdef.getReportSecurity().removeRoleAccess(roleIdToRemove);
1240                                                 WizardSequence ws = rdef.getWizardSequence();
1241                                                 ws.performAction(action,rdef);
1242                                                 return JsonResponse;
1243                                         } catch (Exception ex) {
1244                                                 logger.error(EELFLoggerDelegate.errorLogger,
1245                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
1246                                                 return null;
1247                                         }                               
1248                                 }                       
1249
1250                         @RequestMapping(value = "/report/security/updateReportSecurityInfo", method = RequestMethod.POST)
1251                         public @ResponseBody Map<String,String> updateReportSecurityInfo(
1252                                         @RequestBody Map<String,String> securityInfo, HttpServletRequest request, HttpServletResponse response)
1253                         {
1254
1255                                         Map<String, String> JsonResponse = new HashMap<>();
1256                                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1257                                         try {
1258                                                 JsonResponse.put("status","success");
1259                                                 String OwnerUserId = securityInfo.get("userId");
1260                                                 String isPublic = securityInfo.get("isPublic");
1261                                                 boolean rPublic = isPublic.equals("true"); 
1262                                                 rdef.getReportSecurity().setOwnerID(OwnerUserId);
1263                                                 rdef.setPublic(rPublic);
1264                                                 persistReportDefinition(request, rdef);
1265                                                 return JsonResponse;
1266                                                 
1267                                         } catch (Exception ex) {
1268                                                 logger.error(EELFLoggerDelegate.errorLogger,
1269                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
1270                                                 return null;
1271                                         }                               
1272                                 }
1273
1274                         @RequestMapping(value = "/report/security/toggleUserEditAccess/{userID}", method = RequestMethod.POST)
1275                         public @ResponseBody Map<String,String> toggleUserEditAccess(
1276                                         @PathVariable("userID") String userId,
1277                                         @RequestBody String readOnly, HttpServletRequest request, HttpServletResponse response)
1278                         {
1279                                         Map<String, String> JsonResponse = new HashMap<>();
1280                                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1281                                         try {
1282                                                 String action ="";
1283                                                 JsonResponse.put("status","success");
1284                                                 if (readOnly.equals("N")) {
1285                                                         action = "Grant User Access";
1286                                                 }  else {
1287                                                         action = "Revoke User Access";                                                  
1288                                                 }                                               
1289                                                 rdef.getReportSecurity().updateUserAccess(userId, readOnly);
1290                                                 WizardSequence ws = rdef.getWizardSequence();
1291                                                 ws.performAction(action,rdef);
1292                                                 
1293                                                 return JsonResponse;
1294                                         } catch (Exception ex) {
1295                                                 logger.error(EELFLoggerDelegate.errorLogger,
1296                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
1297                                                 return null;
1298                                         }                               
1299                                 };                      
1300
1301                                 @RequestMapping(value = "/report/security/toggleRoleEditAccess/{roleID}", method = RequestMethod.POST)
1302                                 public @ResponseBody Map<String,String> toggleRoleEditAccess(
1303                                                 @PathVariable("roleID") String roleId,
1304                                                 @RequestBody String readOnly, HttpServletRequest request, HttpServletResponse response)
1305                                 {
1306                                                 Map<String, String> JsonResponse = new HashMap<String, String>();
1307                                                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1308                                                 try {
1309                                                         String action ="";
1310                                                         JsonResponse.put("status","success");
1311                                                         if (readOnly.equals("N")) {
1312                                                                 action = "Grant Role Access";
1313                                                         }  else {
1314                                                                 action = "Revoke Role Access";                                                  
1315                                                         }                                               
1316                                                         rdef.getReportSecurity().updateRoleAccess(roleId, readOnly);
1317                                                         WizardSequence ws = rdef.getWizardSequence();
1318                                                         ws.performAction(action,rdef);
1319                                                         
1320                                                         return JsonResponse;
1321                                                 } catch (Exception ex) {
1322                                                         logger.error(EELFLoggerDelegate.errorLogger,
1323                                                                         "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
1324                                                         return null;
1325                                                 }                               
1326                                         };                      
1327                                 
1328         @RequestMapping(value = { "/report/wizard/security/retrieveReportOwner" }, method = RequestMethod.GET)
1329         public @ResponseBody List<IdNameValue> getReportOwnerInList(HttpServletRequest request)
1330                         throws RaptorException {
1331                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1332
1333                 List<IdNameValue> UserList = new ArrayList<>();
1334                 List excludeValues = new java.util.ArrayList();
1335                 HttpSession session = request.getSession();
1336                 String query = Globals.getCustomizedScheduleQueryForUsers();
1337                 session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
1338                 String userId = AppUtils.getUserID(request);
1339                 session.setAttribute("LOGGED_USERID", userId);
1340                 String[] sessionParameters = Globals.getSessionParams().split(",");
1341                 String param = "";
1342                 for (int i = 0; i < sessionParameters.length; i++) {
1343                         param = (String) session.getAttribute(sessionParameters[0]);
1344                         query = Utils.replaceInString(query, "[" + sessionParameters[i].toUpperCase() + "]",
1345                                         (String) session.getAttribute(sessionParameters[i]));
1346                 }
1347                 boolean isAdmin = AppUtils.isAdminUser(request);
1348                 Vector allUsers = AppUtils.getAllUsers(query, param, isAdmin);
1349
1350                 for (Iterator iter = allUsers.iterator(); iter.hasNext();) {
1351                         IdNameValue value = (IdNameValue) iter.next();
1352
1353                         boolean exclude = false;
1354                         for (Iterator iterE = excludeValues.iterator(); iterE.hasNext();)
1355                                 if (((IdNameValue) iterE.next()).getId().equals(value.getId())) {
1356                                         exclude = true;
1357                                         break;
1358                                 } // if
1359
1360                         if (!exclude)
1361                                 UserList.add(value);
1362                 } // for
1363                 return UserList;
1364         }
1365
1366         
1367         @RequestMapping(value = { "/report/wizard/security/getReportSecurityInfo" }, method = RequestMethod.GET)
1368         public @ResponseBody Map<String,String> getReportSecurityInfo(HttpServletRequest request)
1369          {
1370                 Map<String, String> securityInfoMap = new HashMap<>();
1371                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1372                 String isPublic = Boolean.toString(rdef.isPublic()); 
1373                 String createUser = AppUtils.getUserName(rdef.getCreateID());
1374                 String createDate = rdef.getCreateDate();
1375                 String updateUser = AppUtils.getUserName(rdef.getUpdateID());
1376                 String updateDate = rdef.getUpdateDate();
1377                 String ownerId = rdef.getOwnerID();
1378                 
1379                 securityInfoMap.put("isPublic",isPublic);
1380                 securityInfoMap.put("createdUser",createUser);          
1381                 securityInfoMap.put("createdDate",createDate);          
1382                 securityInfoMap.put("updateUser",updateUser);
1383                 securityInfoMap.put("updatedDate",updateDate);
1384                 securityInfoMap.put("ownerId",ownerId);
1385                 
1386                 return securityInfoMap;
1387         }       
1388         
1389         @RequestMapping(value = { "/report/wizard/security/getReportSecurityUsers" }, method = RequestMethod.GET)
1390         public @ResponseBody List<SecurityEntry> getReportSecurityUsers(HttpServletRequest request)
1391                         throws RaptorException {
1392                 
1393                 List<SecurityEntry> reportUserMapList = new ArrayList<>();
1394                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1395                 Vector reportUsers = rdef.getReportUsers(request);
1396                 int iCount = 0;
1397                 
1398                 for(Iterator iter=reportUsers.iterator(); iter.hasNext(); iCount++) { 
1399                         Map<String, String> reportUserMap = new HashMap<String,String>();
1400                         SecurityEntry rUser = (SecurityEntry) iter.next();
1401                         reportUserMapList.add(rUser);
1402                 }
1403                 
1404                 return reportUserMapList;
1405         }               
1406         
1407         
1408         @RequestMapping(value = { "/report/wizard/security/getReportSecurityRoles" }, method = RequestMethod.GET)
1409         public @ResponseBody List<SecurityEntry> getReportSecurityRoles(HttpServletRequest request)
1410                         throws RaptorException {
1411                 
1412                 List<SecurityEntry> reportRoleList = new ArrayList<>();
1413                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1414                 Vector reportRoles = rdef.getReportRoles(request);
1415                 
1416                 for(Iterator iter=reportRoles.iterator(); iter.hasNext(); ) {
1417                         SecurityEntry rRole = (SecurityEntry) iter.next(); 
1418                         reportRoleList.add(rRole);
1419                 }
1420                 
1421                 return reportRoleList;
1422         }               
1423         
1424         
1425         @RequestMapping(value = { "/report/wizard/retrieve_def_tab_wise_data/{id}",
1426                         "/report/wizard/retrieve_def_tab_wise_data/{id}/{detailId}" }, method = RequestMethod.GET)
1427         public @ResponseBody DefinitionJSON retrieveDefTabWiseData(@PathVariable Map<String, String> pathVariables,
1428                         HttpServletRequest request, HttpServletResponse response) throws RaptorException {
1429                 ReportDefinition rdef;
1430                 ReportRuntime rr;
1431                 String tabId = "Def";
1432                 String id = "";
1433
1434                 if (pathVariables.containsKey("id")) {
1435                         id = pathVariables.get("id");
1436                 }
1437
1438                 ServletContext servletContext = request.getSession().getServletContext();
1439                 if (!Globals.isSystemInitialized()) {
1440                         Globals.initializeSystem(servletContext);
1441                 }
1442                 String copyReportEvent = (String)request.getSession().getAttribute("COPY_REPORT_EVENT");
1443                 if (tabId.equals("Def") && id.equals("InSession") || "true".equals(copyReportEvent)) {
1444                     rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1445
1446                 } else if (tabId.equals("Def") && id.equals("Create")) {
1447                         removeVariablesFromSession(request);
1448                         rdef = (new ReportHandler()).loadReportDefinition(request, "-1");
1449                         rdef.setReportType(AppConstants.RT_LINEAR);
1450
1451                 } else if (tabId.equals("Def") && AppUtils.nvl(id).length() > 0) {
1452                         rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1453                         rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
1454
1455                         if (rdef != null && !rdef.getReportID().equals(id)) {
1456                                 request.getSession().removeAttribute(AppConstants.SI_REPORT_DEFINITION);
1457                                 removeVariablesFromSession(request);
1458                                 rdef = (new ReportHandler()).loadReportDefinition(request, id);
1459                                 request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
1460                         } else if (rr != null && !rr.getReportID().equals(id)) {
1461                                 request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);
1462                                 removeVariablesFromSession(request);
1463                                 rdef = (new ReportHandler()).loadReportDefinition(request, id);
1464                                 request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
1465                         } else if (rdef == null) {
1466                                 rdef = (new ReportHandler()).loadReportDefinition(request, id);
1467                                 request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
1468                         }
1469
1470                 } else {
1471                         rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1472                 }
1473                 DefinitionJSON wizardJSON = new DefinitionJSON();
1474                 if (tabId.equals("Def")) {
1475                         wizardJSON.setTabId("Def");
1476                         wizardJSON.setTabName("Definition");
1477
1478                         wizardJSON.setReportId((rdef != null) ? rdef.getReportID() + "" : "");
1479                         wizardJSON.setReportName((rdef != null) ? rdef.getReportName() : "");
1480                         wizardJSON.setReportDescr((rdef != null) ? rdef.getReportDescr() : "");
1481                         wizardJSON.setReportType((rdef != null) ? rdef.getReportType() : AppConstants.RT_LINEAR);
1482                         wizardJSON.setDataContainerHeight((rdef != null) ? rdef.getDataContainerHeight() : "600");
1483                         wizardJSON.setDataContainerWidth((rdef != null) ? rdef.getDataContainerWidth() : "900");
1484                         wizardJSON.setAllowScheduler((rdef != null) ? rdef.getAllowSchedule() : "false");
1485
1486                         if(wizardJSON.getReportType().equals(AppConstants.RT_LINEAR)) {
1487                                 wizardJSON.setDbInfo((rdef != null) ? rdef.getDBInfo() : "");
1488                                 wizardJSON.setFormHelpText((rdef != null) ? rdef.getFormHelpText() : "");
1489                                 wizardJSON.setPageSize((rdef != null) ? rdef.getPageSize() : 50);
1490                                 List<IdNameBooleanJSON> displayArea = new ArrayList<IdNameBooleanJSON>();
1491                                 IdNameBooleanJSON idNameJSON = new IdNameBooleanJSON();
1492                                 String qMenu = "";
1493                                 for (int i = 0; i < AppUtils.getQuickLinksMenuIDs().size(); i++) {
1494                                         idNameJSON = new IdNameBooleanJSON();
1495                                         qMenu = (String) AppUtils.getQuickLinksMenuIDs().get(i);
1496                                         idNameJSON.setId(qMenu);
1497                                         idNameJSON.setName(qMenu);
1498                                         if (rdef != null && (rdef.getMenuID().equals(qMenu))) {
1499                                                 idNameJSON.setSelected(true);
1500                                         }
1501                                         displayArea.add(idNameJSON);
1502                                 }
1503                                 wizardJSON.setDisplayArea(displayArea);
1504                                 wizardJSON.setHideFormFieldsAfterRun((rdef != null) ? rdef.isHideFormFieldAfterRun() : false);
1505                                 wizardJSON.setMaxRowsInExcelCSVDownload((rdef != null) ? rdef.getMaxRowsInExcelDownload() : 500);
1506                                 wizardJSON.setFrozenColumns((rdef != null) ? rdef.getFrozenColumns() : 0);
1507                                 wizardJSON.setDataGridAlign((rdef != null) ? rdef.getDataGridAlign() : "left");
1508                                 wizardJSON.setEmptyMessage((rdef != null) ? rdef.getEmptyMessage() : "No records found");
1509                                 List<NameBooleanJSON> displayOptions = new ArrayList<NameBooleanJSON>();
1510                                 NameBooleanJSON nameBooleanJSON = new NameBooleanJSON();
1511                                 nameBooleanJSON.setName("HideFormFields");
1512                                 nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideForm() : false);
1513                                 displayOptions.add(nameBooleanJSON);
1514         
1515                                 nameBooleanJSON = new NameBooleanJSON();
1516                                 nameBooleanJSON.setName("HideChart");
1517                                 nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideChart() : false);
1518                                 displayOptions.add(nameBooleanJSON);
1519         
1520                                 nameBooleanJSON = new NameBooleanJSON();
1521                                 nameBooleanJSON.setName("HideReportData");
1522                                 nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideData() : false);
1523                                 displayOptions.add(nameBooleanJSON);
1524         
1525                                 nameBooleanJSON = new NameBooleanJSON();
1526                                 nameBooleanJSON.setName("HideExcel");
1527                                 nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideExcelIcons() : false);
1528                                 displayOptions.add(nameBooleanJSON);
1529         
1530                                 nameBooleanJSON = new NameBooleanJSON();
1531                                 nameBooleanJSON.setName("HidePdf");
1532                                 nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHidePDFIcons() : false);
1533                                 displayOptions.add(nameBooleanJSON);
1534         
1535                                 wizardJSON.setDisplayOptions(displayOptions);
1536         
1537                                 wizardJSON.setRuntimeColSortDisabled((rdef != null) ? rdef.isRuntimeColSortDisabled() : false);
1538                                 wizardJSON.setNumFormCols((rdef != null) ? rdef.getNumFormColsAsInt() : 1);
1539                                 wizardJSON.setReportTitle((rdef != null) ? rdef.getReportTitle() : "");
1540                                 wizardJSON.setReportSubTitle((rdef != null) ? rdef.getReportSubTitle() : "");
1541                                 
1542                                 
1543                                 String schemaSql = Globals.getRemoteDbSchemaSql();
1544                                 DataSet ds = null;
1545                                 ArrayList<IdNameBooleanJSON> dbInfoList = new ArrayList<IdNameBooleanJSON>();
1546                                  try {
1547                                         ds = DbUtils.executeQuery(schemaSql);
1548         
1549                                         String prefix = "", desc = "";
1550                                         
1551                                         for (int i = 0; i < ds.getRowCount(); i++) {
1552                                                 IdNameBooleanJSON dBNameJSON = new IdNameBooleanJSON();
1553                                                 dBNameJSON.setId(ds.getItem(i, 0));
1554                                                 dBNameJSON.setName(ds.getItem(i, 0));
1555                                                 dBNameJSON.setSelected(false);
1556                                                 dbInfoList.add(dBNameJSON);
1557                                         }
1558                         }
1559                         catch (Exception e) {}
1560                                 wizardJSON.setDbInfoList(dbInfoList);
1561                                 
1562                                 /*Robert add*/
1563                                 wizardJSON.setOneTimeRec((rdef != null) ? rdef.getIsOneTimeScheduleAllowed() : "false");
1564                                 wizardJSON.setHourlyRec((rdef != null) ? rdef.getIsHourlyScheduleAllowed() : "false");
1565                                 wizardJSON.setDailyRec((rdef != null) ? rdef.getIsDailyScheduleAllowed() : "false");
1566                                 wizardJSON.setDailyMFRec((rdef != null) ? rdef.getIsDailyMFScheduleAllowed() : "false");
1567                                 wizardJSON.setWeeklyRec((rdef != null) ? rdef.getIsWeeklyScheduleAllowed() : "false");
1568                                 wizardJSON.setMonthlyRec((rdef != null) ? rdef.getIsMonthlyScheduleAllowed() : "false");
1569                                 wizardJSON.setSizedByContent((rdef != null) ? rdef.getSizedByContentOption() : "false");
1570                                 wizardJSON.setRepDefType(rdef.getReportDefType());
1571                         } else if(wizardJSON.getReportType().equals(AppConstants.RT_DASHBOARD)){
1572                                 wizardJSON.setDashboardLayoutHTML((rdef != null) ? rdef.getCustomReport().getDashboardLayoutHTML() : null);
1573                                 wizardJSON.setDashboardLayoutJSON((rdef != null) ? rdef.getCustomReport().getDashboardLayoutJSON() : null);
1574                                 wizardJSON.setDashboardReports((rdef != null) ? rdef.getCustomReport().getDashBoardReports() : null);
1575                         }
1576                 }
1577
1578                 ObjectMapper mapper = new ObjectMapper();
1579                 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
1580                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1581
1582                 return wizardJSON;
1583
1584         }
1585
1586         @RequestMapping(value = "/report/wizard/retrieve_data/{validate}", method = RequestMethod.POST)
1587         public @ResponseBody RaptorResponse retrieveDataForGivenQuery(@PathVariable("validate") boolean validate,
1588                         @RequestBody QueryJSON queryJSON, HttpServletRequest request, HttpServletResponse response)
1589                         throws RaptorException {
1590                 RaptorResponse raptorResponse = new RaptorResponse();
1591                 String sql = queryJSON.getQuery();
1592                 String jsonInString = "";
1593                 
1594                 ServletContext servletContext = request.getSession().getServletContext();
1595                 if (!Globals.isSystemInitialized()) {
1596                         Globals.initializeSystem(servletContext);
1597                 }
1598
1599                 ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1600                 if (rdef == null) {
1601                         ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
1602                         errorJSONRuntime.setErrormessage("Report Definition is not in session;");
1603                         errorJSONRuntime.setStacktrace("");
1604
1605                         ObjectMapper mapper = new ObjectMapper();
1606                         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
1607                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1608
1609                         try {
1610                                 jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
1611                                 raptorResponse.data().put("elements", jsonInString);
1612                                 return raptorResponse;
1613                         } catch (Exception ex1) {
1614                                 logger.error(EELFLoggerDelegate.errorLogger,
1615                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex1);
1616                         }
1617                 } else {
1618                         if (!sql.trim().toUpperCase().startsWith("SELECT")) {
1619                                 ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
1620                                 errorJSONRuntime.setErrormessage("Invalid statement - the SQL must start with the keyword SELECT");
1621                                 errorJSONRuntime.setStacktrace("SQL Error");
1622                                 ObjectMapper mapper = new ObjectMapper();
1623                                 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
1624                                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1625
1626                                 try {
1627                                         jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
1628                                         raptorResponse.data().put("elements", jsonInString);
1629                                         return raptorResponse;
1630
1631                                 } catch (Exception ex) {
1632                                         logger.error(EELFLoggerDelegate.errorLogger,
1633                                                         "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
1634                                 }
1635                         } else {
1636                                 DataSet ds = null;
1637                                 String remoteDb = request.getParameter("remoteDbPrefix");
1638                                 // comment below two lines to test
1639                                 String remoteDbPrefix = (remoteDb != null && !remoteDb.equalsIgnoreCase("null")) ? remoteDb
1640                                                 : rdef.getDBInfo();
1641                                 String userId = AppUtils.getUserID(request);
1642
1643                                 sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId);
1644                                 sql = Utils.replaceInString(sql, "[USERID]", userId);
1645                                 String[] reqParameters = Globals.getRequestParams().split(",");
1646                                 String[] sessionParameters = Globals.getSessionParams().split(",");
1647                                 javax.servlet.http.HttpSession session = request.getSession();
1648                                 logger.debug(EELFLoggerDelegate.debugLogger, ("B4 testRunSQL " + sql));
1649                                 if (request != null) {
1650                                         for (int i = 0; i < reqParameters.length; i++) {
1651                                                 if (!reqParameters[i].startsWith("ff"))
1652                                                         sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase() + "]",
1653                                                                         ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(),request.getParameter(reqParameters[i].toUpperCase())));
1654                                                 else
1655                                                                                                                 sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase() + "]",
1656                                                                         ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(),request.getParameter(reqParameters[i])));
1657                                         }
1658                                 }
1659                                 if (session != null) {
1660                                         for (int i = 0; i < sessionParameters.length; i++) {
1661                                                 logger.debug(EELFLoggerDelegate.debugLogger, (" Session " + " sessionParameters[i] "
1662                                                                 + sessionParameters[i] + " " + (String) session.getAttribute(sessionParameters[i])));
1663                                                 sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase() + "]",
1664                                                                 (String) session.getAttribute(sessionParameters[i]));
1665                                         }
1666                                 }
1667                                 logger.debug(EELFLoggerDelegate.debugLogger, ("After testRunSQL " + sql));
1668                                 try {
1669
1670                                         response.setContentType("application/json");
1671                                         ds = ConnectionUtils.getDataSet(sql, rdef.getDBInfo(), true);
1672
1673                                         QueryResultJSON queryResultJSON = new QueryResultJSON();
1674                                         queryResultJSON.setQuery(queryJSON.getQuery());
1675                                         String query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
1676                                         rdef.parseReportSQL(query,validate);
1677                                         queryResultJSON.setQuery(query);
1678
1679                                         queryResultJSON.setTotalRows(ds.getRowCount());
1680
1681                                         Map<String, String> dvJSON;
1682                                         ArrayList<String> colList = new ArrayList<>();
1683                                         ArrayList<Map<String, String>> reportDataRows = new ArrayList<>();
1684                                         if (!ds.isEmpty()) {
1685
1686                                                 for (int i = 0; i < ds.getColumnCount(); i++) {
1687                                                         colList.add(ds.getColumnName(i));
1688                                                 }
1689                                                 queryResultJSON.setReportDataColumns(colList);
1690                                                 if (queryResultJSON.getTotalRows() > 0) {
1691                                                         for (int r = 0; r < Math.min(ds.getRowCount(), 100); r++) {
1692                                                                 dvJSON = new HashMap<>();
1693                                                                 for (int c = 0; c < ds.getColumnCount(); c++) {
1694                                                                         try {
1695                                                                                 dvJSON.put(ds.getColumnName(c), ds.getString(r, c));
1696                                                                         } catch (Exception ex) {
1697                                                                                 logger.error(EELFLoggerDelegate.errorLogger,
1698                                                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].",
1699                                                                                                 ex);
1700                                                                         }
1701                                                                 }
1702                                                                 reportDataRows.add(dvJSON);
1703
1704                                                         }
1705                                                 }
1706
1707                                         }
1708                                         queryResultJSON.setReportDataRows(reportDataRows);
1709                                         ObjectMapper mapper = new ObjectMapper();
1710                                         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
1711                                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1712                                         if (validate) {
1713                                                 query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
1714                                                 request.setAttribute("sqlValidated", "N");
1715                                                 rdef.parseReportSQL(query);
1716                                                 request.setAttribute("sqlValidated", "Y");
1717                                                 persistReportDefinition(request, rdef);
1718
1719                                         }
1720                                         try {
1721                                                 jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(queryResultJSON);
1722                                                 raptorResponse.data().put("elements", jsonInString);
1723                                                 return raptorResponse;
1724
1725                                         } catch (Exception ex) {
1726                                                 logger.error(EELFLoggerDelegate.errorLogger,
1727                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery]. RaptorException: ",
1728                                                                 ex);
1729                                         }
1730                                 } catch (ReportSQLException ex) {
1731                                         ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
1732                                         if (sql.contains("[")) {
1733                                                 errorJSONRuntime.setErrormessage(
1734                                                                 "Formfield information is present in the query, hence couldn't execute");
1735                                                 errorJSONRuntime
1736                                                                 .setStacktrace("Formfield information is present in the query, hence couldn't execute");
1737                                                 if (validate) {
1738                                                         String query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
1739                                                         request.setAttribute("sqlValidated", "N");
1740                                                         rdef.parseReportSQL(query);
1741                                                         request.setAttribute("sqlValidated", "Y");
1742                                                         persistReportDefinition(request, rdef);
1743
1744                                                 }
1745
1746                                         } else {
1747                                                 errorJSONRuntime.setErrormessage(ex.getMessage());
1748                                                 errorJSONRuntime.setStacktrace(getStackTrace(ex));
1749                                         }
1750                                         ObjectMapper mapper = new ObjectMapper();
1751                                         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
1752                                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1753
1754                                         try {
1755                                                 jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
1756                                                 raptorResponse.data().put("elements", jsonInString);
1757                                                 return raptorResponse;
1758
1759                                         } catch (Exception ex1) {
1760                                                 logger.error(EELFLoggerDelegate.errorLogger,
1761                                                                 "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex1);
1762                                         }
1763                                 }
1764                                 if (validate) {
1765                                         String query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
1766                                         request.setAttribute("sqlValidated", "N");
1767                                         rdef.parseReportSQL(query);
1768                                         request.setAttribute("sqlValidated", "Y");
1769                                         persistReportDefinition(request, rdef);
1770
1771                                 }
1772
1773                         }
1774                 }
1775                 raptorResponse.data().put("elements", jsonInString);
1776                 return raptorResponse;
1777
1778         }
1779         
1780         
1781         @RequestMapping(value = "/report/wizard/get_report_log/{reportID}", method = RequestMethod.GET)
1782         public @ResponseBody ArrayList<ReportLogEntry> getLogs(@PathVariable("reportID") String reportId, HttpServletRequest request,
1783                         HttpServletResponse ReportLogEntry) {
1784                 ArrayList<ReportLogEntry> arrayList = new ArrayList<>();
1785                 try {
1786                         Vector<ReportLogEntry> v = ReportLoader.loadReportLogEntries(reportId);
1787                         for(ReportLogEntry r:v ){
1788                                 arrayList.add(r);
1789                         }
1790                 } catch (RaptorException e) {
1791                         logger.error(EELFLoggerDelegate.errorLogger,
1792                                         "RaptorControllerAsync getLogs.", e);
1793                 }
1794                 return arrayList;
1795         }
1796
1797         @RequestMapping(value = "save_chart", method = RequestMethod.POST)
1798         public void reportChartReceive(@RequestBody ChartJSON chartJSON, HttpServletRequest request,
1799                         HttpServletResponse response) throws IOException {
1800                 //ReportRuntime reportRuntime;
1801                 //reportRuntime = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); // changing
1802                 ReportDefinition reportDefn;
1803                 reportDefn = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);                                                                                                                                                                                                   // session
1804                                                                                                                                                                                                                         // to
1805                                                                                                                                                                                                                         // request
1806                 String reportID = request.getParameter("c_master");
1807         /*      if (reportRuntime == null && AppUtils.nvl(reportID).length() > 0) {
1808                         try {
1809                                 ReportHandler rh = new ReportHandler();
1810                                 reportRuntime = rh.loadReportRuntime(request, reportID);
1811                         } catch (RaptorException ex) {
1812                                 logger.error(EELFLoggerDelegate.errorLogger,
1813                                                 "[Controller.processRequest]Invalid raptor action [reportChartReceive].", ex);
1814                         }
1815                 }*/
1816
1817                 if (reportDefn != null) {
1818                         String chartType = chartJSON.getChartType();
1819                         reportDefn.setChartType(chartJSON.getChartType());
1820                         reportDefn.setChartAnimate(chartJSON.isAnimation());
1821                         reportDefn.setChartWidth(chartJSON.getWidth());
1822                         reportDefn.setChartHeight(chartJSON.getHeight());
1823                         reportDefn.setShowChartTitle(chartJSON.isShowTitle());
1824
1825                         String domainAxis = null;
1826                         domainAxis = chartJSON.getDomainAxis();
1827
1828                         List<DataColumnType> reportCols = reportDefn.getAllColumns();
1829
1830                         for (Iterator<DataColumnType> iter = reportCols.iterator(); iter.hasNext();) {
1831                                 DataColumnType dct = (DataColumnType) iter.next();
1832                                 if (dct.getColId().equals(domainAxis)) {
1833                                         dct.setColOnChart(AppConstants.GC_LEGEND);
1834                                 } else {
1835                                         dct.setColOnChart(null);
1836                                 }
1837                         }
1838
1839                         CategoryAxisJSON categoryAxisJSON = chartJSON.getCategoryAxisJSON();
1840                         String categoryAxis = null;
1841
1842                         categoryAxis = (categoryAxisJSON != null ? categoryAxisJSON.getValue() : "");
1843
1844                         reportCols = reportDefn.getAllColumns();
1845
1846                         for (Iterator<DataColumnType> iter = reportCols.iterator(); iter.hasNext();) {
1847                                 DataColumnType dct = (DataColumnType) iter.next();
1848                                 if (dct.getColId().equals(categoryAxis)) {
1849                                         dct.setChartSeries(true);
1850                                 } else {
1851                                         dct.setChartSeries(false);
1852                                 }
1853                         }
1854
1855                         ArrayList<RangeAxisJSON> rangeAxisList = chartJSON.getRangeAxisList();
1856                         int r = 0;
1857                         HashSet<String> removeRangeAxisMap = new HashSet<>();
1858                         for(RangeAxisJSON rangeAxis:chartJSON.getRangeAxisRemoveList()){                                
1859                                 removeRangeAxisMap.add(rangeAxis.getRangeAxis());
1860                         }
1861                         for (int i = 0; i < rangeAxisList.size(); i++) {
1862                                 RangeAxisJSON rangeAxisJSON = rangeAxisList.get(i);
1863                                 String rangeAxis = rangeAxisJSON.getRangeAxis();
1864                                 String rangeYAxis = AppUtils.nvl(rangeAxisJSON.getRangeYAxis());
1865                                 String rangeChartGroup = AppUtils.nvl(rangeAxisJSON.getRangeChartGroup());
1866                                 String rangeColor = AppUtils.nvl(rangeAxisJSON.getRangeColor());
1867                                 String rangeLineType = AppUtils.nvl(rangeAxisJSON.getRangeLineType());
1868
1869                                 rangefor: for (Iterator<DataColumnType> iterator = reportCols.iterator(); iterator.hasNext();) {
1870                                         DataColumnType dct = (DataColumnType) iterator.next();
1871                                         if (dct.getColId().equals(rangeAxis)) {
1872                                                 if(removeRangeAxisMap.contains(rangeAxis))
1873                                                         dct.setChartSeq(-1); // if we set it to -1, means this range axis will not be included
1874                                                 else
1875                                                         dct.setChartSeq(++r);
1876                                                 
1877                                                 if (!dct.getColId().equals(domainAxis)) {
1878                                                         dct.setColOnChart("0");
1879                                                 }else{
1880                                                         dct.setChartSeq(-1);
1881                                                 }
1882                                                 dct.setYAxis(rangeYAxis); // +"|"+dct.getColId());
1883                                                 dct.setChartGroup(rangeChartGroup); // +"|"+dct.getColId());
1884                                                 dct.setChartColor(rangeColor);
1885                                                 dct.setChartLineType(rangeLineType);
1886
1887                                                 if (chartType.equals(AppConstants.GT_ANNOTATION_CHART)
1888                                                                 || chartType.equals(AppConstants.GT_FLEX_TIME_CHARTS)) {
1889                                                         if (rangeAxisJSON.isShowAsArea()) {
1890                                                                 dct.setIsRangeAxisFilled(true);
1891                                                         } else {
1892                                                                 dct.setIsRangeAxisFilled(false);
1893                                                         }
1894                                                 }
1895                                                 break rangefor;
1896                                         }
1897                                 }
1898
1899                         }
1900                         reportDefn.setChartLeftAxisLabel(chartJSON.getPrimaryAxisLabel());
1901                         reportDefn.setChartRightAxisLabel(chartJSON.getSecondaryAxisLabel());
1902
1903                         reportDefn.setRangeAxisLowerLimit(chartJSON.getMinRange());
1904                         reportDefn.setRangeAxisUpperLimit(chartJSON.getMaxRange());
1905
1906                         if (chartType.equals(AppConstants.GT_ANNOTATION_CHART)
1907                                         || chartType.equals(AppConstants.GT_FLEX_TIME_CHARTS)) {
1908                                 if (chartJSON.getFlexTimeSeriesChartOptions() != null) {
1909                                         reportDefn.setZoomIn(chartJSON.getFlexTimeSeriesChartOptions().getZoomIn());
1910                                         reportDefn.setTimeAxisType(chartJSON.getFlexTimeSeriesChartOptions().getTimeAxisType());
1911                                 }
1912
1913                         }
1914
1915                         if (chartType.equals(AppConstants.GT_TIME_SERIES)) {
1916                                 if (chartJSON.getTimeSeriesChartOptions() != null) {
1917                                         reportDefn.setTimeSeriesRender(chartJSON.getTimeSeriesChartOptions().getLineChartRenderer());
1918                                         reportDefn.setShowXAxisLabel(chartJSON.getTimeSeriesChartOptions().isShowXAxisLabel());
1919                                         reportDefn.setAddXAxisTickers(chartJSON.getTimeSeriesChartOptions().isAddXAxisTicker());
1920                                         reportDefn.setTimeAxis(chartJSON.getTimeSeriesChartOptions().isNonTimeAxis());
1921                                         reportDefn.setMultiSeries(chartJSON.getTimeSeriesChartOptions().isMultiSeries());
1922                                 }
1923
1924                         }
1925
1926                         if (chartType.equals(AppConstants.GT_BAR_3D)) {
1927                                 if (chartJSON.getBarChartOptions() != null) {
1928                                         reportDefn.setChartOrientation(
1929                                                         chartJSON.getBarChartOptions().isVerticalOrientation() ? "vertical" : "horizontal");
1930                                         reportDefn.setChartStacked(chartJSON.getBarChartOptions().isStackedChart());
1931                                         reportDefn.setBarControls(chartJSON.getBarChartOptions().isDisplayBarControls());
1932                                         reportDefn.setXAxisDateType(chartJSON.getBarChartOptions().isxAxisDateType());
1933                                         reportDefn.setLessXaxisTickers(chartJSON.getBarChartOptions().isMinimizeXAxisTickers());
1934                                         reportDefn.setTimeAxis(chartJSON.getBarChartOptions().isTimeAxis());
1935                                         reportDefn.setLogScale(chartJSON.getBarChartOptions().isyAxisLogScale());
1936                                 }
1937                         }
1938
1939                         reportDefn.setLegendLabelAngle(chartJSON.getCommonChartOptions().getLegendLabelAngle());
1940                         reportDefn.setLegendPosition(chartJSON.getCommonChartOptions().getLegendPosition());
1941                         reportDefn.setChartLegendDisplay(chartJSON.getCommonChartOptions().isHideLegend() ? "Y" : "N");
1942                         reportDefn.setAnimateAnimatedChart(chartJSON.getCommonChartOptions().isAnimateAnimatedChart());
1943
1944                         reportDefn.setTopMargin(chartJSON.getCommonChartOptions().getTopMargin());
1945                         reportDefn.setBottomMargin(chartJSON.getCommonChartOptions().getBottomMargin());
1946                         reportDefn.setLeftMargin(chartJSON.getCommonChartOptions().getLeftMargin());
1947                         reportDefn.setRightMargin(chartJSON.getCommonChartOptions().getRightMargin());
1948
1949                         for (Iterator<DataColumnType> iterator = reportCols.iterator(); iterator.hasNext();) {
1950                                 DataColumnType dct = (DataColumnType) iterator.next();
1951                                 if (!(AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND)
1952                                                 || (dct.getChartSeq() != null && dct.getChartSeq() > 0) || dct.isChartSeries())) {
1953                                         dct.setChartSeq(-1);
1954                                         dct.setChartColor(null);
1955                                         dct.setColOnChart(null);
1956                                         dct.setCreateInNewChart(false);
1957                                         dct.setChartGroup(null);
1958                                         dct.setYAxis(null);
1959                                 }
1960                         }
1961
1962                         try {
1963                                 //reportRuntime.persistLinearReport(request);
1964                                 //reportRuntime.persistReport(request);
1965                 persistReportDefinition(request, reportDefn);                   
1966                         } catch (Exception ex) {
1967                                 logger.error(EELFLoggerDelegate.errorLogger,
1968                                                 "[Controller.processRequest]Invalid raptor action [reportChartReceive].", ex);
1969                         }
1970                 }
1971
1972         }
1973
1974         public String getViewName() {
1975                 return viewName;
1976         }
1977
1978         public void setViewName(String viewName) {
1979                 this.viewName = viewName;
1980         }
1981
1982         public String nvl(String s) {
1983                 return (s == null) ? "" : s;
1984         }
1985
1986         public String nvl(String s, String sDefault) {
1987                 return nvl(s).equals("") ? sDefault : s;
1988         }
1989
1990         public static String getStackTrace(Throwable aThrowable) {
1991                 Writer result = new StringWriter();
1992                 PrintWriter printWriter = new PrintWriter(result);
1993                 aThrowable.printStackTrace(printWriter);
1994                 return result.toString();
1995         }
1996
1997         public void persistReportDefinition(HttpServletRequest request, ReportDefinition rdef) throws RaptorException {
1998                 ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
1999                 if (rr != null && rr.getReportID().equals(rdef.getReportID()))
2000                         request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);
2001                 rdef.persistReport(request);
2002         } // persistReportDefinition
2003
2004         // Remove from session
2005         private void removeVariablesFromSession(HttpServletRequest request) {
2006                 HttpSession session = request.getSession();
2007                 session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST);
2008                 session.removeAttribute(AppConstants.DRILLDOWN_INDEX);
2009                 session.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX);
2010                 session.removeAttribute(AppConstants.SI_BACKUP_FOR_REP_ID);
2011                 session.removeAttribute(AppConstants.SI_COLUMN_LOOKUP);
2012                 session.removeAttribute(AppConstants.SI_DASHBOARD_REP_ID);
2013                 session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP);
2014                 session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME);
2015                 session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP);
2016                 session.removeAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP);
2017                 session.removeAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP);
2018                 session.removeAttribute(AppConstants.SI_DATA_SIZE_FOR_TEXTFIELD_POPUP);
2019                 session.removeAttribute(AppConstants.SI_MAP);
2020                 session.removeAttribute(AppConstants.SI_MAP_OBJECT);
2021                 session.removeAttribute(AppConstants.SI_REPORT_DEFINITION);
2022                 session.removeAttribute(AppConstants.SI_REPORT_RUNTIME);
2023                 session.removeAttribute(AppConstants.SI_REPORT_RUN_BACKUP);
2024                 session.removeAttribute(AppConstants.SI_REPORT_SCHEDULE);
2025                 session.removeAttribute(AppConstants.RI_REPORT_DATA);
2026                 session.removeAttribute(AppConstants.RI_CHART_DATA);
2027                 session.removeAttribute(AppConstants.SI_FORMFIELD_INFO);
2028                 session.removeAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO);
2029                 session.removeAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP);
2030                 session.removeAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP);
2031                 Enumeration<String> enum1 = session.getAttributeNames();
2032                 String attributeName = "";
2033                 while (enum1.hasMoreElements()) {
2034                         attributeName = enum1.nextElement();
2035                         if (attributeName.startsWith("parent_")) {
2036                                 session.removeAttribute(attributeName);
2037                         }
2038                 }
2039         }
2040
2041 }