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