Fixed Single Quote issue with Form Fields
[portal/sdk.git] / ecomp-sdk / epsdk-analytics / src / main / java / org / onap / portalsdk / analytics / model / base / ReportWrapper.java
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.model.base;
39
40 import java.io.Serializable;
41 import java.io.StringWriter;
42 import java.util.ArrayList;
43 import java.util.Calendar;
44 import java.util.Collections;
45 import java.util.GregorianCalendar;
46 import java.util.HashMap;
47 import java.util.Iterator;
48 import java.util.List;
49 import java.util.Map;
50 import java.util.Map.Entry;
51 import java.util.Set;
52 import java.util.StringTokenizer;
53 import java.util.TreeSet;
54 import java.util.Vector;
55 import java.util.regex.Matcher;
56 import java.util.regex.Pattern;
57
58 import javax.servlet.http.HttpServletRequest;
59 import javax.xml.bind.JAXBContext;
60 import javax.xml.bind.JAXBException;
61 import javax.xml.bind.Marshaller;
62 import javax.xml.bind.Unmarshaller;
63 import javax.xml.datatype.DatatypeConfigurationException;
64 import javax.xml.datatype.DatatypeFactory;
65 import javax.xml.transform.stream.StreamResult;
66
67 import org.onap.portalsdk.analytics.error.RaptorException;
68 import org.onap.portalsdk.analytics.error.RaptorRuntimeException;
69 import org.onap.portalsdk.analytics.error.UserDefinedException;
70 import org.onap.portalsdk.analytics.model.DataCache;
71 import org.onap.portalsdk.analytics.model.ReportLoader;
72 import org.onap.portalsdk.analytics.model.definition.TableSource;
73 import org.onap.portalsdk.analytics.model.runtime.FormField;
74 import org.onap.portalsdk.analytics.model.runtime.ReportParamValues;
75 import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
76 import org.onap.portalsdk.analytics.system.AppUtils;
77 import org.onap.portalsdk.analytics.system.ConnectionUtils;
78 import org.onap.portalsdk.analytics.system.DbUtils;
79 import org.onap.portalsdk.analytics.system.Globals;
80 import org.onap.portalsdk.analytics.util.AppConstants;
81 import org.onap.portalsdk.analytics.util.CachingUtils;
82 import org.onap.portalsdk.analytics.util.DataSet;
83 import org.onap.portalsdk.analytics.util.RemDbInfo;
84 import org.onap.portalsdk.analytics.util.SQLCorrector;
85 import org.onap.portalsdk.analytics.util.Utils;
86 import org.onap.portalsdk.analytics.xmlobj.ChartAdditionalOptions;
87 import org.onap.portalsdk.analytics.xmlobj.ChartDrillFormfield;
88 import org.onap.portalsdk.analytics.xmlobj.ChartDrillOptions;
89 import org.onap.portalsdk.analytics.xmlobj.ColFilterList;
90 import org.onap.portalsdk.analytics.xmlobj.ColFilterType;
91 import org.onap.portalsdk.analytics.xmlobj.CustomReportType;
92 import org.onap.portalsdk.analytics.xmlobj.DashboardEditorList;
93 import org.onap.portalsdk.analytics.xmlobj.DashboardReports;
94 import org.onap.portalsdk.analytics.xmlobj.DashboardReportsNew;
95 import org.onap.portalsdk.analytics.xmlobj.DataColumnList;
96 import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
97 import org.onap.portalsdk.analytics.xmlobj.DataSourceList;
98 import org.onap.portalsdk.analytics.xmlobj.DataSourceType;
99 import org.onap.portalsdk.analytics.xmlobj.DataminingOptions;
100 import org.onap.portalsdk.analytics.xmlobj.FormFieldList;
101 import org.onap.portalsdk.analytics.xmlobj.FormFieldType;
102 import org.onap.portalsdk.analytics.xmlobj.FormatList;
103 import org.onap.portalsdk.analytics.xmlobj.FormatType;
104 import org.onap.portalsdk.analytics.xmlobj.JavascriptItemType;
105 import org.onap.portalsdk.analytics.xmlobj.JavascriptList;
106 import org.onap.portalsdk.analytics.xmlobj.Marker;
107 import org.onap.portalsdk.analytics.xmlobj.ObjectFactory;
108 import org.onap.portalsdk.analytics.xmlobj.PDFAdditionalOptions;
109 import org.onap.portalsdk.analytics.xmlobj.PredefinedValueList;
110 import org.onap.portalsdk.analytics.xmlobj.ReportMap;
111 import org.onap.portalsdk.analytics.xmlobj.Reports;
112 import org.onap.portalsdk.analytics.xmlobj.SemaphoreList;
113 import org.onap.portalsdk.analytics.xmlobj.SemaphoreType;
114 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
115 import org.onap.portalsdk.core.util.SecurityCodecUtil;
116 import org.owasp.esapi.ESAPI;
117 import org.springframework.beans.factory.annotation.Autowired;
118 import org.springframework.stereotype.Component;
119
120 /**<HR/>
121  * This class is part of <B><I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I></B><BR/>
122  * <HR/>
123  *
124  * --------------------------------------------------------------------------------------------------<BR/>
125  * <B>ReportWrapper.java</B> - This is the base class for the RAPTOR. This involves in creating,<BR/>
126  * modifying, running RAPTOR reports.<BR/>
127  * --------------------------------------------------------------------------------------------------<BR/>
128  *
129  *
130  * <U>Change Log</U><BR/><BR/>
131  *
132  * 31-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> All the elements in the meta xml is copied to the target reports. </LI></UL>
133  * 18-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>
134  * 27-Jul-2009 : Version 8.4 (Sundar); <UL><LI> verifySQLBasedReportAccess method checks for Admin user instead of super user. </LI></UL>
135  * 09-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Bug due to parsing and removing formfields from "and" is bulletproofed to the right "and" to which the formfield is associated. </LI></UL>
136  * 08-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Bug due to parsing and removing formfields when there is no parameter for Daytona specific database is resolved. </LI></UL>
137  * 29-Jun-2009 : Version 8.4 (Sundar); <UL><LI> isLastSeriesALineChart() and setLastSeriesALineChart(String value) method have been added for the Bar Chart enhancements. </LI></UL>
138  * 23-Jun-2009 : Version 8.4 (Sundar); <UL><LI> check for cr.getChartAdditionalOptions() for null value is added.</LI></UL>
139  * 22-Jun-2009 : Version 8.4 (Sundar); <UL><LI> Wrapper functions to call JAXB were added. These Wrapper
140  * functions are related to the Pareto chart, Time Difference Chart, Multiple Pie Chart and generic Chart Options.</LI></UL>
141  *
142  */
143
144 @Component
145 public class ReportWrapper extends org.onap.portalsdk.analytics.RaptorObject implements Serializable{
146
147     private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportWrapper.class);
148
149         protected static RemDbInfo remDbInfo;
150
151         @SuppressWarnings("static-access")
152         @Autowired
153     public void setRemDbInfo(RemDbInfo remDbInfo) {
154                 this.remDbInfo = remDbInfo;
155         }
156
157     protected CustomReportType cr = null;
158
159     protected Vector allColumns = null;
160
161     protected Vector allVisibleColumns = null;
162
163     protected Vector allFilters = null;
164
165     protected String generatedSQL = null;
166
167     protected String generatedChartSQL = null;
168
169         protected String wholeSQL = null;
170
171
172     protected String reportID = null;
173
174     protected String menuID = "";
175
176     protected boolean menuApproved = false;
177
178     protected String reportDefType = "";
179
180     protected ReportSecurity reportSecurity = null;
181
182     protected String reportSQLWithRowNum = null;
183
184     protected String reportSQLOnlyFirstPart = null;
185
186     public ReportWrapper() {
187         super();
188     }
189         
190     private ReportWrapper(CustomReportType cr, String reportID, ReportSecurity reportSecurity) {
191         super();
192
193         if (reportID == null)
194             reportID = "-1";
195
196         this.cr = cr;
197         this.reportID = reportID;
198
199         this.reportSecurity = reportSecurity;
200         }
201
202     public ReportWrapper(ReportWrapper rw) {
203                 this(rw.getCustomReport(), 
204                 rw.getReportID(), rw.reportSecurity);
205
206         this.menuID = rw.getMenuID();
207         this.menuApproved = rw.isMenuApproved();
208
209         this.reportDefType = rw.getReportDefType();
210         }
211     public ReportWrapper(CustomReportType cr, String reportID, String ownerID, String createID,
212             String createDate, String updateID, String updateDate, String menuID,
213             boolean menuApproved) throws RaptorException {
214         this(cr, reportID, null);
215
216         if (ownerID == null && !"-1".equals(reportID)) {
217             try {
218
219                 String rSql = Globals.getReportWrapperFormat();
220                 rSql = rSql.replace("[Globals.getTimeFormat()]", Globals.getTimeFormat());
221                 rSql = rSql.replace("[reportID]", reportID);
222
223                 DataSet ds = DbUtils
224                         .executeQuery(rSql);
225
226                 ownerID = ds.getString(0, 0);
227                 createID = ds.getString(0, 1);
228                 createDate = ds.getString(0, 2);
229                 updateID = ds.getString(0, 3);
230                 updateDate = ds.getString(0, 4);
231                 menuID = nvl(ds.getString(0, 5));
232                 menuApproved = nvl(ds.getString(0, 6)).equals("Y");
233             } catch (Exception e) {
234                 String eMsg = "ReportWrapper.ReportWrapper: Unable to load report record details. Exception: ";
235                 logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] " + eMsg), e);
236                 throw new RaptorRuntimeException(eMsg);
237             }
238         }
239         this.menuID = nvl(menuID);
240         this.menuApproved = menuApproved;
241
242         if (!"-1".equals(reportID)) {
243             updateReportDefType();
244         }
245
246         reportSecurity = new ReportSecurity(reportID, ownerID, createID, createDate, updateID,
247                 updateDate, cr.isPublic());
248     } // ReportWrapper
249
250     public CustomReportType getCustomReport() {
251         return cr;
252     }
253
254     public String getReportID() {
255         return reportID;
256     }
257
258     public String getMenuID() {
259         return menuID;
260     }
261
262     public boolean checkMenuIDSelected(String chkMenuID) {
263         return ("|" + menuID + "|").indexOf("|" + chkMenuID + "|") >= 0;
264     }
265
266     public boolean isMenuApproved() {
267         return menuApproved;
268     }
269
270     public String getReportDefType() {
271         return reportDefType;
272     }
273
274     public void setMenuID(String menuID) {
275         this.menuID = menuID;
276     }
277
278     public void setMenuApproved(boolean menuApproved) {
279         this.menuApproved = menuApproved;
280     }
281
282     public void setReportDefType(String reportDefType) {
283         this.reportDefType = reportDefType;
284     }
285
286     public void updateReportDefType() {
287         this.reportDefType = (nvl(cr.getReportSQL()).length() > 0)
288                 ? ((cr.getDataminingOptions() != null && nvl(cr.getDataminingOptions().getClassifier()).length() > 0)
289                         ? AppConstants.RD_SQL_BASED_DATAMIN
290                         : AppConstants.RD_SQL_BASED)
291                 : AppConstants.RD_VISUAL;
292     }
293
294     public String getJavascriptElement() {
295         return cr.getJavascriptElement();
296     }
297
298     public int getPageSize() {
299         return cr.getPageSize() == null ? 50 : cr.getPageSize();
300     }
301
302     public int getMaxRowsInExcelDownload() {
303         return cr.getMaxRowsInExcelDownload() == null ? 500 : cr.getMaxRowsInExcelDownload();
304     }
305
306     public boolean isDisplayFolderTree() {
307         return cr.isDisplayFolderTree() != null ? cr.isDisplayFolderTree().booleanValue() : false;
308     }
309
310     public boolean isHideFormFieldAfterRun() {
311         return cr.isHideFormFieldAfterRun() != null ? cr.isHideFormFieldAfterRun().booleanValue() : false;
312     }
313
314     public void setHideFormFieldAfterRun(boolean hideFormFieldAfterRun) {
315         cr.setHideFormFieldAfterRun(hideFormFieldAfterRun);
316     }
317
318     public boolean isReportInNewWindow() {
319         return cr.isReportInNewWindow() != null ? cr.isReportInNewWindow().booleanValue() : false;
320     }
321
322     public String getReportType() {
323         return cr.getReportType();
324     }
325
326     public String getReportName() {
327         return cr.getReportName();
328     }
329
330     public String getDBInfo() {
331         return cr.getDbInfo();
332     }
333
334     public String getDBType() {
335         return cr.getDbType();
336     }
337
338     public boolean isDrillDownURLInPopupPresent() {
339         return cr.isDrillURLInPoPUpPresent() != null ? cr.isDrillURLInPoPUpPresent().booleanValue() : false;
340     }
341
342     public void setDrillDownURLInPopupPresent(boolean value) {
343         cr.setDrillURLInPoPUpPresent(value);
344     }
345
346     public String getReportDescr() {
347         return cr.getReportDescr();
348     }
349
350     public String getChartType() {
351         return cr.getChartType();
352     }
353
354     public boolean displayChartTitle() {
355         return cr.isShowChartTitle();
356     }
357
358     public void setShowChartTitle(boolean showTitle) {
359         cr.setShowChartTitle(showTitle);
360     }
361
362     public String getChartTypeFixed() {
363         return cr.getChartTypeFixed();
364     }
365
366     public boolean isChartTypeFixed() {
367         return nvl(cr.getChartTypeFixed()).length() > 0 ? "Y".equals(cr.getChartTypeFixed())
368                 : (!Globals.getAllowRuntimeChartSel());
369     }
370
371     public String getChartLeftAxisLabel() {
372         return cr.getChartLeftAxisLabel();
373     }
374
375     public String getChartRightAxisLabel() {
376         return cr.getChartRightAxisLabel();
377     }
378
379     public String getChartWidth() {
380         return cr.getChartWidth();
381     }
382
383     public int getChartWidthAsInt() {
384         return getIntValue(cr.getChartWidth(), Globals.getDefaultChartWidth());
385     }
386
387     public String getChartHeight() {
388         return cr.getChartHeight() == null ? "500" : cr.getChartHeight();
389     }
390
391
392     public boolean displayPieOrderinRunPage() {
393         String s = "";
394         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getChartMultiplePieOrder() : "";
395         if (nvl(s).indexOf("|") != -1) {
396             s = s.substring(s.indexOf("|") + 1);
397             return getFlagInBoolean(s);
398         } else
399             return false;
400     }
401
402     public boolean isMultiplePieOrderByRow() {
403         String s = "";
404         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getChartMultiplePieOrder() : "";
405         if (nvl(s).indexOf("|") != -1)
406             s = s.substring(0, s.indexOf("|"));
407         return (nvl(s).length() > 0) ? ("row".equals(s) ? true : false) : true;
408     }
409
410     public boolean isMultiplePieOrderByColumn() {
411         String s = "";
412         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getChartMultiplePieOrder() : "";
413         if (nvl(s).indexOf("|") != -1)
414             s = s.substring(0, s.indexOf("|"));
415         return (nvl(s).length() > 0) && ("column".equals(s)) ? true : false;
416     }
417
418     public boolean displayPieLabelDisplayinRunPage() {
419         String s = "";
420         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getChartMultiplePieLabelDisplay()
421                 : "";
422         if (nvl(s).indexOf("|") != -1) {
423             s = s.substring(s.indexOf("|") + 1);
424             return getFlagInBoolean(s);
425         } else
426             return false;
427     }
428
429     public String getMultiplePieLabelDisplay() {
430         String s = "";
431         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getChartMultiplePieLabelDisplay()
432                 : "";
433         if (nvl(s).indexOf("|") != -1)
434             s = s.substring(0, s.indexOf("|"));
435         return s;
436     }
437
438     public boolean displayChartDisplayinRunPage() {
439         String s = "";
440         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getChartDisplay() : "";
441         if (nvl(s).indexOf("|") != -1) {
442             s = s.substring(s.indexOf("|") + 1);
443             return getFlagInBoolean(s);
444         } else
445             return false;
446     }
447
448     public boolean isChartDisplayIn3D() {
449         String s = "";
450         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getChartDisplay() : "";
451         if (nvl(s).length() <= 0)
452             return true;
453         if (nvl(s).indexOf("|") != -1)
454             s = s.substring(0, s.indexOf("|"));
455         return (nvl(s).length() > 0) && ("3D".equals(s)) ? true : false;
456     }
457
458     public boolean displayChartOrientationInRunPage() {
459         String s = "";
460         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getChartOrientation() : "";
461         if (nvl(s).indexOf("|") != -1) {
462             s = s.substring(s.indexOf("|") + 1);
463             return getFlagInBoolean(s);
464         } else
465             return false;
466
467     }
468
469     public String getLinearRegression() {
470         String s = "";
471         s = nvl((cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getLinearRegression() : "Y");
472         return s;
473     }
474
475     public void setLinearRegression(String linear) {
476         cr.getChartAdditionalOptions().setLinearRegression(linear);
477     }
478
479     public String getLinearRegressionColor() {
480         return (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getLinearRegressionColor()
481                 : "";
482     }
483
484     public String getCustomizedRegressionPoint() {
485         return (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getMaxRegression() : "";
486     }
487
488     public void setCustomizedRegressionPoint(String d) {
489         cr.getChartAdditionalOptions().setMaxRegression(d);
490     }
491
492     public void setLinearRegressionColor(String color) {
493         cr.getChartAdditionalOptions().setLinearRegressionColor(color);
494     }
495
496     public String getExponentialRegressionColor() {
497         return (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getExponentialRegressionColor()
498                 : "";
499     }
500
501     public void setExponentialRegressionColor(String color) {
502         cr.getChartAdditionalOptions().setExponentialRegressionColor(color);
503     }
504
505     public void setRangeAxisUpperLimit(String d) {
506         if (cr.getChartAdditionalOptions() != null)
507             cr.getChartAdditionalOptions().setRangeAxisUpperLimit(d);
508     }
509
510     public void setRangeAxisLowerLimit(String d) {
511         if (cr.getChartAdditionalOptions() != null)
512             cr.getChartAdditionalOptions().setRangeAxisLowerLimit(d);
513     }
514
515     public String getRangeAxisUpperLimit() {
516         return (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getRangeAxisUpperLimit() : "";
517     }
518
519     public String getRangeAxisLowerLimit() {
520         return (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getRangeAxisLowerLimit() : "";
521     }
522
523     public boolean isChartAnimate() {
524         return (cr.getChartAdditionalOptions() != null)
525                 ? (cr.getChartAdditionalOptions().isAnimate() != null ? cr.getChartAdditionalOptions().isAnimate()
526                         : false)
527                 : false;
528     }
529
530     public boolean isAnimateAnimatedChart() {
531         return (cr.getChartAdditionalOptions() != null)
532                 ? (cr.getChartAdditionalOptions().isAnimateAnimatedChart() != null
533                         ? cr.getChartAdditionalOptions().isAnimateAnimatedChart()
534                         : false)
535                 : true;
536     }
537
538     public void setAnimateAnimatedChart(boolean animate) {
539         cr.getChartAdditionalOptions().setAnimateAnimatedChart(animate);
540     }
541
542     public void setChartStacked(boolean stacked) {
543         cr.getChartAdditionalOptions().setStacked(stacked);
544     }
545
546     public boolean isChartStacked() {
547         return (cr.getChartAdditionalOptions() != null)
548                 ? (cr.getChartAdditionalOptions().isStacked() != null ? cr.getChartAdditionalOptions().isStacked()
549                         : true)
550                 : false;
551     }
552
553     public void setBarControls(boolean barControls) {
554         cr.getChartAdditionalOptions().setBarControls(barControls);
555     }
556
557     public boolean displayBarControls() {
558         return (cr.getChartAdditionalOptions() != null) ? (cr.getChartAdditionalOptions().isBarControls() != null
559                 ? cr.getChartAdditionalOptions().isBarControls()
560                 : false) : false;
561     }
562
563     public void setXAxisDateType(boolean dateType) {
564         cr.getChartAdditionalOptions().setXAxisDateType(dateType);
565     }
566
567     public boolean isXAxisDateType() {
568         return (cr.getChartAdditionalOptions() != null) ? (cr.getChartAdditionalOptions().isXAxisDateType() != null
569                 ? cr.getChartAdditionalOptions().isXAxisDateType()
570                 : false) : false;
571     }
572
573     public void setLessXaxisTickers(boolean lessTickers) {
574         cr.getChartAdditionalOptions().setLessXaxisTickers(lessTickers);
575     }
576
577     public boolean isLessXaxisTickers() {
578         return (cr.getChartAdditionalOptions() != null) ? (cr.getChartAdditionalOptions().isLessXaxisTickers() != null
579                 ? cr.getChartAdditionalOptions().isLessXaxisTickers()
580                 : false) : false;
581     }
582
583     public void setTimeAxis(boolean timeAxis) {
584         cr.getChartAdditionalOptions().setTimeAxis(timeAxis);
585     }
586
587     public boolean isTimeAxis() {
588         return (cr.getChartAdditionalOptions() != null)
589                 ? (cr.getChartAdditionalOptions().isTimeAxis() != null ? cr.getChartAdditionalOptions().isTimeAxis()
590                         : true)
591                 : true;
592     }
593
594     public void setLogScale(boolean logScale) {
595         cr.getChartAdditionalOptions().setLogScale(logScale);
596     }
597
598     public boolean isLogScale() {
599         return (cr.getChartAdditionalOptions() != null)
600                 ? (cr.getChartAdditionalOptions().isLogScale() != null ? cr.getChartAdditionalOptions().isLogScale()
601                         : false)
602                 : false;
603     }
604
605     public void setMultiSeries(boolean multiSeries) {
606         cr.getChartAdditionalOptions().setMultiSeries(multiSeries);
607         cr.setChartMultiSeries(multiSeries ? "Y" : "N");
608     }
609
610     public boolean isMultiSeries() {
611         if ("Y".equals(AppUtils.nvl(cr.getChartMultiSeries())))
612             cr.getChartAdditionalOptions().setMultiSeries(true);
613         return (cr.getChartAdditionalOptions() != null) ? (cr.getChartAdditionalOptions().isMultiSeries() != null
614                 ? cr.getChartAdditionalOptions().isMultiSeries()
615                 : false) : false;
616     }
617
618     public void setTimeSeriesRender(String timeSeriesRenderer) {
619         cr.getChartAdditionalOptions().setTimeSeriesRender(timeSeriesRenderer);
620     }
621
622     public String getTimeSeriesRender() {
623         return (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getTimeSeriesRender() : "line";
624     }
625
626     public void setShowXAxisLabel(boolean showXaxisLabel) {
627         cr.getChartAdditionalOptions().setShowXAxisLabel(showXaxisLabel);
628     }
629
630     public boolean isShowXaxisLabel() {
631         return (cr.getChartAdditionalOptions() != null) ? (cr.getChartAdditionalOptions().isShowXAxisLabel() != null
632                 ? cr.getChartAdditionalOptions().isShowXAxisLabel()
633                 : false) : false;
634     }
635
636     public void setAddXAxisTickers(boolean addXAxisTickers) {
637         cr.getChartAdditionalOptions().setAddXAxisTickers(addXAxisTickers);
638     }
639
640     public boolean isAddXAxisTickers() {
641         return (cr.getChartAdditionalOptions() != null) ? (cr.getChartAdditionalOptions().isAddXAxisTickers() != null
642                 ? cr.getChartAdditionalOptions().isAddXAxisTickers()
643                 : false) : true;
644     }
645
646     public void setZoomIn(Integer zoomIn) {
647         cr.getChartAdditionalOptions().setZoomIn(zoomIn);
648     }
649
650     public Integer getZoomIn() {
651         return (cr.getChartAdditionalOptions() != null)
652                 ? (cr.getChartAdditionalOptions().getZoomIn() != null ? cr.getChartAdditionalOptions().getZoomIn()
653                         : new Integer("25"))
654                 : new Integer("25");
655     }
656
657     public void setTimeAxisType(String timeAxisType) {
658         cr.getChartAdditionalOptions().setTimeAxisType(timeAxisType);
659     }
660
661     public String getTimeAxisType() {
662         return (cr.getChartAdditionalOptions() != null) ? (cr.getChartAdditionalOptions().getTimeAxisType() != null
663                 ? cr.getChartAdditionalOptions().getTimeAxisType()
664                 : "hourly") : "hourly";
665     }
666
667     public void setTopMargin(Integer topMargin) {
668         cr.getChartAdditionalOptions().setTopMargin(topMargin);
669     }
670
671     public Integer getTopMargin() {
672         return (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getTopMargin()
673                 : new Integer("30");
674     }
675
676     public void setBottomMargin(Integer bottomMargin) {
677         cr.getChartAdditionalOptions().setBottomMargin(bottomMargin);
678     }
679
680     public Integer getBottomMargin() {
681         return (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getBottomMargin()
682                 : new Integer("50");
683     }
684
685     public void setRightMargin(Integer rightMargin) {
686         cr.getChartAdditionalOptions().setRightMargin(rightMargin);
687     }
688
689     public Integer getRightMargin() {
690         return (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getRightMargin()
691                 : new Integer("60");
692     }
693
694     public void setLeftMargin(Integer leftMargin) {
695         cr.getChartAdditionalOptions().setLeftMargin(leftMargin);
696     }
697
698     public Integer getLeftMargin() {
699         return (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getLeftMargin()
700                 : new Integer("100");
701     }
702
703     public boolean isVerticalOrientation() {
704         String s = "";
705         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getChartOrientation() : "";
706         if (nvl(s).length() <= 0)
707             return true;
708         if (nvl(s).indexOf("|") != -1)
709             s = s.substring(0, s.indexOf("|"));
710         return (nvl(s).length() > 0) && ("vertical".equals(s)) ? true : false;
711     }
712
713     public boolean isHorizontalOrientation() {
714         String s = "";
715         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getChartOrientation() : "";
716         if (nvl(s).indexOf("|") != -1)
717             s = s.substring(0, s.indexOf("|"));
718         return (nvl(s).length() > 0) && ("horizontal".equals(s)) ? true : false;
719     }
720
721     public boolean displaySecondaryChartRendererInRunPage() {
722         String s = "";
723         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getSecondaryChartRenderer() : "";
724         if (nvl(s).indexOf("|") != -1) {
725             s = s.substring(s.indexOf("|") + 1);
726             return getFlagInBoolean(s);
727         } else
728             return false;
729
730     }
731
732     public String getSecondaryChartRenderer() {
733         String s = "";
734         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getSecondaryChartRenderer() : "";
735         if (nvl(s).indexOf("|") != -1)
736             s = s.substring(0, s.indexOf("|"));
737         return s;
738     }
739
740     public String getOverlayItemValueOnStackBar() {
741         String s = "";
742         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getOverlayItemValueOnStackBar()
743                 : "N";
744         return s;
745     }
746
747     public boolean displayIntervalInputInRunPage() {
748         String s = "";
749         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getIntervalFromdate() : "";
750         if (nvl(s).indexOf("|") != -1) {
751             s = s.substring(s.indexOf("|") + 1);
752             return getFlagInBoolean(s);
753         } else
754             return false;
755     }
756
757     public boolean showLegendDisplayOptionsInRunPage() {
758         String s = "";
759         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getHidechartLegend() : "";
760         if (nvl(s).indexOf("|") != -1) {
761             s = s.substring(s.indexOf("|") + 1);
762             return getFlagInBoolean(s);
763         } else
764             return false;
765     }
766
767     public String getIntervalFromdate() {
768         String s = "";
769         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getIntervalFromdate() : "";
770         if (nvl(s).indexOf("|") != -1)
771             s = s.substring(0, s.indexOf("|"));
772         return nvl(s, "");
773     }
774
775     public String getIntervalTodate() {
776         String s = "";
777         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getIntervalTodate() : "";
778         if (nvl(s).indexOf("|") != -1)
779             s = s.substring(0, s.indexOf("|"));
780         return nvl(s, "");
781     }
782
783     public String getIntervalLabel() {
784         return cr.getChartAdditionalOptions() != null ? nvl(cr.getChartAdditionalOptions().getIntervalLabel()) : "";
785     }
786
787     public String getLegendPosition() {
788         String s = "";
789         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getLegendPosition() : "";
790         return nvl(s, "bottom");
791     }
792
793     public String getLegendLabelAngle() {
794         String s = "";
795         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getLabelAngle() : "";
796         return nvl(s, "UP90");
797     }
798
799     public String getMaxLabelsInDomainAxis() {
800         String s = "";
801         s = (cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getMaxLabelsInDomainAxis() : "";
802         return nvl(s, "99");
803     }
804
805     public boolean isLastSeriesALineChart() {
806         String s = "";
807         s = nvl((cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getLastSeriesALineChart()
808                 : "");
809         return s.equals("Y");
810     }
811
812     public boolean isLastSeriesABarChart() {
813         String s = "";
814         s = nvl((cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getLastSeriesABarChart()
815                 : "");
816         return s.equals("Y");
817     }
818
819     public void setChartLegendDisplay(String value) {
820         cr.getChartAdditionalOptions().setHidechartLegend(value);
821     }
822
823     public boolean hideChartLegend() {
824         String s = "";
825         s = nvl((cr.getChartAdditionalOptions() != null) ? cr.getChartAdditionalOptions().getHidechartLegend() : "N");
826         if (nvl(s).length() <= 0)
827             s = "N";
828         if (nvl(s).indexOf("|") != -1)
829             s = s.substring(0, s.indexOf("|"));
830         return s.equals("Y");
831     }
832
833     public void setChartToolTips(String value) {
834         cr.getChartAdditionalOptions().setHideToolTips(value);
835     }
836
837     public void setDomainAxisValuesAsString(String value) {
838         cr.getChartAdditionalOptions().setKeepDomainAxisValueAsString(value);
839     }
840
841     public boolean hideChartToolTips() {
842         boolean s = true;
843         s = (cr.getChartAdditionalOptions() != null)
844                 ? (cr.getChartAdditionalOptions().getHideToolTips() != null
845                         ? ("Y".equals(cr.getChartAdditionalOptions().getHideToolTips()) ? true : false)
846                         : (Globals.hideToolTipsGlobally() ? true : false))
847                 : (Globals.hideToolTipsGlobally() ? true : false);
848         return s;
849     }
850
851     public boolean keepDomainAxisValueInChartAsString() {
852         boolean s = true;
853         s = (cr.getChartAdditionalOptions() != null)
854                 ? (cr.getChartAdditionalOptions().getKeepDomainAxisValueAsString() != null
855                         ? ("Y".equals(cr.getChartAdditionalOptions().getKeepDomainAxisValueAsString()) ? true : false)
856                         : false)
857                 : false;
858         return s;
859     }
860
861     public int getChartHeightAsInt() {
862         return getIntValue(cr.getChartHeight(), Globals.getDefaultChartHeight());
863     }
864
865     public boolean isPublic() {
866         return cr.isPublic();
867     }
868
869     public boolean isDashboardType() throws RaptorException {
870         return cr.isDashboardType() != null ? cr.isDashboardType().booleanValue() : false;
871     }
872
873
874     public String getReportSQL() {
875         return cr.getReportSQL();
876     }
877
878     public String getReportTitle() {
879         return cr.getReportTitle();
880     }
881
882     public String getReportSubTitle() {
883         return cr.getReportSubTitle();
884     }
885
886     public String getReportHeader() {
887         return cr.getReportHeader();
888     }
889
890     public String getReportFooter() {
891         return cr.getReportFooter();
892     }
893
894     public String getNumDashCols() {
895         return cr.getNumDashCols();
896     }
897
898     public int getNumDashColsAsInt() {
899         return getIntValue(cr.getNumDashCols(), 1);
900     }
901
902     public String getNumFormCols() {
903         return cr.getNumFormCols();
904     }
905
906     public int getNumFormColsAsInt() {
907         return getIntValue(cr.getNumFormCols(), 5);
908     }
909
910     public String getDisplayOptions() {
911         return cr.getDisplayOptions();
912     }
913
914
915
916     public int getJumpTo() {
917         return cr.getJumpTo() == null ? 1 : cr.getJumpTo();
918     }
919
920     public void setJumpTo(int value) {
921         cr.setJumpTo(value);
922     }
923
924     public int getSearchPageSize() {
925         return cr.getSearchPageSize() == null ? 20 : cr.getSearchPageSize();
926     }
927
928     public void setSearchPageSize(int value) {
929         cr.setSearchPageSize(value);
930     }
931
932     public boolean isToggleLayout() {
933         if (cr.isToggleLayout() != null)
934             return cr.isToggleLayout();
935
936         else
937             return Globals.displayRuntimeOptionsAsDefault();
938
939     }
940
941     public void setToggleLayout(boolean value) {
942         cr.setToggleLayout(value);
943     }
944
945     public boolean isShowPageSize() {
946         if (cr.isShowPageSize() != null)
947             return cr.isShowPageSize();
948
949         else
950             return Globals.displayRuntimeOptionsAsDefault();
951
952     }
953
954     public void setShowPageSize(boolean value) {
955         cr.setShowPageSize(value);
956     }
957
958     public boolean isShowNavPos() {
959         if (cr.isShowNavPos() != null)
960             return cr.isShowNavPos();
961
962         else
963             return Globals.displayRuntimeOptionsAsDefault();
964
965     }
966
967     public void setShowNavPos(boolean value) {
968         cr.setShowNavPos(value);
969     }
970
971     public boolean isShowGotoOption() {
972         if (cr.isShowGotoOption() != null)
973             return cr.isShowGotoOption();
974
975         else
976             return Globals.displayRuntimeOptionsAsDefault();
977
978     }
979
980     public void setShowGotoOption(boolean value) {
981         cr.setShowGotoOption(value);
982     }
983
984     public boolean isPageNav() {
985
986         if (cr.isPageNav() != null)
987             return cr.isPageNav();
988
989         else
990             return Globals.displayRuntimeOptionsAsDefault();
991
992     }
993
994     public void setPageNav(boolean value) {
995         cr.setPageNav(value);
996     }
997
998     public String getNavPosition() {
999         if (cr.getNavPosition() != null)
1000             return cr.getNavPosition();
1001
1002         else
1003             return "top";
1004                 
1005     }
1006
1007     public void setNavPosition(String value) {
1008         cr.setNavPosition(value);
1009     }
1010
1011     public String getDashboardEditor() {
1012         return getDashBoardReportsNew().getDashboardEditor();
1013     }
1014
1015     public void setDashboardEditor(String value) {
1016         getDashBoardReportsNew().setDashboardEditor(value);
1017     }
1018
1019     public DashboardEditorList getDashboardEditorList() {
1020         return getDashBoardReportsNew().getDashboardEditorList();
1021     }
1022
1023     public void setDashboardEditorList(DashboardEditorList value) {
1024         getDashBoardReportsNew().setDashboardEditorList(value);
1025     }
1026
1027     public PDFAdditionalOptions getPDFAdditionalOptions() {
1028         try {
1029             if (cr.getPdfAdditionalOptions() == null)
1030                 addPDFAdditionalOptions(new ObjectFactory());
1031         } catch (RaptorException ex) {
1032             logger.error(EELFLoggerDelegate.debugLogger, "Exception occured in getPDFAdditionalOptions ", ex);
1033         }
1034         return cr.getPdfAdditionalOptions();
1035     }
1036
1037     public String getPDFFont() {
1038         return getPDFAdditionalOptions().getPDFFont() != null ? getPDFAdditionalOptions().getPDFFont()
1039                 : Globals.getDataFontFamily();
1040     }
1041
1042     public void setPDFFont(String value) {
1043         getPDFAdditionalOptions().setPDFFont(value);
1044     }
1045
1046     public int getPDFFontSize() {
1047         return getPDFAdditionalOptions().getPDFFontSize() == null ? 9 : getPDFAdditionalOptions().getPDFFontSize();
1048     }
1049
1050     public void setPDFFontSize(int value) {
1051         getPDFAdditionalOptions().setPDFFontSize(value);
1052     }
1053
1054     public String getPDFOrientation() {
1055         return getPDFAdditionalOptions().getPDFOrientation() != null ? "portrait" : "landscape";
1056     }
1057
1058     public void setPDFOrientation(String value) {
1059         getPDFAdditionalOptions().setPDFOrientation(value);
1060     }
1061
1062     public String getPDFLogo1() {
1063         return getPDFAdditionalOptions().getPDFLogo1();
1064     }
1065
1066     public void setPDFLogo1(String value) {
1067         getPDFAdditionalOptions().setPDFLogo1(value);
1068     }
1069
1070     public String getPDFLogo2() {
1071         return getPDFAdditionalOptions().getPDFLogo2();
1072     }
1073
1074     public void setPDFLogo2(String value) {
1075         getPDFAdditionalOptions().setPDFLogo2(value);
1076     }
1077
1078     public int getPDFLogo1Size() {
1079         return getPDFAdditionalOptions().getPDFLogo1Size() == null ? 0 : getPDFAdditionalOptions().getPDFLogo1Size();
1080     }
1081
1082     public void setPDFLogo1Size(int value) {
1083         getPDFAdditionalOptions().setPDFLogo1Size(value);
1084     }
1085
1086     public int getPDFLogo2Size() {
1087         return getPDFAdditionalOptions().getPDFLogo2Size() == null ? 0 : getPDFAdditionalOptions().getPDFLogo2Size();
1088     }
1089
1090     public void setPDFLogo2Size(int value) {
1091         getPDFAdditionalOptions().setPDFLogo2Size(value);
1092     }
1093
1094     public boolean isPDFCoverPage() {
1095
1096         if (getPDFAdditionalOptions().isPDFCoverPage() != null)
1097             return getPDFAdditionalOptions().isPDFCoverPage();
1098
1099         else
1100             return true;
1101
1102     }
1103
1104     public void setPDFCoverPage(boolean value) {
1105         getPDFAdditionalOptions().setPDFCoverPage(value);
1106     }
1107
1108     public String getPDFFooter1() {
1109         return getPDFAdditionalOptions().getPDFFooter1();
1110     }
1111
1112     public void setPDFFooter1(String value) {
1113         getPDFAdditionalOptions().setPDFFooter1(value);
1114     }
1115
1116     public String getPDFFooter2() {
1117         return getPDFAdditionalOptions().getPDFFooter2();
1118     }
1119
1120     public void setPDFFooter2(String value) {
1121         getPDFAdditionalOptions().setPDFFooter2(value);
1122     }
1123
1124
1125     public String getDataContainerHeight() {
1126         return cr.getDataContainerHeight();
1127     }
1128
1129     public String getDataContainerWidth() {
1130         return cr.getDataContainerWidth();
1131     }
1132
1133     public boolean isAllowSchedule() {
1134         String allowSchedule = getAllowSchedule();
1135         return (allowSchedule != null) ? allowSchedule.startsWith("Y") : false;
1136     }
1137
1138     public String getAllowSchedule() {
1139         return cr.getAllowSchedule();
1140     }
1141
1142
1143
1144     public boolean isMultiGroupColumn() {
1145         String multiGroupColumn = getMultiGroupColumn();
1146         return (multiGroupColumn != null) ? multiGroupColumn.startsWith("Y") : false;
1147     }
1148
1149     public String getMultiGroupColumn() {
1150         return cr.getMultiGroupColumn();
1151     }
1152
1153     public void setMultiGroupColumn(String value) {
1154         cr.setMultiGroupColumn(value);
1155     }
1156
1157     private int getColumnGroupLevel(String colId) throws RaptorException {
1158         DataColumnType dc = getColumnById(colId);
1159         return (dc == null) ? 0 : dc.getLevel();
1160         } 
1161
1162     public int getMaxGroupLevel() {
1163         List reportCols = getAllColumns();
1164         int maxLevel = 0;
1165         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
1166             DataColumnType dc = (DataColumnType) iter.next();
1167             if (dc.getLevel() != null) {
1168                 if (maxLevel < dc.getLevel())
1169                     maxLevel = dc.getLevel();
1170             }
1171                 } 
1172         return maxLevel;
1173         }
1174
1175     private int getColumnGroupStart(String colId) throws RaptorException {
1176         DataColumnType dc = getColumnById(colId);
1177         return (dc == null) ? 0 : dc.getStart();
1178         }
1179
1180     private int getColumnGroupColSpan(String colId) throws RaptorException {
1181         DataColumnType dc = getColumnById(colId);
1182         return (dc == null) ? 0 : dc.getColspan();
1183         }
1184
1185     public void setTopDown(String value) {
1186         cr.setTopDown(value);
1187     }
1188
1189     public boolean isTopDown() {
1190         String topDown = getTopDownOption();
1191         return (topDown != null) ? topDown.startsWith("Y") : false;
1192     }
1193
1194     public String getTopDownOption() {
1195         return cr.getTopDown();
1196     }
1197
1198     public void setSizedByContent(String value) {
1199         cr.setSizedByContent(value);
1200     }
1201
1202     public boolean isSizedByContent() {
1203         String sizedByContent = getSizedByContentOption();
1204         return (sizedByContent != null) ? sizedByContent.startsWith("Y") : false;
1205     }
1206
1207     public String getSizedByContentOption() {
1208         return cr.getSizedByContent();
1209     }
1210
1211     public String getDashboardOptions() {
1212         return cr.getDashboardOptions();
1213     }
1214
1215     public boolean isDashboardOptionHideChart() {
1216         return nvl(getDashboardOptions()).length() > 0 && (getDashboardOptions().charAt(0) == 'Y');
1217     }
1218
1219     public boolean isDashboardOptionHideData() {
1220         return nvl(getDashboardOptions()).length() > 0 && (getDashboardOptions().charAt(1) == 'Y');
1221     }
1222
1223     public boolean isDashboardOptionHideBtns() {
1224         return nvl(getDashboardOptions()).length() > 0 && (getDashboardOptions().charAt(2) == 'Y');
1225     }
1226
1227     public boolean isDisplayOptionHideForm() {
1228         return nvl(getDisplayOptions()).length() > 0 && (getDisplayOptions().charAt(0) == 'Y');
1229     }
1230
1231     public boolean isDisplayOptionHideChart() {
1232         return nvl(getDisplayOptions()).length() > 1 && (getDisplayOptions().charAt(1) == 'Y');
1233     }
1234
1235     public boolean isDisplayOptionHideData() {
1236         return nvl(getDisplayOptions()).length() > 2 && (getDisplayOptions().charAt(2) == 'Y');
1237     }
1238
1239     public boolean isDisplayOptionHideBtns() {
1240         return nvl(getDisplayOptions()).length() > 3 && (getDisplayOptions().charAt(3) == 'Y');
1241     }
1242
1243     public boolean isDisplayOptionHideMap() {
1244         return nvl(getDisplayOptions()).length() > 4 && (getDisplayOptions().charAt(4) == 'Y');
1245     }
1246
1247     public boolean isDisplayOptionHideExcelIcons() {
1248         return nvl(getDisplayOptions()).length() > 5 && (getDisplayOptions().charAt(5) == 'Y');
1249     }
1250
1251     public boolean isDisplayOptionHidePDFIcons() {
1252         return nvl(getDisplayOptions()).length() > 6 && (getDisplayOptions().charAt(6) == 'Y');
1253     }
1254
1255     public String getComment() {
1256         return cr.getComment();
1257     }
1258
1259     public DataSourceList getDataSourceList() {
1260         return cr.getDataSourceList();
1261     }
1262
1263     public ChartAdditionalOptions getChartAdditionalOptions() {
1264         return cr.getChartAdditionalOptions();
1265     }
1266
1267     public ChartDrillOptions getChartDrillOptions() {
1268         return cr.getChartDrillOptions();
1269     }
1270
1271     public DataminingOptions getDataminingOptions() {
1272         return cr.getDataminingOptions();
1273     }
1274
1275     public DashboardReports getDashBoardReports() {
1276         return cr.getDashBoardReports();
1277     }
1278
1279     public DashboardReportsNew getDashBoardReportsNew() {
1280         try {
1281             if (cr.getDashBoardReportsNew() == null)
1282                 addDashboardReportsNew(new ObjectFactory());
1283         } catch (RaptorException ex) {
1284             logger.error(EELFLoggerDelegate.debugLogger, "Exception occured in getDashBoardReportsNew ", ex);
1285         }
1286         return cr.getDashBoardReportsNew();
1287     }
1288
1289     public String getDashboardLayoutHTML() {
1290         return cr.getDashboardLayoutHTML();
1291     }
1292
1293         public String getDashboardLayoutJSON() {
1294                 return cr.getDashboardLayoutJSON();
1295         }
1296         
1297     public FormFieldList getFormFieldList() {
1298         return cr.getFormFieldList();
1299     }
1300
1301     public JavascriptList getJavascriptList() {
1302         return cr.getJavascriptList();
1303     }
1304
1305     public SemaphoreList getSemaphoreList() {
1306         return cr.getSemaphoreList();
1307     }
1308
1309     public void setPageSize(int value) {
1310         cr.setPageSize(value);
1311     }
1312
1313     public void setAllowSchedule(String value) {
1314         cr.setAllowSchedule(value);
1315     }
1316
1317     public void setMaxRowsInExcelDownload(int value) {
1318         cr.setMaxRowsInExcelDownload(value);
1319     }
1320
1321     public void setReportInNewWindow(boolean value) {
1322         cr.setReportInNewWindow(value);
1323     }
1324
1325     public void setDisplayFolderTree(boolean value) {
1326         cr.setDisplayFolderTree(value);
1327     }
1328
1329     public void setReportType(String value) {
1330         cr.setReportType(value);
1331     }
1332
1333     public void setReportName(String value) {
1334         cr.setReportName(value);
1335     }
1336
1337     public void setDBInfo(String value) {
1338             cr.setDbInfo(value);
1339     }
1340
1341     public void setDBType(String value) {
1342             cr.setDbType(value);
1343     }
1344
1345     public void setReportDescr(String value) {
1346         cr.setReportDescr(value);
1347     }
1348
1349     public void setChartType(String value) {
1350         cr.setChartType(value);
1351     }
1352
1353     public void setChartMultiplePieOrder(String value) {
1354         cr.getChartAdditionalOptions().setChartMultiplePieOrder(value);
1355     }
1356
1357     public void setChartMultiplePieLabelDisplay(String value) {
1358         cr.getChartAdditionalOptions().setChartMultiplePieLabelDisplay(value);
1359     }
1360
1361     public void setChartOrientation(String value) {
1362         cr.getChartAdditionalOptions().setChartOrientation(value);
1363     }
1364
1365     public void setSecondaryChartRenderer(String value) {
1366         cr.getChartAdditionalOptions().setSecondaryChartRenderer(value);
1367     }
1368
1369     public void setOverlayItemValueOnStackBar(String value) {
1370         cr.getChartAdditionalOptions().setOverlayItemValueOnStackBar(value);
1371     }
1372
1373     public void setIntervalFromdate(String value) {
1374         cr.getChartAdditionalOptions().setIntervalFromdate(value);
1375     }
1376
1377     public void setIntervalLabel(String value) {
1378         cr.getChartAdditionalOptions().setIntervalLabel(value);
1379     }
1380
1381     public void setIntervalTodate(String value) {
1382         cr.getChartAdditionalOptions().setIntervalTodate(value);
1383     }
1384
1385     public void setLegendPosition(String value) {
1386         cr.getChartAdditionalOptions().setLegendPosition(value);
1387     }
1388
1389     public void setLegendLabelAngle(String value) {
1390         cr.getChartAdditionalOptions().setLabelAngle(value);
1391     }
1392
1393     public void setMaxLabelsInDomainAxis(String value) {
1394         if (nvl(value).length() <= 0)
1395             value = "99";
1396         cr.getChartAdditionalOptions().setMaxLabelsInDomainAxis(value);
1397     }
1398
1399     public void setLastSeriesALineChart(String value) {
1400         cr.getChartAdditionalOptions().setLastSeriesALineChart(value);
1401     }
1402
1403     public void setLastSeriesABarChart(String value) {
1404         cr.getChartAdditionalOptions().setLastSeriesABarChart(value);
1405     }
1406
1407     public void setChartDisplay(String value) {
1408         cr.getChartAdditionalOptions().setChartDisplay(value);
1409     }
1410
1411     public void setChartAnimate(boolean animate) {
1412         if (cr.getChartAdditionalOptions() != null)
1413             cr.getChartAdditionalOptions().setAnimate(animate);
1414         else {
1415             try {
1416                 if (getChartAdditionalOptions() == null)
1417                     addChartAdditionalOptions(new ObjectFactory());
1418             } catch (RaptorException ex) {
1419                 logger.error(EELFLoggerDelegate.debugLogger, "Exception occured in setChartAnimate ", ex);
1420             }
1421             if (cr.getChartAdditionalOptions() != null)
1422                 cr.getChartAdditionalOptions().setAnimate(animate);
1423
1424         }
1425
1426     }
1427
1428     public void addChartAdditionalOptions(ObjectFactory objFactory) throws RaptorException {
1429         ChartAdditionalOptions chartOptions = objFactory.createChartAdditionalOptions();
1430         cr.setChartAdditionalOptions(chartOptions);
1431     }
1432
1433     public void addDashboardReportsNew(ObjectFactory objFactory) throws RaptorException {
1434         DashboardReportsNew dashboardReports = objFactory.createDashboardReportsNew();
1435         cr.setDashBoardReportsNew(dashboardReports);
1436     }
1437
1438     public void addPDFAdditionalOptions(ObjectFactory objFactory) throws RaptorException {
1439         PDFAdditionalOptions pdfOptions = objFactory.createPDFAdditionalOptions();
1440         cr.setPdfAdditionalOptions(pdfOptions);
1441     }
1442
1443     public void setChartTypeFixed(String value) {
1444         cr.setChartTypeFixed(value);
1445     }
1446
1447     public void setChartLeftAxisLabel(String value) {
1448         cr.setChartLeftAxisLabel(value);
1449     }
1450
1451     public void setChartRightAxisLabel(String value) {
1452         cr.setChartRightAxisLabel(value);
1453     }
1454
1455     public void setChartWidth(String value) {
1456         cr.setChartWidth(value);
1457     }
1458
1459     public void setChartHeight(String value) {
1460         cr.setChartHeight(value);
1461     }
1462
1463     public void setChartMultiSeries(String value) {
1464         cr.setChartMultiSeries(value);
1465     }
1466
1467     public void setPublic(boolean value) {
1468         cr.setPublic(value);
1469         if (reportSecurity != null)
1470             reportSecurity.setPublic(value);
1471     }
1472
1473     public void setReportSQL(String value) {
1474         cr.setReportSQL(value);
1475     }
1476
1477     public void setReportTitle(String value) {
1478         cr.setReportTitle(value);
1479     }
1480
1481     public void setReportSubTitle(String value) {
1482         cr.setReportSubTitle(value);
1483     }
1484
1485     public void setReportHeader(String value) {
1486         cr.setReportHeader(value);
1487     }
1488
1489     public void setReportFooter(String value) {
1490         cr.setReportFooter(value);
1491     }
1492
1493     public void setNumFormCols(String value) {
1494         cr.setNumFormCols(value);
1495     }
1496
1497     public void setNumDashCols(String value) {
1498         cr.setNumDashCols(value);
1499     }
1500
1501     public void setDisplayOptions(String value) {
1502         cr.setDisplayOptions(value);
1503     }
1504
1505     public void setDataContainerHeight(String value) {
1506         cr.setDataContainerHeight(value);
1507     }
1508
1509     public void setDataContainerWidth(String value) {
1510         cr.setDataContainerWidth(value);
1511     }
1512
1513     public void setDashboardOptions(String value) {
1514         cr.setDashboardOptions(value);
1515     }
1516
1517     public void setComment(String value) {
1518         cr.setComment(value);
1519     }
1520
1521     public void setDashboardType(boolean dashboardType) {
1522         cr.setDashboardType(dashboardType);
1523     }
1524
1525     public void setDashboardLayoutHTML(String html) {
1526         cr.setDashboardLayoutHTML(html);
1527     }
1528
1529     public void setDataSourceList(DataSourceList value) {
1530         cr.setDataSourceList(value);
1531     }
1532
1533     public void setFormFieldList(FormFieldList value) {
1534         cr.setFormFieldList(value);
1535     }
1536
1537     public void setDashBoardReports(DashboardReports value) {
1538         cr.setDashBoardReports(value);
1539     }
1540
1541     public void setSemaphoreList(SemaphoreList value) {
1542         cr.setSemaphoreList(value);
1543     }
1544
1545     public void setJavascriptList(JavascriptList value) {
1546         cr.setJavascriptList(value);
1547     }
1548
1549     public void setJavascriptElement(String javascriptElement) {
1550         cr.setJavascriptElement(javascriptElement);
1551     }
1552
1553     public void checkUserReadAccess(HttpServletRequest request) throws RaptorException {
1554         reportSecurity.checkUserReadAccess(request, null);
1555     }
1556
1557     public void checkUserReadAccess(HttpServletRequest request, String userID) throws RaptorException {
1558         reportSecurity.checkUserReadAccess(request, userID);
1559     }
1560
1561     public void checkUserWriteAccess(HttpServletRequest request) throws RaptorException {
1562         reportSecurity.checkUserWriteAccess(request);
1563         verifySQLBasedReportAccess(request);
1564     }
1565
1566     public String getOwnerID() {
1567         return reportSecurity.getOwnerID();
1568     }
1569
1570     public String getCreateID() {
1571         return reportSecurity.getCreateID();
1572     }
1573
1574     public String getCreateDate() {
1575         return reportSecurity.getCreateDate();
1576     }
1577
1578     public String getUpdateID() {
1579         return reportSecurity.getUpdateID();
1580     }
1581
1582     public String getUpdateDate() {
1583         return reportSecurity.getUpdateDate();
1584     }
1585
1586     public ReportSecurity getReportSecurity() {
1587         return reportSecurity;
1588     }
1589
1590     /**** Report Maps - Start ****/
1591     public ReportMap getReportMap() {
1592         return cr.getReportMap();
1593     }
1594
1595     public void setReportMap(ReportMap reportMap) {
1596         cr.setReportMap(reportMap);
1597     }
1598
1599     /**** Report Maps - End ****/
1600
1601     /**** Report Chart Drilldown - Start ****/
1602     public ChartDrillOptions getReportChartDrillOptions() {
1603         return cr.getChartDrillOptions();
1604     }
1605
1606     public void setReportChartDrillOptions(ChartDrillOptions chartDrillOptions) {
1607         cr.setChartDrillOptions(chartDrillOptions);
1608     }
1609
1610
1611
1612     public String getFormHelpText() {
1613         String formHelpText = nvl(getComment());
1614
1615         if (formHelpText.indexOf('|') >= 0)
1616             formHelpText = formHelpText.substring(formHelpText.lastIndexOf('|') + 1);
1617
1618         return formHelpText;
1619         } 
1620
1621     public void setFormHelpText(String formHelpText) {
1622         String comment = nvl(getComment());
1623
1624         if (comment.indexOf('|') >= 0)
1625             comment = comment.substring(0, comment.lastIndexOf('|'));
1626         if (comment.length() > 0)
1627             comment += '|';
1628
1629         setComment(comment + formHelpText);
1630         }
1631
1632     public boolean isRuntimeColSortDisabled() {
1633         String comment = nvl(getComment());
1634
1635         if (comment.indexOf('|') < 0)
1636             return false;
1637
1638         return "Y".equals(comment.substring(0, comment.indexOf('|')));
1639         } 
1640     public void setRuntimeColSortDisabled(boolean value) {
1641         String comment = nvl(getComment());
1642
1643         if (comment.indexOf('|') >= 0)
1644             comment = comment.substring(comment.indexOf('|') + 1);
1645
1646         setComment((value ? "Y" : "N") + "|" + comment);
1647         }
1648
1649     /**
1650      * *************************************************************************************************
1651      */
1652
1653     protected void verifySQLBasedReportAccess(HttpServletRequest request) throws RaptorException {
1654         String userID = AppUtils.getUserID(request);
1655         if (getReportDefType().equals(AppConstants.RD_SQL_BASED)
1656                 && (!Globals.getAllowSQLBasedReports()) && (!AppUtils.isAdminUser(request)))
1657             throw new org.onap.portalsdk.analytics.error.UserAccessException(reportID, "[" + userID + "] "
1658                     + AppUtils.getUserName(request), AppConstants.UA_WRITE);
1659         } 
1660
1661     /**
1662      * *************************************************************************************************
1663      */
1664
1665     private String getColumnNameById(String colId) throws RaptorException {
1666         DataColumnType dc = getColumnById(colId);
1667         return (dc == null) ? "NULL" : dc.getColName();
1668         } 
1669     private boolean isViewAction(String value) throws RaptorException {
1670         try {
1671             Vector viewActions = org.onap.portalsdk.analytics.model.DataCache.getDataViewActions();
1672
1673             for (int i = 0; i < viewActions.size(); i++)
1674                 if (value.equals(AppUtils.getBaseActionURL() + ((String) viewActions.get(i))))
1675                     return true;
1676         } catch (Exception e) {
1677             logger.error(EELFLoggerDelegate.debugLogger, "Exception occured in isViewAction ", e);
1678             throw new RaptorRuntimeException("ReportWrapper.isViewAction Exception: "
1679                     + e.getMessage());
1680         }
1681
1682         return false;
1683         }
1684
1685     public String getSelectExpr(DataColumnType dct) {
1686         return getSelectExpr(dct, dct.getColName() /* colName */);
1687         } 
1688
1689
1690
1691     private String getSelectExpr(DataColumnType dct, String colName) {
1692         String colType = dct.getColType();
1693         if (colType.equals(AppConstants.CT_NUMBER)) {
1694             return colName;
1695         } else if (colType.equals(AppConstants.CT_CHAR)
1696                 || ((nvl(dct.getColFormat()).length() == 0) && (!colType
1697                         .equals(AppConstants.CT_DATE))))
1698             return colName;
1699
1700         else
1701             return "TO_CHAR(" + colName + ", '"
1702                     + nvl(dct.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT) + "')";
1703         } 
1704         
1705
1706
1707     public DataSourceType getTableById(String tableId) {
1708         for (Iterator iter = getDataSourceList().getDataSource().iterator(); iter.hasNext();) {
1709             DataSourceType ds = (DataSourceType) iter.next();
1710             if (ds.getTableId().equals(tableId))
1711                 return ds;
1712                 }
1713         return null;
1714         } 
1715
1716     public DataSourceType getTableByDBName(String tableName) {
1717         for (Iterator iter = getDataSourceList().getDataSource().iterator(); iter.hasNext();) {
1718             DataSourceType ds = (DataSourceType) iter.next();
1719             if (ds.getTableName().equals(tableName))
1720                 return ds;
1721                 } 
1722
1723         return null;
1724         }
1725
1726     public DataSourceType getColumnTableById(String colId) {
1727         return getTableById(getColumnById(colId).getTableId());
1728         }
1729
1730     public DataColumnType getColumnById(String colId) {
1731         List reportCols = getAllColumns();
1732         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
1733             DataColumnType dc = (DataColumnType) iter.next();
1734             if (dc.getColId().equalsIgnoreCase(colId)) {
1735                 return dc;
1736             }
1737                 } 
1738
1739         return null;
1740         } 
1741
1742     public DataColumnType getChartLegendColumn() {
1743         List reportCols = getAllColumns();
1744         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
1745             DataColumnType dc = (DataColumnType) iter.next();
1746             if (nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND))
1747                 return dc;
1748                 } 
1749         return null;
1750         } 
1751
1752     public List getChartValueColumnsList(int filter, HashMap formValues) { /*
1753                                                                             * filter; all=0;create without new chart =1;
1754                                                                             * createNewChart=2
1755                                                                             */
1756         List reportCols = getAllColumns();
1757
1758         ArrayList chartValueCols = new ArrayList();
1759         int flag = 0;
1760         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
1761             flag = 0;
1762             DataColumnType dc = (DataColumnType) iter.next();
1763             flag = getDependsOnFormFieldFlag(dc, formValues);
1764
1765             if ((dc.getChartSeq() != null && dc.getChartSeq() > 0) && flag == 0) {
1766                 if (!AppUtils.nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND)) {
1767                     if (nvl(dc.getChartGroup()).length() <= 0) {
1768                         if (filter == 2
1769                                 && (dc.isCreateInNewChart() != null && dc.isCreateInNewChart().booleanValue())) {
1770                             chartValueCols.add(dc);
1771                         } else if (filter == 1
1772                                 && (dc.isCreateInNewChart() == null || !dc.isCreateInNewChart().booleanValue())) {
1773                             chartValueCols.add(dc);
1774                         } else if (filter == 0)
1775                             chartValueCols.add(dc);
1776                     } else
1777                         chartValueCols.add(dc);
1778                 }
1779             }
1780
1781                 } 
1782         Collections.sort(chartValueCols, new ChartSeqComparator());
1783         return chartValueCols;
1784     } 
1785
1786     /** Check whether chart has series (Category) columns **/
1787     public boolean hasSeriesColumn() {
1788         List reportCols = getAllColumns();
1789
1790         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
1791             DataColumnType dc = (DataColumnType) iter.next();
1792             if (dc.isChartSeries() != null && dc.isChartSeries().booleanValue())
1793                 return true;
1794                 } 
1795         return false;
1796         }
1797
1798     public List getChartDisplayNamesList(int filter, HashMap formValues) { 
1799         List reportCols = getAllColumns();
1800         ArrayList chartValueColNames = new ArrayList();
1801         int flag = 0;
1802         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
1803             flag = 0;
1804             DataColumnType dc = (DataColumnType) iter.next();
1805             // if(filter == 2 || filter == 1) {
1806             flag = getDependsOnFormFieldFlag(dc, formValues);
1807
1808             if ((dc.getChartSeq() != null && dc.getChartSeq() > 0) && flag == 0) {
1809                 if (nvl(dc.getChartGroup()).length() <= 0) {
1810                     if (filter == 2 && (dc.isCreateInNewChart() != null && dc.isCreateInNewChart().booleanValue())) {
1811                         chartValueColNames.add(dc.getDisplayName());
1812                     } else if (filter == 1
1813                             && (dc.isCreateInNewChart() == null || !dc.isCreateInNewChart().booleanValue())) {
1814                         chartValueColNames.add(dc.getDisplayName());
1815                     } else if (filter == 0)
1816                         chartValueColNames.add(dc.getDisplayName());
1817                 } else if (filter == 0)
1818                     chartValueColNames.add(dc.getDisplayName());
1819             }
1820
1821
1822         }
1823         return chartValueColNames;
1824         } 
1825
1826     public List getChartColumnColorsList(int filter, HashMap formValues) { 
1827         List reportCols = getAllColumns();
1828         ArrayList chartValueColColors = new ArrayList();
1829         int flag = 0;
1830         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
1831             flag = 0;
1832             DataColumnType dc = (DataColumnType) iter.next();
1833             flag = getDependsOnFormFieldFlag(dc, formValues);
1834
1835             if ((dc.getChartSeq() != null && dc.getChartSeq() > 0) && flag == 0) {
1836                 if (nvl(dc.getChartGroup()).length() <= 0) {
1837                     if (filter == 2 && (dc.isCreateInNewChart() != null && dc.isCreateInNewChart().booleanValue())) {
1838                         chartValueColColors.add(dc.getChartColor());
1839                     } else if (filter == 1
1840                             && (dc.isCreateInNewChart() == null || !dc.isCreateInNewChart().booleanValue())) {
1841                         chartValueColColors.add(dc.getChartColor());
1842                     } else if (filter == 0)
1843                         chartValueColColors.add(dc.getChartColor());
1844                 } else if (filter == 0)
1845                     chartValueColColors.add(dc.getChartColor());
1846             }
1847         }
1848         return chartValueColColors;
1849         } 
1850
1851     public List getChartValueColumnAxisList(int filter, HashMap formValues) { 
1852         List reportCols = getAllColumns();
1853         ArrayList chartValueColAxis = new ArrayList();
1854         int flag = 0;
1855         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
1856             flag = 0;
1857             DataColumnType dc = (DataColumnType) iter.next();
1858             flag = getDependsOnFormFieldFlag(dc, formValues);
1859
1860             if ((dc.getChartSeq() != null && dc.getChartSeq() > 0) && flag == 0) {
1861                 if (nvl(dc.getChartGroup()).length() <= 0) {
1862                     if (filter == 2 && (dc.isCreateInNewChart() != null && dc.isCreateInNewChart().booleanValue())) {
1863                         chartValueColAxis.add(nvl(dc.getColOnChart(), "0"));
1864                     } else if (filter == 1
1865                             && (dc.isCreateInNewChart() == null || !dc.isCreateInNewChart().booleanValue())) {
1866                         chartValueColAxis.add(nvl(dc.getColOnChart(), "0"));
1867                     } else if (filter == 0)
1868                         chartValueColAxis.add(nvl(dc.getColOnChart(), "0"));
1869                 } else if (filter == 0)
1870                     chartValueColAxis.add(nvl(dc.getColOnChart(), "0"));
1871             }
1872         }
1873         return chartValueColAxis;
1874         }
1875
1876
1877     public List getChartValueNewChartList() {
1878         ArrayList chartValueNewChartAxis = new ArrayList();
1879         for (Iterator iter = getChartValueColumnsList(2, null).iterator(); iter.hasNext();)
1880             chartValueNewChartAxis.add(new Boolean(((DataColumnType) iter.next()).isCreateInNewChart()));
1881         return chartValueNewChartAxis;
1882         }
1883
1884     public List getAllChartGroups() {
1885         ArrayList chartGroups = new ArrayList();
1886         String chartGroupName = "";
1887         List reportCols = getAllColumns();
1888         Set groupSet = new TreeSet();
1889         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
1890             DataColumnType dc = (DataColumnType) iter.next();
1891             if (dc.getChartSeq() != null && dc.getChartSeq() > 0) {
1892                 chartGroupName = dc.getChartGroup();
1893                 if (nvl(chartGroupName).length() > 0)
1894                     groupSet.add(chartGroupName);
1895             }
1896         }
1897         List l = new ArrayList(groupSet);
1898         return l;
1899         } 
1900
1901     public HashMap getAllChartYAxis(ReportParamValues reportParamValues) {
1902         String chartYAxis = "";
1903         List reportCols = getAllColumns();
1904         HashMap hashMap = new HashMap();
1905         FormFieldList formFieldList = getFormFieldList();
1906         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
1907             DataColumnType dc = (DataColumnType) iter.next();
1908             if (dc.getChartSeq() != null && dc.getChartSeq() > 0) {
1909                 chartYAxis = dc.getYAxis();
1910                 if (formFieldList != null && reportParamValues != null) {
1911                     for (Iterator iter1 = getFormFieldList().getFormField().iterator(); iter1.hasNext();) {
1912                         FormFieldType fft = (FormFieldType) iter1.next();
1913                         String fieldDisplay = getFormFieldDisplayName(fft);
1914                         String fieldId = "";
1915                         if (fft != null)
1916                             fieldId = fft.getFieldId();
1917                         if (fft != null && !fft.getFieldType().equals(FormField.FFT_BLANK)
1918                                 && !fft.getFieldType().equals(FormField.FFT_LIST_MULTI)
1919                                 && !fft.getFieldType().equals(FormField.FFT_TEXTAREA)) {
1920                             String paramValue = Utils.oracleSafe(nvl(reportParamValues.getParamValue(fieldId)));
1921                             chartYAxis = Utils.replaceInString(chartYAxis, fieldDisplay, nvl(
1922                                     paramValue, ""));
1923                         }
1924                     }
1925                 }
1926                 if (nvl(dc.getChartGroup()).length() > 0)
1927                     hashMap.put(dc.getChartGroup(), chartYAxis);
1928             }
1929         }
1930         return hashMap;
1931         }
1932
1933     public List getChartGroupColumnAxisList(String chartGroupName, HashMap formValues) { /*
1934                                                                                           * filter; all=0;create without
1935                                                                                           * new chart =1;
1936                                                                                           * createNewChart=2
1937                                                                                           */
1938         List reportCols = getAllColumns();
1939         ArrayList chartGroupColAxis = new ArrayList();
1940         String chartGroup = chartGroupName.substring(0, chartGroupName.lastIndexOf("|"));
1941         int flag = 0;
1942         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
1943             DataColumnType dc = (DataColumnType) iter.next();
1944             flag = getDependsOnFormFieldFlag(dc, formValues);
1945
1946             if ((dc.getChartSeq() != null && dc.getChartSeq() > 0) && flag == 0) {
1947                 if (nvl(dc.getChartGroup()).indexOf("|") > 0
1948                         && (nvl(dc.getChartGroup().substring(0, dc.getChartGroup().lastIndexOf("|")))
1949                                 .equals(chartGroup))) {
1950                     chartGroupColAxis.add(dc);
1951                 }
1952             }
1953         }
1954         Collections.sort(chartGroupColAxis, new ChartSeqComparator());
1955         return chartGroupColAxis;
1956         } 
1957
1958     public List getChartGroupValueColumnAxisList(String chartGroupName, HashMap formValues) {
1959         List reportCols = getAllColumns();
1960         String index = chartGroupName.substring(chartGroupName.lastIndexOf("|") + 1);
1961         String chartGroup = chartGroupName.substring(0, chartGroupName.lastIndexOf("|"));
1962         ArrayList chartGroupValueColAxis = new ArrayList();
1963         int flag = 0;
1964
1965         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
1966             flag = 0;
1967             DataColumnType dc = (DataColumnType) iter.next();
1968             flag = getDependsOnFormFieldFlag(dc, formValues);
1969
1970             if ((dc.getChartSeq() != null && dc.getChartSeq() > 0) && flag == 0) {
1971                 if (nvl(dc.getChartGroup()).indexOf("|") > 0
1972                         && (nvl(dc.getChartGroup().substring(0, dc.getChartGroup().lastIndexOf("|")))
1973                                 .equals(chartGroup))) {
1974                     chartGroupValueColAxis.add(dc);
1975                 }
1976             }
1977         }
1978         return chartGroupValueColAxis;
1979         } 
1980
1981     public List getChartGroupDisplayNamesList(String chartGroupName, HashMap formValues) {
1982         List reportCols = getAllColumns();
1983         ArrayList chartGroupValueColNames = new ArrayList();
1984         String chartGroup = chartGroupName.substring(0, chartGroupName.lastIndexOf("|"));
1985         int flag = 0;
1986
1987         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
1988             flag = 0;
1989             DataColumnType dc = (DataColumnType) iter.next();
1990             flag = getDependsOnFormFieldFlag(dc, formValues);
1991
1992             if ((dc.getChartSeq() != null && dc.getChartSeq() > 0) && flag == 0) {
1993                 if (nvl(dc.getChartGroup()).indexOf("|") > 0
1994                         && (nvl(dc.getChartGroup().substring(0, dc.getChartGroup().lastIndexOf("|")))
1995                                 .equals(chartGroup))) {
1996                     chartGroupValueColNames.add(dc.getDisplayName());
1997                 }
1998             }
1999         }
2000         return chartGroupValueColNames;
2001         } 
2002
2003
2004     public List getChartGroupColumnColorsList(String chartGroupName, HashMap formValues) {
2005         List reportCols = getAllColumns();
2006         ArrayList chartValueColColors = new ArrayList();
2007         String chartGroup = chartGroupName.substring(0, chartGroupName.lastIndexOf("|"));
2008         int flag = 0;
2009         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
2010             flag = 0;
2011             DataColumnType dc = (DataColumnType) iter.next();
2012             flag = getDependsOnFormFieldFlag(dc, formValues);
2013
2014             if ((dc.getChartSeq() != null && dc.getChartSeq() > 0) && flag == 0) {
2015                 if (nvl(dc.getChartGroup()).indexOf("|") > 0
2016                         && (nvl(dc.getChartGroup().substring(0, dc.getChartGroup().lastIndexOf("|")))
2017                                 .equals(chartGroup))) {
2018                     chartValueColColors.add(dc.getChartColor());
2019                 }
2020             }
2021         }
2022         return chartValueColColors;
2023         }
2024
2025     public List getCrossTabRowColumns() {
2026         List reportCols = getAllColumns();
2027         Vector v = new Vector(reportCols.size());
2028
2029         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
2030             DataColumnType dc = (DataColumnType) iter.next();
2031             if (nvl(dc.getCrossTabValue()).equals(AppConstants.CV_ROW))
2032                 v.add(dc);
2033                 } 
2034
2035         return v;
2036         } 
2037
2038     public List getCrossTabColColumns() {
2039         List reportCols = getAllColumns();
2040         Vector v = new Vector(reportCols.size());
2041
2042         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
2043             DataColumnType dc = (DataColumnType) iter.next();
2044             if (nvl(dc.getCrossTabValue()).equals(AppConstants.CV_COLUMN))
2045                 v.add(dc);
2046                 } 
2047
2048         return v;
2049         } 
2050
2051     public String getCrossTabDisplayTotal(String rowColPos) {
2052         DataColumnType dct = getCrossTabValueColumn();
2053         if (dct == null)
2054             return "";
2055
2056         String displayTotal = nvl(dct.getDisplayTotal());
2057         if (displayTotal.indexOf('|') >= 0) {
2058             String displayColTotal = displayTotal.substring(0, displayTotal.indexOf('|'));
2059             String displayRowTotal = displayTotal.substring(displayTotal.indexOf('|') + 1);
2060
2061             if (rowColPos.equals(AppConstants.CV_COLUMN))
2062                 displayTotal = displayColTotal;
2063             else if (rowColPos.equals(AppConstants.CV_ROW))
2064                 displayTotal = displayRowTotal;
2065             else if (displayColTotal.equals(displayRowTotal))
2066                 displayTotal = displayColTotal;
2067                 }
2068
2069         return displayTotal;
2070         } 
2071
2072     public DataColumnType getCrossTabValueColumn() {
2073         List reportCols = getAllColumns();
2074         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
2075             DataColumnType dc = (DataColumnType) iter.next();
2076             if (nvl(dc.getCrossTabValue()).equals(AppConstants.CV_VALUE))
2077                 return dc;
2078                 } 
2079
2080         return null;
2081         } 
2082
2083         public int getCrossTabValueColumnIndex() { 
2084         List reportCols = getAllColumns();
2085
2086         int idx = 0;
2087         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
2088             DataColumnType dc = (DataColumnType) iter.next();
2089             if (nvl(dc.getCrossTabValue()).equals(AppConstants.CV_VALUE))
2090                 break;
2091             if (dc.isVisible())
2092                 idx++;
2093                 } 
2094
2095         return idx;
2096         } 
2097
2098     public ColFilterType getFilterById(String colId, int filterIndex) {
2099         DataColumnType dc = getColumnById(colId);
2100         try {
2101             return dc.getColFilterList().getColFilter().get(filterIndex);
2102         } catch (Exception e) {
2103             logger.error(EELFLoggerDelegate.debugLogger, "Exception occured in getFilterById ", e);
2104             return null;
2105         }
2106         }
2107
2108     public boolean needFormInput() {
2109         List reportCols = getAllColumns();
2110         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
2111             DataColumnType dct = (DataColumnType) iter.next();
2112
2113             if (dct.getColFilterList() != null) {
2114                 List fList = dct.getColFilterList().getColFilter();
2115                 for (Iterator iterF = fList.iterator(); iterF.hasNext();) {
2116                     ColFilterType cft = (ColFilterType) iterF.next();
2117
2118                     if (nvl(cft.getArgType()).equals(AppConstants.AT_FORM))
2119                         return true;
2120                                 }
2121                         } 
2122                 } 
2123
2124         return false;
2125         }
2126
2127     public int getNumSortColumns() {
2128         int numSortCols = 0;
2129         for (Iterator iter = getAllColumns().iterator(); iter.hasNext();) {
2130             DataColumnType dct = (DataColumnType) iter.next();
2131             if (dct.getOrderBySeq() != null && dct.getOrderBySeq() > 0)
2132                 numSortCols++;
2133                 } 
2134
2135         return numSortCols;
2136         } 
2137
2138     public SemaphoreType getSemaphoreById(String semaphoreId) {
2139         if (getSemaphoreList() != null && semaphoreId != null)
2140             for (Iterator iter = getSemaphoreList().getSemaphore().iterator(); iter.hasNext();) {
2141                 SemaphoreType sem = (SemaphoreType) iter.next();
2142                 if (sem.getSemaphoreId().equals(semaphoreId))
2143                     return sem;
2144                         }
2145
2146         return null;
2147         } 
2148
2149     public void deleteSemaphore(SemaphoreType semaphore) {
2150         if (getSemaphoreList() != null) {
2151             if (getSemaphoreList().getSemaphore() != null)
2152                 getSemaphoreList().getSemaphore().remove((SemaphoreType) semaphore);
2153         }
2154         } 
2155
2156     public void setSemaphore(SemaphoreType sem) {
2157         if (getSemaphoreList() != null) {
2158             getSemaphoreList().getSemaphore().add(sem);
2159         }
2160
2161         } 
2162
2163     public static FormatType getSemaphoreFormatById(SemaphoreType semaphore, String formatId) {
2164         if (semaphore != null)
2165             for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter
2166                     .hasNext();) {
2167                 FormatType fmt = (FormatType) iter.next();
2168                 if (fmt.getFormatId().equals(formatId))
2169                     return fmt;
2170                         } 
2171
2172         return null;
2173         } 
2174
2175     public FormFieldType getFormFieldById(String fieldId) {
2176         if (getFormFieldList() != null && fieldId != null)
2177             for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) {
2178                 FormFieldType fft = (FormFieldType) iter.next();
2179                 if (fft.getFieldId().equals(fieldId))
2180                     return fft;
2181                         } 
2182
2183         return null;
2184         } 
2185
2186     public FormFieldType getFormFieldByDisplayValue(String fieldDisplay) {
2187         if (getFormFieldList() != null && fieldDisplay != null)
2188             for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) {
2189                 FormFieldType fft = (FormFieldType) iter.next();
2190                 if (fieldDisplay.equals(getFormFieldDisplayName(fft)))
2191                     return fft;
2192                         } 
2193
2194         return null;
2195         }
2196     public String getFormFieldDisplayName(FormFieldType fft) {
2197         return "[" + fft.getFieldName() + "]";
2198         }
2199
2200
2201     public void resetCache(boolean sqlOnly) {
2202         generatedSQL = null;
2203         if (!sqlOnly) {
2204             allColumns = null;
2205             allFilters = null;
2206         }
2207         } 
2208
2209     public String getOuterJoinType(DataSourceType curTable) {
2210         String refDefinition = nvl(curTable.getRefDefinition());
2211         int outerJoinIdx = refDefinition.indexOf(" (+)");
2212         if (outerJoinIdx < 0)
2213             return "";
2214
2215         int equalSignIdx = refDefinition.indexOf("=");
2216         if (refDefinition.indexOf(curTable.getTableId()) < equalSignIdx)
2217             return (outerJoinIdx < equalSignIdx) ? AppConstants.OJ_CURRENT
2218                     : AppConstants.OJ_JOINED;
2219         else
2220             return (outerJoinIdx < equalSignIdx) ? AppConstants.OJ_JOINED
2221                     : AppConstants.OJ_CURRENT;
2222         } 
2223
2224     public String getFormFieldName(ColFilterType filter) {
2225         FormFieldType fft = null;
2226         if (filter.getArgType().equals(AppConstants.AT_FORM))
2227             fft = getFormFieldByDisplayValue(filter.getArgValue());
2228
2229         return (fft != null) ? fft.getFieldId()
2230                 : filter.getColId() + "_f"
2231                         + filter.getFilterSeq();
2232         } 
2233
2234     public String getFormFieldDisplayName(DataColumnType column, ColFilterType filter) {
2235         FormFieldType fft = null;
2236         if (filter.getArgType().equals(AppConstants.AT_FORM))
2237             fft = getFormFieldByDisplayValue(filter.getArgValue());
2238
2239         return (fft != null) ? fft.getFieldName()
2240                 : column.getDisplayName() + "&nbsp;"
2241                         + filter.getExpression();
2242         }
2243
2244     public Calendar getFormFieldRangeStart(ColFilterType filter) {
2245         FormFieldType fft = null;
2246         if (filter.getArgType().equals(AppConstants.AT_FORM))
2247             fft = getFormFieldByDisplayValue(filter.getArgValue());
2248
2249         return (fft != null) ? fft.getRangeStartDate().toGregorianCalendar() : null;
2250         } 
2251
2252     public Calendar getFormFieldRangeEnd(ColFilterType filter) {
2253         FormFieldType fft = null;
2254         if (filter.getArgType().equals(AppConstants.AT_FORM))
2255             fft = getFormFieldByDisplayValue(filter.getArgValue());
2256         return (fft != null) ? fft.getRangeEndDate().toGregorianCalendar() : null;
2257         } 
2258
2259     public String getFormFieldRangeStartSQL(ColFilterType filter) {
2260         FormFieldType fft = null;
2261         if (filter.getArgType().equals(AppConstants.AT_FORM))
2262             fft = getFormFieldByDisplayValue(filter.getArgValue());
2263
2264         return (fft != null) ? fft.getRangeStartDateSQL() : null;
2265         } 
2266
2267     public String getFormFieldRangeEndSQL(ColFilterType filter) {
2268         FormFieldType fft = null;
2269         if (filter.getArgType().equals(AppConstants.AT_FORM))
2270             fft = getFormFieldByDisplayValue(filter.getArgValue());
2271         return (fft != null) ? fft.getRangeEndDateSQL() : null;
2272         }
2273
2274     public String getUniqueTableId(String tableName) {
2275         String tableIdPrefix = tableName.startsWith("MSA_") ? tableName.substring(4, 6)
2276                 : tableName.substring(0, 2);
2277         String tableId = "";
2278
2279         int tableIdN = getDataSourceList().getDataSource().size() + 1;
2280         do {
2281             tableId = tableIdPrefix.toLowerCase() + (tableIdN++);
2282         } while (getTableById(tableId) != null);
2283
2284         return tableId;
2285         } 
2286
2287     protected void deleteDataSourceType(String tableId) {
2288         List dsList = getDataSourceList().getDataSource();
2289         for (Iterator iter = dsList.iterator(); iter.hasNext();) {
2290             DataSourceType dst = (DataSourceType) iter.next();
2291             if (dst.getTableId().equals(tableId))
2292                 iter.remove();
2293             else if (nvl(dst.getRefTableId()).equals(tableId)) {
2294                 dst.setRefTableId(null);
2295                 dst.setRefDefinition(null);
2296             }
2297                 } 
2298
2299         resetCache(false);
2300         }
2301
2302     public static void adjustColumnType(DataColumnType dct) {
2303         dct.setColType(dct.getDbColType());
2304
2305         if (dct.isCalculated())
2306             if (dct.getColName().startsWith("SUM(") || dct.getColName().startsWith("COUNT(")
2307                     || dct.getColName().startsWith("AVG(")
2308                     || dct.getColName().startsWith("STDDEV(")
2309                     || dct.getColName().startsWith("VARIANCE("))
2310                 dct.setColType(AppConstants.CT_NUMBER);
2311             else if (dct.getColName().startsWith("DECODE(") || dct.getColName().startsWith("coalesce("))
2312                 dct.setColType(AppConstants.CT_CHAR);
2313         } 
2314     public static boolean getColumnNoParseDateFlag(DataColumnType dct) {
2315         return (nvls(dct.getComment()).indexOf(AppConstants.CF_NO_PARSE_DATE) >= 0);
2316         }
2317
2318     public static void setColumnNoParseDateFlag(DataColumnType dct, boolean noParseDateFlag) {
2319         dct.setComment(noParseDateFlag ? AppConstants.CF_NO_PARSE_DATE : null);
2320         } 
2321
2322
2323     public static String getSQLBasedFFTColTableName(String fftColId) {
2324         return fftColId.substring(0, fftColId.indexOf('.'));
2325         } 
2326
2327     public static String getSQLBasedFFTColColumnName(String fftColId) {
2328         fftColId = (fftColId.indexOf('|') < 0) ? fftColId
2329                 : fftColId.substring(0, fftColId
2330                         .indexOf('|'));
2331         return fftColId.substring(fftColId.indexOf('.') + 1);
2332         } 
2333     public static String getSQLBasedFFTColDisplayFormat(String fftColId) {
2334         return (fftColId.indexOf('|') < 0) ? ""
2335                 : fftColId
2336                         .substring(fftColId.indexOf('|') + 1);
2337         } 
2338
2339
2340     public List<DataColumnType> getAllColumns() {
2341         if (cr == null)
2342             throw new NullPointerException("CustomReport not initialized");
2343
2344         if (allColumns == null) {
2345             allColumns = new Vector();
2346
2347             List dsList = getDataSourceList().getDataSource();
2348             for (Iterator iter = dsList.iterator(); iter.hasNext();) {
2349                 DataSourceType ds = (DataSourceType) iter.next();
2350                 List dcList = ds.getDataColumnList().getDataColumn();
2351                 for (Iterator iterC = dcList.iterator(); iterC.hasNext();) {
2352                     DataColumnType dc = (DataColumnType) iterC.next();
2353
2354                     allColumns.add(dc);
2355                                 } 
2356                         } 
2357
2358             Collections.sort(allColumns, new OrderSeqComparator());
2359                 } 
2360
2361         return allColumns;
2362         }
2363
2364     public List getOnlyVisibleColumns() {
2365         if (cr == null)
2366             throw new NullPointerException("CustomReport not initialized");
2367
2368         if (allVisibleColumns == null) {
2369             allVisibleColumns = new Vector();
2370
2371             List dsList = getDataSourceList().getDataSource();
2372             for (Iterator iter = dsList.iterator(); iter.hasNext();) {
2373                 DataSourceType ds = (DataSourceType) iter.next();
2374                 List dcList = ds.getDataColumnList().getDataColumn();
2375                 for (Iterator iterC = dcList.iterator(); iterC.hasNext();) {
2376                     DataColumnType dc = (DataColumnType) iterC.next();
2377                     if (dc.isVisible())
2378                         allVisibleColumns.add(dc);
2379                                 } 
2380                         } 
2381
2382             Collections.sort(allVisibleColumns, new OrderSeqComparator());
2383                 } 
2384
2385         return allVisibleColumns;
2386         } 
2387     public int getVisibleColumnCount() {
2388         if (cr == null)
2389             throw new NullPointerException("CustomReport not initialized");
2390         int colCount = 0;
2391         List dsList = getDataSourceList().getDataSource();
2392         for (Iterator iter = dsList.iterator(); iter.hasNext();) {
2393             DataSourceType ds = (DataSourceType) iter.next();
2394             List dcList = ds.getDataColumnList().getDataColumn();
2395             for (Iterator iterC = dcList.iterator(); iterC.hasNext();) {
2396                 DataColumnType dc = (DataColumnType) iterC.next();
2397                 if (dc.isVisible())
2398                     colCount++;
2399                                 } 
2400                         } 
2401
2402         return colCount;
2403     }
2404
2405     public List getAllFilters() {
2406         if (cr == null)
2407             throw new NullPointerException("CustomReport not initialized");
2408
2409         allFilters = new Vector();
2410
2411         List reportCols = getAllColumns();
2412         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
2413             DataColumnType dct = (DataColumnType) iter.next();
2414
2415             if (dct.getColFilterList() != null) {
2416                 List colFilters = dct.getColFilterList().getColFilter();
2417
2418                 for (Iterator iterF = colFilters.iterator(); iterF.hasNext();) {
2419                     ColFilterType cft = (ColFilterType) iterF.next();
2420
2421                     allFilters.add(cft);
2422                                 } 
2423                         } 
2424                 } 
2425         return allFilters;
2426         }
2427
2428     private String formatValue(String value, DataColumnType dc, boolean useDefaultDateFormat) throws RaptorException {
2429         return formatValue(value, dc, useDefaultDateFormat, getColumnTableById(dc.getColId()), null);
2430         }
2431
2432     private String formatValue(String value, DataColumnType dc, boolean useDefaultDateFormat,
2433             DataSourceType ds, FormFieldType fft) throws RaptorException {
2434         String fmtValue = null;
2435
2436         if (nvl(value).length() == 0)
2437             fmtValue = "";
2438         else if (value.equals(AppConstants.FILTER_MAX_VALUE)
2439                 || value.equals(AppConstants.FILTER_MIN_VALUE))
2440             fmtValue = "(SELECT "
2441                     + (value.equals(AppConstants.FILTER_MAX_VALUE) ? "MAX" : "MIN") + "("
2442                     + dc.getColName() + ") FROM " + ds.getTableName() + ")";
2443         else if (dc.getColType().equals(AppConstants.CT_NUMBER)) {
2444             try {
2445                 double vD = Double.parseDouble(value);
2446                 fmtValue = value;
2447             } catch (NumberFormatException ex) {
2448                 throw new UserDefinedException(
2449                         "Expected number, Given String for the form field \"" + fft.getFieldName() + "\"");
2450             }
2451         } else if (dc.getColType().equals(AppConstants.CT_DATE)) {
2452             if (fft != null && (fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)
2453                     || fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)
2454                     || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC))) {
2455                 fmtValue = "TO_DATE('"
2456                         + value
2457                         + "', '"
2458                         + (useDefaultDateFormat ? AppConstants.DEFAULT_DATE_FORMAT
2459                                 : nvl(dc
2460                                                         .getColFormat(), AppConstants.DEFAULT_DATE_FORMAT));
2461                 fmtValue = fmtValue + " HH24";
2462                 if (fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)
2463                         || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC))
2464                     fmtValue = fmtValue + ":MI";
2465                 if (fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC))
2466                     fmtValue = fmtValue + " HH24:MI:SS";
2467             } else {
2468                 fmtValue = "TO_DATE('"
2469                         + value
2470                         + "', '"
2471                         + (useDefaultDateFormat ? AppConstants.DEFAULT_DATE_FORMAT
2472                                 : nvl(dc
2473                                         .getColFormat(), AppConstants.DEFAULT_DATE_FORMAT))
2474                         + "')";
2475                 if (Globals.getMonthFormatUseLastDay())
2476                     if (!useDefaultDateFormat)
2477                         if ("MM/YYYY".equals(nvl(dc.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT))
2478                                 || "MONTH, YYYY"
2479                                         .equals(nvl(dc.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT)))
2480                             fmtValue = "ADD_MONTHS(" + fmtValue + ", 1)-1";
2481             }
2482         } else {
2483             fmtValue = value;
2484             if (!fmtValue.startsWith("'"))
2485                 fmtValue = "'" + fmtValue + "'";
2486         }
2487
2488         return fmtValue;
2489         }
2490
2491     private String formatListValue(String listValue, DataColumnType dc,
2492             boolean useDefaultDateFormat, boolean useOnlyPipeDelimiter) throws RaptorException {
2493         return formatListValue("", listValue, dc, useDefaultDateFormat, useOnlyPipeDelimiter,
2494                 getColumnTableById(dc.getColId()), null);
2495         } 
2496
2497     public String formatListValue(String fieldDisplay, String listValue, DataColumnType dc,
2498             boolean useDefaultDateFormat, boolean useOnlyPipeDelimiter, DataSourceType ds,
2499             String listBaseSQL) throws RaptorException {
2500         StringBuffer fmtValue = new StringBuffer("");
2501         StringTokenizer st = new StringTokenizer(listValue, useOnlyPipeDelimiter ? "|"
2502                 : ",\n\r\f");
2503
2504         while (st.hasMoreTokens()) {
2505             if (fmtValue.length() > 0)
2506                 fmtValue.append(", ");
2507
2508             if (dc == null) {
2509                 String value = st.nextToken().trim();
2510                 if (value.startsWith("'"))
2511                     fmtValue.append(value);
2512                 else
2513                     fmtValue.append("'" + value + "'");
2514             } else
2515                 fmtValue.append(formatValue(st.nextToken().trim(), dc, useDefaultDateFormat,
2516                         ds, null));
2517
2518                 }
2519
2520         if (fmtValue.length() == 0) {
2521             if (nvl(fieldDisplay).length() > 0) {
2522                 fmtValue.append("");
2523             } else {
2524                 fmtValue.append("(");
2525                 fmtValue.append(nvl(listBaseSQL, "NULL"));
2526                 fmtValue.append(")");
2527             }
2528         } else if (fmtValue.charAt(0) != '(') {
2529             fmtValue.insert(0, '(');
2530             fmtValue.append(')');
2531         }
2532
2533         return fmtValue.toString();
2534         } 
2535
2536     private String getColumnSelectStr(DataColumnType dc, ReportParamValues paramValues) {
2537         String colName = dc.isCalculated() ? dc.getColName()
2538                 : ((nvl(dc.getTableId()).length() > 0) ? (dc.getTableId() + "." + dc
2539                         .getColName()) : dc.getColName());
2540         String paramValue = null;
2541         if (dc.isCalculated())
2542             if (getFormFieldList() != null)
2543                 for (Iterator iter2 = getFormFieldList().getFormField().iterator(); iter2
2544                         .hasNext();) {
2545                     FormFieldType fft = (FormFieldType) iter2.next();
2546                     String fieldId = fft.getFieldId();
2547                     String fieldDisplay = getFormFieldDisplayName(fft);
2548                     if (!paramValues.isParameterMultiValue(fieldId)) {
2549                         paramValue = paramValues.getParamValue(fieldId);
2550                         if (paramValue != null && paramValue.length() > 0) {
2551                             colName = Utils.replaceInString(colName, fieldDisplay, Utils
2552                                     .oracleSafe(nvl(paramValue, "NULL")));
2553                         } else {
2554                             colName = Utils.replaceInString(colName, "'" + fieldDisplay + "'", nvl(
2555                                     paramValue, "NULL"));
2556                             colName = Utils.replaceInString(colName, fieldDisplay, nvl(
2557                                     paramValue, "NULL"));
2558                         }
2559                     }
2560                                 }
2561
2562         return colName;
2563         } 
2564
2565     private void addExtraIdSelect(StringBuffer selectExtraIdCl, String drillDownParams,
2566             boolean includeSelectExpr) {
2567                 drillDownParams = drillDownParams.substring(10, drillDownParams.length() - 1); 
2568
2569         selectExtraIdCl.append(", ");
2570         if (includeSelectExpr) {
2571             selectExtraIdCl.append(drillDownParams);
2572             selectExtraIdCl.append(" ");
2573         } // if
2574                 selectExtraIdCl.append(drillDownParams.replace('.', '_')); 
2575         } 
2576
2577     private void addExtraDateSelect(StringBuffer selectExtraDateCl, String drillDownParams,
2578             ReportParamValues paramValues, boolean includeSelectExpr) {
2579         String colId = "";
2580         while (drillDownParams.indexOf('[') >= 0) {
2581             int startIdx = drillDownParams.indexOf('[');
2582             int endIdx = drillDownParams.indexOf(']');
2583
2584             if (startIdx <= endIdx) {
2585                                 colId = drillDownParams.substring(startIdx + 1, endIdx); 
2586             } else {
2587                 drillDownParams = drillDownParams.substring(endIdx + 1);
2588                 continue;
2589             }
2590                                                                                                                                                 
2591
2592             DataColumnType column = getColumnById(colId);
2593             if (column != null)
2594                 if (column.getColType().equals(AppConstants.CT_DATE))
2595                     if (!nvl(column.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT).equals(
2596                             AppConstants.DEFAULT_DATE_FORMAT))
2597                         if (selectExtraDateCl.toString().indexOf(
2598                                 " " + colId + AppConstants.DD_COL_EXTENSION) < 0) {
2599                             selectExtraDateCl.append(", ");
2600                             if (includeSelectExpr) {
2601                                 selectExtraDateCl.append("TO_CHAR("
2602                                         + getColumnSelectStr(column, paramValues) + ", '"
2603                                         + AppConstants.DEFAULT_DATE_FORMAT + "')");
2604                                 selectExtraDateCl.append(" ");
2605                                                         } 
2606                                                         selectExtraDateCl.append(colId + AppConstants.DD_COL_EXTENSION);
2607                                                 } 
2608
2609             drillDownParams = drillDownParams.substring(endIdx + 1);
2610                 } 
2611         } 
2612
2613
2614     public String generateSQL(String userId, HttpServletRequest request) throws RaptorException {
2615         return generateSQL(new ReportParamValues(), userId, request);
2616         } 
2617     public String generateSQL(ReportParamValues paramValues, String userId, HttpServletRequest request)
2618             throws RaptorException {
2619         return generateSQL(paramValues, null, AppConstants.SO_ASC, userId, request);
2620         } 
2621
2622     public String generateSQL(ReportParamValues paramValues, String overrideSortByColId,
2623             String overrideSortByAscDesc, String userId, HttpServletRequest request) throws RaptorException {
2624         if (cr == null)
2625             throw new NullPointerException("CustomReport not initialized");
2626         if (nvl(getWholeSQL()).length() > 0)
2627             return getWholeSQL();
2628         if (paramValues.size() > 0)
2629             resetCache(true);
2630           
2631         if (generatedSQL == null) {
2632             if (getReportDefType().equals(AppConstants.RD_SQL_BASED)
2633                     || getReportDefType().equals(AppConstants.RD_SQL_BASED_DATAMIN)) {
2634                 generatedSQL = generateSQLSQLBased(paramValues, overrideSortByColId,
2635                         overrideSortByAscDesc, userId, request);
2636                 generatedChartSQL = generateSQLSQLBased(paramValues, null,
2637                         AppConstants.SO_ASC, userId, request);
2638             } else if (getReportDefType().equals(AppConstants.RD_VISUAL)
2639                     && !getReportType().equals(AppConstants.RT_CROSSTAB)) {
2640                 generatedSQL = generateSQLVisual(paramValues, overrideSortByColId,
2641                         overrideSortByAscDesc, userId, request);
2642                 generatedChartSQL = generateSQLVisual(paramValues, null,
2643                         AppConstants.SO_ASC, userId, request);
2644             } else {
2645                 generatedSQL = generateSQLCrossTabVisual(paramValues, overrideSortByColId,
2646                         overrideSortByAscDesc, userId, request);
2647             }
2648
2649             generatedSQL = replaceNewLine(generatedSQL, "" + '\n', " " + '\n' + " ");
2650             if (nvl(generatedChartSQL).trim().length() > 0)
2651                 generatedChartSQL = replaceNewLine(generatedChartSQL, "" + '\n', " " + '\n' + " ");
2652                 } 
2653
2654         //Added Below code to by pass single quotes issue with form fields
2655         if(generatedSQL != null && !generatedSQL.isEmpty()) {
2656                 generatedSQL = generatedSQL.replace("'(", "(");
2657                 generatedSQL = generatedSQL.replace(")'", ")");
2658         }
2659         return generatedSQL;
2660         } 
2661
2662     public String generateSQLSQLBased(ReportParamValues paramValues,
2663             String overrideSortByColId, String overrideSortByAscDesc, String userId, HttpServletRequest request)
2664             throws RaptorException {
2665         String sql = getReportSQL();
2666         DataSet ds = null;
2667         String[] reqParameters = Globals.getRequestParams().split(",");
2668         String[] sessionParameters = Globals.getSessionParams().split(",");
2669         String[] scheduleSessionParameters = Globals.getSessionParamsForScheduling().split(",");
2670         javax.servlet.http.HttpSession session = request.getSession();
2671         String dbType = "";
2672         String dbInfo = getDBInfo();
2673         int fieldCount = 0;
2674         Pattern re1 = null;
2675         Matcher matcher = null;
2676         int index = 0;
2677         int posFormField = 0;
2678         int posAnd = 0;
2679         if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) {
2680             try {
2681                 dbType = remDbInfo.getDBType(dbInfo);
2682             } catch (Exception ex) {
2683                 throw new RaptorException(ex);
2684             }
2685         }
2686
2687         sql = sql + " ";
2688         sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ss][Ee][Ll][Ee][Cc][Tt]([\r\n]*|[\\s]*)", Pattern.DOTALL).matcher(sql)
2689                 .replaceAll(" SELECT ");
2690         sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Rr][Ee]([\r\n]*|[\\s]*)", Pattern.DOTALL).matcher(sql)
2691                 .replaceAll(" WHERE ");
2692         sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Nn]([\r\n]*|[\\s]*)", Pattern.DOTALL).matcher(sql)
2693                 .replaceAll(" WHEN ");
2694         sql = Pattern.compile("(^[\r\n]*|([\\s]))[Aa][Nn][Dd]([\r\n]*|[\\s]*)", Pattern.DOTALL).matcher(sql)
2695                 .replaceAll(" AND ");
2696
2697         if (getFormFieldList() != null) {
2698             for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) {
2699
2700                 FormFieldType fft = (FormFieldType) iter.next();
2701                 String fieldId = fft.getFieldId();
2702                 String fieldDisplay = getFormFieldDisplayName(fft);
2703                 if (!fft.getFieldType().equals(FormField.FFT_BLANK)) {
2704                     if (paramValues.isParameterMultiValue(fieldId)) {
2705                         String replaceValue = formatListValue(fieldDisplay, Utils
2706                                 .oracleSafe(nvl(paramValues.getParamValue(fieldId))), null, false,
2707                                 true, null, paramValues.getParamBaseSQL(fieldId));
2708                         if (replaceValue.length() > 0) {
2709                             sql = Utils.replaceInString(sql, fieldDisplay, replaceValue);
2710                         } else {
2711                             fieldCount++;
2712                             if (fieldCount == 1) {
2713                             }
2714                             while (sql.indexOf(fieldDisplay) > 0) {
2715                                 re1 = Pattern.compile(
2716                                         "(^[\r\n]|[\\s])AND(.*?[^\r\n]*)" + "\\[" + fft.getFieldName() + "\\](.*?)\\s",
2717                                         Pattern.DOTALL);
2718                                 posFormField = sql.indexOf(fieldDisplay);
2719                                 int posSelectField = sql.lastIndexOf("SELECT ", posFormField);
2720                                 int andField = 0;
2721                                 int whereField = 0;
2722                                                                 int     whenField = 0;
2723                                 andField = sql.lastIndexOf(" AND ", posFormField);
2724                                 whereField = sql.indexOf(" WHERE", posSelectField);
2725                                 whenField = sql.indexOf(" WHEN", posSelectField);
2726
2727                                 if (posFormField > whereField)
2728                                     andField = sql.lastIndexOf(" AND ", posFormField);
2729                                 if (posFormField > andField && (andField > whereField || andField > whenField))
2730                                     posAnd = andField;
2731                                 else
2732                                     posAnd = 0;
2733                                 matcher = re1.matcher(sql);
2734
2735                                 if (posAnd > 0 && matcher.find(posAnd - 1)) {
2736                                                         
2737                                     matcher = re1.matcher(sql);
2738                                     index = sql != null ? sql.lastIndexOf("[" + fft.getFieldName() + "]") : -1;
2739
2740                                     if (andField > 0)
2741                                         index = andField;
2742                                     else
2743                                         index = whereField;
2744                                     if (index >= 0 && matcher.find(index - 1)) {
2745                                         sql = sql.replace(matcher.group(), " ");
2746                                     }
2747                                 } else {
2748
2749                                     re1 = Pattern.compile(
2750                                             "(^[\r\n]|[\\s])WHERE(.*?[^\r\n]*)\\[" + fft.getFieldName() + "\\](.*?)\\s",
2751                                             Pattern.DOTALL);
2752                                     matcher = re1.matcher(sql);
2753                                     if (whereField != -1) {
2754                                         if (matcher.find(whereField - 1)) {
2755                                             matcher = re1.matcher(sql);
2756                                             index = sql != null ? sql.lastIndexOf("[" + fft.getFieldName() + "]") : -1;
2757                                             if (index >= 0 && matcher.find(index - 30)) {
2758                                                 sql = sql.replace(matcher.group(), " WHERE 1=1 ");
2759                                             }
2760                                         } 
2761                                     } else {
2762                                         sql = Utils.replaceInString(sql, fieldDisplay, replaceValue);
2763                                     }
2764
2765                                 }
2766                             }
2767                         }
2768
2769                     } else {
2770                         String paramValue = "";
2771                         if (paramValues.isParameterTextAreaValueAndModified(fieldId)) {
2772                             String value = "";
2773                             value = nvl(paramValues
2774                                     .getParamValue(fieldId));
2775                             paramValue = value;
2776                         } else
2777                             paramValue = Utils.oracleSafe(nvl(paramValues
2778                                     .getParamValue(fieldId)));
2779
2780                         if (paramValue != null && paramValue.length() > 0) {
2781                             if (paramValue.toLowerCase().trim().startsWith("select ")) {
2782                                 paramValue = Utils.replaceInString(paramValue, "[LOGGED_USERID]", userId);
2783                                 paramValue = Utils.replaceInString(paramValue, "[USERID]", userId);
2784                                 paramValue = Utils.replaceInString(paramValue, "[USER_ID]", userId);
2785
2786                                 paramValue = Utils.replaceInString(paramValue, "''", "'");
2787                                 ds = ConnectionUtils.getDataSet(paramValue, dbInfo);
2788                                 if (ds.getRowCount() > 0)
2789                                     paramValue = ds.getString(0, 0);
2790                             }
2791                             if (fft != null && (fft.getValidationType() != null
2792                                     && (fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)
2793                                             || fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)
2794                                             || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)
2795                                             || fft.getValidationType().equals(FormField.VT_DATE)))) {
2796                                 if (fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)) {
2797                                     sql = Utils.replaceInString(sql, fieldDisplay, nvl(
2798                                             paramValue)
2799                                             + ((nvl(paramValues
2800                                                     .getParamValue(fieldId + "_Hr")).length() > 0)
2801                                                             ? " " + addZero(Utils.oracleSafe(nvl(paramValues
2802                                                                     .getParamValue(fieldId + "_Hr"))))
2803                                                             : ""));
2804                                 } else if (fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)) {
2805                                                     sql = Utils.replaceInString(sql, fieldDisplay, nvl(
2806                                             paramValue)
2807                                             + ((nvl(paramValues
2808                                                     .getParamValue(fieldId + "_Hr")).length() > 0)
2809                                                             ? " " + addZero(Utils.oracleSafe(nvl(paramValues
2810                                                                     .getParamValue(fieldId + "_Hr"))))
2811                                                             : "")
2812                                             + ((nvl(paramValues
2813                                                     .getParamValue(fieldId + "_Min")).length() > 0)
2814                                                             ? ":" + addZero(Utils.oracleSafe(nvl(paramValues
2815                                                                     .getParamValue(fieldId + "_Min"))))
2816                                                             : ""));
2817                                 } else if (fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
2818                                     sql = Utils.replaceInString(sql, fieldDisplay, nvl(
2819                                             paramValue)
2820                                             + ((nvl(paramValues
2821                                                     .getParamValue(fieldId + "_Hr")).length() > 0)
2822                                                             ? " " + addZero(Utils.oracleSafe(nvl(paramValues
2823                                                                     .getParamValue(fieldId + "_Hr"))))
2824                                                             : "")
2825                                             + ((nvl(paramValues
2826                                                     .getParamValue(fieldId + "_Min")).length() > 0)
2827                                                             ? ":" + addZero(Utils.oracleSafe(nvl(paramValues
2828                                                                     .getParamValue(fieldId + "_Min"))))
2829                                                             : "")
2830                                             + ((nvl(paramValues
2831                                                     .getParamValue(fieldId + "_Sec")).length() > 0)
2832                                                             ? ":" + addZero(Utils.oracleSafe(nvl(paramValues
2833                                                                     .getParamValue(fieldId + "_Sec"))))
2834                                                             : ""));
2835                                 } else {
2836                                     sql = Utils.replaceInString(sql, fieldDisplay, nvl(
2837                                             paramValue, "NULL"));
2838                                 }
2839
2840                             } else {
2841                                 if (paramValue != null && paramValue.length() > 0) {
2842                                     if (sql.indexOf("'" + fieldDisplay + "'") != -1
2843                                             || sql.indexOf("'" + fieldDisplay) != -1
2844                                             || sql.indexOf(fieldDisplay + "'") != -1
2845                                             || sql.indexOf("'%" + fieldDisplay + "%'") != -1
2846                                             || sql.indexOf("'%" + fieldDisplay) != -1
2847                                             || sql.indexOf(fieldDisplay + "%'") != -1
2848                                             || sql.indexOf("'_" + fieldDisplay + "_'") != -1
2849                                             || sql.indexOf("'_" + fieldDisplay) != -1
2850                                             || sql.indexOf(fieldDisplay + "_'") != -1
2851                                             || sql.indexOf("'%_" + fieldDisplay + "_%'") != -1
2852                                             || sql.indexOf("^" + fieldDisplay + "^") != -1
2853                                             || sql.indexOf("'%_" + fieldDisplay) != -1
2854                                             || sql.indexOf(fieldDisplay + "_%'") != -1) {
2855                                         sql = Utils.replaceInString(sql, fieldDisplay, nvl(
2856                                                 paramValue, "NULL"));
2857                                     } else {
2858                                         if (sql.indexOf(fieldDisplay) != -1) {
2859                                             if (nvl(paramValue).length() > 0) {
2860                                                 try {
2861                                                     double vD = Double.parseDouble(paramValue);
2862                                                     sql = Utils.replaceInString(sql, fieldDisplay, nvl(
2863                                                             paramValue, "NULL"));
2864
2865                                                 } catch (NumberFormatException ex) {
2866                                                     if (sql.trim().toUpperCase()
2867                                                             .startsWith("SELECT")) {
2868                                                         sql = Utils.replaceInString(sql, fieldDisplay, nvl(
2869                                                                 paramValue, "NULL"));
2870                                                     } else
2871                                                         throw new UserDefinedException(
2872                                                                 "Expected number, Given String for the form field \""
2873                                                                         + fieldDisplay + "\"");
2874                                                 }
2875                                               
2876                                             } else
2877                                                 sql = Utils.replaceInString(sql, fieldDisplay, nvl(
2878                                                         paramValue, "NULL"));
2879
2880                                         }
2881                                     }
2882                                 } else {
2883                                     if ("DAYTONA".equals(dbType) && sql.trim().toUpperCase().startsWith("SELECT")) {
2884                                         sql = sql + " ";
2885                                         re1 = Pattern.compile("(^[\r\n]|[\\s]|[^0-9a-zA-Z])AND(.*?[^\r\n]*)" + "\\["
2886                                                 + fft.getFieldName() + "\\](.*?)\\s", Pattern.DOTALL);
2887                                         posFormField = sql.indexOf(fieldDisplay);
2888                                         posAnd = sql.lastIndexOf(" AND ", posFormField);
2889                                         if (posAnd < 0)
2890                                             posAnd = 0;
2891                                         else if (posAnd > 2)
2892                                             posAnd = posAnd - 2;
2893                                         matcher = re1.matcher(sql);
2894                                         if (matcher.find(posAnd)) {
2895                                             sql = sql.replace(matcher.group(), "");
2896                                         }
2897                                     } else {
2898                                         sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl(
2899                                                 paramValue, "NULL"));
2900                                         sql = Utils.replaceInString(sql, fieldDisplay, nvl(
2901                                                 paramValue, "NULL"));
2902                                     }
2903                                 }
2904                             }
2905
2906                         }
2907
2908                         if ("DAYTONA".equals(dbType) && sql.trim().toUpperCase().startsWith("SELECT")) {
2909                             sql = sql + " ";
2910                             re1 = Pattern.compile("(^[\r\n]|[\\s]|[^0-9a-zA-Z])AND(.*?[^\r\n]*)" + "\\["
2911                                     + fft.getFieldName() + "\\](.*?)\\s", Pattern.DOTALL); // +[\'\\)|\'|\\s]
2912                             posFormField = sql.indexOf(fieldDisplay);
2913                             posAnd = sql.lastIndexOf(" AND ", posFormField);
2914                             if (posAnd < 0)
2915                                 posAnd = 0;
2916                             else if (posAnd > 2)
2917                                 posAnd = posAnd - 2;
2918                             matcher = re1.matcher(sql);
2919                             if (matcher.find(posAnd)) {
2920                                 sql = sql.replace(matcher.group(), " ");
2921                             }
2922                         } else {
2923                             if (fft.isGroupFormField() != null && fft.isGroupFormField().booleanValue()) {
2924                                 sql = Pattern.compile("[[\\s*][,]]\\[" + fft.getFieldName() + "\\](.*?)[,]",
2925                                         Pattern.MULTILINE).matcher(sql).replaceAll(" ");
2926                                 sql = Pattern
2927                                         .compile("(,.+?)[\\s*]\\[" + fft.getFieldName() + "\\][\\s]", Pattern.MULTILINE)
2928                                         .matcher(sql).replaceAll(" ");
2929                                         } else {
2930                                 sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl(
2931                                         paramValue, "NULL"));
2932                                 sql = Utils.replaceInString(sql, fieldDisplay, nvl(
2933                                         paramValue, "NULL"));
2934                             }
2935                         }
2936
2937                                 } 
2938                                 }
2939                         } 
2940             if (request != null) {
2941                 for (int i = 0; i < reqParameters.length; i++) {
2942                     if (!reqParameters[i].startsWith("ff")) {
2943                         if (nvl(request.getParameter(reqParameters[i].toUpperCase())).length() > 0)
2944                             sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase() + "]",
2945                                     ESAPI.encoder().encodeForSQL(SecurityCodecUtil.getCodec(),
2946                                             request.getParameter(reqParameters[i].toUpperCase())));
2947                     } else
2948                         sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase() + "]", ESAPI.encoder()
2949                                 .encodeForSQL(SecurityCodecUtil.getCodec(), request.getParameter(reqParameters[i])));
2950                 }
2951
2952                 for (int i = 0; i < scheduleSessionParameters.length; i++) {
2953                     if (nvl(request.getParameter(scheduleSessionParameters[i])).trim().length() > 0)
2954                         sql = Utils.replaceInString(sql, "[" + scheduleSessionParameters[i].toUpperCase() + "]",
2955                                 ESAPI.encoder().encodeForSQL(SecurityCodecUtil.getCodec(),
2956                                         request.getParameter(scheduleSessionParameters[i])));
2957                 }
2958             }
2959             if (session != null) {
2960                 for (int i = 0; i < sessionParameters.length; i++) {
2961                     sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase() + "]",
2962                             (String) session.getAttribute(sessionParameters[i]));
2963                     
2964                 }
2965             }
2966         } else {
2967             sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId);
2968             sql = Utils.replaceInString(sql, "[USERID]", userId);
2969             sql = Utils.replaceInString(sql, "[USER_ID]", userId);
2970             if (request != null) {
2971                 for (int i = 0; i < reqParameters.length; i++) {
2972                     sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase() + "]", ESAPI.encoder()
2973                             .encodeForSQL(SecurityCodecUtil.getCodec(), request.getParameter(reqParameters[i])));
2974                 }
2975             }
2976             if (session != null) {
2977                 for (int i = 0; i < sessionParameters.length; i++) {
2978                     sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase() + "]",
2979                             (String) session.getAttribute(sessionParameters[i]));
2980                 }
2981             }
2982         }
2983         sql = Utils.replaceInString(sql, "[LOGGED_USERID]",
2984                 ESAPI.encoder().encodeForSQL(SecurityCodecUtil.getCodec(), userId));
2985         sql = Utils.replaceInString(sql, "[USERID]",
2986                 ESAPI.encoder().encodeForSQL(SecurityCodecUtil.getCodec(), userId));
2987         sql = Utils.replaceInString(sql, "[USER_ID]",
2988                 ESAPI.encoder().encodeForSQL(SecurityCodecUtil.getCodec(), userId));
2989
2990         int closeBracketPos = 0;
2991         if (nvl(overrideSortByColId).length() > 0) {
2992             if (sql.lastIndexOf(")") != -1)
2993                 closeBracketPos = sql.lastIndexOf(")");
2994             int idxOrderBy = (closeBracketPos > 0) ? sql.toUpperCase().indexOf("ORDER BY", closeBracketPos)
2995                     : sql.toUpperCase().lastIndexOf("ORDER BY");
2996             DataColumnType dct = getColumnById(overrideSortByColId + "_sort");
2997             if (dct != null && dct.getColName().length() > 0) {
2998                 overrideSortByColId = overrideSortByColId + "_sort";
2999             }
3000             if (idxOrderBy < 0)
3001                 sql += " ORDER BY " + overrideSortByColId + " " + overrideSortByAscDesc;
3002             else {
3003                 int braketCount = 0;
3004                 int idxOrderByClauseEnd = 0;
3005                 for (idxOrderByClauseEnd = idxOrderBy; idxOrderByClauseEnd < sql.length(); idxOrderByClauseEnd++) {
3006                     char ch = sql.charAt(idxOrderByClauseEnd);
3007
3008                     if (ch == '(')
3009                         braketCount++;
3010                     else if (ch == ')') {
3011                         if (braketCount == 0)
3012                             break;
3013                         braketCount--;
3014                     }
3015                                 }
3016
3017                 sql = sql.substring(0, idxOrderBy) + " ORDER BY " + overrideSortByColId + " "
3018                         + overrideSortByAscDesc + sql.substring(idxOrderByClauseEnd);
3019                         }
3020                 } 
3021         sql = Pattern.compile("([\n][\\s]*)", Pattern.DOTALL).matcher(sql).replaceAll(" ");
3022         return sql;
3023         } 
3024
3025     public String generateSQLVisual(ReportParamValues paramValues, String overrideSortByColId,
3026             String overrideSortByAscDesc, String userId, HttpServletRequest request) throws RaptorException {
3027         StringBuffer selectCl = new StringBuffer();
3028         StringBuffer fromCl = new StringBuffer();
3029         StringBuffer whereCl = new StringBuffer();
3030         StringBuffer groupByCl = new StringBuffer();
3031         StringBuffer havingCl = new StringBuffer();
3032         StringBuffer orderByCl = new StringBuffer();
3033         StringBuffer selectExtraIdCl = new StringBuffer();
3034         StringBuffer selectExtraDateCl = new StringBuffer();
3035
3036         int whereClBracketCount = 0;
3037         int havingClBracketCount = 0;
3038         int whereClCarryoverBrackets = 0;
3039         int havingClCarryoverBrackets = 0;
3040
3041         List dsList = getDataSourceList().getDataSource();
3042         for (Iterator iter = dsList.iterator(); iter.hasNext();) {
3043             DataSourceType ds = (DataSourceType) iter.next();
3044
3045             if (fromCl.length() > 0)
3046                 fromCl.append(", ");
3047             fromCl.append(ds.getTableName());
3048             fromCl.append(" ");
3049             fromCl.append(ds.getTableId());
3050
3051             if (nvl(ds.getRefTableId()).length() > 0) {
3052                 if (whereCl.length() > 0)
3053                     whereCl.append(" AND ");
3054                 whereCl.append(ds.getRefDefinition());
3055                         }
3056             TableSource tableSource = null;
3057             String dBInfo = this.cr.getDbInfo();
3058             Vector userRoles = AppUtils.getUserRoles(request);
3059             tableSource = DataCache.getTableSource(ds.getTableName(), dBInfo, userRoles, userId, request);
3060             if (userId != null && (!AppUtils.isSuperUser(request))
3061                     && (!AppUtils.isAdminUser(request)) && tableSource != null
3062                     && nvl(tableSource.getFilterSql()).length() > 0) {
3063                 if (whereCl.length() > 0)
3064                     whereCl.append(" AND ");
3065                 whereCl.append(Utils.replaceInString(Utils.replaceInString(tableSource
3066                         .getFilterSql(), "[" + ds.getTableName() + "]", ds.getTableId()),
3067                         "[USER_ID]", userId));
3068                         }
3069                 }
3070
3071         List reportCols = getAllColumns();
3072
3073         boolean isGroupStmt = false;
3074         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3075             DataColumnType dc = (DataColumnType) iter.next();
3076             if (dc.isGroupBreak()) {
3077                 isGroupStmt = true;
3078                 break;
3079                         } 
3080                 }
3081
3082
3083         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3084             DataColumnType dc = (DataColumnType) iter.next();
3085             String colName = getColumnSelectStr(dc, paramValues);
3086
3087             if (selectCl.length() > 0)
3088                 selectCl.append(", ");
3089             selectCl.append(getSelectExpr(dc, colName));
3090             selectCl.append(" ");
3091             selectCl.append(dc.getColId());
3092             if (nvl(dc.getDrillDownURL()).length() > 0)
3093                 if (isViewAction(dc.getDrillDownURL()))
3094                     addExtraIdSelect(selectExtraIdCl, nvl(dc.getDrillDownParams()), true);
3095                 else
3096                     addExtraDateSelect(selectExtraDateCl, nvl(dc.getDrillDownParams()),
3097                             paramValues, true);
3098             if (dc.isGroupBreak()) {
3099                 if (groupByCl.length() > 0)
3100                     groupByCl.append(", ");
3101                 groupByCl.append(colName);
3102                         } 
3103             boolean isHavingCl = isGroupStmt && (!dc.isGroupBreak());
3104             StringBuffer filterCl = isHavingCl ? havingCl : whereCl;
3105
3106             if (dc.getColFilterList() != null) {
3107                 int fNo = 0;
3108                 List fList = dc.getColFilterList().getColFilter();
3109                 for (Iterator iterF = fList.iterator(); iterF.hasNext(); fNo++) {
3110                     ColFilterType cf = (ColFilterType) iterF.next();
3111
3112                     StringBuffer curFilter = new StringBuffer();
3113                     if (filterCl.length() > 0)
3114                         curFilter.append(" " + cf.getJoinCondition() + " ");
3115                     if ((isHavingCl ? havingClCarryoverBrackets : whereClCarryoverBrackets) > 0)
3116                         for (int b = 0; b < (isHavingCl ? havingClCarryoverBrackets
3117                                 : whereClCarryoverBrackets); b++)
3118                             filterCl.append('(');
3119                     curFilter.append(nvl(cf.getOpenBrackets()));
3120                     curFilter.append(colName + " ");
3121                     curFilter.append(cf.getExpression() + " ");
3122
3123                     boolean applyFilter = true;
3124                     if ((nvl(cf.getArgValue()).length() > 0)
3125                             || (nvl(cf.getArgType()).equals(AppConstants.AT_FORM)))
3126                         if (nvl(cf.getArgType()).equals(AppConstants.AT_FORMULA))
3127                             curFilter.append(cf.getArgValue());
3128                         else if (nvl(cf.getArgType()).equals(AppConstants.AT_VALUE))
3129                             curFilter.append(formatValue(cf.getArgValue(), dc, false));
3130                         else if (nvl(cf.getArgType()).equals(AppConstants.AT_LIST))
3131                             curFilter.append(formatListValue(cf.getArgValue(), dc, false,
3132                                     false));
3133                         else if (nvl(cf.getArgType()).equals(AppConstants.AT_COLUMN))
3134                             curFilter.append(getColumnNameById(cf.getArgValue()));
3135                         else if (nvl(cf.getArgType()).equals(AppConstants.AT_FORM)) {
3136                             String fieldName = getFormFieldName(cf);
3137                             String fieldValue = Utils.oracleSafe(paramValues
3138                                     .getParamValue(fieldName));
3139                             boolean isMultiValue = paramValues
3140                                     .isParameterMultiValue(fieldName);
3141                             boolean usePipeDelimiterOnly = false;
3142
3143                             FormFieldType fft = getFormFieldByDisplayValue(cf.getArgValue());
3144                             if (fft == null)
3145                                 fieldValue = nvl(fieldValue, Utils
3146                                         .oracleSafe(cf.getArgValue()));
3147                             else
3148                                 usePipeDelimiterOnly = fft.getFieldType().equals(
3149                                         FormField.FFT_CHECK_BOX)
3150                                         || fft.getFieldType().equals(FormField.FFT_LIST_MULTI);
3151                             if (fft != null) {
3152                                 String fieldId = fft.getFieldId();
3153                                 if (fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)
3154                                         || fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)
3155                                         || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
3156                                     fieldValue = nvl(
3157                                             fieldValue + " " + addZero(Utils.oracleSafe(nvl(paramValues
3158                                                     .getParamValue(fieldId + "_Hr")))));
3159                                     if (fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)
3160                                             || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
3161                                         fieldValue = fieldValue + (nvl(paramValues
3162                                                 .getParamValue(fieldId + "_Min")).length() > 0
3163                                                         ? ":" + addZero(Utils.oracleSafe(nvl(paramValues
3164                                                                 .getParamValue(fieldId + "_Min"))))
3165                                                         : "");
3166                                     }
3167                                     if (fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
3168                                         fieldValue = fieldValue + (nvl(paramValues
3169                                                 .getParamValue(fieldId + "_Sec")).length() > 0
3170                                                         ? ":" + addZero(Utils.oracleSafe(nvl(paramValues
3171                                                                 .getParamValue(fieldId + "_Sec"))))
3172                                                         : "");
3173                                     }
3174                                 }
3175                             }
3176
3177                             // End
3178                             if (nvl(fieldValue).length() == 0) {
3179                                 // Does not append filter with missing form
3180                                 // field argument
3181                                 applyFilter = false;
3182                             } else if (isMultiValue || "IN".equals(nvl(cf.getExpression()))
3183                                     || "NOT IN".equals(nvl(cf.getExpression()))) {
3184                                 curFilter.append(formatListValue(fieldValue, dc, true,
3185                                         usePipeDelimiterOnly));
3186                             } else {
3187                                 curFilter.append(formatValue(fieldValue, dc, true, getColumnTableById(dc.getColId()), fft));
3188                             }
3189                         } // else
3190                     curFilter.append(nvl(cf.getCloseBrackets()));
3191
3192                     if (applyFilter) {
3193                         filterCl.append(curFilter.toString());
3194
3195                         if (isHavingCl) {
3196                             havingClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl(
3197                                     cf.getCloseBrackets()).length());
3198                             havingClCarryoverBrackets = 0;
3199                         } else {
3200                             whereClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl(
3201                                     cf.getCloseBrackets()).length());
3202                             whereClCarryoverBrackets = 0;
3203                         }
3204                     } else if (nvl(cf.getOpenBrackets()).length() != nvl(cf.getCloseBrackets())
3205                             .length())
3206                         if (nvl(cf.getOpenBrackets()).length() > nvl(cf.getCloseBrackets())
3207                                 .length()) {
3208                             if (isHavingCl)
3209                                 havingClCarryoverBrackets += (nvl(cf.getOpenBrackets())
3210                                         .length() - nvl(cf.getCloseBrackets()).length());
3211                             else
3212                                 whereClCarryoverBrackets += (nvl(cf.getOpenBrackets())
3213                                         .length() - nvl(cf.getCloseBrackets()).length());
3214
3215                             if (isHavingCl)
3216                                 havingClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl(
3217                                         cf.getCloseBrackets()).length());
3218                             else
3219                                 whereClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl(
3220                                         cf.getCloseBrackets()).length());
3221                         } else {
3222                                                 
3223                             if (filterCl.length() > 0) {
3224                                 for (int b = 0; b < nvl(cf.getCloseBrackets()).length()
3225                                         - nvl(cf.getOpenBrackets()).length(); b++)
3226                                     filterCl.append(')');
3227
3228                                 if (isHavingCl)
3229                                     havingClBracketCount += (nvl(cf.getOpenBrackets())
3230                                             .length() - nvl(cf.getCloseBrackets()).length());
3231                                 else
3232                                     whereClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl(
3233                                             cf.getCloseBrackets()).length());
3234                                                         } 
3235                                                 } 
3236                                 } 
3237                         } 
3238                 }
3239
3240         DataColumnType overrideSortByCol = null;
3241         if (overrideSortByColId != null)
3242             overrideSortByCol = getColumnById(overrideSortByColId);
3243
3244         if (overrideSortByCol != null) {
3245             orderByCl.append(getColumnSelectStr(overrideSortByCol, paramValues));
3246             orderByCl.append(" ");
3247             orderByCl.append(nvl(overrideSortByAscDesc, AppConstants.SO_ASC));
3248         } else if (getReportType().equals(AppConstants.RT_CROSSTAB)) {
3249
3250         } else {
3251             Collections.sort(reportCols, new OrderBySeqComparator());
3252             for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3253                 DataColumnType dc = (DataColumnType) iter.next();
3254
3255                 if (dc.getOrderBySeq() > 0) {
3256                     if (orderByCl.length() > 0)
3257                         orderByCl.append(", ");
3258                     orderByCl.append(getColumnSelectStr(dc, paramValues));
3259                     orderByCl.append(" ");
3260                     orderByCl.append(dc.getOrderByAscDesc());
3261                                 } 
3262                         } 
3263             Collections.sort(reportCols, new OrderSeqComparator());
3264                 } 
3265
3266         StringBuffer sql = new StringBuffer();
3267         sql.append(Globals.getGenerateSqlVisualSelect());
3268         sql.append((selectCl.length() == 0) ? Globals.getGenerateSqlVisualCount() : selectCl.toString());
3269         if (groupByCl.length() == 0)
3270             sql.append(selectExtraIdCl.toString());
3271         sql.append(selectExtraDateCl.toString());
3272         sql.append((fromCl.length() == 0) ? Globals.getGenerateSqlVisualDual() : "FROM " + fromCl.toString());
3273         if (whereCl.length() > 0) {
3274             if (whereClBracketCount > 0) {
3275                 for (int b = 0; b < whereClBracketCount; b++)
3276                     whereCl.append(')');
3277             } else if (whereClBracketCount < 0) {
3278                 for (int b = 0; b < Math.abs(whereClBracketCount); b++)
3279                     whereCl.insert(0, '(');
3280                         }
3281
3282             sql.append(" WHERE ");
3283             sql.append(whereCl.toString());
3284                 }
3285         if (groupByCl.length() > 0) {
3286             sql.append(" GROUP BY ");
3287             sql.append(groupByCl.toString());
3288
3289             if (havingCl.length() > 0) {
3290                 if (havingClBracketCount > 0) {
3291                     for (int b = 0; b < havingClBracketCount; b++)
3292                         havingCl.append(')');
3293                 } else if (havingClBracketCount < 0) {
3294                     for (int b = 0; b < Math.abs(havingClBracketCount); b++)
3295                         havingCl.insert(0, '(');
3296                                 }
3297
3298                 sql.append(" HAVING ");
3299                 sql.append(havingCl.toString());
3300             }
3301         }
3302         if (orderByCl.length() > 0) {
3303             sql.append(" ORDER BY ");
3304             sql.append(orderByCl.toString());
3305         }
3306         return sql.toString();
3307         } 
3308
3309     public String generateSQLCrossTabVisual(ReportParamValues paramValues, String overrideSortByColId,
3310             String overrideSortByAscDesc, String userId, HttpServletRequest request) throws RaptorException {
3311         StringBuffer selectCl = new StringBuffer();
3312         StringBuffer fromCl = new StringBuffer();
3313         StringBuffer whereCl = new StringBuffer();
3314         StringBuffer groupByCl = new StringBuffer();
3315         StringBuffer havingCl = new StringBuffer();
3316         StringBuffer orderByCl = new StringBuffer();
3317         StringBuffer selectExtraIdCl = new StringBuffer();
3318         StringBuffer selectExtraDateCl = new StringBuffer();
3319
3320         int whereClBracketCount = 0;
3321         int havingClBracketCount = 0;
3322         int whereClCarryoverBrackets = 0;
3323         int havingClCarryoverBrackets = 0;
3324
3325         List dsList = getDataSourceList().getDataSource();
3326         for (Iterator iter = dsList.iterator(); iter.hasNext();) {
3327             DataSourceType ds = (DataSourceType) iter.next();
3328
3329             if (fromCl.length() > 0)
3330                 fromCl.append(", ");
3331             fromCl.append(ds.getTableName());
3332             fromCl.append(" ");
3333             fromCl.append(ds.getTableId());
3334
3335             if (nvl(ds.getRefTableId()).length() > 0) {
3336                 if (whereCl.length() > 0)
3337                     whereCl.append(" AND ");
3338                 whereCl.append(ds.getRefDefinition());
3339             } 
3340             TableSource tableSource = null;
3341             String dBInfo = this.cr.getDbInfo();
3342             Vector userRoles = AppUtils.getUserRoles(request);
3343             tableSource = DataCache.getTableSource(ds.getTableName(), dBInfo, userRoles, userId, request);
3344             if (userId != null && (!AppUtils.isSuperUser(request))
3345                     && (!AppUtils.isAdminUser(request)) && tableSource != null
3346                     && nvl(tableSource.getFilterSql()).length() > 0) {
3347                 if (whereCl.length() > 0)
3348                     whereCl.append(" AND ");
3349                 whereCl.append(Utils.replaceInString(Utils.replaceInString(tableSource
3350                         .getFilterSql(), "[" + ds.getTableName() + "]", ds.getTableId()),
3351                         "[USER_ID]", userId));
3352             }
3353         } 
3354
3355         List reportCols = getAllColumns();
3356
3357         boolean isGroupStmt = false;
3358         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3359             DataColumnType dc = (DataColumnType) iter.next();
3360             if (dc.isGroupBreak()) {
3361                 isGroupStmt = true;
3362                 break;
3363             } 
3364         } 
3365
3366         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3367             DataColumnType dc = (DataColumnType) iter.next();
3368             String colName = getColumnSelectStr(dc, paramValues);
3369
3370             
3371             if (dc.isVisible()) {
3372                 if (selectCl.length() > 0)
3373                     selectCl.append(", ");
3374                 selectCl.append(getSelectExpr(dc, colName));
3375                 selectCl.append(" ");
3376                 selectCl.append(dc.getColId());
3377              } 
3378
3379
3380             if (nvl(dc.getDrillDownURL()).length() > 0)
3381                 if (isViewAction(dc.getDrillDownURL()))
3382                     addExtraIdSelect(selectExtraIdCl, nvl(dc.getDrillDownParams()), true);
3383                 else
3384                     addExtraDateSelect(selectExtraDateCl, nvl(dc.getDrillDownParams()),
3385                             paramValues, true);
3386
3387             if (dc.isGroupBreak()) {
3388                 if (groupByCl.length() > 0)
3389                     groupByCl.append(", ");
3390                 groupByCl.append(colName);
3391             } 
3392             boolean isHavingCl = isGroupStmt && dc.isVisible() && (!dc.isGroupBreak());
3393             StringBuffer filterCl =
3394                     isGroupStmt ? (dc.isVisible() ? (dc.isGroupBreak() ? whereCl : havingCl) : whereCl) : whereCl;
3395             if (dc.getColFilterList() != null) {
3396                 int fNo = 0;
3397                 List fList = dc.getColFilterList().getColFilter();
3398                 for (Iterator iterF = fList.iterator(); iterF.hasNext(); fNo++) {
3399                     ColFilterType cf = (ColFilterType) iterF.next();
3400
3401                     StringBuffer curFilter = new StringBuffer();
3402                     if (filterCl.length() > 0)
3403                         curFilter.append(" " + cf.getJoinCondition() + " ");
3404                     if ((isHavingCl ? havingClCarryoverBrackets : whereClCarryoverBrackets) > 0)
3405                         for (int b = 0; b < (isHavingCl ? havingClCarryoverBrackets
3406                                 : whereClCarryoverBrackets); b++)
3407                             filterCl.append('(');
3408                     curFilter.append(nvl(cf.getOpenBrackets()));
3409                     curFilter.append(colName + " ");
3410                     curFilter.append(cf.getExpression() + " ");
3411
3412                     boolean applyFilter = true;
3413                     if ((nvl(cf.getArgValue()).length() > 0)
3414                             || (nvl(cf.getArgType()).equals(AppConstants.AT_FORM)))
3415                         if (nvl(cf.getArgType()).equals(AppConstants.AT_FORMULA))
3416                             curFilter.append(cf.getArgValue());
3417                         else if (nvl(cf.getArgType()).equals(AppConstants.AT_VALUE))
3418                             curFilter.append(formatValue(cf.getArgValue(), dc, false));
3419                         else if (nvl(cf.getArgType()).equals(AppConstants.AT_LIST))
3420                             curFilter.append(formatListValue(cf.getArgValue(), dc, false,
3421                                     false));
3422                         else if (nvl(cf.getArgType()).equals(AppConstants.AT_COLUMN))
3423                             curFilter.append(getColumnNameById(cf.getArgValue()));
3424                         else if (nvl(cf.getArgType()).equals(AppConstants.AT_FORM)) {
3425                             String fieldName = getFormFieldName(cf);
3426                             String fieldValue = Utils.oracleSafe(paramValues
3427                                     .getParamValue(fieldName));
3428                             boolean isMultiValue = paramValues
3429                                     .isParameterMultiValue(fieldName);
3430                             boolean usePipeDelimiterOnly = false;
3431
3432                             FormFieldType fft = getFormFieldByDisplayValue(cf.getArgValue());
3433                             if (fft == null)
3434                                 fieldValue = nvl(fieldValue, Utils
3435                                         .oracleSafe(cf.getArgValue()));
3436                             else
3437                                 usePipeDelimiterOnly = fft.getFieldType().equals(
3438                                         FormField.FFT_CHECK_BOX)
3439                                         || fft.getFieldType().equals(FormField.FFT_LIST_MULTI);
3440
3441                             if (nvl(fieldValue).length() == 0)
3442                                 applyFilter = false;
3443                             else if (isMultiValue || "IN".equals(nvl(cf.getExpression()))
3444                                     || "NOT IN".equals(nvl(cf.getExpression())))
3445                                 curFilter.append(formatListValue(fieldValue, dc, true,
3446                                         usePipeDelimiterOnly));
3447                             else
3448                                 curFilter.append(formatValue(fieldValue, dc, true));
3449                         } 
3450                     curFilter.append(nvl(cf.getCloseBrackets()));
3451
3452                     if (applyFilter) {
3453                         filterCl.append(curFilter.toString());
3454
3455                         if (isHavingCl) {
3456                             havingClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl(
3457                                     cf.getCloseBrackets()).length());
3458                             havingClCarryoverBrackets = 0;
3459                         } else {
3460                             whereClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl(
3461                                     cf.getCloseBrackets()).length());
3462                             whereClCarryoverBrackets = 0;
3463                         }
3464                     } else if (nvl(cf.getOpenBrackets()).length() != nvl(cf.getCloseBrackets())
3465                             .length())
3466                         if (nvl(cf.getOpenBrackets()).length() > nvl(cf.getCloseBrackets())
3467                                 .length()) {
3468                             if (isHavingCl)
3469                                 havingClCarryoverBrackets += (nvl(cf.getOpenBrackets())
3470                                         .length() - nvl(cf.getCloseBrackets()).length());
3471                             else
3472                                 whereClCarryoverBrackets += (nvl(cf.getOpenBrackets())
3473                                         .length() - nvl(cf.getCloseBrackets()).length());
3474
3475                             if (isHavingCl)
3476                                 havingClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl(
3477                                         cf.getCloseBrackets()).length());
3478                             else
3479                                 whereClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl(
3480                                         cf.getCloseBrackets()).length());
3481                         } else {
3482                             if (filterCl.length() > 0) {
3483                                 for (int b = 0; b < nvl(cf.getCloseBrackets()).length()
3484                                         - nvl(cf.getOpenBrackets()).length(); b++)
3485                                     filterCl.append(')');
3486
3487                                 if (isHavingCl)
3488                                     havingClBracketCount += (nvl(cf.getOpenBrackets())
3489                                             .length() - nvl(cf.getCloseBrackets()).length());
3490                                 else
3491                                     whereClBracketCount += (nvl(cf.getOpenBrackets()).length() - nvl(
3492                                             cf.getCloseBrackets()).length());
3493                             } 
3494                         } 
3495                 }
3496             } 
3497         } 
3498
3499         DataColumnType overrideSortByCol = null;
3500         if (overrideSortByColId != null)
3501             overrideSortByCol = getColumnById(overrideSortByColId);
3502
3503         if (overrideSortByCol != null) {
3504             orderByCl.append(getColumnSelectStr(overrideSortByCol, paramValues));
3505             orderByCl.append(" ");
3506             orderByCl.append(nvl(overrideSortByAscDesc, AppConstants.SO_ASC));
3507         } else if (getReportType().equals(AppConstants.RT_CROSSTAB)) {
3508         } else {
3509             Collections.sort(reportCols, new OrderBySeqComparator());
3510             for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3511                 DataColumnType dc = (DataColumnType) iter.next();
3512
3513                 if (dc.getOrderBySeq() > 0) {
3514                     if (orderByCl.length() > 0)
3515                         orderByCl.append(", ");
3516                     orderByCl.append(getColumnSelectStr(dc, paramValues));
3517                     orderByCl.append(" ");
3518                     orderByCl.append(dc.getOrderByAscDesc());
3519                 } 
3520             } 
3521             Collections.sort(reportCols, new OrderSeqComparator());
3522         } 
3523
3524
3525         StringBuffer sql = new StringBuffer();
3526         sql.append(Globals.getGenerateSqlVisualSelect());
3527         sql.append((selectCl.length() == 0) ? Globals.getGenerateSqlVisualCount() : selectCl.toString());
3528         if (groupByCl.length() == 0)
3529             sql.append(selectExtraIdCl.toString());
3530         sql.append(selectExtraDateCl.toString());
3531         sql.append((fromCl.length() == 0) ? Globals.getGenerateSqlVisualDual() : "FROM " + fromCl.toString());
3532         if (whereCl.length() > 0) {
3533             if (whereClBracketCount > 0) {
3534                 for (int b = 0; b < whereClBracketCount; b++)
3535                     whereCl.append(')');
3536             } else if (whereClBracketCount < 0) {
3537                 for (int b = 0; b < Math.abs(whereClBracketCount); b++)
3538                     whereCl.insert(0, '(');
3539             } 
3540
3541             sql.append(" WHERE ");
3542             sql.append(whereCl.toString());
3543         } 
3544         if (groupByCl.length() > 0) {
3545             sql.append(" GROUP BY ");
3546             sql.append(groupByCl.toString());
3547
3548             if (havingCl.length() > 0) {
3549                 if (havingClBracketCount > 0) {
3550                     for (int b = 0; b < havingClBracketCount; b++)
3551                         havingCl.append(')');
3552                 } else if (havingClBracketCount < 0) {
3553                     for (int b = 0; b < Math.abs(havingClBracketCount); b++)
3554                         havingCl.insert(0, '(');
3555                 } 
3556                 sql.append(" HAVING ");
3557                 sql.append(havingCl.toString());
3558             }
3559         }
3560         if (orderByCl.length() > 0) {
3561             sql.append(" ORDER BY ");
3562             sql.append(orderByCl.toString());
3563         }
3564
3565         logger.debug(EELFLoggerDelegate.debugLogger, "Created SQL statement: {}", sql);
3566
3567         return sql.toString();
3568     } 
3569
3570     public String generatePagedSQL(int pageNo, String userId, HttpServletRequest request,
3571             boolean getColumnNamesFromReportSQL, ReportParamValues paramValues) throws RaptorException {
3572         int counter = 0;
3573         if (!Globals.isMySQL())
3574             counter = 1;
3575         return generateSubsetSQL(pageNo * getPageSize() + counter, ((pageNo + 1) * getPageSize())
3576                 + ((pageNo == 0) ? 1 : 0), userId, request, getColumnNamesFromReportSQL, paramValues);
3577         } 
3578
3579     public String generateSubsetSQL(int startRow, int endRow, String userId, HttpServletRequest request,
3580             boolean getColumnNamesFromReportSQL, ReportParamValues paramValues) throws RaptorException {
3581         String dbInfo = getDBInfo();
3582         String dbType = "";
3583                 String partSql = "";
3584                 String reportSQL = getWholeSQL();
3585                 if (!CachingUtils.isReportSqlExists(request.getSession().getId()+reportSQL)) {
3586         if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) {
3587             try {
3588                 dbType = remDbInfo.getDBType(dbInfo);
3589             } catch (Exception ex) {
3590                 throw new RaptorException(ex);
3591             }
3592         }
3593         List reportCols = getAllColumns();
3594         String wholeSQL_OrderBy = getWholeSQL();
3595         reportSQL = reportSQL.replace(";", "");
3596         setWholeSQL(reportSQL);
3597         if (nvl(reportSQL).length() > 0)
3598             reportSQL = generateSQL(userId, request);
3599         if (nvl(reportSQL).toUpperCase().indexOf("ORDER BY ") < 0) {
3600             StringBuffer sortBy = null;
3601
3602             if (nvl(reportSQL).toUpperCase().indexOf("GROUP BY ") < 0)
3603                 if (getDataSourceList().getDataSource().size() > 0) {
3604                                                 DataSourceType dst = (DataSourceType) getDataSourceList().getDataSource().get(0);
3605                     String tId = dst.getTableId();
3606                     String tPK = dst.getTablePK();
3607                     if (nvl(tPK).length() > 0) {
3608                         sortBy = new StringBuffer();
3609                         StringTokenizer st = new StringTokenizer(tPK, ", ");
3610                         while (st.hasMoreTokens()) {
3611                             if (sortBy.length() > 0)
3612                                 sortBy.append(",");
3613                             sortBy.append(tId);
3614                             sortBy.append(".");
3615                             sortBy.append(st.nextToken());
3616                     }
3617                                                 }
3618                                         } 
3619             if (nvl(reportSQL).trim().toUpperCase().startsWith("SELECT")) {
3620
3621             }
3622         }
3623         StringBuffer colNames = new StringBuffer();
3624         StringBuffer colExtraIdNames = new StringBuffer();
3625         StringBuffer colExtraDateNames = new StringBuffer();
3626
3627         if (getColumnNamesFromReportSQL) {
3628                                 String getColumnDef = "SELECT * FROM ( "+reportSQL+ ") derivedtable WHERE 1 > 2 ";
3629                                 DataSet ds = ConnectionUtils.getDataSet(getColumnDef, dbInfo);
3630             List reportCols1 = getAllColumns();
3631             reportCols = new Vector();
3632             outer: for (Iterator iter = reportCols1.iterator(); iter.hasNext();) {
3633                 DataColumnType dct = (DataColumnType) iter.next();
3634                 for (int k = 0; k < ds.getColumnCount(); k++) {
3635                     if (dct.getColId().toUpperCase().trim().equals(ds.getColumnName(k).trim())) {
3636                         reportCols.add(dct);
3637                         continue outer;
3638                     }
3639                 }
3640             }
3641
3642             if (getFormFieldList() != null) {
3643                 String paramValue = "";
3644                 for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) {
3645                     FormFieldType fft = (FormFieldType) iter.next();
3646                     if (fft.isGroupFormField() != null && fft.isGroupFormField().booleanValue()) {
3647                         paramValue = Utils.oracleSafe(nvl(paramValues
3648                                 .getParamValue(fft.getFieldId())));
3649                         outer: for (Iterator iter1 = reportCols1.iterator(); iter1.hasNext();) {
3650                             DataColumnType dct = (DataColumnType) iter1.next();
3651                             if (("[" + fft.getFieldName() + "]").equals(dct.getColName().trim())) {
3652                                 dct.setDisplayName(paramValue);
3653                                 continue outer;
3654                             }
3655                         }
3656
3657                     }
3658                 }
3659             }
3660
3661         }
3662
3663         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3664             DataColumnType dc = (DataColumnType) iter.next();
3665             if (colNames.length() > 0)
3666                 colNames.append(", ");
3667             colNames.append(dc.getColId());
3668             if (nvl(dc.getDrillDownURL()).length() > 0)
3669                 if (isViewAction(dc.getDrillDownURL()))
3670                     addExtraIdSelect(colExtraIdNames, nvl(dc.getDrillDownParams()), false);
3671                 else
3672                                                 addExtraDateSelect(colExtraDateNames, nvl(dc.getDrillDownParams()), null, false);
3673                         }
3674
3675         if (reportSQL.toUpperCase().indexOf("GROUP BY ") < 0)
3676             colNames.append(colExtraIdNames.toString());
3677
3678         if ("DAYTONA".equals(dbType) && reportSQL.trim().toUpperCase().startsWith("SELECT")) {
3679             if (endRow == -1)
3680                                         endRow = (getMaxRowsInExcelDownload() > 0) ? getMaxRowsInExcelDownload()
3681                                                         : Globals.getDownloadLimit();
3682             reportSQL = reportSQL + " LIMIT TO " + (startRow == 0 ? startRow + 1 : startRow) + "->" + endRow;
3683             return reportSQL;
3684         } else if ("DAYTONA".equals(dbType)) {
3685             return reportSQL;
3686         }
3687
3688
3689         String rSQL = Globals.getGenerateSubsetSql();
3690         rSQL = rSQL.replace("[colNames.toString()]", colNames.toString());
3691         rSQL = rSQL.replace("[reportSQL]", reportSQL);
3692
3693         reportSQL = rSQL;
3694
3695         reportSQLOnlyFirstPart = Globals.getReportSqlOnlyFirstPart();
3696         reportSQLOnlyFirstPart = reportSQLOnlyFirstPart.replace("[colNames.toString()]", colNames.toString());
3697
3698         reportSQLWithRowNum = reportSQL;
3699
3700         String parta = Globals.getReportSqlOnlySecondPartA();
3701         String partb = Globals.getReportSqlOnlySecondPartB();
3702
3703         if (!AppUtils.isNotEmpty(getDBType())) {
3704             setDBType(Globals.getDBType());
3705         }
3706
3707         int closeBracketPos = 0;
3708         if (wholeSQL_OrderBy.lastIndexOf(")") != -1)
3709             closeBracketPos = wholeSQL_OrderBy.lastIndexOf(")");
3710         int idxOrderBy = (closeBracketPos > 0) ? wholeSQL_OrderBy.toUpperCase().indexOf("ORDER BY", closeBracketPos)
3711                 : wholeSQL_OrderBy.toUpperCase().lastIndexOf("ORDER BY");
3712         String orderbyclause = "";
3713         if (idxOrderBy < 0) {
3714             orderbyclause = " ORDER BY 1 ";
3715             partSql += " " + orderbyclause + " ";
3716         } else {
3717             orderbyclause = wholeSQL_OrderBy.substring(idxOrderBy);
3718             partSql += " " + orderbyclause + " ";
3719         }
3720
3721                         CachingUtils.putPageSql(request.getSession().getId()+getWholeSQL(), partSql);
3722                         CachingUtils.putReportSql(request.getSession().getId()+getWholeSQL(), reportSQL);
3723                 }else {
3724                         if (!AppUtils.isNotEmpty(getDBType())) {
3725                                 setDBType(Globals.getDBType());
3726                         }
3727                 }
3728                 if(startRow >= 0 && CachingUtils.isReportSqlExists(request.getSession().getId()+getWholeSQL()) ) {
3729                         partSql = CachingUtils.getPageSql(request.getSession().getId()+getWholeSQL());
3730                         reportSQL = CachingUtils.getReportSql(request.getSession().getId()+getWholeSQL());
3731                         }
3732                 
3733         if (getDBType().equals(AppConstants.MYSQL)) {
3734             partSql = partSql + " LIMIT " + String.valueOf(startRow) + " , " + String.valueOf(endRow);
3735         } else if (getDBType().equals(AppConstants.ORACLE)) {
3736             partSql = "where rnum >= " + String.valueOf(startRow) + " and rnum <= "
3737                     + ( Integer.parseInt(String.valueOf(endRow)));
3738         } else if (getDBType().equals(AppConstants.POSTGRESQL)) {
3739             partSql = partSql + " LIMIT " + String.valueOf(endRow) + " , " + String.valueOf(startRow);
3740         }
3741
3742          
3743         reportSQL += partSql;
3744
3745         return reportSQL;
3746
3747         } 
3748
3749     public String generateChartSQL(ReportParamValues paramValues, String userId, HttpServletRequest request)
3750             throws RaptorException {
3751         List reportCols = getAllColumns();
3752         List chartValueCols = getChartValueColumnsList(AppConstants.CHART_ALL_COLUMNS, null); 
3753         String reportSQL = generateSQL(userId, request);
3754         logger.debug(EELFLoggerDelegate.debugLogger, ("SQL " + reportSQL));
3755         String legendCol = "1 a";
3756         StringBuffer groupCol = new StringBuffer();
3757         StringBuffer seriesCol = new StringBuffer();
3758         StringBuffer valueCols = new StringBuffer();
3759
3760         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3761             DataColumnType dc = (DataColumnType) iter.next();
3762             String colName = getColumnSelectStr(dc, paramValues);
3763             if (nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND))
3764                 legendCol = getSelectExpr(dc, colName) + " " + dc.getColId();
3765             if ((!nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND))
3766                     && (dc.getChartSeq() == null || dc.getChartSeq() <= 0) && dc.isGroupBreak()) {
3767                 groupCol.append(", ");
3768                 groupCol.append(colName + " " + dc.getColId());
3769             }
3770                 } 
3771         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3772             DataColumnType dc = (DataColumnType) iter.next();
3773             if (dc.isChartSeries() != null && dc.isChartSeries().booleanValue()) {
3774                 seriesCol.append(", " + getSelectExpr(dc, getColumnSelectStr(dc, paramValues)) + " " + dc.getColId());
3775             }
3776         }
3777
3778
3779         for (Iterator iter = chartValueCols.iterator(); iter.hasNext();) {
3780             DataColumnType dc = (DataColumnType) iter.next();
3781             String colName = getColumnSelectStr(dc, paramValues);
3782             seriesCol.append("," + formatChartColumn(colName) + " " + dc.getColId());
3783                 } 
3784
3785         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3786             DataColumnType dc = (DataColumnType) iter.next();
3787             String colName = getColumnSelectStr(dc, paramValues);
3788             if (colName.equals(AppConstants.RI_CHART_TOTAL_COL))
3789                 seriesCol.append(", " + AppConstants.RI_CHART_TOTAL_COL + " " + AppConstants.RI_CHART_TOTAL_COL);
3790             if (colName.equals(AppConstants.RI_CHART_COLOR))
3791                 seriesCol.append(", " + AppConstants.RI_CHART_COLOR + " " + AppConstants.RI_CHART_COLOR);
3792             if (colName.equals(AppConstants.RI_CHART_MARKER_START))
3793                 seriesCol.append(", " + AppConstants.RI_CHART_MARKER_START + " " + AppConstants.RI_CHART_MARKER_START);
3794             if (colName.equals(AppConstants.RI_CHART_MARKER_END))
3795                 seriesCol.append(", " + AppConstants.RI_CHART_MARKER_END + " " + AppConstants.RI_CHART_MARKER_END);
3796             if (colName.equals(AppConstants.RI_CHART_MARKER_TEXT_LEFT))
3797                 seriesCol.append(
3798                         ", " + AppConstants.RI_CHART_MARKER_TEXT_LEFT + " " + AppConstants.RI_CHART_MARKER_TEXT_LEFT);
3799             if (colName.equals(AppConstants.RI_CHART_MARKER_TEXT_RIGHT))
3800                 seriesCol.append(
3801                         ", " + AppConstants.RI_CHART_MARKER_TEXT_RIGHT + " " + AppConstants.RI_CHART_MARKER_TEXT_RIGHT);
3802             if (colName.equals(AppConstants.RI_ANOMALY_TEXT))
3803                 seriesCol.append(", " + AppConstants.RI_ANOMALY_TEXT + " " + AppConstants.RI_ANOMALY_TEXT);
3804         }
3805
3806
3807         String final_sql = "";
3808         reportSQL = Utils.replaceInString(reportSQL, " from ", " FROM ");
3809         reportSQL = Utils.replaceInString(reportSQL, " select ", " SELECT ");
3810         reportSQL = Utils.replaceInString(reportSQL, " union ", " UNION ");
3811         int pos = 0;
3812         int pos_first_select = 0;
3813         int pos_dup_select = 0;
3814         int pos_prev_select = 0;
3815         int pos_last_select = 0;
3816         if (reportSQL.indexOf("FROM", pos) != -1) {
3817             pos = reportSQL.indexOf("FROM", pos);
3818             pos_dup_select = reportSQL.lastIndexOf("SELECT", pos);
3819             pos_first_select = reportSQL.indexOf("SELECT");
3820             logger.debug(EELFLoggerDelegate.debugLogger, ("pos_select " + pos_first_select + " " + pos_dup_select));
3821             if (pos_dup_select > pos_first_select) {
3822                 logger.debug(EELFLoggerDelegate.debugLogger, ("********pos_dup_select ********" + pos_dup_select));
3823                 pos_prev_select = pos_first_select;
3824                 pos_last_select = pos_dup_select;
3825                 while (pos_last_select > pos_prev_select) {
3826                     logger.debug(EELFLoggerDelegate.debugLogger,
3827                             ("pos_last , pos_prev " + pos_last_select + " " + pos_prev_select));
3828                     pos = reportSQL.indexOf("FROM", pos + 2);
3829                     pos_prev_select = pos_last_select;
3830                     pos_last_select = reportSQL.lastIndexOf("SELECT", pos);
3831                     logger.debug(EELFLoggerDelegate.debugLogger, ("in WHILE LOOP LAST " + pos_last_select));
3832                 }
3833             }
3834
3835         }
3836         final_sql += " " + reportSQL.substring(pos);
3837         logger.debug(EELFLoggerDelegate.debugLogger, ("Final SQL " + final_sql));
3838         String sql = "SELECT " + legendCol + ", " + legendCol + "_1" + seriesCol.toString()
3839                 + nvl(valueCols.toString(), ", 1")
3840                 + groupCol.toString()
3841                 + final_sql;
3842         logger.debug(EELFLoggerDelegate.debugLogger, ("Final sql in generateChartSQL " + sql));
3843
3844         return sql;
3845         } 
3846
3847     private String formatChartColumn(String colName) {
3848
3849         logger.debug(EELFLoggerDelegate.debugLogger, ("Format Chart Column Input colName" + colName));
3850         colName = colName.trim();
3851         colName = Utils.replaceInString(colName, "TO_CHAR", "to_char");
3852         colName = Utils.replaceInString(colName, "to_number", "TO_NUMBER");
3853         colName = colName.replaceAll(",[\\s]*\\(", ",(");
3854         StringBuffer colNameBuf = new StringBuffer(colName);
3855         int pos = 0;
3856                 int     posFormatStart = 0;
3857                 int     posFormatEnd = 0;
3858         String format = "";
3859         if (colNameBuf.indexOf("999") == -1 && colNameBuf.indexOf("990") == -1) {
3860             logger.debug(EELFLoggerDelegate.debugLogger, (" return colName " + colNameBuf.toString()));
3861             return colNameBuf.toString();
3862         }
3863         while (colNameBuf.indexOf("to_char") != -1) {
3864             if (colNameBuf.indexOf("999") != -1 || colNameBuf.indexOf("990") != -1) {
3865                 pos = colNameBuf.indexOf("to_char");
3866                 colNameBuf.insert(pos, " TO_NUMBER ( CR_RAPTOR.SAFE_TO_NUMBER (");
3867                 pos = colNameBuf.indexOf("to_char");
3868                 colNameBuf.replace(pos, pos + 7, "TO_CHAR");
3869                 logger.debug(EELFLoggerDelegate.debugLogger, ("After adding to_number " + colNameBuf.toString()));
3870                 posFormatStart = colNameBuf.indexOf(",'", pos) + 1;
3871                 posFormatEnd = colNameBuf.indexOf(")", posFormatStart);
3872                 logger.debug(EELFLoggerDelegate.debugLogger, (posFormatStart + " " + posFormatEnd + " " + pos));
3873                 format = colNameBuf.substring(posFormatStart, posFormatEnd);
3874                 colNameBuf.insert(posFormatEnd + 1, " ," + format + ") , " + format + ")");
3875                 logger.debug(EELFLoggerDelegate.debugLogger, ("colNameBuf " + colNameBuf.toString()));
3876             }
3877         }
3878         logger.debug(EELFLoggerDelegate.debugLogger, (" return colName " + colNameBuf.toString()));
3879         return colNameBuf.toString();
3880     }
3881
3882     public String generateTotalSQLLinear(ReportParamValues paramValues, String userId, HttpServletRequest request)
3883             throws RaptorException {
3884         List reportCols = getAllColumns();
3885         String reportSQL = generateSQL(userId, request);
3886
3887         StringBuffer sbSelect = new StringBuffer();
3888         StringBuffer sbTotal = new StringBuffer();
3889         StringBuffer colNames = new StringBuffer();
3890         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3891
3892             DataColumnType dc = (DataColumnType) iter.next();
3893             if (colNames.length() > 0)
3894                 colNames.append(", ");
3895             colNames.append(dc.getColId());
3896         }
3897         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3898             DataColumnType dct = (DataColumnType) iter.next();
3899
3900             String colName = getColumnSelectStr(dct, paramValues);
3901
3902             sbSelect.append((sbSelect.length() == 0) ? "SELECT " : ", ");
3903
3904             sbSelect.append(colName);
3905             sbSelect.append(" ");
3906             sbSelect.append(dct.getColId());
3907
3908             sbTotal.append((sbTotal.length() == 0) ? "SELECT " : ", ");
3909             if (nvl(dct.getDisplayTotal()).length() > 0) {
3910                 String displayTotal = dct.getDisplayTotal();
3911                 StringBuffer sb = new StringBuffer();
3912                 for (int i = 0; i < displayTotal.length(); i++) {
3913                     char ch = displayTotal.charAt(i);
3914                     if (ch == '+' || ch == '-')
3915                         sb.append(dct.getColId() + ")");
3916                     sb.append(ch);
3917                                 } 
3918                 sb.append(dct.getColId() + ")");
3919                 sbTotal.append(getSelectExpr(dct, sb.toString()));
3920             } else
3921                 sbTotal.append("NULL");
3922             sbTotal.append(" total_");
3923             sbTotal.append(dct.getColId());
3924                 } 
3925
3926         logger.debug(EELFLoggerDelegate.debugLogger, ("REPORTWRAPPER " + reportSQL));
3927         int pos = 0;
3928         int pos_first_select = 0;
3929         int pos_dup_select = 0;
3930         int pos_prev_select = 0;
3931         int pos_last_select = 0;
3932         reportSQL = replaceNewLine(reportSQL, " from ", " FROM ");
3933         reportSQL = replaceNewLine(reportSQL, "from ", " FROM ");
3934         reportSQL = replaceNewLine(reportSQL, "FROM ", " FROM ");
3935
3936         reportSQL = " " + reportSQL;
3937         reportSQL = replaceNewLine(reportSQL, "select ", " SELECT ");
3938         reportSQL = replaceNewLine(reportSQL, "SELECT ", " SELECT ");
3939         if (reportSQL.indexOf("FROM", pos) != -1) {
3940             pos = reportSQL.indexOf("FROM", pos);
3941             pos_dup_select = reportSQL.lastIndexOf("SELECT", pos);
3942             pos_first_select = reportSQL.indexOf("SELECT");
3943             logger.debug(EELFLoggerDelegate.debugLogger, ("pos_select " + pos_first_select + " " + pos_dup_select));
3944             if (pos_dup_select > pos_first_select) {
3945                 logger.debug(EELFLoggerDelegate.debugLogger, ("********pos_dup_select ********" + pos_dup_select));
3946                 pos_prev_select = pos_first_select;
3947                 pos_last_select = pos_dup_select;
3948                 while (pos_last_select > pos_prev_select) {
3949                     logger.debug(EELFLoggerDelegate.debugLogger,
3950                             ("pos_last , pos_prev " + pos_last_select + " " + pos_prev_select));
3951                     pos = reportSQL.indexOf("FROM", pos + 2);
3952                     pos_prev_select = pos_last_select;
3953                     pos_last_select = reportSQL.lastIndexOf("SELECT", pos);
3954                     logger.debug(EELFLoggerDelegate.debugLogger, ("in WHILE LOOP LAST " + pos_last_select));
3955                 }
3956             }
3957
3958         }
3959
3960         logger.debug(EELFLoggerDelegate.debugLogger, (" *************** " + pos + " " + reportSQL));
3961         sbSelect.append(" " + reportSQL.substring(pos));
3962         logger.debug(EELFLoggerDelegate.debugLogger, (" **************** " + sbSelect.toString()));
3963         sbTotal.append(" FROM (");
3964         sbTotal.append(sbSelect.toString());
3965         sbTotal.append(") totalSQL");
3966
3967         String dbType = "";
3968         String dbInfo = getDBInfo();
3969         if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) {
3970             try {
3971                 dbType = remDbInfo.getDBType(dbInfo);
3972             } catch (Exception ex) {
3973                 throw new RaptorException(ex);
3974             }
3975         }
3976         if ("DAYTONA".equals(dbType)) {
3977             sbTotal.append("(" + colNames + ")");
3978         }
3979         String sql = sbTotal.toString();
3980         sql = Utils.replaceInString(sql, " from ", " FROM ");
3981         sql = Utils.replaceInString(sql, "select ", "SELECT ");
3982         logger.debug(EELFLoggerDelegate.debugLogger, ("Before SQL Corrector " + sql));
3983         String corrected_SQL = new SQLCorrector().fixSQL(new StringBuffer(sql));
3984         logger.debug(EELFLoggerDelegate.debugLogger, ("************"));
3985         logger.debug(EELFLoggerDelegate.debugLogger, ("Corrected SQL " + corrected_SQL));
3986         return corrected_SQL;
3987         } 
3988
3989     public String generateTotalSQLCrossTab(String sql, String rowColPos,
3990             String userId, HttpServletRequest request, ReportParamValues paramValues) throws RaptorException {
3991         List reportCols = getAllColumns();
3992         String reportSQL = sql;
3993
3994         StringBuffer sbSelect = new StringBuffer();
3995         StringBuffer sbGroup = new StringBuffer();
3996         StringBuffer sbTotal = new StringBuffer();
3997         StringBuffer colNames = new StringBuffer();
3998         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3999
4000             DataColumnType dc = (DataColumnType) iter.next();
4001             if (colNames.length() > 0)
4002                 colNames.append(", ");
4003             colNames.append(dc.getColId());
4004         }
4005         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
4006             DataColumnType dct = (DataColumnType) iter.next();
4007
4008             if (!dct.isVisible())
4009                 continue;
4010
4011             String colName = getColumnSelectStr(dct, paramValues);
4012             String colExpr = getSelectExpr(dct, colName);
4013
4014             sbSelect.append((sbSelect.length() == 0) ? "SELECT " : ", ");
4015
4016             if (nvl(dct.getCrossTabValue()).equals(rowColPos)) {
4017                 sbSelect.append(dct.getColId());
4018                 sbGroup.append((sbGroup.length() == 0) ? " GROUP BY " : ", ");
4019                 sbGroup.append(dct.getColId());
4020
4021                 sbTotal.append((sbTotal.length() == 0) ? "SELECT " : ", ");
4022                 sbTotal.append(dct.getColId());
4023             } else if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_VALUE)) {
4024                                 
4025                 sbSelect.append(dct.getColId());
4026
4027                 String displayTotal = getCrossTabDisplayTotal(rowColPos);
4028                 if (displayTotal.length() > 0) {
4029                                         
4030                     StringBuffer sb = new StringBuffer();
4031                     for (int i = 0; i < displayTotal.length(); i++) {
4032                         char ch = displayTotal.charAt(i);
4033                         if (ch == '+' || ch == '-')
4034                             sb.append(dct.getColId() + ")");
4035                         sb.append(ch);
4036                                         } 
4037                     sb.append(dct.getColId() + ")");
4038
4039                     displayTotal = sb.toString();
4040                 } else
4041                     displayTotal = "COUNT(*)";
4042
4043                 sbTotal.append((sbTotal.length() == 0) ? "SELECT " : ", ");
4044                 sbTotal.append(getSelectExpr(dct, displayTotal));
4045                 sbTotal.append(" total_");
4046                 sbTotal.append(dct.getColId());
4047             } else {
4048                                 
4049                 sbSelect.append(dct.getColId());
4050                         } 
4051
4052             sbSelect.append(" ");
4053             sbSelect.append(dct.getColId());
4054                 } 
4055
4056         sbSelect.append(reportSQL.substring(reportSQL.toUpperCase().indexOf(" FROM ")));
4057
4058         sbTotal.append(" FROM (");
4059         sbTotal.append(sbSelect.toString());
4060         sbTotal.append(") totalSQL");
4061         sbTotal.append(sbGroup.toString());
4062         String dbType = "";
4063         String dbInfo = getDBInfo();
4064         if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) {
4065             try {
4066                 dbType = remDbInfo.getDBType(dbInfo);
4067             } catch (Exception ex) {
4068                 throw new RaptorException(ex);
4069             }
4070         }
4071         if ("DAYTONA".equals(dbType)) {
4072             sbTotal.append("(" + colNames + ")");
4073         }
4074
4075         sql = "";
4076         if (getReportDefType().equals(AppConstants.RD_SQL_BASED)) {
4077             sql = Utils.replaceInString(sbTotal.toString(), " from ", " FROM ");
4078             sql = Utils.replaceInString(sql, "select ", "SELECT ");
4079             return new SQLCorrector().fixSQL(new StringBuffer(sql));
4080         }
4081
4082         return sbTotal.toString();
4083
4084         } 
4085
4086     public String generateTotalSQLCrossTab(ReportParamValues paramValues, String rowColPos,
4087             String userId, HttpServletRequest request) throws RaptorException {
4088         List reportCols = getAllColumns();
4089         String reportSQL = generateSQL(userId, request);
4090
4091         StringBuffer sbSelect = new StringBuffer();
4092         StringBuffer sbGroup = new StringBuffer();
4093         StringBuffer sbTotal = new StringBuffer();
4094         StringBuffer colNames = new StringBuffer();
4095         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
4096
4097             DataColumnType dc = (DataColumnType) iter.next();
4098             if (colNames.length() > 0)
4099                 colNames.append(", ");
4100             colNames.append(dc.getColId());
4101         }
4102         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
4103             DataColumnType dct = (DataColumnType) iter.next();
4104
4105             if (!dct.isVisible())
4106                 continue;
4107
4108             String colName = getColumnSelectStr(dct, paramValues);
4109             String colExpr = getSelectExpr(dct, colName);
4110
4111             sbSelect.append((sbSelect.length() == 0) ? "SELECT " : ", ");
4112
4113             if (nvl(dct.getCrossTabValue()).equals(rowColPos)) {
4114                 sbSelect.append(colExpr);
4115
4116                 sbGroup.append((sbGroup.length() == 0) ? " GROUP BY " : ", ");
4117                 sbGroup.append(dct.getColId());
4118
4119                 sbTotal.append((sbTotal.length() == 0) ? "SELECT " : ", ");
4120                 sbTotal.append(dct.getColId());
4121             } else if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_VALUE)) {
4122                 sbSelect.append(colName);
4123
4124                 String displayTotal = getCrossTabDisplayTotal(rowColPos);
4125                 if (displayTotal.length() > 0) {
4126                     StringBuffer sb = new StringBuffer();
4127                     for (int i = 0; i < displayTotal.length(); i++) {
4128                         char ch = displayTotal.charAt(i);
4129                         if (ch == '+' || ch == '-')
4130                             sb.append(dct.getColId() + ")");
4131                         sb.append(ch);
4132                                         } 
4133                     sb.append(dct.getColId() + ")");
4134
4135                     displayTotal = sb.toString();
4136                 } else
4137                     displayTotal = "COUNT(*)";
4138
4139                 sbTotal.append((sbTotal.length() == 0) ? "SELECT " : ", ");
4140                 sbTotal.append(getSelectExpr(dct, displayTotal));
4141                 sbTotal.append(" total_");
4142                 sbTotal.append(dct.getColId());
4143             } else {
4144                 sbSelect.append(colExpr);
4145                         }
4146
4147             sbSelect.append(" ");
4148             sbSelect.append(dct.getColId());
4149                 }
4150
4151         sbSelect.append(reportSQL.substring(reportSQL.toUpperCase().indexOf(" FROM ")));
4152
4153         sbTotal.append(" FROM (");
4154         sbTotal.append(sbSelect.toString());
4155         sbTotal.append(") totalSQL");
4156         sbTotal.append(sbGroup.toString());
4157         String dbType = "";
4158         String dbInfo = getDBInfo();
4159         if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) {
4160             try {
4161                 dbType = remDbInfo.getDBType(dbInfo);
4162             } catch (Exception ex) {
4163                 throw new RaptorException(ex);
4164             }
4165         }
4166         if ("DAYTONA".equals(dbType)) {
4167             sbTotal.append("(" + colNames + ")");
4168         }
4169
4170         String sql = "";
4171         if (getReportDefType().equals(AppConstants.RD_SQL_BASED)) {
4172             sql = Utils.replaceInString(sbTotal.toString(), " from ", " FROM ");
4173             sql = Utils.replaceInString(sql, "select ", "SELECT ");
4174             return new SQLCorrector().fixSQL(new StringBuffer(sql));
4175         }
4176
4177         return sbTotal.toString();
4178
4179         } 
4180
4181     public String generateDistinctValuesSQL(ReportParamValues paramValues, DataColumnType dct,
4182             String userId, HttpServletRequest request) throws RaptorException {
4183         DataSourceType dst = getColumnTableById(dct.getColId());
4184         String colName = getColumnSelectStr(dct, paramValues);
4185         String colExpr = getSelectExpr(dct, colName);
4186         ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
4187         StringBuffer sb = new StringBuffer();
4188         sb.append("SELECT DISTINCT ");
4189         if (getReportDefType().equals(AppConstants.RD_SQL_BASED)) {
4190             sb.append(dct.getColId());
4191             sb.append(" FROM (");
4192             sb.append(rr.getWholeSQL());
4193             sb.append(") " + (Globals.isPostgreSQL() || Globals.isMySQL() ? " AS " : "") + " report_sql ORDER BY 1");
4194         } else {
4195             sb.append(colExpr);
4196             sb.append(" ");
4197             sb.append(dct.getColId());
4198             if (!colExpr.equals(colName)) {
4199                 sb.append(", ");
4200                 sb.append(colName);
4201                         } 
4202             sb.append(" FROM ");
4203             sb.append(dst.getTableName());
4204             sb.append(" ");
4205             sb.append(dst.getTableId());
4206             sb.append(" ORDER BY ");
4207             sb.append(colName);
4208             if (dct.getColType().equals(AppConstants.CT_DATE))
4209                 sb.append(" DESC");
4210                 } 
4211
4212         return sb.toString();
4213         } 
4214
4215     public DataSourceType getTableWithoutColumns() {
4216         List dsList = getDataSourceList().getDataSource();
4217         for (Iterator iter = dsList.iterator(); iter.hasNext();) {
4218             DataSourceType ds = (DataSourceType) iter.next();
4219
4220             if (ds.getDataColumnList().getDataColumn().isEmpty())
4221                 return ds;
4222                 } 
4223
4224         return null;
4225         } 
4226
4227     public CustomReportType cloneCustomReportClearTables() throws RaptorException {
4228         ReportWrapper nrw = new ReportWrapper(cloneCustomReport(), reportID, getOwnerID(),
4229                 getCreateID(), getCreateDate(), getUpdateID(), getUpdateDate(), getMenuID(),
4230                 isMenuApproved());
4231
4232         DataSourceType ndst = null;
4233         while ((ndst = nrw.getTableWithoutColumns()) != null)
4234             nrw.deleteDataSourceType(ndst.getTableId());
4235
4236         return nrw.getCustomReport();
4237         } 
4238
4239     public String marshal() throws RaptorException {
4240         StringWriter sw = new StringWriter();
4241         ObjectFactory objFactory = new ObjectFactory();
4242
4243         try {
4244             JAXBContext jc = JAXBContext.newInstance("org.onap.portalsdk.analytics.xmlobj");
4245             Marshaller m = jc.createMarshaller();
4246             m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
4247             m.marshal(
4248                     (getTableWithoutColumns() == null) ? objFactory.createCustomReport(cr)
4249                             : objFactory.createCustomReport(cloneCustomReportClearTables()),
4250                     new StreamResult(sw));
4251         } catch (JAXBException ex) {
4252             logger.error(EELFLoggerDelegate.debugLogger, "Exception occured in marshal ", ex);
4253             throw new RaptorException(ex.getMessage(), ex.getCause());
4254         }
4255         return sw.toString();
4256         }
4257
4258     public static CustomReportType unmarshalCR(String reportXML) throws RaptorException {
4259         try {
4260             JAXBContext jc = JAXBContext.newInstance("org.onap.portalsdk.analytics.xmlobj");
4261             Unmarshaller u = jc.createUnmarshaller();
4262             javax.xml.bind.JAXBElement<CustomReportType> doc =
4263                     (javax.xml.bind.JAXBElement<CustomReportType>) u.unmarshal(new java.io.StringReader(
4264                             reportXML));
4265             return doc.getValue();
4266         } catch (JAXBException ex) {
4267             logger.error(EELFLoggerDelegate.debugLogger, "Exception occured in unmarshalCR ", ex);
4268             throw new RaptorException(ex.getMessage(), ex.getCause());
4269         }
4270
4271
4272         } 
4273
4274     protected static CustomReportType createBlankCR() throws RaptorException {
4275         return createBlankCR("N/A");
4276         }
4277     protected static CustomReportType createBlankCR(String createID) throws RaptorException {
4278         ObjectFactory objFactory = new ObjectFactory();
4279         CustomReportType cr = objFactory.createCustomReportType();
4280         try {
4281             cr.setReportName("");
4282             cr.setReportDescr("");
4283             cr.setChartType("");
4284             cr.setPublic(false);
4285             cr.setCreateId(createID);
4286             cr.setCreateDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar()));
4287             cr.setReportType("");
4288             cr.setPageSize(50);
4289
4290             DataSourceList dataSourceList = objFactory.createDataSourceList();
4291             cr.setDataSourceList(dataSourceList);
4292         } catch (DatatypeConfigurationException ex) {
4293             logger.error(EELFLoggerDelegate.debugLogger, "Exception occured in createBlankCR ", ex);
4294             throw new RaptorException(ex.getMessage(), ex.getCause());
4295         }
4296         return cr;
4297         } 
4298
4299     protected void replaceCustomReportWithClone() throws RaptorException {
4300         try {
4301             CustomReportType clone = cloneCustomReport();
4302             this.cr = clone;
4303         } catch (Exception e) {
4304             logger.debug(EELFLoggerDelegate.debugLogger,
4305                     ("[SYSTEM ERROR] ReportWrapper.replaceCustomReportWithClone generated exception for report ["
4306                             + reportID + "]. Exception: "),
4307                     e);
4308             throw new RaptorException(
4309                     "[SYSTEM ERROR] ReportWrapper.replaceCustomReportWithClone generated exception for report ["
4310                             + reportID + "]. Exception: " + e.getMessage(),
4311                     e.getCause());
4312         }
4313         }
4314
4315     public FormatType cloneFormatType(ObjectFactory objFactory, FormatType ft)
4316             throws JAXBException {
4317         FormatType nft = objFactory.createFormatType();
4318
4319         nft.setLessThanValue(ft.getLessThanValue());
4320         nft.setExpression(ft.getExpression());
4321         nft.setBold(ft.isBold());
4322         nft.setItalic(ft.isItalic());
4323         nft.setUnderline(ft.isUnderline());
4324         if (nvl(ft.getBgColor()).length() > 0)
4325             nft.setBgColor(ft.getBgColor());
4326         if (nvl(ft.getFontColor()).length() > 0)
4327             nft.setFontColor(ft.getFontColor());
4328         if (nvl(ft.getFontFace()).length() > 0)
4329             nft.setFontFace(ft.getFontFace());
4330         if (nvl(ft.getFontSize()).length() > 0)
4331             nft.setFontSize(ft.getFontSize());
4332         if (nvl(ft.getAlignment()).length() > 0)
4333             nft.setAlignment(ft.getAlignment());
4334         if (nvl(ft.getComment()).length() > 0)
4335             nft.setComment(ft.getComment());
4336
4337         nft.setFormatId(ft.getFormatId());
4338
4339         return nft;
4340         } 
4341
4342     public SemaphoreType cloneSemaphoreType(ObjectFactory objFactory, SemaphoreType st)
4343             throws JAXBException {
4344         SemaphoreType nst = objFactory.createSemaphoreType();
4345
4346         nst.setSemaphoreName(st.getSemaphoreName());
4347         nst.setSemaphoreType(st.getSemaphoreType());
4348         nst.setSemaphoreId(st.getSemaphoreId());
4349         if (nvl(st.getComment()).length() > 0)
4350             nst.setComment(st.getComment());
4351
4352         if (st.getFormatList() != null) {
4353             FormatList formatList = objFactory.createFormatList();
4354             nst.setFormatList(formatList);
4355
4356             for (Iterator iter = st.getFormatList().getFormat().iterator(); iter.hasNext();)
4357                 formatList.getFormat().add(
4358                         cloneFormatType(objFactory, (FormatType) iter.next()));
4359         } // if
4360
4361         return nst;
4362         }
4363
4364     public Reports cloneDashboardType(ObjectFactory objFactory, Reports rpt)
4365             throws JAXBException {
4366         Reports nrpt = objFactory.createReports();
4367
4368         nrpt.setReportId(rpt.getReportId());
4369         nrpt.setBgcolor(rpt.getBgcolor());
4370         return nrpt;
4371                 } 
4372
4373     public Marker cloneMarkerType(ObjectFactory objFactory, Marker marker)
4374             throws JAXBException {
4375         Marker nMarker = objFactory.createMarker();
4376         nMarker.setAddressColumn(marker.getAddressColumn());
4377         nMarker.setDataColumn(marker.getDataColumn());
4378         nMarker.setDataHeader(marker.getDataHeader());
4379         nMarker.setMarkerColor(marker.getMarkerColor());
4380         return nMarker;
4381                 }
4382
4383     public ChartDrillFormfield cloneChartDrillFormfield(ObjectFactory objFactory,
4384             ChartDrillFormfield chartDrillFormfield)
4385             throws JAXBException {
4386         ChartDrillFormfield nChartDrillFormfield = objFactory.createChartDrillFormfield();
4387         nChartDrillFormfield.setFormfield(chartDrillFormfield.getFormfield());
4388         return nChartDrillFormfield;
4389                 } 
4390
4391     public boolean isChartDrillDownContainsName(String name) {
4392         for (Iterator iter = getChartDrillOptions().getTargetFormfield().iterator(); iter
4393                 .hasNext();) {
4394             org.onap.portalsdk.analytics.xmlobj.ChartDrillFormfield cdf =
4395                     (org.onap.portalsdk.analytics.xmlobj.ChartDrillFormfield) iter.next();
4396             if (cdf.getFormfield().equals(name)) {
4397                 return true;
4398             }
4399         }
4400         return false;
4401     }
4402
4403     public FormFieldType cloneFormFieldType(ObjectFactory objFactory, FormFieldType fft)
4404             throws JAXBException {
4405         FormFieldType nfft = objFactory.createFormFieldType();
4406
4407         nfft.setColId(fft.getColId());
4408         nfft.setFieldName(fft.getFieldName());
4409         nfft.setFieldType(fft.getFieldType());
4410         if (nvl(fft.getVisible()).length() > 0)
4411             nfft.setVisible(fft.getVisible());
4412                 if (nvl(fft.getValidationType()).length() > 0 || (fft.getValidationType() != null && fft.getValidationType().isEmpty()))
4413             nfft.setValidationType(fft.getValidationType());
4414         if (nvl(fft.getMandatory()).length() > 0)
4415             nfft.setMandatory(fft.getMandatory());
4416                 if (nvl(fft.getDefaultValue()).length() > 0 || (fft.getDefaultValue() != null && fft.getDefaultValue().isEmpty()))
4417             nfft.setDefaultValue(fft.getDefaultValue());
4418         nfft.setOrderBySeq(fft.getOrderBySeq());
4419                 if (nvl(fft.getFieldSQL()).length() > 0  || (fft.getFieldSQL()  != null && fft.getFieldSQL().isEmpty()))
4420             nfft.setFieldSQL(fft.getFieldSQL());
4421                 if (nvl(fft.getFieldDefaultSQL()).length() > 0 || (fft.getFieldDefaultSQL()  != null && fft.getFieldDefaultSQL().isEmpty()))
4422             nfft.setFieldDefaultSQL(fft.getFieldDefaultSQL());
4423         if (fft.getRangeStartDate() != null)
4424             nfft.setRangeStartDate(fft.getRangeStartDate());
4425         if (fft.getRangeEndDate() != null)
4426             nfft.setRangeEndDate(fft.getRangeEndDate());
4427         if (fft.getRangeStartDateSQL() != null)
4428             nfft.setRangeStartDateSQL(fft.getRangeStartDateSQL());
4429         if (fft.getRangeEndDateSQL() != null)
4430             nfft.setRangeEndDateSQL(fft.getRangeEndDateSQL());
4431
4432         if (nvl(fft.getComment()).length() > 0)
4433             nfft.setComment(fft.getComment());
4434
4435         if (fft.getPredefinedValueList() != null) {
4436             PredefinedValueList predefinedValueList = objFactory.createPredefinedValueList();
4437             nfft.setPredefinedValueList(predefinedValueList);
4438
4439             for (Iterator iter = fft.getPredefinedValueList().getPredefinedValue().iterator(); iter
4440                     .hasNext();)
4441                 predefinedValueList.getPredefinedValue().add(new String((String) iter.next()));
4442                 }
4443         if (nvl(fft.getDependsOn()).length() > 0)
4444             nfft.setDependsOn(fft.getDependsOn());
4445
4446         nfft.setGroupFormField(
4447                 (fft.isGroupFormField() != null && fft.isGroupFormField().booleanValue()) ? true : false);
4448         if (nvl(fft.getMultiSelectListSize()).length() > 0)
4449             nfft.setMultiSelectListSize(fft.getMultiSelectListSize());
4450
4451         nfft.setFieldId(fft.getFieldId());
4452         return nfft;
4453         } 
4454
4455     public JavascriptItemType cloneJavascriptType(ObjectFactory objFactory, JavascriptItemType jit)
4456             throws JAXBException {
4457         JavascriptItemType njit = objFactory.createJavascriptItemType();
4458
4459         njit.setId(jit.getId());
4460         njit.setFieldId(jit.getFieldId());
4461         njit.setCallText(jit.getCallText());
4462         return njit;
4463         } 
4464
4465     public ColFilterType cloneColFilterType(ObjectFactory objFactory, ColFilterType cft)
4466             throws JAXBException {
4467         ColFilterType ncft = objFactory.createColFilterType();
4468
4469         ncft.setColId(cft.getColId());
4470         ncft.setFilterSeq(cft.getFilterSeq());
4471         ncft.setJoinCondition(cft.getJoinCondition());
4472         if (nvl(cft.getOpenBrackets()).length() > 0)
4473             ncft.setOpenBrackets(cft.getOpenBrackets());
4474         ncft.setExpression(cft.getExpression());
4475         if (nvl(cft.getArgType()).length() > 0)
4476             ncft.setArgType(cft.getArgType());
4477         if (nvl(cft.getArgValue()).length() > 0)
4478             ncft.setArgValue(cft.getArgValue());
4479         if (nvl(cft.getCloseBrackets()).length() > 0)
4480             ncft.setCloseBrackets(cft.getCloseBrackets());
4481         if (nvl(cft.getComment()).length() > 0)
4482             ncft.setComment(cft.getComment());
4483
4484         return ncft;
4485         } 
4486
4487     public DataColumnType cloneDataColumnType(ObjectFactory objFactory, DataColumnType dct)
4488             throws JAXBException {
4489         DataColumnType ndct = objFactory.createDataColumnType();
4490
4491         ndct.setTableId(dct.getTableId());
4492         ndct.setDbColName(dct.getDbColName());
4493         if (nvl(dct.getCrossTabValue()).length() > 0)
4494             ndct.setCrossTabValue(dct.getCrossTabValue());
4495         ndct.setColName(dct.getColName());
4496         ndct.setDisplayName(dct.getDisplayName());
4497         if (dct.getDisplayWidth() > 0)
4498             ndct.setDisplayWidth(dct.getDisplayWidth());
4499         if (nvl(dct.getDisplayWidthInPxls()).length() > 0)
4500             ndct.setDisplayWidthInPxls(dct.getDisplayWidthInPxls());
4501         if (nvl(dct.getDisplayAlignment()).length() > 0)
4502             ndct.setDisplayAlignment(dct.getDisplayAlignment());
4503         if (nvl(dct.getDisplayHeaderAlignment()).length() > 0)
4504             ndct.setDisplayHeaderAlignment(dct.getDisplayHeaderAlignment());
4505         ndct.setOrderSeq(dct.getOrderSeq());
4506         ndct.setVisible(dct.isVisible());
4507         ndct.setCalculated(dct.isCalculated());
4508         ndct.setColType(dct.getColType());
4509         if (dct.getColType().equals(AppConstants.CT_HYPERLINK)) {
4510             ndct.setHyperlinkURL(dct.getHyperlinkURL());
4511             ndct.setHyperlinkType(dct.getHyperlinkType());
4512             if ("IMAGE".equals(dct.getHyperlinkType())) {
4513                 ndct.setActionImg(dct.getActionImg());
4514             }
4515         }
4516
4517         if (dct.getIndentation() != null) {
4518             ndct.setIndentation(dct.getIndentation());
4519         }
4520
4521         if (nvl(dct.getColFormat()).length() > 0)
4522             ndct.setColFormat(dct.getColFormat());
4523         ndct.setGroupBreak(dct.isGroupBreak());
4524         ndct.setNowrap(dct.getNowrap());
4525         if (nvl(dct.getYAxis()).length() > 0)
4526             ndct.setYAxis(dct.getYAxis());
4527         if (dct.getOrderBySeq() != null && dct.getOrderBySeq() > 0)
4528             ndct.setOrderBySeq(dct.getOrderBySeq());
4529         if (nvl(dct.getOrderByAscDesc()).length() > 0)
4530             ndct.setOrderByAscDesc(dct.getOrderByAscDesc());
4531         if (nvl(dct.getDisplayTotal()).length() > 0)
4532             ndct.setDisplayTotal(dct.getDisplayTotal());
4533         if (nvl(dct.getColOnChart()).length() > 0)
4534             ndct.setColOnChart(dct.getColOnChart());
4535         if (dct.getChartSeq() != null)
4536             ndct.setChartSeq(dct.getChartSeq());
4537         if (nvl(dct.getChartColor()).length() > 0)
4538             ndct.setChartColor(dct.getChartColor());
4539         if (nvl(dct.getChartLineType()).length() > 0)
4540             ndct.setChartLineType(dct.getChartLineType());
4541         ndct.setChartSeries((dct.isChartSeries() != null && dct.isChartSeries().booleanValue()) ? true : false);
4542         ndct.setIsRangeAxisFilled(
4543                 (dct.isIsRangeAxisFilled() != null && dct.isIsRangeAxisFilled().booleanValue()) ? true : false);
4544
4545         if (dct.isCreateInNewChart() != null)
4546             ndct.setCreateInNewChart(dct.isCreateInNewChart());
4547         if (nvl(dct.getDrillDownType()).length() > 0)
4548             ndct.setDrillDownType(dct.getDrillDownType());
4549         ndct.setDrillinPoPUp(dct.isDrillinPoPUp() != null ? dct.isDrillinPoPUp() : false);
4550         if (nvl(dct.getDrillDownURL()).length() > 0)
4551             ndct.setDrillDownURL(dct.getDrillDownURL());
4552         if (nvl(dct.getDrillDownParams()).length() > 0)
4553             ndct.setDrillDownParams(dct.getDrillDownParams());
4554         if (nvl(dct.getComment()).length() > 0)
4555             ndct.setComment(dct.getComment());
4556         if (nvl(dct.getDependsOnFormField()).length() > 0)
4557             ndct.setDependsOnFormField(dct.getDependsOnFormField());
4558         if (dct.getColFilterList() != null) {
4559             ColFilterList colFilterList = objFactory.createColFilterList();
4560             ndct.setColFilterList(colFilterList);
4561
4562             for (Iterator iter = dct.getColFilterList().getColFilter().iterator(); iter
4563                     .hasNext();)
4564                 colFilterList.getColFilter().add(
4565                         cloneColFilterType(objFactory, (ColFilterType) iter.next()));
4566                 }
4567
4568         if (nvl(dct.getSemaphoreId()).length() > 0)
4569             ndct.setSemaphoreId(dct.getSemaphoreId());
4570         if (nvl(dct.getDbColType()).length() > 0)
4571             ndct.setDbColType(dct.getDbColType());
4572         else {
4573             ndct.setDbColType(dct.getColType());
4574             adjustColumnType(ndct);
4575         }
4576         if (nvl(dct.getChartGroup()).length() > 0)
4577             ndct.setChartGroup(dct.getChartGroup());
4578
4579         if (nvl(dct.getYAxis()).length() > 0)
4580             ndct.setYAxis(dct.getYAxis());
4581
4582         if (nvl(dct.getDependsOnFormField()).length() > 0)
4583             ndct.setDependsOnFormField(dct.getDependsOnFormField());
4584
4585         if (nvl(dct.getNowrap()).length() > 0)
4586             ndct.setNowrap(dct.getNowrap());
4587
4588         if (dct.getIndentation() != null) {
4589             ndct.setIndentation(dct.getIndentation());
4590         }
4591
4592         ndct.setEnhancedPagination(
4593                 (dct.isEnhancedPagination() != null && dct.isEnhancedPagination().booleanValue()) ? true : false);
4594         if (nvl(dct.getDataMiningCol()).length() > 0)
4595             ndct.setDataMiningCol(dct.getDataMiningCol());
4596
4597         ndct.setColId(dct.getColId());
4598
4599         return ndct;
4600         } 
4601
4602     public DataSourceType cloneDataSourceType(ObjectFactory objFactory, DataSourceType dst)
4603             throws JAXBException {
4604         DataSourceType ndst = objFactory.createDataSourceType();
4605
4606         ndst.setTableName(dst.getTableName());
4607         ndst.setTablePK(dst.getTablePK());
4608         ndst.setDisplayName(dst.getDisplayName());
4609         if (nvl(dst.getRefTableId()).length() > 0)
4610             ndst.setRefTableId(dst.getRefTableId());
4611         if (nvl(dst.getRefDefinition()).length() > 0)
4612             ndst.setRefDefinition(dst.getRefDefinition());
4613         if (nvl(dst.getComment()).length() > 0)
4614             ndst.setComment(dst.getComment());
4615         DataColumnList dataColumnList = objFactory.createDataColumnList();
4616         ndst.setDataColumnList(dataColumnList);
4617
4618         for (Iterator iter = dst.getDataColumnList().getDataColumn().iterator(); iter
4619                 .hasNext();)
4620             dataColumnList.getDataColumn().add(
4621                     cloneDataColumnType(objFactory, (DataColumnType) iter.next()));
4622         ndst.setTableId(dst.getTableId());
4623
4624         return ndst;
4625         } 
4626
4627     public CustomReportType cloneCustomReport() throws RaptorException {
4628         ObjectFactory objFactory = new ObjectFactory();
4629         CustomReportType ncr = objFactory.createCustomReportType();
4630         try {
4631             ncr.setReportName(cr.getReportName());
4632             ncr.setReportDescr(cr.getReportDescr());
4633             if (nvl(cr.getNumDashCols()).length() > 0)
4634                 ncr.setNumDashCols(cr.getNumDashCols());
4635             if (nvl(cr.getDashboardLayoutHTML()).length() > 0)
4636                 ncr.setDashboardLayoutHTML(cr.getDashboardLayoutHTML());
4637                         if (nvl(cr.getDashboardLayoutJSON()).length() > 0)
4638                                 ncr.setDashboardLayoutJSON(cr.getDashboardLayoutJSON());                        
4639             if (nvl(cr.getDbInfo()).length() > 0)
4640                 ncr.setDbInfo(cr.getDbInfo());
4641             ncr.setChartType(cr.getChartType());
4642             if (nvl(cr.getChartTypeFixed()).length() > 0)
4643                 ncr.setChartTypeFixed(cr.getChartTypeFixed());
4644             if (nvl(cr.getChartMultiSeries()).length() > 0)
4645                 ncr.setChartMultiSeries(cr.getChartMultiSeries());
4646             if (nvl(cr.getChartLeftAxisLabel()).length() > 0)
4647                 ncr.setChartLeftAxisLabel(cr.getChartLeftAxisLabel());
4648             if (nvl(cr.getChartRightAxisLabel()).length() > 0)
4649                 ncr.setChartRightAxisLabel(cr.getChartRightAxisLabel());
4650             if (nvl(cr.getChartWidth()).length() > 0)
4651                 ncr.setChartWidth(cr.getChartWidth());
4652             if (nvl(cr.getChartHeight()).length() > 0)
4653                 ncr.setChartHeight(cr.getChartHeight());
4654             ncr.setShowChartTitle(cr.isShowChartTitle());
4655             ncr.setPublic(cr.isPublic());
4656             ncr.setHideFormFieldAfterRun(cr.isHideFormFieldAfterRun());
4657             ncr.setCreateId(cr.getCreateId());
4658             ncr.setCreateDate(cr.getCreateDate());
4659             if (nvl(cr.getReportSQL()).length() > 0)
4660                 ncr.setReportSQL(cr.getReportSQL());
4661             if (nvl(cr.getReportTitle()).length() > 0)
4662                 ncr.setReportTitle(cr.getReportTitle());
4663             if (nvl(cr.getReportSubTitle()).length() > 0)
4664                 ncr.setReportSubTitle(cr.getReportSubTitle());
4665             if (nvl(cr.getReportHeader()).length() > 0)
4666                 ncr.setReportHeader(cr.getReportHeader());
4667             if (cr.getFrozenColumns() != null)
4668                 ncr.setFrozenColumns(cr.getFrozenColumns());
4669             if (nvl(cr.getPdfImgLogo()).length() > 0)
4670                 ncr.setPdfImgLogo(cr.getPdfImgLogo());
4671             if (nvl(cr.getEmptyMessage()).length() > 0)
4672                 ncr.setEmptyMessage(cr.getEmptyMessage());
4673             if (nvl(cr.getWidthNoColumn()).length() > 0)
4674                 ncr.setWidthNoColumn(cr.getWidthNoColumn());
4675             if (nvl(cr.getDataGridAlign()).length() > 0)
4676                 ncr.setDataGridAlign(cr.getDataGridAlign());
4677                 ncr.setReportFooter(cr.getReportFooter());
4678                 ncr.setNumFormCols(cr.getNumFormCols());
4679                 ncr.setDisplayOptions(cr.getDisplayOptions());
4680                 ncr.setDataContainerHeight(cr.getDataContainerHeight());
4681                 ncr.setDataContainerWidth(cr.getDataContainerWidth());
4682                 ncr.setAllowSchedule(cr.getAllowSchedule());
4683                 ncr.setTopDown(cr.getTopDown());
4684                 ncr.setSizedByContent(cr.getSizedByContent());
4685                 ncr.setComment(cr.getComment());
4686                 ncr.setDashboardOptions(cr.getDashboardOptions());
4687                 ncr.setDashboardType(cr.isDashboardType());
4688                 ncr.setReportInNewWindow(cr.isReportInNewWindow());
4689             ncr.setDisplayFolderTree(cr.isDisplayFolderTree());
4690             if (cr.getDashBoardReports() == null) {
4691                 if (cr.getMaxRowsInExcelDownload() != null && cr.getMaxRowsInExcelDownload() > 0)
4692                     ncr.setMaxRowsInExcelDownload(cr.getMaxRowsInExcelDownload());
4693             }
4694
4695             if (nvl(cr.getJavascriptElement()).length() > 0)
4696                 ncr.setJavascriptElement(cr.getJavascriptElement());
4697             if (nvl(cr.getFolderId()).length() > 0)
4698                 ncr.setFolderId(cr.getFolderId());
4699             ncr.setDrillURLInPoPUpPresent(
4700                     (cr.isDrillURLInPoPUpPresent() != null && cr.isDrillURLInPoPUpPresent().booleanValue()) ? true
4701                             : false);
4702                 ncr.setIsOneTimeScheduleAllowed(cr.getIsOneTimeScheduleAllowed());
4703                 ncr.setIsHourlyScheduleAllowed(cr.getIsHourlyScheduleAllowed());
4704                 ncr.setIsDailyScheduleAllowed(cr.getIsDailyScheduleAllowed());
4705                 ncr.setIsDailyMFScheduleAllowed(cr.getIsDailyMFScheduleAllowed());
4706                 ncr.setIsWeeklyScheduleAllowed(cr.getIsWeeklyScheduleAllowed());
4707                 ncr.setIsMonthlyScheduleAllowed(cr.getIsMonthlyScheduleAllowed());
4708
4709             ncr.setPageSize(cr.getPageSize());
4710             ncr.setReportType(cr.getReportType());
4711                         ncr.setFormFieldGroupsJSON(cr.getFormFieldGroupsJSON());
4712             DataSourceList dataSourceList = objFactory.createDataSourceList();
4713             ncr.setDataSourceList(dataSourceList);
4714
4715             for (Iterator iter = cr.getDataSourceList().getDataSource().iterator(); iter.hasNext();) {
4716                 dataSourceList.getDataSource().add(
4717                         cloneDataSourceType(objFactory, (DataSourceType) iter.next()));
4718             }
4719
4720             if (cr.getFormFieldList() != null) {
4721                 FormFieldList formFieldList = objFactory.createFormFieldList();
4722                 ncr.setFormFieldList(formFieldList);
4723                 ncr.getFormFieldList().setComment(formFieldList.getComment());
4724
4725                 for (Iterator iter = cr.getFormFieldList().getFormField().iterator(); iter
4726                         .hasNext();)
4727                     formFieldList.getFormField().add(
4728                             cloneFormFieldType(objFactory, (FormFieldType) iter.next()));
4729                 formFieldList.setComment(cr.getFormFieldList().getComment());
4730                         } 
4731
4732             if (cr.getJavascriptList() != null) {
4733                 JavascriptList javascriptList = objFactory.createJavascriptList();
4734                 ncr.setJavascriptList(javascriptList);
4735
4736                 for (Iterator iter = cr.getJavascriptList().getJavascriptItem().iterator(); iter
4737                         .hasNext();)
4738                     javascriptList.getJavascriptItem().add(
4739                             cloneJavascriptType(objFactory, (JavascriptItemType) iter.next()));
4740                         }
4741
4742             if (cr.getSemaphoreList() != null) {
4743                 SemaphoreList semaphoreList = objFactory.createSemaphoreList();
4744                 ncr.setSemaphoreList(semaphoreList);
4745
4746                 for (Iterator iter = cr.getSemaphoreList().getSemaphore().iterator(); iter
4747                         .hasNext();) {
4748                     semaphoreList.getSemaphore().add(
4749                             cloneSemaphoreType(objFactory, (SemaphoreType) iter.next()));
4750                 }
4751                         } 
4752
4753             if (nvl(cr.getDashboardOptions()).length() > 0)
4754                 ncr.setDashboardOptions(cr.getDashboardOptions());
4755             if (cr.isDashboardType() != null)
4756                 ncr.setDashboardType(cr.isDashboardType());
4757             if (cr.isReportInNewWindow() != null)
4758                 ncr.setReportInNewWindow(cr.isReportInNewWindow());
4759             ncr.setDisplayFolderTree(cr.isDisplayFolderTree());
4760             if (cr.getDashBoardReports() == null) {
4761                 if (cr.getMaxRowsInExcelDownload() != null && cr.getMaxRowsInExcelDownload() > 0)
4762                     ncr.setMaxRowsInExcelDownload(cr.getMaxRowsInExcelDownload());
4763             }
4764
4765             if (cr.getDashBoardReports() != null) {
4766                 DashboardReports dashboardReports = objFactory.createDashboardReports();
4767                 ncr.setDashBoardReports(dashboardReports);
4768
4769                 for (Iterator iter = cr.getDashBoardReports().getReportsList().iterator(); iter
4770                         .hasNext();) {
4771                     dashboardReports.getReportsList().add(
4772                             cloneDashboardType(objFactory, (Reports) iter.next()));
4773                 }
4774                         } 
4775
4776             if (cr.getChartAdditionalOptions() != null) {
4777                 ChartAdditionalOptions chartAdditionalOptions = objFactory.createChartAdditionalOptions();
4778                 if (nvl(cr.getChartAdditionalOptions().getChartMultiplePieOrder()).length() > 0)
4779                     chartAdditionalOptions
4780                             .setChartMultiplePieOrder(cr.getChartAdditionalOptions().getChartMultiplePieOrder());
4781                 if (nvl(cr.getChartAdditionalOptions().getChartMultiplePieLabelDisplay()).length() > 0)
4782                     chartAdditionalOptions.setChartMultiplePieLabelDisplay(
4783                             cr.getChartAdditionalOptions().getChartMultiplePieLabelDisplay());
4784
4785                 if (nvl(cr.getChartAdditionalOptions().getChartOrientation()).length() > 0)
4786                     chartAdditionalOptions.setChartOrientation(cr.getChartAdditionalOptions().getChartOrientation());
4787                 if (nvl(cr.getChartAdditionalOptions().getSecondaryChartRenderer()).length() > 0)
4788                     chartAdditionalOptions
4789                             .setSecondaryChartRenderer(cr.getChartAdditionalOptions().getSecondaryChartRenderer());
4790
4791                 if (nvl(cr.getChartAdditionalOptions().getChartDisplay()).length() > 0)
4792                     chartAdditionalOptions.setChartDisplay(cr.getChartAdditionalOptions().getChartDisplay());
4793                 if (nvl(cr.getChartAdditionalOptions().getHideToolTips()).length() > 0)
4794                     chartAdditionalOptions.setHideToolTips(cr.getChartAdditionalOptions().getHideToolTips());
4795                 if (nvl(cr.getChartAdditionalOptions().getHidechartLegend()).length() > 0)
4796                     chartAdditionalOptions.setHidechartLegend(cr.getChartAdditionalOptions().getHidechartLegend());
4797                 if (nvl(cr.getChartAdditionalOptions().getLegendPosition()).length() > 0)
4798                     chartAdditionalOptions.setLegendPosition(cr.getChartAdditionalOptions().getLegendPosition());
4799                 if (nvl(cr.getChartAdditionalOptions().getLabelAngle()).length() > 0)
4800                     chartAdditionalOptions.setLabelAngle(cr.getChartAdditionalOptions().getLabelAngle());
4801
4802                 if (nvl(cr.getChartAdditionalOptions().getIntervalFromdate()).length() > 0)
4803                     chartAdditionalOptions.setIntervalFromdate(cr.getChartAdditionalOptions().getIntervalFromdate());
4804                 if (nvl(cr.getChartAdditionalOptions().getIntervalTodate()).length() > 0)
4805                     chartAdditionalOptions.setIntervalTodate(cr.getChartAdditionalOptions().getIntervalTodate());
4806                 if (nvl(cr.getChartAdditionalOptions().getIntervalLabel()).length() > 0)
4807                     chartAdditionalOptions.setIntervalLabel(cr.getChartAdditionalOptions().getIntervalLabel());
4808
4809                 if (nvl(cr.getChartAdditionalOptions().getLastSeriesALineChart()).length() > 0)
4810                     chartAdditionalOptions
4811                             .setLastSeriesALineChart(cr.getChartAdditionalOptions().getLastSeriesALineChart());
4812                 if (nvl(cr.getChartAdditionalOptions().getLastSeriesABarChart()).length() > 0)
4813                     chartAdditionalOptions
4814                             .setLastSeriesABarChart(cr.getChartAdditionalOptions().getLastSeriesABarChart());
4815
4816                 if (nvl(cr.getChartAdditionalOptions().getMaxLabelsInDomainAxis()).length() > 0)
4817                     chartAdditionalOptions
4818                             .setMaxLabelsInDomainAxis(cr.getChartAdditionalOptions().getMaxLabelsInDomainAxis());
4819                 if (nvl(cr.getChartAdditionalOptions().getLinearRegression()).length() > 0)
4820                     chartAdditionalOptions.setLinearRegression(cr.getChartAdditionalOptions().getLinearRegression());
4821                 if (nvl(cr.getChartAdditionalOptions().getLinearRegressionColor()).length() > 0)
4822                     chartAdditionalOptions
4823                             .setLinearRegressionColor(cr.getChartAdditionalOptions().getLinearRegressionColor());
4824                 if (nvl(cr.getChartAdditionalOptions().getExponentialRegressionColor()).length() > 0)
4825                     chartAdditionalOptions.setExponentialRegressionColor(
4826                             cr.getChartAdditionalOptions().getExponentialRegressionColor());
4827                 if (nvl(cr.getChartAdditionalOptions().getMaxRegression()).length() > 0)
4828                     chartAdditionalOptions.setMaxRegression(cr.getChartAdditionalOptions().getMaxRegression());
4829                 if (nvl(cr.getChartAdditionalOptions().getRangeAxisUpperLimit()).length() > 0)
4830                     chartAdditionalOptions
4831                             .setRangeAxisUpperLimit(cr.getChartAdditionalOptions().getRangeAxisUpperLimit());
4832                 if (nvl(cr.getChartAdditionalOptions().getRangeAxisLowerLimit()).length() > 0)
4833                     chartAdditionalOptions
4834                             .setRangeAxisLowerLimit(cr.getChartAdditionalOptions().getRangeAxisLowerLimit());
4835                 if (nvl(cr.getChartAdditionalOptions().getOverlayItemValueOnStackBar()).length() > 0)
4836                     chartAdditionalOptions.setOverlayItemValueOnStackBar(
4837                             cr.getChartAdditionalOptions().getOverlayItemValueOnStackBar());
4838                 chartAdditionalOptions.setAnimate((cr.getChartAdditionalOptions().isAnimate() != null
4839                         && cr.getChartAdditionalOptions().isAnimate().booleanValue()) ? true : false);
4840
4841                 if (nvl(cr.getChartAdditionalOptions().getKeepDomainAxisValueAsString()).length() > 0)
4842                     chartAdditionalOptions.setKeepDomainAxisValueAsString(
4843                             cr.getChartAdditionalOptions().getKeepDomainAxisValueAsString());
4844
4845                 // Animate
4846                 chartAdditionalOptions
4847                         .setAnimateAnimatedChart((cr.getChartAdditionalOptions().isAnimateAnimatedChart() != null
4848                                 && cr.getChartAdditionalOptions().isAnimateAnimatedChart().booleanValue()) ? true
4849                                         : false);
4850                 chartAdditionalOptions.setStacked((cr.getChartAdditionalOptions().isStacked() != null
4851                         && cr.getChartAdditionalOptions().isStacked().booleanValue()) ? true : false);
4852                 chartAdditionalOptions.setBarControls((cr.getChartAdditionalOptions().isBarControls() != null
4853                         && cr.getChartAdditionalOptions().isBarControls().booleanValue()) ? true : false);
4854                 chartAdditionalOptions.setXAxisDateType((cr.getChartAdditionalOptions().isXAxisDateType() != null
4855                         && cr.getChartAdditionalOptions().isXAxisDateType().booleanValue()) ? true : false);
4856                 chartAdditionalOptions.setLessXaxisTickers((cr.getChartAdditionalOptions().isLessXaxisTickers() != null
4857                         && cr.getChartAdditionalOptions().isLessXaxisTickers().booleanValue()) ? true : false);
4858                 chartAdditionalOptions.setTimeAxis((cr.getChartAdditionalOptions().isTimeAxis() != null
4859                         && cr.getChartAdditionalOptions().isTimeAxis().booleanValue()) ? true : false);
4860
4861                 if (nvl(cr.getChartAdditionalOptions().getTimeSeriesRender()).length() > 0)
4862                     chartAdditionalOptions.setTimeSeriesRender(cr.getChartAdditionalOptions().getTimeSeriesRender());
4863
4864                 chartAdditionalOptions.setMultiSeries((cr.getChartAdditionalOptions().isMultiSeries() != null
4865                         && cr.getChartAdditionalOptions().isMultiSeries().booleanValue()) ? true : false);
4866
4867                 chartAdditionalOptions.setTopMargin(cr.getChartAdditionalOptions().getTopMargin() != null
4868                         ? cr.getChartAdditionalOptions().getTopMargin()
4869                         : new Integer(30));
4870                 chartAdditionalOptions.setBottomMargin(cr.getChartAdditionalOptions().getBottomMargin() != null
4871                         ? cr.getChartAdditionalOptions().getBottomMargin()
4872                         : new Integer(50));
4873                 chartAdditionalOptions.setLeftMargin(cr.getChartAdditionalOptions().getLeftMargin() != null
4874                         ? cr.getChartAdditionalOptions().getLeftMargin()
4875                         : new Integer(100));
4876                 chartAdditionalOptions.setRightMargin(cr.getChartAdditionalOptions().getRightMargin() != null
4877                         ? cr.getChartAdditionalOptions().getRightMargin()
4878                         : new Integer(60));
4879
4880                 ncr.setChartAdditionalOptions(chartAdditionalOptions);
4881                         } 
4882
4883             if (nvl(cr.getJavascriptElement()).length() > 0)
4884                 ncr.setJavascriptElement(cr.getJavascriptElement());
4885             if (nvl(cr.getFolderId()).length() > 0)
4886                 ncr.setFolderId(cr.getFolderId());
4887
4888             if (cr.getChartDrillOptions() != null) {
4889                 ChartDrillOptions chartDrillOptions = objFactory.createChartDrillOptions();
4890
4891                 if (nvl(cr.getChartDrillOptions().getDrillReportId()).length() > 0)
4892                     chartDrillOptions.setDrillReportId(cr.getChartDrillOptions().getDrillReportId());
4893
4894                 for (Iterator iter = cr.getChartDrillOptions().getTargetFormfield().iterator(); iter
4895                         .hasNext();) {
4896                     chartDrillOptions.getTargetFormfield().add(
4897                             cloneChartDrillFormfield(objFactory, (ChartDrillFormfield) iter.next()));
4898
4899                 }
4900
4901                 if (nvl(cr.getChartDrillOptions().getDrillXAxisFormField()).length() > 0)
4902                     chartDrillOptions.setDrillXAxisFormField(cr.getChartDrillOptions().getDrillXAxisFormField());
4903                 if (nvl(cr.getChartDrillOptions().getDrillYAxisFormField()).length() > 0)
4904                     chartDrillOptions.setDrillYAxisFormField(cr.getChartDrillOptions().getDrillYAxisFormField());
4905                 if (nvl(cr.getChartDrillOptions().getDrillSeriesFormField()).length() > 0)
4906                     chartDrillOptions.setDrillSeriesFormField(cr.getChartDrillOptions().getDrillSeriesFormField());
4907
4908                 ncr.setChartDrillOptions(chartDrillOptions);
4909             }
4910                 ncr.setIsOneTimeScheduleAllowed(cr.getIsOneTimeScheduleAllowed());
4911                 ncr.setIsHourlyScheduleAllowed(cr.getIsHourlyScheduleAllowed());
4912                 ncr.setIsDailyScheduleAllowed(cr.getIsDailyScheduleAllowed());
4913                 ncr.setIsDailyMFScheduleAllowed(cr.getIsDailyMFScheduleAllowed());
4914                 ncr.setIsWeeklyScheduleAllowed(cr.getIsWeeklyScheduleAllowed());
4915                 ncr.setIsMonthlyScheduleAllowed(cr.getIsMonthlyScheduleAllowed());
4916
4917             ncr.setPageSize(cr.getPageSize());
4918             ncr.setReportType(cr.getReportType());
4919
4920             if (cr.getReportMap() != null) {
4921                 ReportMap repMap = objFactory.createReportMap();
4922                 if (nvl(cr.getReportMap().getMarkerColor()).length() > 0)
4923                     repMap.setMarkerColor(cr.getReportMap().getMarkerColor());
4924                 if (nvl(cr.getReportMap().getUseDefaultSize()).length() > 0)
4925                     repMap.setUseDefaultSize(cr.getReportMap().getUseDefaultSize());
4926                 if (nvl(cr.getReportMap().getHeight()).length() > 0)
4927                     repMap.setHeight(cr.getReportMap().getHeight());
4928                 if (nvl(cr.getReportMap().getWidth()).length() > 0)
4929                     repMap.setWidth(cr.getReportMap().getWidth());
4930                 if (nvl(cr.getReportMap().getIsMapAllowedYN()).length() > 0)
4931                     repMap.setIsMapAllowedYN(cr.getReportMap().getIsMapAllowedYN());
4932                 if (nvl(cr.getReportMap().getAddAddressInDataYN()).length() > 0)
4933                     repMap.setAddAddressInDataYN(cr.getReportMap().getAddAddressInDataYN());
4934                 if (nvl(cr.getReportMap().getAddressColumn()).length() > 0)
4935                     repMap.setAddressColumn(cr.getReportMap().getAddressColumn());
4936                 if (nvl(cr.getReportMap().getDataColumn()).length() > 0)
4937                     repMap.setDataColumn(cr.getReportMap().getDataColumn());
4938                 if (nvl(cr.getReportMap().getDefaultMapType()).length() > 0)
4939                     repMap.setDefaultMapType(cr.getReportMap().getDefaultMapType());
4940                 if (nvl(cr.getReportMap().getLatColumn()).length() > 0)
4941                     repMap.setLatColumn(cr.getReportMap().getLatColumn());
4942                 if (nvl(cr.getReportMap().getLongColumn()).length() > 0)
4943                     repMap.setLongColumn(cr.getReportMap().getLongColumn());
4944                 if (nvl(cr.getReportMap().getColorColumn()).length() > 0)
4945                     repMap.setColorColumn(cr.getReportMap().getColorColumn());
4946                 if (nvl(cr.getReportMap().getLegendColumn()).length() > 0)
4947                     repMap.setLegendColumn(cr.getReportMap().getLegendColumn());
4948
4949                 for (Iterator iter = cr.getReportMap().getMarkers().iterator(); iter
4950                         .hasNext();) {
4951                     repMap.getMarkers().add(
4952                             cloneMarkerType(objFactory, (Marker) iter.next()));
4953
4954                 }
4955
4956                 ncr.setReportMap(repMap);
4957             }
4958
4959                 } catch (JAXBException ex) { 
4960             logger.error(EELFLoggerDelegate.debugLogger, "Exception occured in cloneCustomReport ", ex);
4961             throw new RaptorException(ex.getMessage(), ex.getCause());
4962         }
4963
4964         return ncr;
4965         } 
4966
4967
4968
4969     private int getIntValue(String value, int defaultValue) {
4970         int iValue = defaultValue;
4971         try {
4972             iValue = Integer.parseInt(value);
4973         } catch (Exception e) {
4974             logger.error(EELFLoggerDelegate.debugLogger, "Exception occured in getIntValue ", e);
4975         }
4976
4977         return iValue;
4978         } 
4979
4980     public static String replaceNewLine(String strSource, String strFind, String chrReplace) {
4981         StringBuffer sbfTemp = new StringBuffer();
4982
4983         try {
4984             int intIndex = strSource.indexOf(strFind, 0);
4985             if (intIndex >= 0) {
4986                 int intStart = 0;
4987
4988                 int intTotalSize = strSource.length();
4989
4990                 while (intStart < intTotalSize &&
4991                         ((intIndex = strSource.indexOf(strFind, intStart)) >= 0)) {
4992                     if (intIndex == intStart) {
4993                         sbfTemp.append(chrReplace);
4994                     } else {
4995                         sbfTemp.append(strSource.substring(intStart, intIndex));
4996                         sbfTemp.append(chrReplace);
4997                     }
4998                     intStart = intIndex + strFind.length();
4999                 }
5000                 sbfTemp.append(strSource.substring(intStart));
5001             } else {
5002                 sbfTemp.append(strSource);
5003             }
5004         } catch (Exception expGeneral) {
5005             logger.error(EELFLoggerDelegate.debugLogger, "Exception occured in replaceNewLine ", expGeneral);
5006             sbfTemp = new StringBuffer(strSource);
5007         }
5008
5009         return sbfTemp.toString();
5010     }
5011
5012
5013     public String getFolderId() {
5014         return nvl(cr.getFolderId()).length() > 0 ? cr.getFolderId() : "NULL";
5015     }
5016
5017     public void setFolderId(String folderId) {
5018         cr.setFolderId(folderId);
5019     }
5020
5021     public String addZero(String num) {
5022         int numInt = 0;
5023         try {
5024             numInt = Integer.parseInt(num);
5025         } catch (NumberFormatException ex) {
5026             numInt = 0;
5027         }
5028         if (numInt < 10)
5029             return "0" + numInt;
5030         else
5031             return "" + numInt;
5032     }
5033
5034     public String getIsDailyMFScheduleAllowed() {
5035         return cr.getIsDailyMFScheduleAllowed();
5036     }
5037
5038     public void setIsDailyMFScheduleAllowed(String isDailyMFScheduleAllowed) {
5039         cr.setIsDailyMFScheduleAllowed(isDailyMFScheduleAllowed);
5040     }
5041
5042     public String getIsDailyScheduleAllowed() {
5043         return cr.getIsDailyScheduleAllowed();
5044     }
5045
5046     public void setIsDailyScheduleAllowed(String isDailyScheduleAllowed) {
5047         cr.setIsDailyScheduleAllowed(isDailyScheduleAllowed);
5048     }
5049
5050     public String getIsHourlyScheduleAllowed() {
5051         return cr.getIsHourlyScheduleAllowed();
5052     }
5053
5054     public void setIsHourlyScheduleAllowed(String isHourlyScheduleAllowed) {
5055         cr.setIsHourlyScheduleAllowed(isHourlyScheduleAllowed);
5056     }
5057
5058     public String getIsMonthlyScheduleAllowed() {
5059         return cr.getIsMonthlyScheduleAllowed();
5060     }
5061
5062     public void setIsMonthlyScheduleAllowed(String isMonthlyScheduleAllowed) {
5063         cr.setIsMonthlyScheduleAllowed(isMonthlyScheduleAllowed);
5064     }
5065
5066     public String getIsOneTimeScheduleAllowed() {
5067         return cr.getIsOneTimeScheduleAllowed();
5068     }
5069
5070     public void setIsOneTimeScheduleAllowed(String isOneTimeScheduleAllowed) {
5071         cr.setIsOneTimeScheduleAllowed(isOneTimeScheduleAllowed);
5072     }
5073
5074     public String getIsWeeklyScheduleAllowed() {
5075         return cr.getIsWeeklyScheduleAllowed();
5076     }
5077
5078     public void setIsWeeklyScheduleAllowed(String isWeeklyScheduleAllowed) {
5079         cr.setIsWeeklyScheduleAllowed(isWeeklyScheduleAllowed);
5080
5081     }
5082
5083     public static boolean isNull(String a) {
5084         if ((a == null) || (a.length() == 0) || "null".equalsIgnoreCase(a))
5085             return true;
5086         else
5087             return false;
5088     }
5089
5090     public int getDependsOnFormFieldFlag(DataColumnType dc, HashMap formValues) {
5091         int flag = 0;
5092         String fieldValue = "";
5093         if (nvl(dc.getDependsOnFormField()).length() > 0 && nvl(dc.getDependsOnFormField()).indexOf("[") != -1) {
5094             if (formValues != null) {
5095                 Set set = formValues.entrySet();
5096                 String value = "";
5097                 for (Iterator iter1 = set.iterator(); iter1.hasNext();) {
5098                     Map.Entry entry = (Entry) iter1.next();
5099                     value = (String) entry.getValue();
5100                     if (dc.getDependsOnFormField().equals("[" + entry.getKey() + "]")) {
5101                         fieldValue = nvl(value);
5102
5103                         if (fieldValue.length() > 0 && !"NULL".equals(fieldValue)) {
5104                             flag = 0;
5105                         } else {
5106                             flag = 1;
5107                         }
5108
5109                     }
5110                 }
5111             }
5112         }
5113
5114         return flag;
5115     }
5116
5117     public String getClassifier() {
5118         return (cr.getDataminingOptions() != null ? cr.getDataminingOptions().getClassifier() : "");
5119     }
5120
5121     public void setClassifier(String classifier) {
5122         cr.getDataminingOptions().setClassifier(classifier);
5123     }
5124
5125     public int getForecastingPeriod() {
5126         return (cr.getDataminingOptions() != null
5127                 ? new Integer(cr.getDataminingOptions().getForecastingUnits()).intValue()
5128                 : -1);
5129     }
5130
5131     public void setForecastingPeriod(String period) {
5132         cr.getDataminingOptions().setForecastingUnits(period);
5133     }
5134
5135     public String getForecastingTimeFormat() {
5136         return (cr.getDataminingOptions() != null ? cr.getDataminingOptions().getTimeformat() : "");
5137     }
5138
5139     public void setForecastingTimeFormat(String format) {
5140         cr.getDataminingOptions().setTimeformat(format);
5141     }
5142
5143     /**
5144      * Get Number of Columns to Frozen in Data Grid
5145      */
5146
5147     public int getFrozenColumns() {
5148         return cr.getFrozenColumns() == null ? 0 : cr.getFrozenColumns();
5149     }
5150
5151     public String getFrozenColumnId() {
5152         int noOfColumns = cr.getFrozenColumns() == null ? 0 : cr.getFrozenColumns();
5153         if (noOfColumns != 0) {
5154             List reportCols = getOnlyVisibleColumns();
5155             int colIdx = 0;
5156             for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
5157                 ++colIdx;
5158                 DataColumnType dc = (DataColumnType) iter.next();
5159                 if (colIdx == noOfColumns) {
5160
5161                     return dc.getColId();
5162                 } else
5163                     continue;
5164             } // for
5165             return "";
5166         } else
5167             return "";
5168
5169     }
5170
5171     /**
5172      * Set Number of Columns to Frozen in Data Grid
5173      */
5174
5175     public void setFrozenColumns(int frozenColumns) {
5176         cr.setFrozenColumns(frozenColumns);
5177     }
5178
5179     /**
5180      * @return the reportSQLWithRowNum for ZK Support
5181      */
5182     public String getReportSQLWithRowNum() {
5183         return reportSQLWithRowNum;
5184     }
5185
5186     /**
5187      * @param reportSQLWithRowNum the reportSQLWithRowNum to set for ZK Support
5188      */
5189     public void setReportSQLWithRowNum(String reportSQLWithRowNum) {
5190         this.reportSQLWithRowNum = reportSQLWithRowNum;
5191     }
5192
5193     public void setReportSQLOnlyFirstPart(String reportSQLOnlyFirstPart) {
5194         this.reportSQLOnlyFirstPart = reportSQLOnlyFirstPart;
5195     }
5196
5197     public String getReportSQLOnlyFirstPart() {
5198         return this.reportSQLOnlyFirstPart;
5199     }
5200
5201     public String getTemplateFile() throws RaptorException {
5202         return ReportLoader.getTemplateFile(getReportID());
5203     }
5204
5205     public String getPdfImg() {
5206         return cr.getPdfImgLogo();
5207     }
5208
5209     public String getEmptyMessage() {
5210         String emptyMessage = cr.getEmptyMessage();
5211         if (nvl(emptyMessage).length() <= 0)
5212             emptyMessage = Globals.getReportEmptyMessage();
5213         return emptyMessage;
5214     }
5215
5216     public void setPdfImg(String img_loc) {
5217         cr.setPdfImgLogo(img_loc);
5218     }
5219
5220     public void setEmptyMessage(String emptyMessage) {
5221         cr.setEmptyMessage(emptyMessage);
5222     }
5223
5224     public void setDrillReportIdForChart(String reportId) {
5225         cr.getChartDrillOptions().setDrillReportId(reportId);
5226     }
5227
5228     public String getDrillReportIdForChart() {
5229         return (cr.getChartDrillOptions() != null) ? cr.getChartDrillOptions().getDrillReportId() : "";
5230     }
5231
5232     public void setDrillXAxisFormField(String formField) {
5233         cr.getChartDrillOptions().setDrillXAxisFormField(formField);
5234     }
5235
5236     public String getDrillXAxisFormField() {
5237         return (cr.getChartDrillOptions() != null) ? cr.getChartDrillOptions().getDrillXAxisFormField() : "";
5238     }
5239
5240     public void setDrillYAxisFormField(String formField) {
5241         cr.getChartDrillOptions().setDrillYAxisFormField(formField);
5242     }
5243
5244     public String getDrillYAxisFormField() {
5245         return (cr.getChartDrillOptions() != null) ? cr.getChartDrillOptions().getDrillYAxisFormField() : "";
5246     }
5247
5248     public void setDrillSeriesFormField(String formField) {
5249         cr.getChartDrillOptions().setDrillSeriesFormField(formField);
5250     }
5251
5252     public String getDrillSeriesFormField() {
5253         return (cr.getChartDrillOptions() != null) ? cr.getChartDrillOptions().getDrillSeriesFormField() : "";
5254     }
5255
5256     public boolean isEnhancedPaginationNeeded() {
5257         List reportCols = getAllColumns();
5258
5259         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
5260             DataColumnType dc = (DataColumnType) iter.next();
5261             if (dc.isEnhancedPagination() != null && dc.isEnhancedPagination().booleanValue())
5262                 return true;
5263                 } 
5264         return false;
5265     }
5266
5267     public DataColumnType getColumnWhichNeedEnhancedPagination() {
5268         List reportCols = getAllColumns();
5269
5270         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
5271             DataColumnType dc = (DataColumnType) iter.next();
5272             if (dc.isEnhancedPagination() != null && dc.isEnhancedPagination().booleanValue())
5273                 return dc;
5274                 } 
5275         return null;
5276     }
5277
5278     public void setDataGridAlign(String align) {
5279         cr.setDataGridAlign(align);
5280     }
5281
5282     public String getDataGridAlign() {
5283         return (cr.getDataGridAlign() != null) ? cr.getDataGridAlign() : "left";
5284     }
5285
5286     public void setWidthNoColumn(String width) {
5287         cr.setWidthNoColumn(width);
5288     }
5289
5290     public String getWidthNoColumn() {
5291         return (cr.getWidthNoColumn() != null) ? cr.getWidthNoColumn() : "30px";
5292     }
5293
5294     public void setWholeSQL(String sql) {
5295         wholeSQL = sql;
5296     }
5297
5298     public String getWholeSQL() {
5299         return wholeSQL;
5300     }
5301
5302