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