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