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