18d312789c77c85b0f7fe242a41f40d7ac751686
[portal/sdk.git] /
1 /*-
2  * ================================================================================
3  * eCOMP Portal SDK
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ================================================================================
19  */
20 package org.openecomp.portalsdk.analytics.model.runtime;
21
22 import java.io.BufferedWriter;
23 import java.io.FileWriter;
24 import java.io.IOException;
25 import java.io.UnsupportedEncodingException;
26 import java.text.ParsePosition;
27 import java.text.SimpleDateFormat;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collections;
31 import java.util.Enumeration;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Map.Entry;
37 import java.util.Set;
38 import java.util.SortedSet;
39 import java.util.TreeSet;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
42
43 import javax.servlet.http.HttpServletRequest;
44 import javax.servlet.http.HttpSession;
45
46 import org.apache.commons.lang.time.DateUtils;
47 import org.openecomp.portalsdk.analytics.error.RaptorException;
48 import org.openecomp.portalsdk.analytics.model.ReportHandler;
49 import org.openecomp.portalsdk.analytics.model.base.ChartSeqComparator;
50 import org.openecomp.portalsdk.analytics.system.AppUtils;
51 import org.openecomp.portalsdk.analytics.system.ConnectionUtils;
52 import org.openecomp.portalsdk.analytics.util.AppConstants;
53 import org.openecomp.portalsdk.analytics.util.DataSet;
54 import org.openecomp.portalsdk.analytics.util.HtmlStripper;
55 import org.openecomp.portalsdk.analytics.util.Utils;
56 import org.openecomp.portalsdk.analytics.view.ReportData;
57 import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType;
58 import org.openecomp.portalsdk.analytics.xmlobj.FormFieldType;
59 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
60 import org.openecomp.portalsdk.core.web.support.UserUtils;
61
62 public class ChartD3Helper {
63         
64         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ChartD3Helper.class);
65
66         
67         private ReportRuntime reportRuntime;
68         private String chartType;
69
70         public static final long HOUR = 3600*1000;      
71         public static final long DAY = 3600*1000*24;    
72         public static final long MONTH = 3600*1000*24*31;       
73         public static final long YEAR = 3600*1000*24*365;       
74         
75         
76         public ChartD3Helper() {
77                 
78         }
79
80         /**
81          * @return the chartType
82          */
83         public String getChartType() {
84                 return chartType;
85         }
86
87         /**
88          * @param chartType the chartType to set
89          */
90         public void setChartType(String chartType) {
91                 this.chartType = chartType;
92         }
93
94         public ChartD3Helper(ReportRuntime rr) {
95                 this.reportRuntime = rr;
96         }
97         
98         public String createVisualization(String reportID, HttpServletRequest request) throws RaptorException {
99                 //From annotations chart
100                 clearReportRuntimeBackup(request);
101                 
102                 //HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
103         final Long user_id = new Long((long) UserUtils.getUserId(request));
104                 //String action = request.getParameter(AppConstants.RI_ACTION);
105                 //String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
106
107                 ReportHandler rh = new ReportHandler();
108                 ReportData reportData = null;
109                  HashMap<String, String> chartOptionsMap = new HashMap<String, String>();
110                 try {
111                  if(reportID !=null) {  
112                          reportRuntime = rh.loadReportRuntime(request, reportID, true, 1);
113                          setChartType(reportRuntime.getChartType());
114                          reportData             = reportRuntime.loadReportData(0, user_id.toString(), 10000,request, false);
115                  }
116                  
117                 
118                         
119                         String rotateLabelsStr = "";
120                         rotateLabelsStr = AppUtils.nvl(reportRuntime.getLegendLabelAngle());
121                         if(rotateLabelsStr.toLowerCase().equals("standard")) {
122                                 rotateLabelsStr = "0";
123                         } else if (rotateLabelsStr.toLowerCase().equals("up45")) {
124                                 rotateLabelsStr = "45";
125                         } else if (rotateLabelsStr.toLowerCase().equals("down45")) {
126                                 rotateLabelsStr = "-45";
127                         } else if (rotateLabelsStr.toLowerCase().equals("up90")) {
128                                 rotateLabelsStr = "90";
129                         } else if (rotateLabelsStr.toLowerCase().equals("down90")) {
130                                 rotateLabelsStr = "-90";
131                         } else
132                                 rotateLabelsStr = "0";
133                         
134                         String width                                                    = (AppUtils.getRequestNvlValue(request, "width").length()>0?AppUtils.getRequestNvlValue(request, "width"):(AppUtils.nvl(reportRuntime.getChartWidth()).length()>0?reportRuntime.getChartWidth():"700"));
135                         String height                                                   = (AppUtils.getRequestNvlValue(request, "height").length()>0?AppUtils.getRequestNvlValue(request, "height"):(AppUtils.nvl(reportRuntime.getChartHeight()).length()>0?reportRuntime.getChartHeight():"300"));
136                         String animationStr                                     = (AppUtils.getRequestNvlValue(request, "animation").length()>0?AppUtils.getRequestNvlValue(request, "animation"):new Boolean(reportRuntime.isAnimateAnimatedChart()).toString());
137                         
138                         String rotateLabels                                     = (AppUtils.getRequestNvlValue(request, "rotateLabels").length()>0?AppUtils.getRequestNvlValue(request, "rotateLabels"):(rotateLabelsStr.length()>0?rotateLabelsStr:"0"));
139                         String staggerLabelsStr                                 = (AppUtils.getRequestNvlValue(request, "staggerLabels").length()>0?AppUtils.getRequestNvlValue(request, "staggerLabels"):"false");
140                         String showMaxMinStr                                    = (AppUtils.getRequestNvlValue(request, "showMaxMin").length()>0?AppUtils.getRequestNvlValue(request, "showMaxMin"):"false");
141                         String showControlsStr                                  = (AppUtils.getRequestNvlValue(request, "showControls").length()>0?AppUtils.getRequestNvlValue(request, "showControls"):new Boolean(reportRuntime.displayBarControls()).toString());
142                         String showLegendStr                                    = (AppUtils.getRequestNvlValue(request, "showLegend").length()>0?AppUtils.getRequestNvlValue(request, "showLegend"):new Boolean(!new Boolean(reportRuntime.hideChartLegend())).toString()); 
143                         String topMarginStr                                     = AppUtils.getRequestNvlValue(request, "topMargin");
144                         String topMargin                                                = (AppUtils.nvl(topMarginStr).length()<=0)?(reportRuntime.getTopMargin()!=null?reportRuntime.getTopMargin().toString():"30"):topMarginStr;
145                         String bottomMarginStr                                  = AppUtils.getRequestNvlValue(request, "bottomMargin");
146                         String bottomMargin                                     = (AppUtils.nvl(bottomMarginStr).length()<=0)?(reportRuntime.getBottomMargin()!=null?reportRuntime.getBottomMargin().toString():"50"):bottomMarginStr;
147                         String leftMarginStr                                    = AppUtils.getRequestNvlValue(request, "leftMargin");
148                         String leftMargin                                               = (AppUtils.nvl(leftMarginStr).length()<=0)?(reportRuntime.getLeftMargin()!=null?reportRuntime.getLeftMargin().toString():"100"):leftMarginStr;
149                         String rightMarginStr                                   = AppUtils.getRequestNvlValue(request, "rightMargin");
150                         String rightMargin                                              = (AppUtils.nvl(rightMarginStr).length()<=0)?(reportRuntime.getRightMargin()!=null?reportRuntime.getRightMargin().toString():"160"):rightMarginStr;
151                         String showTitleStr                                     = (AppUtils.getRequestNvlValue(request, "showTitle").length()>0?AppUtils.getRequestNvlValue(request, "showTitle"):new Boolean(reportRuntime.displayChartTitle()).toString()); 
152                         String subType                                                  = AppUtils.getRequestNvlValue(request, "subType").length()>0?AppUtils.getRequestNvlValue(request, "subType"):(AppUtils.nvl(reportRuntime.getTimeSeriesRender()).equals("area")?reportRuntime.getTimeSeriesRender():"");
153                         String stackedStr                                               = AppUtils.getRequestNvlValue(request, "stacked").length()>0?AppUtils.getRequestNvlValue(request, "stacked"):new Boolean(reportRuntime.isChartStacked()).toString();
154                         String horizontalBar                                    = AppUtils.getRequestNvlValue(request, "horizontalBar").length()>0?AppUtils.getRequestNvlValue(request, "horizontalBar"):new Boolean(reportRuntime.isHorizontalOrientation()).toString();
155                         String barRealTimeAxis                                  = AppUtils.getRequestNvlValue(request, "barRealTimeAxis");
156                         String barReduceXAxisLabels                             = AppUtils.getRequestNvlValue(request, "barReduceXAxisLabels").length()>0?AppUtils.getRequestNvlValue(request, "barReduceXAxisLabels"):new Boolean(reportRuntime.isLessXaxisTickers()).toString();;
157                         String timeAxis                                                 = AppUtils.getRequestNvlValue(request, "timeAxis").length()>0?AppUtils.getRequestNvlValue(request, "timeAxis"):new Boolean(reportRuntime.isTimeAxis()).toString();
158                         String logScale                                                 = AppUtils.getRequestNvlValue(request, "logScale").length()>0?AppUtils.getRequestNvlValue(request, "logScale"):new Boolean(reportRuntime.isLogScale()).toString();
159                         String precision                                                = AppUtils.getRequestNvlValue(request, "precision").length()>0?AppUtils.getRequestNvlValue(request, "precision"):"2";
160                         
161
162                         chartOptionsMap.put("width", width);
163                         chartOptionsMap.put("height", height);
164                         chartOptionsMap.put("animation", animationStr);
165                         chartOptionsMap.put("rotateLabels", rotateLabels);
166                         chartOptionsMap.put("staggerLabels", staggerLabelsStr);
167                         chartOptionsMap.put("showMaxMin", showMaxMinStr);
168                         chartOptionsMap.put("showControls", showControlsStr);
169                         chartOptionsMap.put("showLegend", showLegendStr);
170                         chartOptionsMap.put("topMargin", topMargin);
171                         chartOptionsMap.put("bottomMargin", bottomMargin);
172                         chartOptionsMap.put("leftMargin", leftMargin);
173                         chartOptionsMap.put("rightMargin", rightMargin);
174                         chartOptionsMap.put("showTitle", showTitleStr);
175                         chartOptionsMap.put("subType", subType);
176                         chartOptionsMap.put("stacked", stackedStr);
177                         chartOptionsMap.put("horizontalBar", horizontalBar);
178                         chartOptionsMap.put("timeAxis", timeAxis);
179                         chartOptionsMap.put("barRealTimeAxis", barRealTimeAxis);
180                         chartOptionsMap.put("barReduceXAxisLabels", barReduceXAxisLabels);
181                         
182                         chartOptionsMap.put("logScale", logScale);
183                         chartOptionsMap.put("precision", precision);
184                         
185                 
186                 } catch (RaptorException ex) {
187                         ex.printStackTrace();
188                 }
189                 return createVisualization(reportRuntime, chartOptionsMap, request);
190         }
191         
192         public String createVisualization(ReportRuntime reportRuntime, HttpServletRequest request) throws RaptorException {
193                 
194                 String rotateLabelsStr = "";
195                 rotateLabelsStr = AppUtils.nvl(reportRuntime.getLegendLabelAngle());
196                 if(rotateLabelsStr.toLowerCase().equals("standard")) {
197                         rotateLabelsStr = "0";
198                 } else if (rotateLabelsStr.toLowerCase().equals("up45")) {
199                         rotateLabelsStr = "45";
200                 } else if (rotateLabelsStr.toLowerCase().equals("down45")) {
201                         rotateLabelsStr = "-45";
202                 } else if (rotateLabelsStr.toLowerCase().equals("up90")) {
203                         rotateLabelsStr = "90";
204                 } else if (rotateLabelsStr.toLowerCase().equals("down90")) {
205                         rotateLabelsStr = "-90";
206                 } else
207                         rotateLabelsStr = "0";
208                 
209                 HashMap<String,String> chartOptionsMap = new HashMap<String, String>();
210                 chartOptionsMap.put("width", reportRuntime.getChartWidth());
211                 chartOptionsMap.put("height", reportRuntime.getChartHeight());
212                 chartOptionsMap.put("animation", new Boolean(reportRuntime.isAnimateAnimatedChart()).toString());
213                 chartOptionsMap.put("rotateLabels", rotateLabelsStr);
214                 chartOptionsMap.put("staggerLabels", "false");
215                 chartOptionsMap.put("showMaxMin", "false");
216                 chartOptionsMap.put("showControls", new Boolean(reportRuntime.displayBarControls()).toString());
217                 chartOptionsMap.put("showLegend", new Boolean(!reportRuntime.hideChartLegend()).toString());
218                 chartOptionsMap.put("topMargin", reportRuntime.getTopMargin()!=null?reportRuntime.getTopMargin().toString():"30");
219                 chartOptionsMap.put("bottomMargin", reportRuntime.getBottomMargin()!=null?reportRuntime.getBottomMargin().toString():"50");
220                 chartOptionsMap.put("leftMargin", reportRuntime.getLeftMargin()!=null?reportRuntime.getLeftMargin().toString():"100");
221                 chartOptionsMap.put("rightMargin", reportRuntime.getRightMargin()!=null?reportRuntime.getRightMargin().toString():"160");
222                 chartOptionsMap.put("showTitle", new Boolean(reportRuntime.displayChartTitle()).toString());
223                 chartOptionsMap.put("subType", (AppUtils.nvl(reportRuntime.getTimeSeriesRender()).equals("area")?reportRuntime.getTimeSeriesRender():""));
224                 chartOptionsMap.put("stacked", new Boolean(reportRuntime.isChartStacked()).toString());
225                 chartOptionsMap.put("horizontalBar", new Boolean(reportRuntime.isHorizontalOrientation()).toString());
226                 chartOptionsMap.put("timeAxis", new Boolean(reportRuntime.isTimeAxis()).toString());
227                 chartOptionsMap.put("barReduceXAxisLabels", new Boolean(reportRuntime.isLessXaxisTickers()).toString());
228
229                 chartOptionsMap.put("logScale", new Boolean(reportRuntime.isLogScale()).toString());
230                 chartOptionsMap.put("precision", "2");
231                 
232
233                 
234                 return createVisualization(reportRuntime, chartOptionsMap, request);
235         }
236         
237         public String createVisualization(ReportRuntime reportRuntime, HashMap<String,String> chartOptionsMap, HttpServletRequest request) throws RaptorException {
238                 
239                 //String width, String height, boolean animation, String rotateLabels, boolean staggerLabels, boolean showMaxMin, boolean showLegend, boolean showControls, String topMargin, String bottomMargin, boolean showTitle, String subType
240                 
241                 boolean isEmbedded = false;
242                 if(request.getParameter("embedded")!=null) { 
243                         isEmbedded = true;              
244                 }
245                 String width                            = chartOptionsMap.get("width");
246                 String height                           = chartOptionsMap.get("height");
247                 boolean animation                       = getBooleanValue(chartOptionsMap.get("animation"), true);
248                 String rotateLabels             = chartOptionsMap.get("rotateLabels");
249                 boolean staggerLabels           = getBooleanValue(chartOptionsMap.get("staggerLabels"));
250                 boolean showMaxMin                      = getBooleanValue(chartOptionsMap.get("showMaxMin"), false);
251                 boolean showLegend                      = getBooleanValue(chartOptionsMap.get("showLegend"), true);
252                 boolean showControls            = getBooleanValue(chartOptionsMap.get("showControls"), true);
253                 String topMargin                        = chartOptionsMap.get("topMargin");
254                 String bottomMargin             = chartOptionsMap.get("bottomMargin");
255                 String leftMargin                       = chartOptionsMap.get("leftMargin");
256                 String rightMargin                      = chartOptionsMap.get("rightMargin");
257                 boolean showTitle                       = getBooleanValue(chartOptionsMap.get("showTitle"), true);
258                 String subType                          = chartOptionsMap.get("subType");
259                 boolean stacked                         = getBooleanValue(chartOptionsMap.get("stacked"), false);
260                 boolean horizontalBar           = getBooleanValue(chartOptionsMap.get("horizontalBar"), false);
261                 boolean barRealTimeAxis         = getBooleanValue(chartOptionsMap.get("barRealTimeAxis"), true);
262                 boolean barReduceXAxisLabels= getBooleanValue(chartOptionsMap.get("barReduceXAxisLabels"), false);
263                 boolean timeAxis                        = getBooleanValue(chartOptionsMap.get("timeAxis"), true);
264                 
265                 
266                 boolean logScale = getBooleanValue(chartOptionsMap.get("logScale"), false);
267                 
268                 int precision    =  2;
269                 
270                 try {
271                         precision = Integer.parseInt(chartOptionsMap.get("precision"));
272                 } catch (NumberFormatException ex) {
273                         
274                 }
275                 
276         final Long user_id = new Long((long) UserUtils.getUserId(request));
277
278         HttpSession session = null;
279         session = request.getSession();
280         String chartType = reportRuntime.getChartType();
281             List l = reportRuntime.getAllColumns();
282             List lGroups = reportRuntime.getAllChartGroups();
283             HashMap mapYAxis = reportRuntime.getAllChartYAxis(reportRuntime.getReportParamValues());
284             //ReportParamValues reportParamValues = reportRuntime.getReportParamValues();
285             String chartLeftAxisLabel = reportRuntime.getFormFieldFilled(nvl(reportRuntime.getChartLeftAxisLabel()));
286             String chartRightAxisLabel = reportRuntime.getFormFieldFilled(nvl(reportRuntime.getChartRightAxisLabel()));
287             
288             boolean multipleSeries = reportRuntime.isMultiSeries();
289             
290                 java.util.HashMap formValues = null;
291                 formValues = getRequestParametersMap(reportRuntime, request);
292             
293             
294             String legendColumnName = (reportRuntime.getChartLegendColumn()!=null)?reportRuntime.getChartLegendColumn().getDisplayName():"Legend Column";
295                 boolean displayChart = (nvl(chartType).length()>0)&&reportRuntime.getDisplayChart();
296                 HashMap additionalChartOptionsMap = new HashMap();
297
298                 StringBuffer wholeScript = new StringBuffer("");
299                 
300                 String title = reportRuntime.getReportTitle();
301                 
302                 title = parseTitle(title, formValues);
303                 
304                 String chartScriptsPath = (isEmbedded?AppUtils.getChartScriptsPath(""):AppUtils.getChartScriptsPath());
305                 
306                 if(displayChart) {
307                         DataSet ds = null;
308                         try {
309                                 if (!(chartType.equals(AppConstants.GT_HIERARCHICAL) || chartType.equals(AppConstants.GT_HIERARCHICAL_SUNBURST) || chartType.equals(AppConstants.GT_ANNOTATION_CHART))) {
310                                         ds = (DataSet) loadChartData(new Long(user_id).toString(), request);
311                                 } else if(chartType.equals(AppConstants.GT_ANNOTATION_CHART)) {
312                                         String reportSQL = reportRuntime.getWholeSQL();
313                                         String dbInfo = reportRuntime.getDBInfo();
314                                         ds = ConnectionUtils.getDataSet(reportSQL, dbInfo);
315                                         if(ds.getRowCount()<=0) {
316                                                 logger.debug(EELFLoggerDelegate.debugLogger, ("********************************************************************************"));
317                                                 logger.debug(EELFLoggerDelegate.debugLogger, (chartType.toUpperCase()+" - " + "Report ID : " + reportRuntime.getReportID() + " DATA IS EMPTY"));
318                                                 logger.debug(EELFLoggerDelegate.debugLogger, ("QUERY - " + reportSQL));
319                                                 logger.debug(EELFLoggerDelegate.debugLogger, ("********************************************************************************"));
320                                         }
321                                 } else if(chartType.equals(AppConstants.GT_HIERARCHICAL)||chartType.equals(AppConstants.GT_HIERARCHICAL_SUNBURST)) {
322                                         String reportSQL = reportRuntime.getWholeSQL();
323                                         String dbInfo = reportRuntime.getDBInfo();
324                                         ds = ConnectionUtils.getDataSet(reportSQL, dbInfo);
325                                 }
326                         } catch (RaptorException ex) {
327                                 //throw new RaptorException("Error while loading chart data", ex);
328                                 logger.error(EELFLoggerDelegate.debugLogger, ("********************************************************************************"));
329                                 logger.error(EELFLoggerDelegate.debugLogger, (chartType.toUpperCase()+" - " + "Report ID : " + reportRuntime.getReportID() + " ERROR THROWN FOR GIVEN QUERY "));
330                                 logger.error(EELFLoggerDelegate.debugLogger, ("QUERY - " + reportRuntime.getWholeSQL()));
331                                 logger.error(EELFLoggerDelegate.debugLogger, ("ERROR STACK TRACE" + ex.getMessage()));
332                                 logger.error(EELFLoggerDelegate.debugLogger, ("********************************************************************************"));
333                                 
334                         }
335                         if(ds==null) {
336                                 //displayChart = false;
337                                 if(chartType.equals(AppConstants.GT_ANNOTATION_CHART))
338                                         ds = new DataSet();
339                                 else
340                                         displayChart = false;
341                         }
342                         if(displayChart) {
343                                 
344                                 if (chartType.equals(AppConstants.GT_BAR_3D)) {
345                                         
346                                         // get category if not give the column name for the data column use this to develop series.
347                                         boolean hasCategoryAxis = reportRuntime.hasSeriesColumn();
348                                         
349                                         boolean hasCustomizedChartColor = false;
350                                     int flag = 0;
351                                     flag = hasCategoryAxis?1:0;
352                                         Object uniqueElements [] = null;
353                                         ArrayList uniqueElementsList = new ArrayList();
354                                         Object uniqueXAxisElements[] = null;
355                                 ArrayList ts = new ArrayList();  
356                                 //Set<String> ts1 = new HashSet();
357                                 ArrayList<String> ts1 = new ArrayList();
358                                         HashMap<String, String> columnMap = new HashMap();
359                                         String uniqueXAxisStr = "";
360                                         if(!timeAxis){
361                                                 for (int i = 0; i < ds.getRowCount(); i++) {
362                                                         uniqueXAxisStr = ds.getString(i, 0);
363                                                         ts1.add(uniqueXAxisStr);
364                                                 }
365                                         }
366                                         uniqueElementsList.addAll(ts1);
367                                         uniqueXAxisElements = ts1.toArray();
368                                         
369                                         if(flag == 1) {
370                                                 StringBuffer catStr = new StringBuffer("");
371                                                 String color="";
372                                         for (int i = 0; i < ds.getRowCount(); i++) {
373                                                 catStr = new StringBuffer("");
374                                                 catStr.append(ds.getString(i, 2));
375                                                          try {
376                                                                  if(ds.getString(i, "chart_color")!=null) {
377                                                                          color = ds.getString(i,  "chart_color");
378                                                                          hasCustomizedChartColor = true;
379                                                                          catStr.append("|"+color);
380                                                                  }
381                                                          } catch (ArrayIndexOutOfBoundsException ex) {
382                                                                  //System.out.println("No Chart Color");
383                                                          }
384
385                                                     if(catStr.length()>0) {
386                                                         //duplicates are avoided
387                                                         if(!ts.contains(catStr.toString()))
388                                                                                 ts.add(catStr.toString());
389                                                         
390                                                     }
391                                                     /* Get Chart LeftAxis Label even from Range Axis definition. */
392                                                         DataColumnType dct = null; 
393                                                         for (Iterator iter = l.iterator(); iter.hasNext();) {
394                                                             dct = (DataColumnType) iter.next();
395                                                             if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) {
396                                                                    if(nvl(chartLeftAxisLabel).length()<=0) {
397                                                                            chartLeftAxisLabel = nvl(dct.getYAxis());
398                                                                            chartLeftAxisLabel = (chartLeftAxisLabel.indexOf("|")!=-1)?chartLeftAxisLabel.substring(0,chartLeftAxisLabel.indexOf("|")):"";
399                                                                    }
400                                                             }
401                                                         }
402                                                     
403                                         }
404                                         //Object uniqueElements [] = ts.toArray();
405                                         //SortedSet s = Collections.synchronizedSortedSet(ts);
406                                         uniqueElements = ts.toArray();
407                                         } else {
408                                         DataColumnType dct = null; 
409                                         List yTextSeries = reportRuntime.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues);
410                                         //if(columnValuesList.size() == 1) {
411                                                 for (Iterator iter = l.iterator(); iter.hasNext();) {
412                                                     dct = (DataColumnType) iter.next();
413                                                     
414                                                     if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) {
415                                                         if((dct.isChartSeries()!=null && dct.isChartSeries().booleanValue()) || (dct.getChartSeq()!=null && dct.getChartSeq()>0) ) {
416                                                         
417                                                         if(nvl(dct.getChartColor()).length()>0) hasCustomizedChartColor = true;
418                                                         if(hasCustomizedChartColor) {
419                                                                 //duplicates are avoided
420                                                                 if(!ts.contains(dct.getDisplayName()+"|"+nvl(dct.getChartColor())))
421                                                                         ts.add(dct.getDisplayName()+"|"+nvl(dct.getChartColor()));
422                                                         } else {
423                                                                 //duplicates are avoided
424                                                                 if(!ts.contains(dct.getDisplayName()))
425                                                                         ts.add(dct.getDisplayName());
426                                                         }
427                                                            if(nvl(chartLeftAxisLabel).length()<=0) {
428                                                                    chartLeftAxisLabel = nvl(dct.getYAxis());
429                                                                    chartLeftAxisLabel = (chartLeftAxisLabel.indexOf("|")!=-1)?chartLeftAxisLabel.substring(0,chartLeftAxisLabel.indexOf("|")):"";
430                                                            }
431                                                            columnMap.put(dct.getDisplayName(), dct.getColId());
432                                                            /*
433                                                            ts.add(dct.getDisplayName());
434                                                            if(nvl(chartLeftAxisLabel).length()<=0) {
435                                                                    chartLeftAxisLabel = nvl(dct.getYAxis());
436                                                                    chartLeftAxisLabel = (chartLeftAxisLabel.indexOf("|")!=-1)?chartLeftAxisLabel.substring(0,chartLeftAxisLabel.indexOf("|")):"";
437                                                            }
438                                                            columnMap.put(dct.getDisplayName(), dct.getColId());
439                                                            */
440                                                     }
441                                                           }
442                                                     
443                                                 }
444                                                 //SortedSet s = Collections.synchronizedSortedSet(ts);
445                                                 uniqueElements = ts.toArray();
446                                                 
447                                         }
448                                         
449                                         wholeScript.append("<!DOCTYPE html>\n");
450                                         wholeScript.append("<html>\n");
451                                         wholeScript.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF8\">\n");
452                                         wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n");
453                                         wholeScript.append("<link href=\""+ chartScriptsPath +"d3/css/nv.d3.css\" rel=\"stylesheet\" type=\"text/css\">\n");
454                                         //wholeScript.append("")
455                                         wholeScript.append("<style>\n   " +
456                                                                                 " body { \n" +
457                                                                                 "       overflow-y:scroll; \n" +
458                                                                                 "       } \n" +
459                                                                                 " text { \n" +
460                                                                                 "       font: 12px sans-serif; \n" +
461                                                                                 " } \n" +
462                                                                                 " svg { \n" +
463                                                                                 "  display: block;\n" +
464                                                                                 " } \n" +
465                                                                                 " #chart"+reportRuntime.getReportID()+" svg { \n" +
466                                                                                 " height: "+ (nvl(height).length()>0?(height.endsWith("px")?height:height+"px"):"420px") + "; \n" +
467                                                                                 " width:  "+ (nvl(width).length()>0?(width.endsWith("px")?width:width+"px"):"700px") + "; \n" +
468                                                                                 " min-width: 100px; \n" +
469                                                                                 " min-height: 100px; \n" +
470                                                                                 " } \n" +
471                                                                                 " tr.z-row-over > td.z-row-inner, tr.z-row-over > .z-cell {" +
472                                                                                 " background-color: rgb(255, 255, 255); "+
473                                                                                 "} \n");
474                                         
475                                         wholeScript.append(".nodatadiv {\n");
476                                         wholeScript.append("    display: table-cell;\n");
477                                         wholeScript.append("    width: 700px;\n");
478                                         wholeScript.append("    height:370px;\n");
479                                         wholeScript.append("    text-align:center;\n");
480                                         wholeScript.append("    vertical-align: middle;\n");
481                                         wholeScript.append("}\n");
482                                         wholeScript.append(".nodatainner {\n");
483                                         wholeScript.append("    padding: 10px;\n");
484                                         wholeScript.append("}\n");
485                                         
486                                         wholeScript.append(" </style> \n" );
487                                         wholeScript.append("<body> \n");
488                                         if(showTitle)
489                                                 wholeScript.append("<div align=\"center\"><H3>" + title +"</H3></div>");
490
491                                         wholeScript.append("<div id=\"chart"+reportRuntime.getReportID()+"\"> <svg></svg> </div> \n");
492                                         //js files
493                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/d3.v3.min.js\"></script>");
494                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/nv.d3.min.js\"></script> \n");
495                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/tooltip.js\"></script> \n");
496                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/utils.js\"></script> \n");
497                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/axis.min.js\"></script> \n");
498                                         //wholeScript.append("<script src=\""+ AppUtils.getBaseFolderURL() +"d3/js/models/discreteBar.js\"></script> \n");
499                                         //wholeScript.append("<script src=\""+ AppUtils.getBaseFolderURL() +"d3/js/models/discreteBarChart.js\"></script> \n");
500                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/multiChart.js\"></script> \n");
501                                         //json
502                                         wholeScript.append("<script> \n");
503                                         wholeScript.append("historicalBarChart = [ \n");
504                                         //wholeScript.append("{ \n");
505                                          // data
506                                         ArrayList dataSeries = new ArrayList();
507                                         
508                                         String uniqueElement = "";
509                                         for (int i = 0; i < uniqueElements.length; i++) {
510                                                 uniqueElement = (String)uniqueElements[i];
511                                                 if(multipleSeries && (nvl(chartRightAxisLabel).length() > 0))
512                                                   dataSeries.add(new StringBuffer(" { \"type\":\"bar\", \"key\": \""+ (hasCustomizedChartColor?(uniqueElement.indexOf("|")!=-1?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement):uniqueElement) +"\", \"yAxis\": \""+(i+1)+"\", "+ (hasCustomizedChartColor?("\"color\": \""+uniqueElement.substring(uniqueElement.indexOf("|")+1) + "\","):"")+"\"values\": ["));
513                                                 else
514                                                   dataSeries.add(new StringBuffer(" { \"type\":\"bar\", \"key\": \""+ (hasCustomizedChartColor?(uniqueElement.indexOf("|")!=-1?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement):uniqueElement) +"\", \"yAxis\": \""+(1)+"\", "+ (hasCustomizedChartColor?("\"color\": \""+uniqueElement.substring(uniqueElement.indexOf("|")+1) + "\","):"")+"\"values\": ["));
515                                         }       
516                                         
517                                         // added to load all date elements
518                                         HashMap<String, HashMap<String, String>> dataSeriesMap = new HashMap<String, HashMap<String, String>>();
519                                         
520                                         for (int i = 0; i < uniqueElements.length; i++) {
521                                                 if(multipleSeries && (nvl(chartRightAxisLabel).length() > 0))
522                                                dataSeriesMap.put((String) uniqueElements[i], new HashMap<String, String>());            
523                                                   //dataSeries.add(new StringBuffer(" { \"type\":\"bar\", \"key\": \""+ uniqueElements[i] +"\", \"yAxis\": \""+(i+1)+"\", \"values\": ["));
524                                                 else
525                                                     dataSeriesMap.put((String) uniqueElements[i], new HashMap<String, String>());               
526
527                                                   //dataSeries.add(new StringBuffer(" { \"type\":\"bar\", \"key\": \""+ uniqueElements[i] +"\", \"yAxis\": \""+(1)+"\", \"values\": ["));
528                                         }       
529
530                                         String dateStr = null;
531                                         java.util.Date date = null;
532                                         
533                                 final int YEARFLAG = 1;
534                                 final int MONTHFLAG = 2;
535                                 final int DAYFLAG = 3;
536                                 final int HOURFLAG = 4;
537                                 final int MINFLAG = 5;
538                                 final int SECFLAG = 6;
539                                 final int MILLISECFLAG = 7;
540                                 final int DAYOFTHEWEEKFLAG = 8;
541                                 final int FLAGDATE = 9;
542
543                                         int flagNoDate        = 0;
544                                 
545                                         int MAXNUM = 0;
546                                         int YAXISNUM = 0;
547                                         int flagNull = 0;
548                                         
549                                         double YAXISDOUBLENUM = 0.0;
550                                         double MAXDOUBLENUM = 0.0;
551                                         int MAXNUMDECIMALPLACES = 0;
552                                         
553                                         int formatFlag = 0;
554                                 
555                                 TreeSet<String> dateStrList = new TreeSet<String>();
556                                 // added to store all date elements 
557                                         SortedSet<String> sortSet = new TreeSet<String>();
558                                 int count = 0;
559                                         if(flag!= 1) {
560                                                 HashMap dataSeriesStrMap = new HashMap();
561                                                 HashMap dataSeriesOverAllMap = new HashMap();
562                                                 String valueDataSeries = "";
563
564                                                 for (int j = 0; j < uniqueElements.length; j++) {
565                                                         dataSeriesStrMap = new HashMap();
566                                                  for (int i = 0; i < ds.getRowCount(); i++) {
567                                                          flagNoDate        = 0;
568                                                          YAXISNUM = 0;
569                                                          YAXISDOUBLENUM = 0.0;
570                                                          flagNull= 0;
571                                                          dateStr = ds.getString(i, 1);
572                                                          if(timeAxis) {
573                                                                  date = getDateFromDateStr(dateStr);
574                                                                  formatFlag = getFlagFromDateStr(dateStr);
575                                                          }
576                                                          uniqueElement = (String)uniqueElements[j];
577                                             if(date==null) {
578                                                         //continue;
579                                                         flagNoDate = 1;
580                                                         int pos = 0;
581                                                         //if(!((String)uniqueElementsList.get(i)).equals(dateStr)) {
582                                                                 for (int f=0 ; f< uniqueXAxisElements.length; f++) {
583                                                                         if(uniqueXAxisElements[f].equals(dateStr)){
584                                                                                 pos = f ;
585                                                                                 break;
586                                                                         }
587                                                                 }
588                                                                 /*for(int f=0; f<uniqueElementsList.size() && f < pos; f++)
589                                                                 {
590                                                                         StringBuffer strBuf = ((StringBuffer)dataSeries.get(j));
591                                                                     if(strBuf.indexOf((String)uniqueElementsList.get(f)) < 0 ) {
592                                                                         dataSeriesStrMap.put((String)uniqueElementsList.get(f), value);
593                                                                         //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + (String)uniqueElementsList.get(f)  + "\" , \"y\": null },");
594                                                                     }
595                                                                 }*/
596                                                         //}
597
598                                                         dateStrList.add("'"+dateStr+"'");
599                                                         //uniqueElement = (String)uniqueElements[j];
600                                                               try {
601                                                                          YAXISNUM = Integer.parseInt(ds.getString(i, columnMap.get((hasCustomizedChartColor?(uniqueElement.indexOf("|")!=-1?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement):uniqueElement))));
602                                                                          //if(MAXNUM < YAXISNUM) MAXNUM = YAXISNUM;
603                                                                                          if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
604                                                                       } catch (NumberFormatException ex) {
605                                                                                           try {
606                                                                                                   YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, columnMap.get((hasCustomizedChartColor?(uniqueElement.indexOf("|")!=-1?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement):uniqueElement))));
607                                                                                                   MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
608                                                                                                   if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
609                                                                                           } catch (NumberFormatException ex1) {
610                                                                                                   flagNull = 1;
611                                                                                           }
612                                                                                         //flagNull = 1;
613                                                                                   }
614                                                                                     /* For Non-date type value enclose with double quotes  */
615                                                                                         // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr  + "\" , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
616                                                                                                 if(logScale) {
617                                                                                         // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr  + "\" , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():(YAXISNUM>0?new Double(Math.log10(new Integer(YAXISNUM).doubleValue())).toString():null)):null) +"}, ");
618                                                                                                          valueDataSeries = "{ \"x\":\"" + dateStr  + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): null) +"}, ";
619                                                                                                          dataSeriesStrMap.put(dateStr, valueDataSeries);
620                                                                                                 } else {
621                                                                                                          //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr  + "\" , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
622                                                                                                          valueDataSeries = "{ \"x\":\"" + dateStr  + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ";
623                                                                                                          dataSeriesStrMap.put(dateStr, valueDataSeries);
624                                                                                                         
625                                                                                                 }               
626                                                                                          
627                                                                                       dataSeriesOverAllMap.put(uniqueElements[j], dataSeriesStrMap);    
628                                                         
629                                                                          //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":\"" + ds.getString(i, columnMap.get((String)uniqueElements[j])) +"\"}, ");
630                                                     } else {
631                                                         
632                                                              if(!barRealTimeAxis) { // true - non-time  
633                                                                 if(!dateStrList.contains(new Long(date.getTime()).toString())) {
634                                                                         dateStrList.add(new Long(date.getTime()).toString());
635                                                                         for (int k = 0; k < uniqueElements.length; k++) {
636                                                                                 //((StringBuffer) dataSeries.get(k)).append ("{ \"x\":" + date.getTime()  + " , \"y\":null}, ");
637                                                                                 HashMap<String, String> dataMap = dataSeriesMap.get((String) uniqueElements[k]);
638                                                                                 dataMap.put(date.getTime()+"", "null");
639
640                                                                         }
641                                                                 }
642                                                              }                                                  
643                                                          //if(ds.getString(i, 2).equals(uniqueElements[j])) {
644                                                         /*if(!dateStrList.contains(new Long(date.getTime()).toString())) {
645                                                                 for (int k = 0; k < uniqueElements.length; k++) {
646                                                                         ((StringBuffer) dataSeries.get(k)).append ("{ \"x\":" + date.getTime()  + " , \"y\":null}, ");
647                                                                 }
648                                                         }*/
649                                                         //dateStrList.add(new Long(date.getTime()).toString());
650                                                               try {
651                                                                         YAXISNUM = Integer.parseInt(ds.getString(i, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
652                                                                          dateStrList.add(new Long(date.getTime()).toString());
653                                                                          //if(MAXNUM < YAXISNUM) MAXNUM = YAXISNUM;
654                                                                                          if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
655                                                                       } catch (NumberFormatException ex) {
656                                                                                           try {
657                                                                                   YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
658                                                                                                   MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
659                                                                                                   if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
660                                                                                           } catch (NumberFormatException ex1) {
661                                                                                                   flagNull = 1;
662                                                                                           }
663                                                                                   
664                                                                                         //flagNull = 1;
665                                                                                   }
666                                                                 HashMap<String, String> dataMap = dataSeriesMap.get((String) uniqueElements[j]);
667                                                                                 if(logScale) {
668                                                                         dataMap.put(date.getTime()+"", (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():(YAXISNUM>0?new Double(Math.log10(new Integer(YAXISNUM).doubleValue())).toString():null)): "null"));
669                                                                                 } else {
670                                                                                         dataMap.put(date.getTime()+"", (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(YAXISDOUBLENUM).toString():new Integer(YAXISNUM).toString()): "null"));
671                                                                                 }               
672
673                                                               
674                                                                                         // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime()  + " , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
675
676                                                         //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime()  + " , \"y\":" + ds.getString(i, columnMap.get((String)uniqueElements[j])) +"}, ");
677                                                     }
678                                                          //}
679                                                  }
680                                                 }
681                                                 for(int kI = 0; kI < uniqueElements.length; kI++) {
682                                                         HashMap dataSeriesStrMap1 = (HashMap) dataSeriesOverAllMap.get(uniqueElements[kI]);
683                                                         for (int kL = 0; kL < uniqueXAxisElements.length; kL++) {
684                                                                 if(dataSeriesStrMap1.containsKey(uniqueXAxisElements[kL])) {
685                                                                         ((StringBuffer) dataSeries.get(kI)).append ((String)dataSeriesStrMap1.get(uniqueXAxisElements[kL]));
686                                                                 } else {
687                                                                         ((StringBuffer) dataSeries.get(kI)).append ("{ \"x\":\"" + uniqueXAxisElements[kL]  + "\" , \"y\": null }, ");
688                                                                 }
689                                                         }
690                                                 }
691                                                 
692                                         } else {
693                                                 HashMap dataSeriesStrMap = new HashMap();
694                                                 HashMap dataSeriesOverAllMap = new HashMap();
695                                                 String valueDataSeries = "";
696                                                 for (int j = 0; j < uniqueElements.length; j++) {
697                                                         dataSeriesStrMap = new HashMap();
698                                                         
699                                                          for (int i = 0; i < ds.getRowCount(); i++) {
700                                                                  flagNoDate = 0;
701                                                                  YAXISNUM = 0;
702                                                                  YAXISDOUBLENUM = 0.0;
703                                                                  flagNull= 0;
704                                                                  //flagSecondNull = 0;
705                                                                  dateStr = ds.getString(i, 1);
706                                                                  if(timeAxis) {
707                                                                          date = getDateFromDateStr(dateStr);
708                                                                          formatFlag = getFlagFromDateStr(dateStr);
709                                                                  }
710                                                                  uniqueElement = (String)uniqueElements[j];
711                                                                  if(date==null) {
712                                                                 //continue;
713                                                                 flagNoDate = 1;
714                                                                 int pos = 0;
715                                                                 //if(!((String)uniqueElementsList.get(i)).equals(dateStr)) {
716                                                                         for (int f=0 ; f< uniqueXAxisElements.length; f++) {
717                                                                                 if(uniqueXAxisElements[f].equals(dateStr)){
718                                                                                         pos = f ;
719                                                                                         break;
720                                                                                 }
721                                                                         }
722                                                                         /*for(int f=0; f<uniqueElementsList.size() && f < pos; f++)
723                                                                         {
724                                                                                 StringBuffer strBuf = ((StringBuffer)dataSeries.get(j));
725                                                                             if(strBuf.indexOf((String)uniqueElementsList.get(f)) < 0 ) {
726                                                                                 dataSeriesStrMap.put((String)uniqueElementsList.get(f), value);
727                                                                                 //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + (String)uniqueElementsList.get(f)  + "\" , \"y\": null },");
728                                                                             }
729                                                                         }*/
730                                                                 //}
731
732                                                                                          if(ds.getString(i, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))) {
733                                                                           dateStrList.add("'"+dateStr+"'");
734                                                                               try {
735                                                                                          YAXISNUM = Integer.parseInt(ds.getString(i, 3));
736                                                                                          if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
737                                                                                       } catch (NumberFormatException ex) {
738                                                                                                           try {
739                                                                                                                   YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, 3));
740                                                                                                                   MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
741                                                                                                                   if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
742                                                                                                            } catch (NumberFormatException ex1) {
743                                                                                                                           flagNull = 1;
744                                                                                                            }
745                                                                                                   
746                                                                                                      //flagNull = 1;
747                                                                                                   }
748                                                                                          
749                                                                                 if(logScale) {
750                                                                                          if(timeAxis) {
751                                                                           //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + dateStr  + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): null) +"}, ");
752                                                                                                  valueDataSeries = "{ \"x\":" + dateStr  + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): null) +"}, ";
753                                                                                                  dataSeriesStrMap.put(dateStr, valueDataSeries);
754                                                                                          } else {
755                                                                                  // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr  + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): null) +"}, ");
756                                                                                                  valueDataSeries = "{ \"x\":\"" + dateStr  + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): null) +"}, ";
757                                                                                                  dataSeriesStrMap.put(dateStr, valueDataSeries);
758                                                                                          }
759                                                                                 } else {
760                                                                                          if(timeAxis) {
761                                                                                   //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + dateStr  + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ");
762                                                                                                  valueDataSeries = "{ \"x\":" + dateStr  + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ";
763                                                                                                  dataSeriesStrMap.put(dateStr, valueDataSeries);
764                                                                                                  
765                                                                                          } else {
766                                                                                   //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr  + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ");
767                                                                                                  valueDataSeries = "{ \"x\":\"" + dateStr  + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ";
768                                                                                                  dataSeriesStrMap.put(dateStr, valueDataSeries);
769                                                                                                  
770                                                                                          }
771                                                                                 }
772                                                                 
773                                                                                  /*if(ds.getString(i, 2).equals(uniqueElements[j])) {
774                                                                                 dateStrList.add("'"+dateStr+"'");
775                                                                                          ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr  + "\" , \"y\":\"" + ds.getString(i, 3) +"\"}, ");
776                                                                                  */
777                                                                          }
778                                                                       dataSeriesOverAllMap.put(uniqueElements[j], dataSeriesStrMap);    
779                                                             } else {
780                                                                  //date = MMDDYYYYFormat.parse(ds.getString(i, 1), new ParsePosition(0));
781                                                              if(!barRealTimeAxis) { // true - non-time  
782                                                                 if(!dateStrList.contains(new Long(date.getTime()).toString())) {
783                                                                         dateStrList.add(new Long(date.getTime()).toString());
784                                                                         for (int k = 0; k < uniqueElements.length; k++) {
785                                                                                 //((StringBuffer) dataSeries.get(k)).append ("{ \"x\":" + date.getTime()  + " , \"y\":null}, ");
786                                                                                 HashMap<String, String> dataMap = dataSeriesMap.get((String) uniqueElements[k]);
787                                                                                 dataMap.put(date.getTime()+"", "null");
788
789                                                                         }
790                                                                 }
791                                                              }
792                                                                          if(ds.getString(i, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))) {
793                                                                 dateStrList.add(new Long(date.getTime()).toString());
794                                                                       try {
795                                                                                  YAXISNUM = Integer.parseInt(ds.getString(i, 3));
796                                                                                  if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
797                                                                               } catch (NumberFormatException ex) {
798                                                                                                           try {
799                                                                                                                   YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, 3));
800                                                                                                                   MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
801                                                                                                                   if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
802                                                                                                            } catch (NumberFormatException ex1) {
803                                                                                                                           flagNull = 1;
804                                                                                                            }
805                                                                                           
806                                                                                             //flagNull = 1;
807                                                                                           }
808                                                                                  
809                                                                       //if(ds.getString(i, 2).equals(uniqueElements[j])) {
810                                                                         //  dateStrList.add("'"+dateStr+"'");
811                                                                         HashMap<String, String> dataMap = dataSeriesMap.get((String) uniqueElements[j]);
812                                                                                         if(logScale) {
813                                                                                 dataMap.put(date.getTime()+"", (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): "null"));
814                                                                                         } else  {
815                                                                                         if(dataMap.containsKey(new String(""+date.getTime())) && dataMap.get(new String(""+date.getTime())).equals("null")) {
816                                                                                                 dataMap.remove(date.getTime());
817                                                                                         }
818                                                                                                 dataMap.put(date.getTime()+"", (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(YAXISDOUBLENUM).toString():new Integer(YAXISNUM).toString()): "null"));
819                                                                                                 //System.out
820                                                                                                 //              .println(dataMap + " " + dataSeriesMap);
821                                                                                         //}
822                                                                                 }
823                                                                                         // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime()  + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ");
824                                                                 
825
826                                                                 //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime()  + " , \"y\":" + ds.getString(i, 3) +"}, ");
827                                                                  } else if (AppUtils.nvl(ds.getString(i, 2)).length()<=0) {
828                                                                          dateStrList.add(new Long(date.getTime()).toString());
829                                                                          HashMap<String, String> dataMap1 = null;
830                                                                          String  uniqueElement1 = "";
831                                                                          for (int j1 = 0; j1 < uniqueElements.length; j1++) {
832                                                                                  uniqueElement1 = (String)uniqueElements[j];
833                                                                                  if(ds.getString(i, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement1.lastIndexOf("|") != -1) ?uniqueElement1.substring(0, uniqueElement1.lastIndexOf("|")):uniqueElement1))) {
834                                                                                          dataMap1 = dataSeriesMap.get((String) uniqueElements[j1]);
835                                                                                          if(!dataMap1.containsKey(new String(""+date.getTime()))) 
836                                                                                                  dataMap1.put(date.getTime()+"", "null");
837                                                                                  }
838                                                                          }
839                                                                   }
840                                                         }
841                                                                 // dataSeriesOverAllMap.put(uniqueElements[j], dataSeriesMap);
842                                                          }
843                                                         
844                                                 }
845                                                 for(int kI = 0; kI < uniqueElements.length; kI++) {
846                                                         HashMap dataSeriesStrMap1 = (HashMap) dataSeriesOverAllMap.get(uniqueElements[kI]);
847                                                         for (int kL = 0; kL < uniqueXAxisElements.length; kL++) {
848                                                                 if(dataSeriesStrMap1.containsKey(uniqueXAxisElements[kL])) {
849                                                                         ((StringBuffer) dataSeries.get(kI)).append ((String)dataSeriesStrMap1.get(uniqueXAxisElements[kL]));
850                                                                 } else {
851                                                                         ((StringBuffer) dataSeries.get(kI)).append ("{ \"x\":\"" + uniqueXAxisElements[kL]  + "\" , \"y\": null }, ");
852                                                                 }
853                                                         }
854                                                 }
855                                         }
856                                         
857                                         StringBuffer dateStrBuf = new StringBuffer("");
858                                         /*if(count == 1) {
859                                          Long initialDate = Long.parseLong((String)ds.getString(0, 0));
860                                          Long endDate     = Long.parseLong((String) ds.getString(ds.getRowCount(), 0));
861                                          java.util.Date date1 = null;
862                                          
863                                          while ( initialDate <= endDate) {
864                                                  //System.out.println("********** " + df.format(initialDate));
865                                                  date1 = new java.util.Date(initialDate.longValue() * 1000);
866                                                  initialDate = initialDate + HOUR;
867                                                  
868                                                  dateStrBuf.append(initialDate+",");
869                                                  sortSet.add(""+initialDate);
870                                                  //DateUtils.addHours(date1, 1);
871                                          }                                                       
872                                         }*/
873                                         
874                                         if(dateStrList.size()>0) {
875                                                  SortedSet<String> s = Collections.synchronizedSortedSet(dateStrList);
876                                                  Object[] dateElements = (Object[]) s.toArray();
877                                                  
878                                                  String element = "";
879                                                  /* if not date value */
880                                                  if(!timeAxis) {
881                                                          for (int i = 0; i < dateElements.length; i++) {
882                                                                 dateStrBuf.append(dateElements[i]+",");
883                                                          }
884                                                  } else {
885                                                          if(!barRealTimeAxis || (flagNoDate == 1)) { // non-time
886                                                                  for (int i = 0; i < dateElements.length; i++) {
887                                                                          dateStrBuf.append(dateElements[i]+",");
888                                                                  }
889                                                          } else {
890                                                                  Long initialDate = Long.parseLong((String)dateElements[0]);
891                                                                  Long endDate     = Long.parseLong((String) dateElements[dateElements.length-1]);
892                                                                  java.util.Date date1 = null;
893                                                                  //first value
894                                                                  date1 = new java.util.Date(initialDate.longValue());
895         /*                                                       DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss Z");  
896                                                               System.out.println(formatter.format(new java.util.Date(initialDate.longValue())));                                                         
897         */                                                       //initialDate = initialDate + HOUR;
898                                                                  
899                                                                  dateStrBuf.append(initialDate+",");
900                                                                  sortSet.add(""+initialDate);
901                                                                  
902                                                                 // DateUtils.
903                                                                  
904                                                                  while ( initialDate <= endDate) {
905                                                                          //System.out.println("********** " + df.format(initialDate));
906                                                                          //date1 = new java.util.Date(initialDate.longValue() * 1000);
907                                                                          date1 = new java.util.Date(initialDate.longValue());
908                                                                          if(formatFlag==HOURFLAG)
909                                                                                  date1 = DateUtils.addHours(date1, 1);
910                                                                          else if(formatFlag==MINFLAG) 
911                                                                                  date1 = DateUtils.addMinutes(date1, 30);
912                                                                          else if (formatFlag == DAYFLAG)
913                                                                                  date1 = DateUtils.addDays(date1, 1);
914                                                                          else if (formatFlag == MONTHFLAG)
915                                                                                  date1 = DateUtils.addMonths(date1, 1);
916                                                                          else if (formatFlag == YEARFLAG)
917                                                                                  date1 = DateUtils.addMonths(date1, 1);
918                                                                          initialDate = date1.getTime();
919                                                                          
920                                                                          if(initialDate <= endDate) {
921                                                                                  dateStrBuf.append(initialDate+",");
922                                                                                  sortSet.add(""+initialDate);
923                                                                          }
924                                                                          //DateUtils.addHours(date1, 1);
925                                                                  }                                                       
926                                                                  //DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
927                                                                  //df.setTimeZone(TimeZone.getTimeZone("UTC"));
928                                                                  //java.util.Date date1 = new java.util.Date(initialDate.longValue() * 1000);
929                                                                  //java.util.Date d  = df.  
930                                                                  //for ()
931                                                  }
932                                            }
933                                                  dateStrBuf.deleteCharAt(dateStrBuf.length()-1);
934                                         }
935                                         
936                                         if(timeAxis) {
937                                                 //if(!barRealTimeAxis) { // false - non-time
938                                                 Object[] dateAllElements = (Object[]) sortSet.toArray();
939                                                 
940                                                  for (int i = 0; i < uniqueElements.length; i++) {
941                                                                 HashMap<String, String> dataMap = dataSeriesMap.get((String)uniqueElements[i]);
942                                                                 for (int j=0; j<dateAllElements.length;j++) {
943                                                                         //if(strBuf.toString().indexOf((String) dateAllElements[j]) == -1) {
944                                                                         if(!dataMap.containsKey((String) dateAllElements[j])) {
945                                                                                 dataMap.put((String) dateAllElements[j], "null");
946                                                                                 //((StringBuffer) dataSeries.get(i)).append ("{ \"x\":" + dateAllElements[j]  + " , \"y\":null}, ");
947                                                                         }
948                                                                 }
949                                                  }
950                                                 //}
951                                         }
952                                          String valueStr = "";
953                                          for (int i = 0; i < uniqueElements.length; i++) {
954                                                  HashMap<String, String> dataMap = dataSeriesMap.get((String)uniqueElements[i]);
955                                                  Set<String> keySet = dataMap.keySet();
956                                                  ArrayList<String> keySortedList = new ArrayList<String>(new TreeSet<String>(keySet));
957                                                  
958                                                  for (int k=0; k < keySortedList.size(); k++) {
959                                                          valueStr = dataSeriesMap.get((String)uniqueElements[i]).get(keySortedList.get(k));
960                                                          if(valueStr.equals("null")) 
961                                                                  valueStr = null;
962                                                          else {
963                                                                 //if(logScale) 
964                                                                  //valueStr = new Double(Math.log10(new Double(valueStr).doubleValue())).toString();
965                                                          }
966                                                         ((StringBuffer) dataSeries.get(i)).append ("{ \"x\":" + keySortedList.get(k)  + " , \"y\":" + valueStr +"}, ");
967                                                                 // ((StringBuffer) dataSeries.get(i)).append ("{ \"x\":" + keySortedList.get(k)  + " , \"y\":" + valueStr +"}, ");
968                                                  }
969                                                  
970                                                 // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime()  + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ");
971                                          }
972
973                                         for (int i = 0; i < uniqueElements.length; i++) {
974                                                 StringBuffer strBuf = ((StringBuffer) dataSeries.get(i));
975                                                 ((StringBuffer) dataSeries.get(i)).deleteCharAt(((StringBuffer) dataSeries.get(i)).lastIndexOf(","));
976                                                 if(i < (uniqueElements.length -1) ) {
977                                                         ((StringBuffer) dataSeries.get(i)).append("] } , \n");
978                                                 }
979                                                 else {
980                                                         ((StringBuffer) dataSeries.get(i)).append("] } \n");
981                                                 }
982                                         }
983                    if(ds.getRowCount() > 0) {
984                                         for (int i = 0; i < uniqueElements.length; i++) {
985                                                 wholeScript.append((StringBuffer)dataSeries.get(i));
986                                         }
987                    }
988                                         
989                                 
990                                 wholeScript.append("]; \n");
991
992                                 //add global variable
993                                 wholeScript.append("var chart; \n");
994                                         //javascript to create Bar Chart
995                                         wholeScript.append("nv.addGraph(function() { \n");
996                                         if(horizontalBar /*&& flagNoDate == 1*/)
997                                                 wholeScript.append(" chart = nv.models.multiBarHorizontalChart() \n");
998                                         else /*if (flagNoDate == 1)*/
999                                                 wholeScript.append(" chart = nv.models.multiBarChart() \n");
1000                                         /*else
1001                                                 wholeScript.append(" var chart = nv.models.multiBarTimeSeriesChart() \n");*/
1002                                         
1003                                         wholeScript.append("           .margin({top: "+ topMargin +", right: "+ rightMargin +", bottom: "+ bottomMargin +", left: " + leftMargin +"}) \n");
1004                                                         if(showLegend) {
1005                                                                 wholeScript.append("                    .showLegend(true) \n  ");
1006                                                         } else {
1007                                                                 wholeScript.append("                    .showLegend(false) \n  ");
1008                                                         }
1009                                                         if(!horizontalBar && barReduceXAxisLabels)
1010                                                                 wholeScript.append("          .reduceXTicks(true) \n ");
1011                                                         else if (!horizontalBar) {
1012                                                                 wholeScript.append("          .reduceXTicks(false) \n ");
1013                                                                 //wholeScript.append(" chart.lines1.forceY(["+(nvl(reportRuntime.getRangeAxisLowerLimit()).length()<=0?"0":reportRuntime.getRangeAxisLowerLimit()) +", "+ (nvl(reportRuntime.getRangeAxisUpperLimit()).length()<=0?UPPER_RANGE:reportRuntime.getRangeAxisUpperLimit()) + "]); \n" +
1014                                                                 double UPPER_RANGE = 0;
1015                                                                 if(Math.ceil((MAXDOUBLENUM+(MAXDOUBLENUM*25/100))/100) * 100 >= 1) {
1016                                                                         UPPER_RANGE = Math.ceil(MAXDOUBLENUM+(MAXDOUBLENUM*25/100));
1017                                                                 } else UPPER_RANGE = 1;
1018                                                                 wholeScript.append("          .forceY(["+(nvl(reportRuntime.getRangeAxisLowerLimit()).length()<=0?"0":reportRuntime.getRangeAxisLowerLimit()) +", "+ (nvl(reportRuntime.getRangeAxisUpperLimit()).length()<=0?UPPER_RANGE:reportRuntime.getRangeAxisUpperLimit()) + "])\n"); 
1019                                                         }
1020                                                         if(!animation) {
1021                                                                 wholeScript.append("                    .delay(0) \n  ");
1022                                                         }
1023                                                         if(showControls) {
1024                                                                 wholeScript.append("                    .showControls(true) \n  ");
1025                                                         } else if (!showControls){
1026                                                                 wholeScript.append("                    .showControls(false) \n  ");
1027                                                         } 
1028                                                         if(stacked && !logScale)
1029                                                                 wholeScript.append("                    .stacked(true)\n  ");
1030                                                         else if(!stacked || logScale)
1031                                                                 wholeScript.append("                    .stacked(false)\n  ");
1032                                                         if(logScale) {
1033                                                                 wholeScript.append("                    .logScale(true)\n  ");
1034                                                         } else {
1035                                                                 wholeScript.append("                    .logScale(false)\n  ");
1036                                                         }
1037                                                         
1038                                                         if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
1039                                                                 wholeScript.append("                            .legendPos('right')\n" );
1040                                                         } else {
1041                                                                 wholeScript.append("                            .legendPos('top')\n" );
1042                                                         }
1043                                                         if(uniqueElements.length <= 10) {
1044                                                                 wholeScript.append("           .color(d3.scale.category10().range()); \n" +
1045                                                         "  chart.xAxis\n");
1046                                                         } else if (uniqueElements.length <= 20) {
1047                                                                 wholeScript.append("           .color(d3.scale.category50().range()); \n" +
1048                                                         "  chart.xAxis\n");
1049                                                         } else {
1050                                                                 wholeScript.append("           .color(d3.scale.category50().range()); \n" +
1051                                                         "  chart.xAxis\n");
1052                                                                 
1053                                                         }
1054                                                         
1055                                                         if(flagNoDate == 0)
1056                                                                 wholeScript.append("    .tickValues(["+ dateStrBuf.toString() + "])\n ");
1057                                                         else {
1058                                                                 wholeScript.append("    .tickValues(["+ dateStrBuf.toString() + "])\n ");
1059                                                         }
1060                                                         if(staggerLabels) {
1061                                                                 wholeScript.append("            .staggerLabels(true) \n");
1062                                                         } else {
1063                                                                 wholeScript.append("            .staggerLabels(false) \n");
1064                                                         }
1065                                                         if(!horizontalBar) {
1066                                                                 if(showMaxMin) {
1067                                                                         wholeScript.append("                    .showMaxMin(true) \n  ");
1068                                                                 } else {
1069                                                                         wholeScript.append("                    .showMaxMin(false) \n  ");
1070                                                                 }
1071                                                         }
1072                                                         if(nvl(rotateLabels).length()>0) {
1073                                                                 wholeScript.append("                    .rotateLabels("+ rotateLabels+ ") \n  ");
1074                                                         } else {
1075                                                                 wholeScript.append("                    .rotateLabels(\"0\") \n  ");
1076                                                         }
1077                                                         //wholeScript.append("             .axisLabel('" + legendColumnName + "')");
1078                                         if(flagNoDate == 1 || !timeAxis) {
1079                                                 wholeScript.append(";\n");
1080                                         } else {
1081                                                 wholeScript.append("\n        .tickFormat(function(d) { \n");
1082                                                 if(timeAxis) {
1083                                                         if(formatFlag==HOURFLAG)
1084                                                                 wholeScript.append("         return d3.time.format('%x %H')(new Date(d)) }); \n");
1085                                                         else if(formatFlag==MINFLAG)
1086                                                                 wholeScript.append("         return d3.time.format('%x %H:%M')(new Date(d)) }); \n");
1087                                                         else if(formatFlag==SECFLAG)
1088                                                                 wholeScript.append("         return d3.time.format('%X')(new Date(d)) }); \n");
1089                                                         else if(formatFlag==MONTHFLAG)
1090                                                                 wholeScript.append("         return d3.time.format('%b %y')(new Date(d)) }); \n");                                                      
1091                                                else 
1092                                                                 wholeScript.append("         return d3.time.format('%x')(new Date(d)) }); \n");
1093                                                         
1094                                                 } else {
1095                                                                 wholeScript.append("         return d; }); \n");
1096                                                 }
1097                                         }
1098
1099                                          if(nvl(chartRightAxisLabel).length() > 0) {
1100                                                    //if(flagNoDate == 1)
1101                                                            wholeScript.append("  chart.yAxis\n");
1102                                                    //else
1103                                                          //  wholeScript.append("  chart.yAxis1\n");
1104                                                         if(logScale) {
1105                                                                 wholeScript.append("                    .logScale(true)\n  ");
1106                                                         } else {
1107                                                                 wholeScript.append("                    .logScale(false)\n  ");
1108                                                         }
1109    
1110                                                         wholeScript.append("             .axisLabel('" + chartLeftAxisLabel  + "') \n" +
1111                                                 "        .tickFormat(d3.format(',.0f')); \n");
1112                                                 /*"  chart.yAxis2\n " +
1113                                                 "             .axisLabel('" + chartRightAxisLabel  + "') \n" +
1114                                                 "        .tickFormat(d3.format(',.0f')); \n");*/
1115                                                 
1116                                          
1117                                          } else {
1118                                                    //if(flagNoDate == 1)
1119                                                            wholeScript.append("  chart.yAxis\n");
1120                                                    //else
1121                                                          //  wholeScript.append("  chart.yAxis1\n");
1122                                                                 if(logScale) {
1123                                                                         wholeScript.append("                    .logScale(true)\n  ");
1124                                                                 } else {
1125                                                                         wholeScript.append("                    .logScale(false)\n  ");
1126                                                                 }
1127                                                            wholeScript.append("             .axisLabel('" + chartLeftAxisLabel  + "') \n");
1128                                                         
1129                                                          if(MAXDOUBLENUM <=5 && MAXNUMDECIMALPLACES == 0 ) MAXNUMDECIMALPLACES = 2;
1130                                                          if( MAXNUMDECIMALPLACES >=3 ) MAXNUMDECIMALPLACES = 2;
1131                                                           if(!logScale)
1132                                                                 wholeScript.append("        .tickFormat(d3.format(',."+MAXNUMDECIMALPLACES+"f')); \n");
1133                                                           else 
1134                                                                   wholeScript.append("        .tickFormat(d3.format(',." + precision + "f')); \n"); 
1135                                                         //"        .tickFormat(d3.format(',.0f')); \n");
1136                                          }
1137                                                         wholeScript.append(" d3.select('#chart"+reportRuntime.getReportID()+" svg') \n" +
1138                                                         "  .datum(historicalBarChart) \n" );
1139                                                         if(animation)
1140                                                                 wholeScript.append("  .transition().duration(1000) \n" );
1141                                                         else
1142                                                                 wholeScript.append("  .transition().duration(0) \n" );
1143                                                         wholeScript.append("  .call(chart); \n" +
1144                                                         "nv.utils.windowResize(chart.update); \n" +
1145                                                         "return chart; \n" +
1146                                                         "}); \n");
1147                                                         wholeScript.append("function redraw() { \n");
1148                                                         //wholeScript.append(" nv.utils.windowResize(chart.update); \n");
1149                                                         wholeScript.append("    d3.select('#chart"+reportRuntime.getReportID()+" svg') \n")     ;       
1150                                                         wholeScript.append("            .datum(historicalBarChart) \n");                
1151                                                         wholeScript.append("            .transition().duration(500) \n");               
1152                                                         wholeScript.append("            .call(chart); \n");             
1153                                                         wholeScript.append("} \n");             
1154                                                         wholeScript.append("\n");               
1155                                                         wholeScript.append(" setInterval(function () { \n");
1156                                                         wholeScript.append(" redraw(); \n");
1157                                                         wholeScript.append(" }, 1500) \n");
1158                                                         
1159                                         wholeScript.append("if(historicalBarChart.length <= 0 ) {\n");  
1160                                         wholeScript.append("    document.getElementById(\"chart"+reportRuntime.getReportID()+"\").innerHTML = \"<div id='noData'><b>No Data Available</b></div>\";\n");
1161                                         wholeScript.append("    document.getElementById(\"chart"+reportRuntime.getReportID()+"\").className=\"nodatadiv\";\n");
1162                                         wholeScript.append("    document.getElementById(\"nodata\").className=\"nodatainner\";\n");
1163                                         wholeScript.append("}\n");
1164                                         wholeScript.append("</script> </body></html> \n");
1165
1166                                 } else if (chartType.equals(AppConstants.GT_TIME_SERIES)) {
1167                                         
1168                                         // get category if not give the column name for the data column use this to develop series.
1169                                         boolean hasCategoryAxis = reportRuntime.hasSeriesColumn();
1170                                         
1171                                         
1172                                 final int YEARFLAG = 1;
1173                                 final int MONTHFLAG = 2;
1174                                 final int DAYFLAG = 3;
1175                                 final int HOURFLAG = 4;
1176                                 final int MINFLAG = 5;
1177                                 final int SECFLAG = 6;
1178                                 final int MILLISECFLAG = 7;
1179                                 final int DAYOFTHEWEEKFLAG = 8;
1180                                 final int FLAGDATE = 9;
1181
1182                                 int flag = 0;
1183                                     flag = hasCategoryAxis?1:0;
1184                                         String uniqueElements [] = null;
1185                                 //TreeSet ts = new TreeSet();
1186                                         ArrayList ts = new ArrayList<String>();
1187                                         HashMap<String, String> columnMap = new HashMap();
1188                                 //check timeAxis
1189                                         String dateStr = null;
1190                                         java.util.Date date = null;
1191                                          if( ds.getRowCount() > 0) {
1192                                                  dateStr = ds.getString(0, 1);
1193                                                  if(!timeAxis) {
1194                                                                  date = getDateFromDateStr(dateStr);
1195                                                                  if(date!=null) {
1196                                                                          reportRuntime.setTimeAxis(true);
1197                                                                                 timeAxis                        = reportRuntime.isTimeAxis();
1198
1199
1200                                                                  }
1201                                                  }
1202                                          }
1203                                                  
1204                                         ArrayList<String> ts1 = new ArrayList();
1205                                         ArrayList uniqueElementsList = new ArrayList();
1206                                         Object uniqueXAxisElements[] = null;
1207                                         String uniqueXAxisStr = "";
1208                                         if(!timeAxis){
1209                                                 for (int i = 0; i < ds.getRowCount(); i++) {
1210                                                         uniqueXAxisStr = ds.getString(i, 0);
1211                                                         ts1.add(uniqueXAxisStr);
1212                                                 }
1213                                         }
1214                                         uniqueElementsList.addAll(ts1);
1215                                         uniqueXAxisElements = ts1.toArray();
1216                                         //test start
1217                                         /* int TOTAL = 0;
1218                                          int VALUE = 0;
1219                                          int flagNull = 0;
1220                                          String KEY = "";
1221                                          String COLOR = "";
1222                                          TreeSet<String> colorList = new TreeSet<String>();
1223                                          for (int i = 0; i < ds.getRowCount(); i++) {
1224                                                  VALUE = 0;
1225                                                  try {
1226                                                   VALUE = Integer.parseInt(ds.getString(i, 2));
1227                                                   TOTAL = TOTAL+VALUE;
1228                                                  } catch (NumberFormatException ex) {
1229                                                          flagNull = 1;
1230                                                  }
1231                                                  KEY = ds.getString(i, 0);
1232                                                  try {
1233                                                          if(ds.getString(i, "chart_color")!=null) {
1234                                                                  colorList.add(KEY+"|"+ds.getString(i,  "chart_color"));                                         
1235                                                          }
1236                                                  } catch (ArrayIndexOutOfBoundsException ex) {
1237                                                          System.out.println("No Chart Color");
1238                                                  }
1239                                                  wholeScript.append("{ \""+ "key" +"\":\""+ KEY+"\", \""+ "y" +"\":"+VALUE+"}, \n");
1240                                                  
1241                                          }
1242                                          StringBuffer color = new StringBuffer("");
1243                                          if(colorList.size()>0) {
1244                                                  SortedSet<String> s = Collections.synchronizedSortedSet(colorList);
1245                                                  Object[] colorElements = (Object[]) s.toArray();
1246                                                  
1247                                                  String element = "";
1248                                                  
1249                                                  for (int i = 0; i < colorElements.length; i++) {
1250                                                          element = ((String)colorElements[i]);
1251                                                         color.append("'"+element.substring(element.indexOf("|")+1)+"',");
1252                                                  }
1253                                                  color.deleteCharAt(color.length()-1);
1254                                          }*/
1255                                         
1256                                         //test end
1257                                         boolean hasCustomizedChartColor = false;
1258                                         if(flag == 1) {
1259                                                 StringBuffer catStr = new StringBuffer("");
1260                                                 String color="";
1261                                         for (int i = 0; i < ds.getRowCount(); i++) {
1262                                                 catStr = new StringBuffer("");
1263                                                 catStr.append(ds.getString(i, 2));
1264                                                          try {
1265                                                                  if(ds.getString(i, "chart_color")!=null) {
1266                                                                          color = ds.getString(i,  "chart_color");
1267                                                                          hasCustomizedChartColor = true;
1268                                                                          catStr.append("|"+color);
1269                                                                  }
1270                                                          } catch (ArrayIndexOutOfBoundsException ex) {
1271                                                                  //System.out.println("No Chart Color");
1272                                                          }
1273                                                          
1274                                             if(catStr.length()>0) {
1275                                                 //duplicates are avoided
1276                                                 if(!ts.contains(catStr.toString()))
1277                                                                         ts.add(catStr.toString());
1278                                                 
1279                                             }
1280                                         }
1281                                         //Object uniqueElements [] = ts.toArray();
1282                                         //SortedSet s = Collections.synchronizedSortedSet(ts);
1283                                         //uniqueElements = (String[]) ts.toArray();
1284                                         DataColumnType dct = null;
1285                                         List yTextSeries = reportRuntime.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues);
1286                                         if(yTextSeries.size()==1) {
1287                                                 for (Iterator iter = l.iterator(); iter.hasNext();) {
1288                                                     dct = (DataColumnType) iter.next();
1289                                                     //System.out.println(dct.getDisplayName() + " " + yText);
1290                                                     if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) {
1291                                                            if(nvl(chartLeftAxisLabel).length()<=0) {
1292                                                                    chartLeftAxisLabel = nvl(dct.getYAxis());
1293                                                                    chartLeftAxisLabel = (chartLeftAxisLabel.indexOf("|")!=-1)?chartLeftAxisLabel.substring(0,chartLeftAxisLabel.indexOf("|")):"";
1294                                                            }
1295                                                     }
1296                                                 }
1297                                         }
1298                                         Object tempArray[] = ts.toArray();
1299                                         uniqueElements = Arrays.copyOf(tempArray, tempArray.length, String[].class);
1300                                         
1301                                         } else {
1302                                         DataColumnType dct = null; 
1303                                         
1304                                         List yTextSeries = reportRuntime.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues);
1305                                         //if(columnValuesList.size() == 1) {
1306                                         int dctIndex = 0;
1307                                                 for (Iterator iter = l.iterator(); iter.hasNext();) {
1308                                                     dct = (DataColumnType) iter.next();
1309                                                     //System.out.println(dct.getDisplayName() + " " + yText);
1310                                                     if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) {
1311                                                         if(yTextSeries.contains((String)dct.getDisplayName())) {
1312                                                                 if(nvl(dct.getChartColor()).length()>0) hasCustomizedChartColor = true;
1313                                                                 if(hasCustomizedChartColor) {
1314                                                                         //duplicates are avoided
1315                                                                         if(!ts.contains(dct.getDisplayName()+"|"+nvl(dct.getChartColor())))
1316                                                                                 ts.add(dct.getDisplayName()+"|"+nvl(dct.getChartColor()));
1317                                                                 } else {
1318                                                                         //duplicates are avoided
1319                                                                         if(!ts.contains(dct.getDisplayName()))
1320                                                                                 ts.add(dct.getDisplayName());
1321                                                                 }
1322                                                                    if(nvl(chartLeftAxisLabel).length()<=0) {
1323                                                                            chartLeftAxisLabel = nvl(dct.getYAxis());
1324                                                                            chartLeftAxisLabel = (chartLeftAxisLabel.indexOf("|")!=-1)?chartLeftAxisLabel.substring(0,chartLeftAxisLabel.indexOf("|")):"";
1325                                                                    }
1326                                                                    if(nvl(chartRightAxisLabel).length()>0) {
1327                                                                            String dctYAxis = nvl(dct.getYAxis());
1328                                                                            String yAxis = (dctYAxis.indexOf("|")!=-1)?dctYAxis.substring(0,dctYAxis.indexOf("|")):dctYAxis;
1329                                                                            if(chartRightAxisLabel.equals(yAxis)) {
1330                                                                                    if(ts.contains(dct.getDisplayName())) {
1331                                                                                            if(hasCustomizedChartColor) {
1332                                                                                                    ts.set(dctIndex, dct.getDisplayName()+"|R|"+nvl(dct.getChartColor()));
1333                                                                                            } else {
1334                                                                                                    ts.set(dctIndex, dct.getDisplayName()+"|R");
1335                                                                                            }
1336                                                                                    }
1337                                                                            }
1338                                                                    }
1339                                                                    columnMap.put(dct.getDisplayName(), dct.getColId());
1340                                                        }
1341                                                         dctIndex++;
1342                                                                 }
1343                                                     
1344                                                 }
1345                                                         
1346                                                 //SortedSet s = Collections.synchronizedSortedSet(ts);
1347                                                 Object tempArray[] = ts.toArray();
1348                                                 uniqueElements = Arrays.copyOf(tempArray, tempArray.length, String[].class);
1349                                                 //uniqueElements = (String[]) ts.toArray();
1350                                                 
1351                                         }
1352                                         
1353                                         wholeScript.append("<!DOCTYPE html>\n");
1354                                         wholeScript.append("<html>\n");
1355                                         wholeScript.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF8\">\n");
1356                                         wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n");
1357                                         wholeScript.append("<link href=\""+ chartScriptsPath +"d3/css/nv.d3.css\" rel=\"stylesheet\" type=\"text/css\">\n");
1358                                         wholeScript.append("<style>\n   " +
1359                                                                                 " body { \n" +
1360                                                                                 "       overflow-y:scroll; \n" +
1361                                                                                 "       } \n" +
1362                                                                                 " text { \n" +
1363                                                                                 "       font: 12px sans-serif; \n" +
1364                                                                                 " } \n" +
1365                                                                                 " svg { \n" +
1366                                                                                 "  display: block;\n" +
1367                                                                                 " } \n" +
1368                                                                                 " #chart"+reportRuntime.getReportID()+" svg { \n" +
1369                                                                                 " height: "+ (nvl(height).length()>0?(height.endsWith("px")?height:height+"px"):"420px") + "; \n" +
1370                                                                                 " width:  "+ (nvl(width).length()>0?(width.endsWith("px")?width:width+"px"):"700px") + "; \n" +
1371                                                                                 " min-width: 100px; \n" +
1372                                                                                 " min-height: 100px; \n" +
1373                                                                                 " } \n" +
1374                                                                                 " tr.z-row-over > td.z-row-inner, tr.z-row-over > .z-cell {" +
1375                                                                                 " background-color: rgb(255, 255, 255); "+
1376                                                                                 "}\n");
1377                                         wholeScript.append(".nodatadiv {\n");
1378                                         wholeScript.append("    display: table-cell;\n");
1379                                         wholeScript.append("    width: 700px;\n");
1380                                         wholeScript.append("    height:370px;\n");
1381                                         wholeScript.append("    text-align:center;\n");
1382                                         wholeScript.append("    vertical-align: middle;\n");
1383                                         wholeScript.append("}\n");
1384                                         wholeScript.append(".nodatainner {\n");
1385                                         wholeScript.append("    padding: 10px;\n");
1386                                         wholeScript.append("}\n");
1387                                         
1388                                         wholeScript.append(" </style> \n" );
1389                                         
1390                                         wholeScript.append("<body> \n");
1391                                         
1392                                         if(showTitle)
1393                                                 wholeScript.append("<div align=\"center\"><H3>" + title +"</H3></div>");
1394                                         
1395                                         
1396                                         wholeScript.append("<div id=\"chart"+reportRuntime.getReportID()+"\"> <svg></svg> </div> \n");
1397                                         //js files
1398                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/d3.v3.min.js\"></script>\n");
1399                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/nv.d3.min.js\"></script> \n");
1400                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/axis.min.js\"></script> \n");
1401                                         //wholeScript.append("<script src=\""+ AppUtils.getBaseFolderURL() +"d3/js/models/cumulativeLineChart.js\"></script> \n");
1402                                         //if(multipleSeries) 
1403                                                 //wholeScript.append("<script src=\""+ AppUtils.getBaseFolderURL() +"d3/js/models/multiChart.js\"></script> \n");
1404                                         
1405                                         //json
1406                                         wholeScript.append("<script> \n");
1407
1408                                         wholeScript.append("historicalBarChart = [ \n");
1409                                         //wholeScript.append("{ \n");
1410                                         ArrayList dataSeries = new ArrayList();
1411                                         String uniqueElement = "";
1412                                         
1413                                         String [] uniqueRevElements = null;
1414                                         //Added to make sure order appears same as legend
1415                                         /*if(nvl(subType).length() > 0 && subType.equals("area")) {
1416                                                 uniqueRevElements = reverse((String[])uniqueElements);
1417                                         } else {*/
1418                                                 uniqueRevElements = (String[])uniqueElements;
1419                                         //}
1420
1421                                         int RIGHTAXISSERIES = 0;
1422                                         for (int i = 0; i < uniqueRevElements.length; i++) {
1423                                                 //element.substring(element.indexOf("|")+1)
1424                                                 uniqueElement = (String)uniqueRevElements[i];
1425                                                 if(multipleSeries && (nvl(chartRightAxisLabel).length() > 0)) {
1426                                                         if(nvl(subType).length() > 0 && subType.equals("area")) {
1427                                                                 if(nvl(uniqueElement).indexOf("|R") !=-1)
1428                                                                         dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((uniqueElement.indexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement) +"\", \"yAxis\": \""+(2)+"\", "+ (hasCustomizedChartColor && (uniqueElement.lastIndexOf("|") != -1) ?("\"color\": \""+uniqueElement.substring(uniqueElement.lastIndexOf("|")+1) + "\","):"")+" \"values\": ["));
1429                                                                 else
1430                                                                         dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((uniqueElement.indexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement) +"\", \"yAxis\": \""+(1)+"\", "+ (hasCustomizedChartColor && (uniqueElement.lastIndexOf("|") != -1) ?("\"color\": \""+uniqueElement.substring(uniqueElement.lastIndexOf("|")+1) + "\","):"")+" \"values\": ["));
1431                                                         } else {
1432                                                                 if(nvl(uniqueElement).indexOf("|R") !=-1)
1433                                                                         dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((uniqueElement.indexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement) +"\", \"yAxis\": \""+(2)+"\","+ (hasCustomizedChartColor && (uniqueElement.lastIndexOf("|") != -1) ?("\"color\": \""+uniqueElement.substring(uniqueElement.lastIndexOf("|")+1) + "\","):"")+" \"values\": ["));
1434                                                                 else
1435                                                                         dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((uniqueElement.indexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement) +"\", \"yAxis\": \""+(1)+"\","+ (hasCustomizedChartColor && (uniqueElement.lastIndexOf("|") != -1) ?("\"color\": \""+uniqueElement.substring(uniqueElement.lastIndexOf("|")+1) + "\","):"")+" \"values\": ["));
1436                                                         }
1437                                                         RIGHTAXISSERIES = dataSeries.size()-1;
1438                                                         //dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((DataColumnType)columnMap.get(i)).getDisplayName() +"\", \"yAxis\": \""+(i+1)+"\", \"values\": ["));
1439                                                 }
1440                                                 else {
1441                                                                 dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((uniqueElement.indexOf("|")!= -1)?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement) +"\", \"yAxis\": \""+(1)+"\","+ (hasCustomizedChartColor && (uniqueElement.lastIndexOf("|") != -1)?("\"color\": \""+uniqueElement.substring(uniqueElement.lastIndexOf("|")+1) + "\","):"")+"\"values\": ["));
1442                                                 }
1443
1444                                         }
1445                                         /*StringBuffer dataSeries1 = new StringBuffer("");
1446                                         dataSeries1.append(" { key: \"Series1\",values: [");
1447                                         StringBuffer dataSeries2 = new StringBuffer("");
1448                                         dataSeries2.append(" { key: \"Series2\", values: [");
1449                                         StringBuffer dataSeries3 = new StringBuffer("");
1450                                         dataSeries3.append(" { key: \"Series3\", values: [");
1451                                         */
1452
1453                                         
1454                                         //long minTime = 1000000000000000L;
1455                                         int MAXNUM = 0;
1456                                         double MAXDOUBLENUM = 0.0;
1457                                         int YAXISNUM = 0;
1458                                         double YAXISDOUBLENUM = 0.0;
1459                                         int MAXNUMDECIMALPLACES = 0;
1460                                         int flagNull = 0;
1461                                         int flagSecondNull = 0;
1462                                         TreeSet dateList = new TreeSet();
1463                                         int formatFlag = 0;
1464                                         if(flag!= 1) {
1465                                                 for (int j = 0; j < uniqueRevElements.length; j++) {
1466                                                  for (int i = 0; i < ds.getRowCount(); i++) {
1467                                                          flagNull = 0;
1468                                                          flagSecondNull=0;
1469                                                          YAXISNUM = 0;
1470                                                          YAXISDOUBLENUM = 0.0;
1471                                                          dateStr = "";
1472                                                          date = null;
1473                                                          dateStr = ds.getString(i, 1);
1474                                                          if(timeAxis) {
1475                                                                  date = getDateFromDateStr(dateStr);
1476                                                                  formatFlag = getFlagFromDateStr(dateStr);
1477                                                          } 
1478                                                          if(date==null && timeAxis) continue;
1479                                                         
1480                                                          
1481                                                          //if(ds.getString(i, 2).equals(uniqueElements[j])) {
1482                                                       //if(minTime > date.getTime())
1483                                                          // minTime = date.getTime();
1484                                                     uniqueElement = (String)uniqueRevElements[j];
1485                                                       try {
1486                                                          YAXISNUM = Integer.parseInt(ds.getString(i, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
1487                                                          if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
1488                                                       } catch (NumberFormatException ex) {
1489                                                           try {
1490                                                                   YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
1491                                                                   if(RIGHTAXISSERIES!=j) {
1492                                                                           MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
1493                                                                               if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
1494                                                                   }
1495                                                           } catch (NumberFormatException ex1) {
1496                                                                   flagNull = 1;
1497                                                           }
1498                                                       }
1499                                                       
1500                                                             if(date==null) {
1501                                                                 dateList.add(dateStr);          
1502                                                                 ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr  + "\" , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
1503                                                             } else {
1504                                                                 dateList.add(new Long(date.getTime()).toString());
1505                                                                 ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime()  + " , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
1506                                                             }
1507                                                             
1508                                                                          
1509
1510                                                                   if(nvl(subType).length() > 0 && subType.equals("area")) {
1511                                                                           
1512                                                                           if(flagNull!=1) {
1513                                                                                  if(i<ds.getRowCount()-1) {
1514                                                                               try {
1515                                                                                          YAXISNUM = Integer.parseInt(ds.getString(i+1, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
1516                                                                                          if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
1517                                                                                       } catch (NumberFormatException ex) {
1518                                                                                           try {
1519                                                                                           YAXISDOUBLENUM = Double.parseDouble(ds.getString(i+1, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
1520                                                                                           if(RIGHTAXISSERIES!=j) {
1521                                                                                                   MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
1522                                                                                                       if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
1523                                                                                           }
1524                                                                                           } catch (NumberFormatException ex1) {
1525                                                                                                   flagSecondNull = 1;
1526                                                                                           }
1527                                                                                       }
1528                                                               
1529                                                                                                   if(flagSecondNull==1 && date == null) {
1530                                                                                                           ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr  + "\" , \"y\":" + null +"}, ");
1531                                                                                                   } else if( flagSecondNull == 1){
1532                                                                                                           ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime()  + " , \"y\":" + null +"}, ");
1533                                                                                                   }
1534                                                                                  }
1535                                                                           } else {
1536                                                                                          if(i<ds.getRowCount()-1) {
1537                                                                                                   dateStr = ds.getString(i+1, 1);
1538                                                                                                   
1539                                                                                                   if(!timeAxis) {
1540                                                                                                           ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr  + "\" , \"y\":" + null +"}, ");
1541                                                                                                   } else {
1542                                                                                                           date = getDateFromDateStr(dateStr);
1543                                                                                                           ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime()  + " , \"y\":" + null +"}, ");
1544                                                                                                   }
1545                                                                                                   //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime()  + " , \"y\":" + null +"}, ");
1546                                                                                          }
1547                                                                           }
1548                                                                           
1549                                                                      }
1550                                                                           
1551                                                                          
1552                                                          //}
1553                                                  }
1554                                                  //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + minTime  + " , \"y\":" + 0 +"}, ");
1555                                                 }
1556                                                 
1557                                         } else {
1558                                                 for (int j = 0; j < uniqueRevElements.length; j++) {
1559                                                  for (int i = 0; i < ds.getRowCount(); i++) {
1560                                                          YAXISNUM = 0;
1561                                                          YAXISDOUBLENUM = 0.0;
1562                                                          flagNull= 0;
1563                                                  flagSecondNull = 0;
1564                                                          dateStr = ds.getString(i, 1);
1565                                                          if(timeAxis) {
1566                                                                  date = getDateFromDateStr(dateStr);
1567                                                                  formatFlag = getFlagFromDateStr(dateStr);
1568                                                          }
1569                                                 
1570                                                          if(date==null && timeAxis) continue;
1571                                                          
1572                                                     uniqueElement = (String)uniqueRevElements[j];
1573                                                          //date = MMDDYYYYFormat.parse(ds.getString(i, 1), new ParsePosition(0));
1574                                                          if(ds.getString(i, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))) {
1575                                                       //if(minTime > date.getTime())
1576                                                         //  minTime = date.getTime();
1577                                                       try {
1578                                                                  YAXISNUM = Integer.parseInt(ds.getString(i, 3));
1579                                                                       if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
1580                                                               } catch (NumberFormatException ex) {
1581                                                                   try {
1582                                                                           YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, 3));
1583                                                                           if(RIGHTAXISSERIES!=j) {
1584                                                                                   MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
1585                                                                                       if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
1586                                                                                   
1587                                                                           }
1588                                                                           } catch (NumberFormatException ex1) {
1589                                                                                   flagNull = 1;
1590                                                                           }
1591                                                               }
1592                                                                  
1593                                                       if(date==null) {
1594                                                                 dateList.add(dateStr);          
1595                                                                 ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + dateStr  + " , \"y\":" + (flagNull==0?(YAXISDOUBLENUM!=0.0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
1596                                                             } else {
1597                                                                 dateList.add(new Long(date.getTime()).toString());
1598                                                                 ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime()  + " , \"y\":" + (flagNull==0?(YAXISDOUBLENUM!=0.0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
1599                                                             }
1600                                                       
1601
1602                                                                           if(nvl(subType).length() > 0 && subType.equals("area")) {
1603                                                                                   
1604                                                                                   if(flagNull!=1) {
1605                                                                                           if(i<ds.getRowCount()-1) {
1606                                                                                                   for (int k = i+1; k < ds.getRowCount(); k++) {
1607                                                                                                           if (ds.getString(k, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))) {
1608                                                                                                                   try {
1609                                                                                                                           YAXISNUM = Integer.parseInt(ds.getString(k, 3));
1610                                                                                                               if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
1611                                                                                                                   } catch (NumberFormatException ex) {
1612                                                                                                                           try {
1613                                                                                                                                   YAXISDOUBLENUM = Double.parseDouble(ds.getString(k, 3));
1614                                                                                                                                   if(RIGHTAXISSERIES!=j) {
1615                                                                                                                          MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
1616                                                                                                                               if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
1617                                                                                                                                   }
1618                                                                                                                           } catch (NumberFormatException ex1) {
1619                                                                                                                                   flagSecondNull = 1;
1620                                                                                                                           }
1621                                                                                                                   }
1622                                                                                                                   break;
1623                                                                                                           }
1624                                                                                                   }
1625                                                                       
1626                                                                                                   if(date==null && flagSecondNull==1){
1627                                                                                                           ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + dateStr  + " , \"y\":" + null +"}, ");
1628                                                                                                   } else if(flagSecondNull == 1){
1629                                                                                         ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime()  + " , \"y\":" + null +"}, ");
1630                                                                                                   }
1631                                                                                                   //}
1632                                                                                           }
1633                                                                                   } else {
1634                                                                                           if(i<ds.getRowCount()-1) {
1635                                                                                                   for (int k = i+1; k < ds.getRowCount(); k++) {
1636                                                                                                           if (ds.getString(k, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))) {
1637                                                                                                                   dateStr = ds.getString(k, 1);
1638                                                                                                                   if(!timeAxis) {
1639                                                                                                                           ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime()  + " , \"y\":" + null +"}, ");
1640                                                                                                                           break;
1641                                                                                                                   } else {
1642                                                                                                                           date = getDateFromDateStr(dateStr);
1643                                                                                                                           ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime()  + " , \"y\":" + null +"}, ");
1644                                                                                                                           break;
1645                                                                                                                   }
1646                                                                                                           }
1647                                                                                                   }
1648                                                                                           }
1649                                                                                   }
1650                                                                              }
1651                                                                          
1652                                                          }
1653                                                  }
1654                                                 // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + minTime  + " , \"y\":" + 0 +"}, ");
1655
1656                                         }
1657 /*                                               if(ds.getString(i, 2).equals("Series1")) {
1658                                                          dataSeries1.append("[ " + date.getTime()  + " , " + ds.getString(i, 3) +"], ");
1659                                                  } else if (ds.getString(i, 2).equals("Series2")) {
1660                                                          dataSeries2.append("[ " + date.getTime()  + " , " + ds.getString(i, 3) +"], ");
1661                                                  } else if (ds.getString(i, 2).equals("Series3")) {
1662                                                          dataSeries3.append("[ " + date.getTime()  + " , " + ds.getString(i, 3) +"], ");
1663                                                  }
1664 */                                       }
1665                                          
1666                                                 for (int i = 0; i < uniqueRevElements.length; i++) {
1667                                                         StringBuffer strBuf = ((StringBuffer) dataSeries.get(i));
1668                                                         ((StringBuffer) dataSeries.get(i)).deleteCharAt(((StringBuffer) dataSeries.get(i)).lastIndexOf(","));
1669                                                         if(i < (uniqueRevElements.length -1) ) {
1670                                                                 ((StringBuffer) dataSeries.get(i)).append("] } , \n");
1671                                                         }
1672                                                         else {
1673                                                                 ((StringBuffer) dataSeries.get(i)).append("] } \n");
1674                                                         }
1675                                                 }
1676                                          
1677                                                 for (int i = 0; i < uniqueRevElements.length; i++) {
1678                                                         wholeScript.append((StringBuffer)dataSeries.get(i));
1679                                                 }
1680 /*                                       wholeScript.append(dataSeries1);
1681                                          wholeScript.append(dataSeries2);
1682                                          wholeScript.append(dataSeries3);
1683 */                                       wholeScript.append("];\n");
1684                                         
1685                     /* Sorting is commented out.*/
1686                                         StringBuffer dateStrBuf = new StringBuffer("");
1687                                         if(dateList.size()>0) {
1688                                                  //SortedSet<String> s = Collections.synchronizedSortedSet(dateList);
1689                                                  Object[] dateElements = (Object[]) dateList.toArray();
1690                                                  
1691                                                  String element = "";
1692                                                  
1693                                                  for (int i = 0; i < dateElements.length; i++) {
1694                                                         dateStrBuf.append(dateElements[i]+",");
1695                                                  }
1696                                                  dateStrBuf.deleteCharAt(dateStrBuf.length()-1);
1697                                         }
1698
1699                     wholeScript.append(" var chart;\n");  
1700                                         wholeScript.append("nv.addGraph(function() { \n");
1701                                                         //" var chart = nv.models.cumulativeLineChart() \n" + nv.models.lineWithFocusChart()
1702 //                                                      " chart = nv.models.lineChart() \n" +
1703                                         if(nvl(subType).length() > 0 && subType.equals("area")) {
1704                                                 wholeScript.append(" chart = nv.models.stackedAreaChart() \n");
1705                                                 if(showControls) {
1706                                                         wholeScript.append("                    .showControls(true) \n  ");
1707                                                 } else {
1708                                                         wholeScript.append("                    .showControls(false) \n  ");
1709                                                 }                                               
1710                                         } else { 
1711                                             wholeScript.append(" chart = nv.models.multiChart() \n");
1712                                             if(nvl(chartRightAxisLabel).length() > 0) {
1713                                                         wholeScript.append("                    .dualaxis(true) \n ");  
1714                                                 } else {
1715                                                         wholeScript.append("                    .dualaxis(false) \n ");
1716                                                 }
1717                                             
1718                                                 if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
1719                                                         wholeScript.append("                            .legendPos('right')\n" );
1720                                                 } else {
1721                                                         wholeScript.append("                            .legendPos('top')\n" );
1722                                                 }
1723                                             
1724                                             
1725                                         }
1726                                         
1727                                                         wholeScript.append("           .margin({top: "+ topMargin +", right: "+ rightMargin +", bottom: "+ bottomMargin +", left: " + leftMargin +"}) \n");
1728                                                         if(showLegend) {
1729                                                                 wholeScript.append("                    .showLegend(true) \n  ");
1730                                                         } else {
1731                                                                 wholeScript.append("                    .showLegend(false) \n  ");
1732                                                         }
1733                                                         
1734                                                         if(nvl(subType).length() > 0 && subType.equals("area")) {
1735                                                                  if( MAXNUMDECIMALPLACES >=3 ) {
1736                                                                          wholeScript.append(" .yAxisTooltipFormat(d3.format(',.3f')) \n");
1737                                                                  } else {
1738                                                                          wholeScript.append(" .yAxisTooltipFormat(d3.format(',."+MAXNUMDECIMALPLACES+ "f')) \n");
1739                                                                  }
1740
1741                                                                 wholeScript.append(".x (function(d) {return d.x;}) \n" +
1742                                                                  ".y (function(d) {return d.y;}) \n"); 
1743                                                         }
1744                                                         
1745                                                         //"                     .x(function(d) { return d[0] }) \n" +
1746                                                         //"                     .y(function(d) { return d[1] }) \n" +
1747                                                         //"           .forceY("+(nvl(reportRuntime.getRangeAxisLowerLimit()).length()<=0?"0":reportRuntime.getRangeAxisLowerLimit()) +", "+ Math.ceil((MAXNUM+(MAXNUM*25/100))/100) * 100 + ") \n" + // reportRuntime.getRangeAxisUpperLimit()+") \n" +                 
1748                                                         wholeScript.append("           .color(d3.scale.category10().range()); \n");
1749                                                         if(!(nvl(subType).length() > 0 && subType.equals("area"))) {
1750                                                                 double UPPER_RANGE = 0;
1751                                                                 if(Math.ceil((MAXDOUBLENUM+(MAXDOUBLENUM*25/100))/100) * 100 >= 1) {
1752                                                                         UPPER_RANGE = Math.ceil(MAXDOUBLENUM+(MAXDOUBLENUM*25/100));
1753                                                                 } else UPPER_RANGE = 1;
1754                                                                 
1755                                                                 wholeScript.append(" chart.lines1.forceY(["+(nvl(reportRuntime.getRangeAxisLowerLimit()).length()<=0?"0":reportRuntime.getRangeAxisLowerLimit()) +", "+ (nvl(reportRuntime.getRangeAxisUpperLimit()).length()<=0?UPPER_RANGE:reportRuntime.getRangeAxisUpperLimit()) + "]); \n" +
1756                                                           " chart.lines2.forceY([0,1]); \n");
1757                                                         } 
1758                                                         wholeScript.append("  chart.xAxis\n");
1759                                                         if(reportRuntime.isShowXaxisLabel()) {
1760                                                         // X axis label is commented for time-being. This should be derived from request parameter.
1761                                                         //"             .axisLabel('" + legendColumnName + "') \n" +
1762                                                                 wholeScript.append("             .axisLabel('" + legendColumnName + "') \n");
1763                                                         } else {
1764                                                                 wholeScript.append("             .axisLabel('') \n");
1765                                                         }
1766                                                         if(reportRuntime.isAddXAxisTickers()) {
1767                                                                 wholeScript.append("             .tickValues(["+ dateStrBuf.toString()+ "])\n ");
1768                                                         } else {
1769                                                                 //wholeScript.append("             .tickValues([])\n ");
1770                                                         }
1771                                         if(staggerLabels) {
1772                                                 wholeScript.append("            .staggerLabels(true) \n");
1773                                         } else {
1774                                                 wholeScript.append("            .staggerLabels(false) \n");
1775                                         }
1776                                         if(showMaxMin) {
1777                                                 wholeScript.append("                    .showMaxMin(true) \n  ");
1778                                         } else {
1779                                                 wholeScript.append("                    .showMaxMin(false) \n  ");
1780                                         }
1781                                         
1782                                         if(nvl(rotateLabels).length()>0) {
1783                                                 wholeScript.append("                    .rotateLabels("+ rotateLabels+ ") \n  ");
1784                                         } else {
1785                                                 wholeScript.append("                    .rotateLabels(\"0\") \n  ");
1786                                         }
1787                                         
1788                                                         wholeScript.append("        .tickFormat(function(d) { \n");
1789                                         if(formatFlag==DAYFLAG)
1790                                                         wholeScript.append("         return d3.time.format('%m/%d/%Y')(new Date(d)) }); \n");           
1791                                         else if(formatFlag==HOURFLAG)
1792                                                         wholeScript.append("         return d3.time.format('%x %H')(new Date(d)) }); \n");
1793                                         else if(formatFlag==MINFLAG)
1794                                                 wholeScript.append("         return d3.time.format('%x %H:%M')(new Date(d)) }); \n");
1795                                         else if(formatFlag==SECFLAG)
1796                                                 wholeScript.append("         return d3.time.format('%x %X')(new Date(d)) }); \n");
1797                                         else if(formatFlag==MONTHFLAG)
1798                                                 wholeScript.append("         return d3.time.format('%b %y')(new Date(d)) }); \n");
1799                                         
1800                                         else if(timeAxis)
1801                                                         wholeScript.append("         return d3.time.format('%x')(new Date(d)) }); \n");
1802                                         else
1803                                                 wholeScript.append("        return d; }); \n");
1804                                          if(nvl(chartRightAxisLabel).length() > 0) {    
1805                                                  if(nvl(subType).length() > 0 && subType.equals("area")) {
1806                                                         wholeScript.append("  chart.yAxis\n");
1807                                                  } else {
1808                                                          wholeScript.append("  chart.yAxis1\n");
1809                                                  }
1810                                                         wholeScript.append("             .axisLabel('" + chartLeftAxisLabel  + "') \n");
1811                                                         //if(nvl(subType).length() > 0 && subType.equals("area")) {     
1812                                                          if(MAXDOUBLENUM <=5 && MAXNUMDECIMALPLACES == 0 ) MAXNUMDECIMALPLACES = 2;
1813                                                          if( MAXNUMDECIMALPLACES >=3 ) MAXNUMDECIMALPLACES = 2;
1814                                                                 wholeScript.append("        .tickFormat(d3.format(',."+MAXNUMDECIMALPLACES+"f')); \n");
1815                                                         /*} else {
1816                                                                 wholeScript.append("        .tickFormat(d3.format(',.2f')); \n");
1817                                                         }*/
1818                                                 //                      "        .tickFormat(function (d) {return d;} ); \n");
1819                                                 //"    .tickFormat(function(d) {if (d >= 1000) return Math.round(d/1000)+\"K\"; else return d;}); \n"); 
1820                                                         if(!(nvl(subType).length() > 0 && subType.equals("area"))) {
1821                                                 wholeScript.append("  chart.yAxis2\n " +
1822                                                 "             .axisLabel('" + chartRightAxisLabel  + "') \n" +
1823                                                 "        .tickFormat(d3.format(',.02f')); \n");
1824                                                 //"    .tickFormat(function(d) {if (d >= 1000) return Math.round(d/1000)+\"K\"; else return d;}); \n"); 
1825                                                 //" .tickFormat(function(d) {if( d <= 1) return Math.round(d*100)+\"%\"; else return d;}); \n");
1826                                                 //      " .tickFormat(function(d) { return d;}); \n");
1827                                                         }
1828                                                 
1829                                          
1830                                          } else {
1831                                                  if(nvl(subType).length() > 0 && subType.equals("area")) {
1832                                                          wholeScript.append("  chart.yAxis\n");
1833                                                  } else {
1834                                                          wholeScript.append("  chart.yAxis1\n");
1835                                                  }
1836                                                  wholeScript.append("             .axisLabel('" + chartLeftAxisLabel  + "') \n");
1837                                                         //if(nvl(subType).length() > 0 && subType.equals("area")) {
1838                                                  if(MAXDOUBLENUM <=5 && MAXNUMDECIMALPLACES == 0 ) MAXNUMDECIMALPLACES = 2;
1839                                                  if( MAXNUMDECIMALPLACES >=3 ) {
1840                                                          MAXNUMDECIMALPLACES = 2;
1841                                                  }
1842                                                                 wholeScript.append("        .tickFormat(d3.format(',."+MAXNUMDECIMALPLACES+"f')); \n");
1843                                                         /*} else {
1844                                                                 wholeScript.append("        .tickFormat(d3.format(',.2f')); \n");
1845                                                         }*/
1846                                                     //"    .tickFormat(function(d) {if (d >= 1000) return Math.round(d/1000)+\"K\"; else return d;}); \n");      
1847                                          }
1848                                                         wholeScript.append(" d3.select('#chart"+reportRuntime.getReportID()+" svg') \n" +
1849                                                         "  .datum(historicalBarChart) \n" );
1850                                                         if(animation)
1851                                                                 wholeScript.append("  .transition().duration(1000) \n" );
1852                                                         wholeScript.append("  .call(chart); \n" +
1853                                                         "nv.utils.windowResize(chart.update); \n" +
1854                                                         "return chart; \n" +
1855                                                         "}); \n");
1856
1857                                                         wholeScript.append("function redraw() { \n");
1858                                                         //wholeScript.append(" nv.utils.windowResize(chart.update); \n");
1859                                                         wholeScript.append("    d3.select('#chart"+reportRuntime.getReportID()+" svg') \n")     ;       
1860                                                         wholeScript.append("            .datum(historicalBarChart) \n");                
1861                                                         wholeScript.append("            .transition().duration(500) \n");               
1862                                                         wholeScript.append("            .call(chart); \n");             
1863                                                         wholeScript.append("} \n");             
1864                                                         wholeScript.append("\n");               
1865                                                         wholeScript.append(" setInterval(function () { \n");
1866                                                         wholeScript.append(" redraw(); \n");
1867                                                         wholeScript.append(" }, 1500) \n");
1868                                                         
1869                                                         wholeScript.append("if(historicalBarChart.length <= 0 ) {\n");  
1870                                                         wholeScript.append("    document.getElementById(\"chart"+reportRuntime.getReportID()+"\").innerHTML = \"<div id='noData'><b>No Data Available</b></div>\";\n");
1871                                                         wholeScript.append("    document.getElementById(\"chart"+reportRuntime.getReportID()+"\").className=\"nodatadiv\";\n");
1872                                                         wholeScript.append("    document.getElementById(\"nodata\").className=\"nodatainner\";\n");
1873                                                         wholeScript.append("}\n");
1874                                                         
1875                                         wholeScript.append("</script> </body> </html> \n");
1876                                         
1877                                 } else if (chartType.equals(AppConstants.GT_PIE) || chartType.equals(AppConstants.GT_PIE_3D)) {
1878                                         wholeScript.append("<!DOCTYPE html>\n");
1879                                         wholeScript.append("<html>\n");
1880                                         wholeScript.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF8\">\n");
1881                                         wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n");
1882                                         wholeScript.append("<link href=\""+ AppUtils.getBaseFolderURL() +"d3/css/nv.d3.css\" rel=\"stylesheet\" type=\"text/css\">\n");
1883                                         wholeScript.append("<style>\n   " +
1884                                                                                 " body { \n" +
1885                                                                                 "       overflow-y:scroll; \n" +
1886                                                                                 "       } \n" +
1887                                                                                 " text { \n" +
1888                                                                                 "       font: 12px sans-serif; \n" +
1889                                                                                 " } \n" +
1890                                                                                 " tr.z-row-over > td.z-row-inner, tr.z-row-over > .z-cell {" +
1891                                                                                 " background-color: rgb(255, 255, 255); "+
1892                                                                                 "} "+
1893                                                                                 " svg {   display: block; } " + 
1894                                                                                 " #chart"+reportRuntime.getReportID()+" svg { \n" +
1895                                                                                 " height: "+ (nvl(height).length()>0?(height.endsWith("px")?height:height+"px"):"420px") + "; \n" +
1896                                                                                 " width:  "+ (nvl(width).length()>0?(width.endsWith("px")?width:width+"px"):"700px") + "; \n" +
1897                                                                                 " min-width: 100px; \n" +
1898                                                                                 " min-height: 100px; \n" +
1899                                                                                 " } \n" +
1900                                                                                 " </style> \n" );
1901                                         wholeScript.append("<body> \n");
1902                                         
1903                                         if(showTitle)
1904                                                 wholeScript.append("<div align=\"center\"><H3>" + title +"</H3></div>");
1905                                         
1906                                         wholeScript.append("<div id=\"chart"+reportRuntime.getReportID()+"\"><svg></svg></div>");
1907                                                         //"<svg id=\"test2\"></svg>\n");
1908                                         //js files
1909                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/d3.v3.min.js\"></script>\n");
1910                                         wholeScript.append("<script src=\""+ chartScriptsPath  +"d3/js/nv.d3.min.js\"></script> \n");
1911                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/legend.js\"></script> \n");
1912                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/pie.js\"></script> \n");
1913                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/pieChart.js\"></script> \n");
1914                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/utils.js\"></script> \n");
1915                                         wholeScript.append("<script> \n");
1916
1917                                         wholeScript.append("historicalBarChart = [ \n");
1918                                          double TOTAL = 0;
1919                                          double VALUE = 0;
1920                                          int flagNull = 0;
1921                                          String KEY = "";
1922                                          String COLOR = "";
1923                                          TreeSet<String> colorList = new TreeSet<String>();
1924                                          for (int i = 0; i < ds.getRowCount(); i++) {
1925                                                  VALUE = 0;
1926                                                  try {
1927                                                   VALUE = Double.parseDouble(ds.getString(i, 2));
1928                                                   TOTAL = TOTAL+VALUE;
1929                                                  } catch (NumberFormatException ex) {
1930                                                          flagNull = 1;
1931                                                  }
1932                                                  KEY = ds.getString(i, 0);
1933                                                  try {
1934                                                          if(ds.getString(i, "chart_color")!=null) {
1935                                                                  colorList.add(KEY+"|"+ds.getString(i,  "chart_color"));                                         
1936                                                          }
1937                                                  } catch (ArrayIndexOutOfBoundsException ex) {
1938                                                          //System.out.println("No Chart Color");
1939                                                  }
1940                                                  wholeScript.append("{ \""+ "key" +"\":\""+ KEY+"\", \""+ "y" +"\":"+VALUE+"}, \n");
1941                                                  
1942                                          }
1943                                          StringBuffer color = new StringBuffer("");
1944                                          if(colorList.size()>0) {
1945                                                  SortedSet<String> s = Collections.synchronizedSortedSet(colorList);
1946                                                  Object[] colorElements = (Object[]) s.toArray();
1947                                                  
1948                                                  String element = "";
1949                                                  
1950                                                  for (int i = 0; i < colorElements.length; i++) {
1951                                                          element = ((String)colorElements[i]);
1952                                                         color.append("'"+element.substring(element.lastIndexOf("|")+1)+"',");
1953                                                  }
1954                                                  color.deleteCharAt(color.length()-1);
1955                                          }
1956                                          
1957                                          wholeScript.append("];\n");
1958                                          
1959
1960                                         wholeScript.append("var chart; \n");    
1961                                         wholeScript.append("nv.addGraph(function() { \n" +
1962                                                 " var width1= 700, height1=720; \n" +
1963                                                         "  chart = nv.models.pieChart() \n" +
1964                                                         "           .margin({top: "+ topMargin +", right: "+ rightMargin +", bottom: "+ bottomMargin +", left: " + leftMargin +"}) \n" +
1965                                                         
1966                                                         //"                     .x(function(d) { return d.key +\" \"+ Math.round(d.y/"+TOTAL+" *100) + \"%\"  }) \n" +
1967                                                         "                       .x(function(d) { return d.key  }) \n" +
1968                                                         "                       .y(function(d) { return d.y }) \n");
1969                                         if(colorList.size()>0) {
1970                                                         wholeScript.append("           .color(["+ color.toString() + "] ) \n");
1971                                         }
1972                                         //wholeScript.append("                  .values(function(d) { return d }) \n");         
1973                                                         //"           .color(d3.scale.category10().range()); \n" +
1974                                                         if(showLegend) {
1975                                                                 wholeScript.append(" chart.showLegend(true);\n ");
1976                                                         } else {
1977                                                                 wholeScript.append(" chart.showLegend(false);\n ");
1978                                                         }
1979                                                         
1980                                                         //wholeScript.append("chart.showLegend(false);\n" +
1981                                                         //"                     .width(width1) \n" +
1982                                                         //"                     .height(height1); \n" +         
1983                                                         wholeScript.append(" d3.select('#chart"+reportRuntime.getReportID()+" svg') \n" +
1984                                                         "  .datum(historicalBarChart) \n");
1985                                         if(animation)
1986                                                 wholeScript.append("  .transition().duration(1200) \n" );
1987 /*                                                      "   .attr(\"width\", width1) \n" +
1988                                                         "   .attr(\"height\", height1) \n" +
1989 */                                                      wholeScript.append("  .call(chart); \n" +
1990                                                         " nv.utils.windowResize(chart.update);\n"+  
1991                                                         "return chart; \n" +
1992                                                         "}); \n");
1993
1994                                         wholeScript.append("function redraw() { \n");
1995                                         //wholeScript.append(" nv.utils.windowResize(chart.update); \n");
1996                                         wholeScript.append("    d3.select('#chart"+reportRuntime.getReportID()+" svg') \n")     ;       
1997                                         wholeScript.append("            .datum(historicalBarChart) \n");                
1998                                         wholeScript.append("            .transition().duration(500) \n");               
1999                                         wholeScript.append("            .call(chart); \n");             
2000                                         wholeScript.append("} \n");             
2001                                         wholeScript.append("\n");               
2002                                         wholeScript.append(" setInterval(function () { \n");
2003                                         wholeScript.append(" redraw(); \n");
2004                                         wholeScript.append(" }, 1500) \n");
2005
2006
2007
2008                                         wholeScript.append("if(historicalBarChart.length <= 0 ) {\n");  
2009                                         wholeScript.append("    document.getElementById(\"chart"+reportRuntime.getReportID()+"\").innerHTML = \"<div id='noData'><b>No Data Available</b></div>\";\n");
2010                                         wholeScript.append("    document.getElementById(\"chart"+reportRuntime.getReportID()+"\").className=\"nodatadiv\";\n");
2011                                         wholeScript.append("    document.getElementById(\"nodata\").className=\"nodatainner\";\n");
2012                                         wholeScript.append("}\n");
2013
2014                                         wholeScript.append("</script> </body> </html> \n");
2015                                         
2016                                 } else if (chartType.equals(AppConstants.GT_ANNOTATION_CHART) || chartType.equals(AppConstants.GT_FLEX_TIME_CHARTS)) {
2017                                         
2018                                         boolean timeCharts = chartType.equals(AppConstants.GT_FLEX_TIME_CHARTS);
2019                                         
2020                                         String dateStr = null;
2021                                         java.util.Date date = null;
2022                                         
2023                                 final int YEARFLAG = 1;
2024                                 final int MONTHFLAG = 2;
2025                                 final int DAYFLAG = 3;
2026                                 final int HOURFLAG = 4;
2027                                 final int MINFLAG = 5;
2028                                 final int SECFLAG = 6;
2029                                 final int MILLISECFLAG = 7;
2030                                 final int DAYOFTHEWEEKFLAG = 8;
2031                                 final int FLAGDATE = 9;
2032
2033                                         int flagNoDate        = 0;
2034                                 
2035                                         int MAXNUM = 0;
2036                                         int YAXISNUM = 0;
2037                                         int flagNull = 0;
2038                                         
2039                                         double YAXISDOUBLENUM = 0.0;
2040                                         double MAXDOUBLENUM = 0.0;
2041                                         int MAXNUMDECIMALPLACES = 0;
2042                                         
2043                                         int formatFlag = 0;
2044                                 
2045                                 TreeSet<String> dateStrList = new TreeSet<String>();
2046                                 // added to store all date elements 
2047                                         SortedSet<String> sortSet = new TreeSet<String>();
2048                                 int count = 0;
2049                                 
2050                                 int flag = 0;
2051                                 boolean hasCategoryAxis = reportRuntime.hasSeriesColumn();
2052                                 flag = hasCategoryAxis?1:0;
2053
2054
2055                                 String anomalyText = "";
2056                                 
2057                                 StringBuffer dataStrBuf = new StringBuffer("");
2058                                 StringBuffer annotationsStrBuf = new StringBuffer("");
2059                                 
2060                                 String xAxisLabel = (reportRuntime.getChartLegendColumn()!=null)?reportRuntime.getChartLegendColumn().getDisplayName():"";
2061                                 
2062                                 //finding actual string
2063                                 String actualText = "";
2064                                 DataColumnType dct = null;
2065                                 for (Iterator iter = l.iterator(); iter.hasNext();) {
2066                                     dct = (DataColumnType) iter.next();
2067                                     if((dct.getChartSeq()!=null && dct.getChartSeq() >=0) && !AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND)) {
2068                                            //if(AppUtils.nvl(dct.getDisplayName()).toLowerCase().contains("actual")) {
2069                                                 actualText = dct.getDisplayName();
2070                                                 break;
2071                                            //}
2072                                 }
2073                                 }
2074                                 
2075                                 int anomalyRec = 0;
2076                                 int columnIndex = 1;
2077                                 ArrayList columnNames = new ArrayList();
2078                                 ArrayList columnValues = new ArrayList();
2079                                 Set set = null;
2080                                 String columnName = "";
2081                                 String columnValue = "";
2082                                 long minDate = 0L;
2083                                 long maxDate = 0L;
2084                                 StringBuffer seriesBuffer = new StringBuffer("");
2085                                 
2086                                         for (int i = 0; i < ds.getRowCount(); i++) {
2087                                                 columnNames = new ArrayList();
2088                                                 columnValues = new ArrayList();
2089                                                 columnName = "";
2090                                                 columnValue = "";
2091                                                 columnIndex = 1;
2092                                                 anomalyText = "";
2093                                         dateStr                         = ds.getString(i, 0);
2094                                                 date = getDateFromDateStr(dateStr);
2095                                                  if(date.getTime() > maxDate )
2096                                                          maxDate = date.getTime();
2097                                                  
2098                                                  formatFlag             = getFlagFromDateStr(dateStr);
2099                                                  
2100                                                  
2101                                                  for (;columnIndex<ds.getColumnCount();columnIndex++) {
2102                                                          columnName = ds.getColumnName(columnIndex);
2103                                                          if(!timeCharts && !columnName.toLowerCase().equals("anomaly_text")) {
2104                                                                  columnNames.add(columnName);
2105                                                                  columnValues.add(AppUtils.nvls(ds.getString(i, columnIndex), "null"));
2106                                                          } else if (timeCharts) {
2107                                                                  columnNames.add(columnName);
2108                                                                  columnValues.add(AppUtils.nvls(ds.getString(i, columnIndex), "null"));
2109                                                          }
2110                                                  }
2111 /*                                               actual                         = ds.getString(i,  "actual");
2112                                                  //forecast                     = ds.getString(i,  "forecast");
2113                                                  upperBound             = ds.getString(i, "upperBound");
2114                                                  lowerBound             = ds.getString(i, "lowerBound");
2115                                                  
2116 */                                               if(!timeCharts)
2117                                                         anomalyText             = ds.getString(i, "anomaly_text");
2118                                                  //dataStrBuf.append("                          [new Date(moment(\""+dateStr+"\")),"+ actual /*+","+ forecast*/+","+ lowerBound +","+ upperBound +"],\n");
2119                                                  dataStrBuf.append("                            [new Date(moment(\""+dateStr+"\"))");
2120                                                  for(int c=0; c< columnNames.size(); c++ ) {
2121                                                                 columnName = (String) columnNames.get(c);
2122                                                                 columnValue = (String) columnValues.get(c);
2123                                                         for (Iterator iter1 = l.iterator(); iter1.hasNext();) {
2124                                                             dct = (DataColumnType) iter1.next();
2125                                                         if((dct.getChartSeq()!=null && dct.getChartSeq() >=0) && !AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND)) {
2126                                                                    if((!timeCharts && !AppUtils.nvl(dct.getColId()).toLowerCase().equals("anomaly_text")) && AppUtils.nvl(dct.getColId()).toLowerCase().equals(columnName.toLowerCase())) {
2127                                                                            dataStrBuf.append(","+columnValue);
2128                                                                            break;
2129                                                                    } else if(timeCharts && AppUtils.nvl(dct.getColId()).toLowerCase().equals(columnName.toLowerCase())){
2130                                                                            dataStrBuf.append(","+columnValue);
2131                                                                            //break;
2132                                                                    }
2133                                                         }
2134                                                         }
2135                                                  }
2136                                                  
2137                                                  dataStrBuf.append("],\n");
2138                                                  if(!timeCharts) {
2139                                                          if(AppUtils.nvl(anomalyText).length()>0) {
2140                                                                  ++anomalyRec;
2141                                                                  annotationsStrBuf.append("anns.push( {\n");
2142                                                                  annotationsStrBuf.append("     series: '"+actualText+"',\n");
2143                                                                  annotationsStrBuf.append("     x: moment(\""+dateStr+"\"),\n");
2144                                                                  annotationsStrBuf.append(" shortText: '"+ IntToLetter(anomalyRec).toUpperCase() +"',\n");
2145                                                                  annotationsStrBuf.append(" text: '"+ anomalyText + "'\n");
2146                                                                  annotationsStrBuf.append("});\n");
2147                                                                  //anomalyRec++;
2148                                                          }
2149                                                          
2150                                                  }
2151                                         }
2152                                         
2153                                         //if(!timeCharts)
2154                                                 //anomalyRec = anomalyRec - 1;
2155                                         
2156                                         minDate =  maxDate - (new Long(reportRuntime.getZoomIn()).longValue()*60*60*1000);
2157                                         System.out.println(new java.util.Date(maxDate) + " " + new java.util.Date(minDate) + " " + reportRuntime.getZoomIn());
2158                                         if(dataStrBuf.lastIndexOf(",")!= -1)
2159                                                 dataStrBuf.deleteCharAt(dataStrBuf.lastIndexOf(","));
2160                                         
2161                                         wholeScript = new StringBuffer("");
2162                                         wholeScript.append("<!DOCTYPE html>\n");
2163                                         wholeScript.append("<html>\n");
2164                                         wholeScript.append(" <head>\n");
2165                                         //wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7; IE=EmulateIE9\">\n");
2166                                         wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n");
2167                                         wholeScript.append("<script type=\"text/javascript\" src=\""+ chartScriptsPath +"dy3/js/dygraph-combined.js\"></script>\n");
2168                                         wholeScript.append("<script type=\"text/javascript\" src=\""+ chartScriptsPath +"dy3/js/moment.min.js\"></script>\n");
2169                                         wholeScript.append("<script type=\"text/javascript\" src=\""+ chartScriptsPath +"dy3/js/interaction.min.js\"></script>\n");
2170                                         
2171                                         wholeScript.append("<script type=\"text/javascript\">\n");
2172                                         if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("30min")) {
2173                                         wholeScript.append("var click=2;\n");
2174                                 } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) {
2175                                         wholeScript.append("var click=3;\n");
2176                                 } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) {
2177                                         wholeScript.append("var click=3;\n");
2178                                 } else
2179                                         wholeScript.append("var click=3;\n");
2180                                         //wholeScript.append("  var click=0;\n");
2181                                         wholeScript.append("    function downV3(event, g, context) { \n");
2182                                         wholeScript.append("            context.initializeMouseDown(event, g, context); \n");
2183                                         wholeScript.append("            if (event.altKey || event.shiftKey) { \n");
2184                                         wholeScript.append("                    var minDate = g.xAxisRange()[0]; \n");
2185                                         wholeScript.append("                    var maxDate = g.xAxisRange()[1]; \n");
2186                                 if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) {
2187                                         wholeScript.append("                    if(((maxDate-minDate)/(1000*60*60*24)) > 6) \n");
2188                                         wholeScript.append("                            Dygraph.startZoom(event, g, context); \n");
2189                                 } else if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) {
2190                                         wholeScript.append("                    if(((maxDate-minDate)/(1000*60*60)) > 6) \n");
2191                                         wholeScript.append("                            Dygraph.startZoom(event, g, context); \n");
2192                                 } else if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("30min")) {
2193                                         wholeScript.append("                    if(((maxDate-minDate)/(1000*60*60*2)) > 6) \n");
2194                                         wholeScript.append("                            Dygraph.startZoom(event, g, context); \n");
2195                                         
2196                                 } else {
2197                                         wholeScript.append("                    if(((maxDate-minDate)/(1000*60*60)) > 6) \n");
2198                                         wholeScript.append("                            Dygraph.startZoom(event, g, context); \n");
2199                                 }
2200                                         if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("30min")) {
2201                                         wholeScript.append("    click=2;\n");
2202                                 } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) {
2203                                         wholeScript.append("    click=3;\n");
2204                                 } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) {
2205                                         wholeScript.append("    click=3;\n");
2206                                 } else
2207                                         wholeScript.append("    click=3;\n");
2208                                 wholeScript.append("            } else if (event.ctrlKey) {\n");
2209                                 
2210                                 
2211                                 wholeScript.append("            click++;\n");
2212                                 wholeScript.append("            if(click == 1)\n");
2213                                 wholeScript.append("                    zoom_custom(3600);\n");
2214                                 wholeScript.append("            else if(click == 2)\n");
2215                                 wholeScript.append("                    zoom_custom(12*3600);\n");
2216                                 wholeScript.append("            else if(click == 3)\n");
2217                                 wholeScript.append("                    zoom_custom(86400);\n");
2218                                 wholeScript.append("            else if (click == 4)\n");
2219                                 wholeScript.append("                    zoom_custom(7*86400);\n");
2220                                 wholeScript.append("            else if (click == 5)\n");
2221                                 wholeScript.append("                    zoom_custom(30*86400);\n");
2222                                 wholeScript.append("            else if (click == 6)\n");
2223                                 wholeScript.append("                    zoom_custom(90*86400);\n");
2224                                 wholeScript.append("            else if (click == 7)\n");
2225                                 wholeScript.append("                    zoom_custom(180*86400);\n");
2226                                 wholeScript.append("            else if (click == 8)\n");
2227                                 wholeScript.append("                    zoom_custom(365*86400);\n");
2228                                 wholeScript.append("            else if (click == 10)\n");
2229                                 wholeScript.append("                    zoom_custom(5*365*86400);\n");
2230                                 wholeScript.append("            else { \n");
2231                                 wholeScript.append("                    reset();\n");
2232                                 wholeScript.append("            }\n");
2233                                 //wholeScript.append("          \n");
2234                                         wholeScript.append("            } else {\n");
2235                                         wholeScript.append("                    Dygraph.startPan(event, g, context); \n");
2236                                         wholeScript.append("            } \n");
2237                                         wholeScript.append("    } \n");
2238                                         wholeScript.append("</script>\n ");
2239                                         wholeScript.append("<style type=\"text/css\">\n");
2240                                         wholeScript.append(".annotation {\n");
2241                                         wholeScript.append("}");
2242                                         wholeScript.append(".dygraph-title {\n");
2243                                         wholeScript.append("color: black;\n");
2244                                         wholeScript.append("font-weight:bold; \n");
2245                                         wholeScript.append("}\n");
2246                                         wholeScript.append(".dygraph-axis-label-x { ");
2247                                         wholeScript.append("-webkit-transform:rotate(-0deg);");
2248                                     wholeScript.append("display:block;");
2249                                                   /*position:absolute;
2250                                                   right:-5px;
2251                                                   top:15px;*/
2252                                         wholeScript.append("}\n");
2253                                         
2254                                         int widthInt = 0;
2255                                         if(nvl(width).length() > 0) {
2256                                                 try {
2257                                                         widthInt = new Integer(width).intValue();
2258                                                 } catch(Exception ex) {
2259                                                         if(width.endsWith("px")) {
2260                                                                 try {
2261                                                                 widthInt = new Integer(width.substring(0, width.indexOf("px")));
2262                                                                 } catch (Exception ex1) {
2263                                                                         widthInt = 700;
2264                                                                 }
2265                                                         } else {
2266                                                                 widthInt = 700;
2267                                                         }
2268                                                 }
2269                                         } else widthInt = 700;
2270                                         
2271                                         wholeScript.append(".dygraph-legend {\n");
2272                                         wholeScript.append("    left: "+(widthInt-200)+"px !important;\n");
2273                                         wholeScript.append("    top: 5px !important;\n");
2274                                         wholeScript.append("}\n");
2275                                         
2276                                         wholeScript.append(".nodatadiv {\n");
2277                                         wholeScript.append("    display: table-cell;\n");
2278                                         wholeScript.append("    width: 700px;\n");
2279                                         wholeScript.append("    height:370px;\n");
2280                                         wholeScript.append("    text-align:center;\n");
2281                                         wholeScript.append("    vertical-align: middle;\n");
2282                                         wholeScript.append("}\n");
2283                                         wholeScript.append(".nodatainner {\n");
2284                                         wholeScript.append("    padding: 10px;\n");
2285                                         wholeScript.append("}\n");
2286
2287                                         wholeScript.append("canvas {\n");
2288                                         wholeScript.append("    -webkit-touch-callout: none; \n");
2289                                         wholeScript.append("    -webkit-user-select: none;\n");
2290                                         wholeScript.append("    -khtml-user-select: none;\n");
2291                                         wholeScript.append("    -moz-user-select: none;\n");
2292                                         wholeScript.append("    user-select: none;\n");
2293                                         wholeScript.append("    user-select: none;\n");
2294                                         wholeScript.append("    outline: none;\n");
2295                                         wholeScript.append("    -webkit-tap-highlight-color: rgba(255, 255, 255, 0); /* mobile webkit */\n");
2296                                         wholeScript.append("}\n");
2297                                         wholeScript.append("</style>\n");
2298                                         wholeScript.append("</head>\n");
2299                                         wholeScript.append("<body> \n");
2300                                         
2301 /*                                      if(showTitle)
2302                                                 wholeScript.append("    <p align=\"center\"><b> " + (AppUtils.nvl(reportRuntime.getReportTitle()).length()>0?reportRuntime.getReportTitle():reportRuntime.getReportName()) + "</b></p>\n");
2303 */                                      
2304                                         wholeScript.append("    <table>\n");
2305                                         if(showTitle) {
2306                                                 wholeScript.append("        <tr> \n ");
2307                                                 wholeScript.append("            <td> \n ");
2308                                                 wholeScript.append("                            <div class=\"dygraph-label dygraph-title\" align=\"center\">"+title+"</div> \n");
2309                                                 wholeScript.append("            </td> \n ");
2310                                         }
2311                                         
2312                                         wholeScript.append("        </tr> \n ");
2313
2314                                         wholeScript.append("        <tr> \n ");
2315                                         wholeScript.append("            <td> \n ");
2316                                         if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()<=0 || reportRuntime.getLegendPosition().equals("top")) {
2317                                                 wholeScript.append("                            <div id=\"labelDiv"+reportRuntime.getReportID()+"\"></div>\n");
2318                                         }
2319                                         wholeScript.append("                            <div id=\"message"+reportRuntime.getReportID()+"\"></div> \n");
2320                                         wholeScript.append("            </td> \n ");
2321                                         
2322                                         wholeScript.append("        </tr> \n ");
2323                                         wholeScript.append("            <tr>\n");
2324                                         wholeScript.append("                    <td>\n");
2325                                         
2326                                         int heightInt = 0;
2327                                         if(nvl(height).length() > 0) {
2328                                                 try {
2329                                                         heightInt = new Integer(height).intValue();
2330                                                         heightInt -= 50;
2331                                                 } catch(Exception ex) {
2332                                                         if(height.endsWith("px")) {
2333                                                                 try {
2334                                                                         heightInt = new Integer(height.substring(0, height.indexOf("px")));
2335                                                                         heightInt -= 50;
2336                                                                 } catch (Exception ex1) {
2337                                                                         heightInt = 420;
2338                                                                 }
2339                                                         } else {
2340                                                                 heightInt = 420;
2341                                                         }
2342                                                 }
2343                                         } else heightInt = 420;                                 
2344                                         if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
2345                                                 wholeScript.append("                            <div id=\"div_g"+reportRuntime.getReportID()+"\" style=\"width:"+ (widthInt-250)+ "px; \n" );
2346                                         } else {
2347                                                 wholeScript.append("                            <div id=\"div_g"+reportRuntime.getReportID()+"\" style=\"width:"+ (widthInt)+ "px; \n" );
2348                                         }
2349                                         wholeScript.append("                                    height:"+ heightInt +"px;\"></div> \n");
2350                                         wholeScript.append("                    </td>\n");
2351                                         if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
2352                                                 wholeScript.append("                    <td valign=\"top\">\n");
2353                                                 wholeScript.append("                            <div id=\"labelDiv3716\" valign=\"top\" style=\"width:250px;height:"+ heightInt +"px;\"></div>\n"); 
2354                                                 wholeScript.append("                    </td>\n");
2355                                         }
2356                                         wholeScript.append("            </tr>\n");
2357                                         if(anomalyRec > 0) {
2358                                                 wholeScript.append("            <tr>\n");
2359                                                 wholeScript.append("                    <td>\n");
2360                                                 wholeScript.append("                            <table>\n");
2361                                                 wholeScript.append("                                    <tr>\n");
2362                                                 wholeScript.append("                                            <td align=\"center\"><font size=\"2px\"><B><align=\"center\">Anomaly Description</align></B></font></td>\n");
2363                                                 wholeScript.append("                                    </tr>\n");
2364                                                 wholeScript.append("                                    <tr>\n");
2365                                                 wholeScript.append("                                            <td><div id=\"list"+reportRuntime.getReportID()+"\" style=\"width:" + widthInt + "px; height:50px;\"></div></td>\n" );
2366                                                 wholeScript.append("                                    </tr>\n");
2367                                                 wholeScript.append("                            </table>\n");
2368                                                 wholeScript.append("                    </td>\n");
2369                                                 wholeScript.append("            </tr>\n");
2370                                         }
2371                                         wholeScript.append("    </table>\n");
2372                                         
2373                                         wholeScript.append("       <script type=\"text/javascript\">\n");
2374                                         wholeScript.append("                    Dygraph.addEvent(document, \"mousewheel\", function() { lastClickedGraph = null; });\n");
2375                                         wholeScript.append("                    Dygraph.addEvent(document, \"click\", function() { lastClickedGraph = null; });\n");
2376                                         wholeScript.append("             var data = []; \n");
2377                                         wholeScript.append("                    data = [\n ");
2378                                         wholeScript.append(                             dataStrBuf.toString());
2379                                         wholeScript.append("                    ];\n");
2380                                         wholeScript.append("      if(data.length > 0 ) { \n");
2381                                         wholeScript.append(" var orig_range = [ data[0][0].valueOf(), data[data.length - 1][0].valueOf() ];\n");
2382                                         if(!timeCharts) {
2383                                                 wholeScript.append("                    function nameAnnotation(ann) { \n");
2384                                                 wholeScript.append("                return ann.shortText; \n");
2385                                                 //wholeScript.append("                          var m = moment(ann.x);\n");
2386                                                 //wholeScript.append("                          return \"(\" + ann.series + \", \" + m.format(\"YYYY-MM-DD HH\"); + \")\"; \n");
2387                                                 wholeScript.append("                    }\n");  
2388                                                 wholeScript.append("            anns = [];\n");
2389                                         }
2390                                         wholeScript.append("            var graph_initialized = false;\n");
2391                                         wholeScript.append("            if(navigator.platform == 'iPad') { ");
2392                                         wholeScript.append("            g = new Dygraph(\n");
2393                                         wholeScript.append("                    document.getElementById(\"div_g"+reportRuntime.getReportID()+"\"),\n");
2394                                         //data here
2395                                         /*wholeScript.append("                  [\n");
2396                                                                                 wholeScript.append(dataStrBuf.toString());
2397                                         wholeScript.append("                    ],\n");*/
2398                                         wholeScript.append(" data , \n");
2399                                         wholeScript.append("                    {\n");
2400                                         
2401                                         //Labels here
2402                                         
2403                                         dct = null;
2404                                         StringBuffer labelStrBuf = new StringBuffer("");
2405                                         StringBuffer colorsStrBuf = new StringBuffer("");
2406                                         StringBuffer visibilityStrBuf = new StringBuffer("");
2407                                         int countChartValues = 0;
2408                                 for (Iterator iter = l.iterator(); iter.hasNext();) {
2409                                     dct = (DataColumnType) iter.next();
2410                                 if((dct.getChartSeq()!=null && dct.getChartSeq() >=0) || AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND)) {
2411                                            if(!AppUtils.nvl(dct.getDisplayName()).toLowerCase().equals("anomaly_text")) {
2412                                                    countChartValues++;
2413                                                 labelStrBuf.append("'"+ dct.getDisplayName()+"',");
2414                                                 if(!AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))
2415                                                  colorsStrBuf.append("'"+ AppUtils.nvl(dct.getChartColor())+"',");
2416                                                 visibilityStrBuf.append("true,");
2417                                            }
2418                                 }
2419                                 }
2420                                 if(labelStrBuf.indexOf(",")!=-1) {
2421                                         labelStrBuf.deleteCharAt(labelStrBuf.lastIndexOf(","));
2422                                         visibilityStrBuf.deleteCharAt(visibilityStrBuf.lastIndexOf(","));
2423                                 }
2424                                 if(colorsStrBuf.indexOf(",")!=-1)
2425                                         colorsStrBuf.deleteCharAt(colorsStrBuf.lastIndexOf(","));
2426                                 //if(showTitle)
2427                                                 //wholeScript.append("title: '" + (AppUtils.nvl(reportRuntime.getReportTitle()).length()>0?reportRuntime.getReportTitle():reportRuntime.getReportName()) + "',\n");
2428                                 wholeScript.append("maxNumberWidth:6,\n");
2429                                 wholeScript.append("xAxisHeight: 70,\n");
2430                                 wholeScript.append("yAxisLabelWidth: 70,\n");
2431                                 wholeScript.append("xAxisLabelWidth: 45,\n");
2432                                 wholeScript.append("axes: {\n");
2433                                 wholeScript.append("x: {\n");
2434                                 wholeScript.append("    axisLabelFormatter: function(d, gran) {\n");
2435                                 wholeScript.append("            var month = d.getMonth()+1;\n");
2436                                 wholeScript.append("            var day = d.getDate();\n");
2437                                 wholeScript.append("            var year = d.getFullYear();\n");
2438                                 wholeScript.append("            var hour = d.getHours();\n");
2439                                 wholeScript.append("            var minutes = d.getMinutes();\n");
2440                                 wholeScript.append("            var seconds = d.getSeconds();\n");
2441                                 wholeScript.append("            var wholeString = Dygraph.zeropad(month)+'/'+Dygraph.zeropad(day);\n");
2442                                // wholeScript.append("          if(hour >= 0 && minutes > 0 && seconds > 0) {\n");
2443                                 //wholeScript.append("                  wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes)+':'+Dygraph.zeropad(seconds);\n");
2444                                 //wholeScript.append("          } else if (hour >= 0 && minutes > 0 && seconds == 0) {\n");
2445                                 if(AppUtils.nvl(reportRuntime.getTimeAxisType()).length()==0 || AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly"))
2446                                         wholeScript.append("                    wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes);\n");
2447                                 //wholeScript.append("          } else if (hour >= 0 && (minutes >= 0 && seconds > 0)) {\n");
2448                                 //wholeScript.append("                  wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes)+':'+Dygraph.zeropad(seconds);\n");
2449                                 //wholeScript.append("          }  else if (hour >= 0) { \n");
2450                                 //wholeScript.append("                  wholeString += ' ' + Dygraph.zeropad(hour); \n");
2451                                 //wholeScript.append("          }  \n");
2452                                 wholeScript.append("            return wholeString; \n");
2453                                 wholeScript.append("      },\n");
2454                                 wholeScript.append("      ticker: function (a, b, pixels, opts, dygraph, vals) { \n ");
2455                                 wholeScript.append("             if(((b-a)/(1000*60*60)) <= 6) { \n");
2456                                 wholeScript.append("                    return Dygraph.getDateAxis(a, b, Dygraph.THIRTY_MINUTELY, opts, dygraph); \n");
2457                                 wholeScript.append("            } else if(((b-a)/(1000*60*60)) <= 12) { \n");
2458                                 wholeScript.append("       return Dygraph.getDateAxis(a, b, Dygraph.HOURLY, opts, dygraph); \n");
2459                                 wholeScript.append("            } else if (((b-a)/(1000*60*60)) <= 25) \n ");
2460                                 wholeScript.append("                    return Dygraph.getDateAxis(a, b, Dygraph.TWO_HOURLY, opts, dygraph); \n ");
2461                                 wholeScript.append("            else if(((b-a)/(1000*60*60)) <= 78) \n ");
2462                                 wholeScript.append("                    return Dygraph.getDateAxis(a, b, Dygraph.SIX_HOURLY, opts, dygraph); \n ");
2463                                 wholeScript.append("            else if(((b-a)/(1000*60*60*24)) <= 12)\n");
2464                                 wholeScript.append("                    return Dygraph.getDateAxis(a, b, Dygraph.DAILY, opts, dygraph); \n"); 
2465                                 wholeScript.append("            else if(((b-a)/(1000*60*60*24)) <= 90) \n");
2466                                 wholeScript.append("                    return Dygraph.getDateAxis(a, b, Dygraph.WEEKLY, opts, dygraph); \n"); 
2467                                 wholeScript.append("            else \n");
2468                                 wholeScript.append("                    return Dygraph.getDateAxis(a, b, Dygraph.MONTHLY, opts, dygraph); \n"); 
2469                                 wholeScript.append("      }, \n");      
2470                                 wholeScript.append("      valueFormatter: function(ms) { \n");
2471                                 wholeScript.append("    return new Date(ms).strftime(\"%m/%d/%Y %H:%M\"); \n");
2472                                 wholeScript.append(      " }\n" );
2473                                 wholeScript.append("  }\n");
2474                                 wholeScript.append("},\n");
2475                                 wholeScript.append(" interactionModel : { \n");
2476                                 wholeScript.append("    'mousedown' : downV4,\n");
2477                                 wholeScript.append("    touchstart : newDygraphTouchstart,\n");
2478                                         wholeScript.append("    touchend : Dygraph.defaultInteractionModel.touchend,\n");
2479                                         wholeScript.append("    touchmove : Dygraph.defaultInteractionModel.touchmove\n");
2480                                         //wholeScript.append("  'dblclick' : dblClickV3,\n");
2481                                         //wholeScript.append("  'mousewheel' : scrollV3\n");
2482                                 
2483                                 /*wholeScript.append("    'mousedown' : downV3,\n");
2484                                 wholeScript.append("    'mousemove' : moveV3,\n");
2485                                         wholeScript.append("    'mouseup' : upV3,\n");
2486                                         wholeScript.append("    'click' : clickV3,\n");
2487                                         wholeScript.append("    'dblclick' : dblClickV3,\n");
2488                                         wholeScript.append("    'mousewheel' : scrollV3\n");*/
2489                                         wholeScript.append("},\n");
2490                                         /*wholeScript.append("  zoomCallback: function(minDate, maxDate, yRanges) {     \n");
2491                                 if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) {
2492                                         wholeScript.append("            if(((maxDate-minDate)/(1000*60*60*24)) < 6) { \n");
2493                                         wholeScript.append("                    maxDate = new Date(minDate).setMinutes(6*24*60);\n");
2494                                         wholeScript.append("                    g.updateOptions({\n");
2495                                         wholeScript.append("                            interactionModel: {},\n");
2496                                         wholeScript.append("                            dateWindow: [minDate, maxDate]\n");
2497                                         wholeScript.append("                    });\n");
2498                                 } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) {
2499                                         wholeScript.append("            if(((maxDate-minDate)/(1000*60*60)) <= 6) { \n");
2500                                         wholeScript.append("                    maxDate = new Date(minDate).setMinutes(360);\n");
2501                                         wholeScript.append("                    g.updateOptions({\n");
2502                                         wholeScript.append("                            interactionModel: {},\n");
2503                                         wholeScript.append("                            dateWindow: [minDate, maxDate]\n");
2504                                         wholeScript.append("                    });\n");
2505                                 } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("30min")) {
2506                                         wholeScript.append("            if(((maxDate-minDate)/(1000*60*60)) <= 3) { \n");
2507                                         wholeScript.append("                    maxDate = new Date(minDate).setMinutes(180);\n");
2508                                         wholeScript.append("                    g.updateOptions({\n");
2509                                         wholeScript.append("                            interactionModel: {},\n");
2510                                         wholeScript.append("                            dateWindow: [minDate, maxDate]\n");
2511                                         wholeScript.append("                    });\n");
2512                                 } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("weekly")) {
2513                                         wholeScript.append("            if(((maxDate-minDate)/(1000*60*60*24)) < 7) { \n");
2514                                         wholeScript.append("                    maxDate = new Date(minDate).setMinutes(7*24*60);\n");
2515                                         wholeScript.append("                    g.updateOptions({\n");
2516                                         wholeScript.append("                            interactionModel: {},\n");
2517                                         wholeScript.append("                            dateWindow: [minDate, maxDate]\n");
2518                                         wholeScript.append("                    });\n");
2519                                 }
2520                                         wholeScript.append("                    } else {\n");
2521                                         wholeScript.append("                    g.updateOptions({\n");
2522                                         wholeScript.append("                            interactionModel : {\n");
2523                                         wholeScript.append("                                    'mousedown' : downV3,\n");
2524                                         wholeScript.append("                                    'mousemove' : moveV3,\n");
2525                                         wholeScript.append("                                    'mouseup' : upV3,\n");
2526                                         wholeScript.append("                                    'click' : clickV3,\n");
2527                                         wholeScript.append("                                    'dblclick' : dblClickV3,\n");
2528                                         wholeScript.append("                                    'mousewheel' : scrollV3\n");
2529                                         wholeScript.append("                            }\n");
2530                                         wholeScript.append("                    });\n");
2531                                         wholeScript.append("       } \n");
2532                                         wholeScript.append("  } ,\n");*/
2533                                 wholeScript.append("dateWindow: ["+minDate+", "+maxDate+"],\n");
2534                                 wholeScript.append("labels: ["+ labelStrBuf +"],\n");
2535                                 wholeScript.append("labelsDiv: \"labelDiv"+reportRuntime.getReportID()+"\",\n");
2536                                 wholeScript.append("labelsShowZeroValues: true,\n");
2537                                 if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
2538                                         wholeScript.append("labelsSeparateLines: true,\n");
2539                                 }
2540                                 wholeScript.append("labelsDivWidth: 200,\n");
2541                                 
2542                                 wholeScript.append("animatedZooms: true,\n");
2543                                 wholeScript.append("strokeWidth: 3.0,\n");
2544                                 wholeScript.append("strokeBorderWidth: 2.0,\n");
2545                                 /*wholeScript.append(" labelsDivStyles: { \n");
2546                                 wholeScript.append("    'backgroundColor': 'rgba(200, 200, 255, 0.75)',\n");
2547                                 wholeScript.append("    'padding': '4px',\n");
2548                                 wholeScript.append("    'border': '1px solid black',\n");
2549                                 wholeScript.append("    'borderRadius': '10px',\n");
2550                                 wholeScript.append("    'boxShadow': '4px 4px 4px #888',\n");
2551                                 wholeScript.append("    'width': '50px'\n");
2552                                 wholeScript.append("}, \n");
2553                                 */
2554                                 wholeScript.append("visibility: ["+ visibilityStrBuf +"],\n");
2555                                 if(colorsStrBuf.length() > 0 && colorsStrBuf.length()>=(countChartValues*3+5))
2556                                         wholeScript.append("colors: ["+ colorsStrBuf +"],\n");
2557                                         
2558                                         wholeScript.append("                    legend: 'always', \n");
2559                                         //Yaxis label here
2560                                         wholeScript.append("                            ylabel: '"+ chartLeftAxisLabel +"'  , \n");
2561                                         
2562                                         //Xaxis label here
2563                                         wholeScript.append("                            xlabel: '"+ xAxisLabel +"'  , \n");
2564                                         
2565                                         //draw points
2566                                         wholeScript.append("                            drawPoints: true, \n");
2567                                         
2568                                         //stacked graph
2569                                         wholeScript.append("                            stackedGraph: false, \n");
2570                                         
2571                                         dct = null; 
2572                                 for (Iterator iter = l.iterator(); iter.hasNext();) {
2573                                     dct = (DataColumnType) iter.next();
2574                                     if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) {
2575                                         if(!AppUtils.nvl(dct.getDisplayName()).toLowerCase().equals("anomaly_text")) {
2576                                         if(dct.getChartSeq()!=null && dct.getChartSeq() >=0) {
2577                                                 wholeScript.append("                            '"+ dct.getDisplayName() + "': {\n");
2578                                                 if(AppUtils.nvl(dct.getChartLineType()).length()>0)
2579                                                         wholeScript.append("                                    strokePattern: Dygraph.DASHED_LINE,\n");
2580                                                 if(dct.isIsRangeAxisFilled()!=null && dct.isIsRangeAxisFilled().booleanValue()) {
2581                                                         wholeScript.append("                                    fillGraph: true\n");
2582                                                 }
2583                                                 wholeScript.append("                            },\n");
2584                                         }
2585                                         }
2586                                     }
2587                                 }
2588                                 
2589 /*                                      //each labels
2590                                         wholeScript.append("                            'Forecast': {\n");
2591                                         
2592                                         //if dashed line
2593                                         wholeScript.append("                                    strokePattern: Dygraph.DASHED_LINE,\n");
2594                                         
2595                                         //if fillable
2596                                         wholeScript.append("                                    fillGraph: true\n");
2597                                         
2598                                         // close each labels
2599                                         wholeScript.append("                            }\n");
2600 */                                      
2601                                         // callback method
2602                                 if(anomalyRec > 0) {
2603                                                 wholeScript.append("                            drawCallback: function(g, is_initial) { \n");
2604                                                 wholeScript.append("                                    if (is_initial) { \n");
2605                                                 wholeScript.append("                                            graph_initialized = true; \n");
2606                                                 wholeScript.append("                                            if (anns.length > 0) { \n");
2607                                                 wholeScript.append("                                                    g.setAnnotations(anns); \n");
2608                                                 wholeScript.append("                                            }\n");
2609                                                 wholeScript.append("                                    }\n");
2610                                                 
2611                                                 wholeScript.append("                            var anns1 = g.annotations();\n");
2612                                                 //wholeScript.append("                          var html = \"\";\n");
2613                                                 wholeScript.append("                var html = \"<select id='x' size='1' style='width: "+ widthInt +"px; font-family : courier; font-size:8pt; font-weight:bold;'>\";\n");
2614                                                 wholeScript.append("                            for (var i = anns1.length-1; i >= 0 ; i--) {\n");
2615                                                 wholeScript.append("                                    var name = nameAnnotation(anns1[i]);\n");
2616                                                 //wholeScript.append("                                  html += \"<span id='\" + name + \"'>\"\n");
2617                                                 wholeScript.append("                                    if(i==anns1.length-1)\n");                                        
2618                                                 wholeScript.append("                            html += \"<option value='\" + name + \"' selected ><font size=1>\" \n");
2619                                                 wholeScript.append("                    else \n");                      
2620                                                 wholeScript.append("                    html += \"<option value='\" + name + \"'><font size=1>\" \n");
2621                                                 wholeScript.append("                    html += name \n");
2622                                                 //wholeScript.append("                                  html += name + \": \" + (anns1[i].shortText || '(icon)')\n");
2623                                                 //wholeScript.append("                                  html += \" -> \" + anns1[i].text + \"</span><br/>\";\n");
2624                                                 wholeScript.append("                                    html += \"&nbsp;:&nbsp;\" + anns1[i].text + \"</font></option>\";\n");
2625                                                 wholeScript.append("                            }\n");
2626                                                 wholeScript.append("               html += \"</select>\" \n");
2627                                                 wholeScript.append("                            document.getElementById(\"list"+reportRuntime.getReportID()+"\").innerHTML = html;\n");
2628                                                 wholeScript.append("                            }\n");
2629                                 
2630                                         
2631                                         wholeScript.append("                    }\n");
2632                                         wholeScript.append("          )\n");
2633                                         
2634                                         //push annotations
2635                                         wholeScript.append(annotationsStrBuf.toString());
2636                                         
2637                                         wholeScript.append("      if (graph_initialized) {\n");
2638                                         wholeScript.append("            g.setAnnotations(anns);\n");
2639                                         wholeScript.append("      }     \n");
2640                                         //upate handler script
2641
2642                                         wholeScript.append("     var saveBg = '';\n");
2643                                         wholeScript.append("     var num = 0;\n");
2644                                         wholeScript.append("      g.updateOptions( {\n");
2645                                         wholeScript.append("            annotationMouseOverHandler: function(ann) { \n");
2646                                         //wholeScript.append("          document.getElementById(nameAnnotation(ann)).style.fontWeight = 'bold';\n");
2647                                         //wholeScript.append("          saveBg = ann.div.style.backgroundColor;\n");
2648                                         //wholeScript.append("          ann.div.style.backgroundColor = '#ddd';\n");
2649                                         wholeScript.append("            var selectobject = document.getElementById(\"x\");\n");
2650                                         wholeScript.append("            for(var i=0; i<selectobject.length;i++) {\n ");
2651                                         wholeScript.append("                    if(selectobject.options[i].value == nameAnnotation(ann)) {\n ");
2652                                         wholeScript.append("                      selectobject.options[i].selected = true; \n ");
2653                                         wholeScript.append("                    } ");
2654                                         wholeScript.append("            } ");
2655                                         
2656                                         wholeScript.append("       },\n");
2657                                         wholeScript.append("       annotationMouseOutHandler: function(ann) {\n");
2658                                         wholeScript.append("       document.getElementById(nameAnnotation(ann)).style.fontWeight = 'normal';\n");
2659                                         wholeScript.append("            ann.div.style.backgroundColor = saveBg;\n");
2660                                         //wholeScript.append("          var selectobject = document.getElementById(\"x\");\n");
2661                                         //wholeScript.append("          for(var i=0; i<selectobject.length;i++) {\n ");
2662                                         //wholeScript.append("                  if(selectobject.options[i].value == nameAnnotation(ann)) {\n ");
2663                                         //wholeScript.append("                    selectobject.options[i].selected = false; \n ");
2664                                         //wholeScript.append("                          } ");
2665                                         //wholeScript.append("                  } ");
2666                                         
2667                                         wholeScript.append("      }\n");
2668                                 }
2669                                         wholeScript.append("      });\n");
2670                                         
2671                                         //Other devices
2672                                         wholeScript.append("} else { \n");
2673                                         
2674                                         wholeScript.append("            g = new Dygraph(\n");
2675                                         wholeScript.append("                    document.getElementById(\"div_g"+reportRuntime.getReportID()+"\"),\n");
2676                                         //data here
2677                                         /*wholeScript.append("                  [\n");
2678                                                                                 wholeScript.append(dataStrBuf.toString());
2679                                         wholeScript.append("                    ],\n");*/
2680                                         wholeScript.append(" data , \n");
2681                                         wholeScript.append("                    {\n");
2682                                         
2683                                         //Labels here
2684                                         
2685                                         dct = null;
2686                                         labelStrBuf = new StringBuffer("");
2687                                         colorsStrBuf = new StringBuffer("");
2688                                         visibilityStrBuf = new StringBuffer("");
2689                                         countChartValues = 0;
2690                                 for (Iterator iter = l.iterator(); iter.hasNext();) {
2691                                     dct = (DataColumnType) iter.next();
2692                                 if((dct.getChartSeq()!=null && dct.getChartSeq() >=0) || AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND)) {
2693                                            if(!AppUtils.nvl(dct.getDisplayName()).toLowerCase().equals("anomaly_text")) {
2694                                                    countChartValues++;
2695                                                 labelStrBuf.append("'"+ dct.getDisplayName()+"',");
2696                                                 if(!AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))
2697                                                  colorsStrBuf.append("'"+ AppUtils.nvl(dct.getChartColor())+"',");
2698                                                 visibilityStrBuf.append("true,");
2699                                            }
2700                                 }
2701                                 }
2702                                 if(labelStrBuf.indexOf(",")!=-1) {
2703                                         labelStrBuf.deleteCharAt(labelStrBuf.lastIndexOf(","));
2704                                         visibilityStrBuf.deleteCharAt(visibilityStrBuf.lastIndexOf(","));
2705                                 }
2706                                 if(colorsStrBuf.indexOf(",")!=-1)
2707                                         colorsStrBuf.deleteCharAt(colorsStrBuf.lastIndexOf(","));
2708                                 //if(showTitle)
2709                                                 //wholeScript.append("title: '" + (AppUtils.nvl(reportRuntime.getReportTitle()).length()>0?reportRuntime.getReportTitle():reportRuntime.getReportName()) + "',\n");
2710                                 wholeScript.append("maxNumberWidth:6,\n");
2711                                 wholeScript.append("xAxisHeight: 70,\n");
2712                                 wholeScript.append("yAxisLabelWidth: 70,\n");
2713                                 wholeScript.append("xAxisLabelWidth: 45,\n");
2714                                 wholeScript.append("axes: {\n");
2715                                 wholeScript.append("x: {\n");
2716                                 wholeScript.append("    axisLabelFormatter: function(d, gran) {\n");
2717                                 wholeScript.append("            var month = d.getMonth()+1;\n");
2718                                 wholeScript.append("            var day = d.getDate();\n");
2719                                 wholeScript.append("            var year = d.getFullYear();\n");
2720                                 wholeScript.append("            var hour = d.getHours();\n");
2721                                 wholeScript.append("            var minutes = d.getMinutes();\n");
2722                                 wholeScript.append("            var seconds = d.getSeconds();\n");
2723                                 wholeScript.append("            var wholeString = Dygraph.zeropad(month)+'/'+Dygraph.zeropad(day);\n");
2724                                // wholeScript.append("          if(hour >= 0 && minutes > 0 && seconds > 0) {\n");
2725                                 //wholeScript.append("                  wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes)+':'+Dygraph.zeropad(seconds);\n");
2726                                 //wholeScript.append("          } else if (hour >= 0 && minutes > 0 && seconds == 0) {\n");
2727                                 if(AppUtils.nvl(reportRuntime.getTimeAxisType()).length()==0 || AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly"))
2728                                         wholeScript.append("                    wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes);\n");
2729                                 //wholeScript.append("          } else if (hour >= 0 && (minutes >= 0 && seconds > 0)) {\n");
2730                                 //wholeScript.append("                  wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes)+':'+Dygraph.zeropad(seconds);\n");
2731                                 //wholeScript.append("          }  else if (hour >= 0) { \n");
2732                                 //wholeScript.append("                  wholeString += ' ' + Dygraph.zeropad(hour); \n");
2733                                 //wholeScript.append("          }  \n");
2734                                 wholeScript.append("            return wholeString; \n");
2735                                 wholeScript.append("      },\n");
2736                                 wholeScript.append("      ticker: function (a, b, pixels, opts, dygraph, vals) { \n ");
2737                                 wholeScript.append("             if(((b-a)/(1000*60*60)) <= 6) { \n");
2738                                 wholeScript.append("                    return Dygraph.getDateAxis(a, b, Dygraph.THIRTY_MINUTELY, opts, dygraph); \n");
2739                                 wholeScript.append("            } else if(((b-a)/(1000*60*60)) <= 12) { \n");
2740                                 wholeScript.append("       return Dygraph.getDateAxis(a, b, Dygraph.HOURLY, opts, dygraph); \n");
2741                                 wholeScript.append("            } else if (((b-a)/(1000*60*60)) <= 25) \n ");
2742                                 wholeScript.append("                    return Dygraph.getDateAxis(a, b, Dygraph.TWO_HOURLY, opts, dygraph); \n ");
2743                                 wholeScript.append("            else if(((b-a)/(1000*60*60)) <= 78) \n ");
2744                                 wholeScript.append("                    return Dygraph.getDateAxis(a, b, Dygraph.SIX_HOURLY, opts, dygraph); \n ");
2745                                 wholeScript.append("            else if(((b-a)/(1000*60*60*24)) <= 12)\n");
2746                                 wholeScript.append("                    return Dygraph.getDateAxis(a, b, Dygraph.DAILY, opts, dygraph); \n"); 
2747                                 wholeScript.append("            else if(((b-a)/(1000*60*60*24)) <= 90) \n");
2748                                 wholeScript.append("                    return Dygraph.getDateAxis(a, b, Dygraph.WEEKLY, opts, dygraph); \n"); 
2749                                 wholeScript.append("            else \n");
2750                                 wholeScript.append("                    return Dygraph.getDateAxis(a, b, Dygraph.MONTHLY, opts, dygraph); \n"); 
2751                                 wholeScript.append("      }, \n");      
2752                                 wholeScript.append("      valueFormatter: function(ms) { \n");
2753                                 wholeScript.append("    return new Date(ms).strftime(\"%m/%d/%Y %H:%M\"); \n");
2754                                 wholeScript.append(      " }\n" );
2755                                 wholeScript.append("  }\n");
2756                                 wholeScript.append("},\n");
2757                                 wholeScript.append(" interactionModel : { \n");
2758                                 
2759                                 wholeScript.append("    'mousedown' : downV3,\n");
2760                                 wholeScript.append("    'mousemove' : moveV3,\n");
2761                                         wholeScript.append("    'mouseup' : upV3,\n");
2762                                         wholeScript.append("    'click' : clickV3,\n");
2763                                         wholeScript.append("    'dblclick' : dblClickV3,\n");
2764                                         wholeScript.append("    'mousewheel' : scrollV3\n");
2765                                         wholeScript.append("},\n");
2766                                         wholeScript.append("  zoomCallback: function(minDate, maxDate, yRanges) {       \n");
2767                                 if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) {
2768                                         wholeScript.append("            if(((maxDate-minDate)/(1000*60*60*24)) < 6) { \n");
2769                                         wholeScript.append("                    maxDate = new Date(minDate).setMinutes(6*24*60);\n");
2770                                         wholeScript.append("                    g.updateOptions({\n");
2771                                         wholeScript.append("                            interactionModel: {},\n");
2772                                         wholeScript.append("                            dateWindow: [minDate, maxDate]\n");
2773                                         wholeScript.append("                    });\n");
2774                                 } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) {
2775                                         wholeScript.append("            if(((maxDate-minDate)/(1000*60*60)) <= 6) { \n");
2776                                         wholeScript.append("                    maxDate = new Date(minDate).setMinutes(360);\n");
2777                                         wholeScript.append("                    g.updateOptions({\n");
2778                                         wholeScript.append("                            interactionModel: {},\n");
2779                                         wholeScript.append("                            dateWindow: [minDate, maxDate]\n");
2780                                         wholeScript.append("                    });\n");
2781                                 } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("30min")) {
2782                                         wholeScript.append("            if(((maxDate-minDate)/(1000*60*60)) <= 3) { \n");
2783                                         wholeScript.append("                    maxDate = new Date(minDate).setMinutes(180);\n");
2784                                         wholeScript.append("                    g.updateOptions({\n");
2785                                         wholeScript.append("                            interactionModel: {},\n");
2786                                         wholeScript.append("                            dateWindow: [minDate, maxDate]\n");
2787                                         wholeScript.append("                    });\n");
2788                                 } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("weekly")) {
2789                                         wholeScript.append("            if(((maxDate-minDate)/(1000*60*60*24)) < 7) { \n");
2790                                         wholeScript.append("                    maxDate = new Date(minDate).setMinutes(7*24*60);\n");
2791                                         wholeScript.append("                    g.updateOptions({\n");
2792                                         wholeScript.append("                            interactionModel: {},\n");
2793                                         wholeScript.append("                            dateWindow: [minDate, maxDate]\n");
2794                                         wholeScript.append("                    });\n");
2795                                 }
2796                                         wholeScript.append("                    } else {\n");
2797                                         wholeScript.append("                    g.updateOptions({\n");
2798                                         wholeScript.append("                            interactionModel : {\n");
2799                                         wholeScript.append("                                    'mousedown' : downV3,\n");
2800                                         wholeScript.append("                                    'mousemove' : moveV3,\n");
2801                                         wholeScript.append("                                    'mouseup' : upV3,\n");
2802                                         wholeScript.append("                                    'click' : clickV3,\n");
2803                                         wholeScript.append("                                    'dblclick' : dblClickV3,\n");
2804                                         wholeScript.append("                                    'mousewheel' : scrollV3\n");
2805                                         wholeScript.append("                            }\n");
2806                                         wholeScript.append("                    });\n");
2807                                         wholeScript.append("       } \n");
2808                                         wholeScript.append("  } ,\n");
2809                                 wholeScript.append("dateWindow: ["+minDate+", "+maxDate+"],\n");
2810                                 wholeScript.append("labels: ["+ labelStrBuf +"],\n");
2811                                 wholeScript.append("labelsDiv: \"labelDiv"+reportRuntime.getReportID()+"\",\n");
2812                                 wholeScript.append("labelsShowZeroValues: true,\n");
2813                                 if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
2814                                         wholeScript.append("labelsSeparateLines: true,\n");
2815                                 }
2816                                 wholeScript.append("labelsDivWidth: 200,\n");
2817                                 
2818                                 
2819                                 wholeScript.append("animatedZooms: true,\n");
2820                                 wholeScript.append("strokeWidth: 3.0,\n");
2821                                 wholeScript.append("strokeBorderWidth: 2.0,\n");
2822                                 
2823                                 /*wholeScript.append(" labelsDivStyles: { \n");
2824                                 wholeScript.append("    'backgroundColor': 'rgba(200, 200, 255, 0.75)',\n");
2825                                 wholeScript.append("    'padding': '4px',\n");
2826                                 wholeScript.append("    'border': '1px solid black',\n");
2827                                 wholeScript.append("    'borderRadius': '10px',\n");
2828                                 wholeScript.append("    'boxShadow': '4px 4px 4px #888',\n");
2829                                 wholeScript.append("    'width': '50px'\n");
2830                                 wholeScript.append("}, \n");
2831                                 */
2832                                 wholeScript.append("visibility: ["+ visibilityStrBuf +"],\n");
2833                                 if(colorsStrBuf.length() > 0 && colorsStrBuf.length()>=(countChartValues*3+5))
2834                                         wholeScript.append("colors: ["+ colorsStrBuf +"],\n");
2835                                         
2836                                         wholeScript.append("                    legend: 'always', \n");
2837                                         //Yaxis label here
2838                                         wholeScript.append("                            ylabel: '"+ chartLeftAxisLabel +"'  , \n");
2839                                         
2840                                         //Xaxis label here
2841                                         wholeScript.append("                            xlabel: '"+ xAxisLabel +"'  , \n");
2842                                         
2843                                         
2844                                         //draw points
2845                                         wholeScript.append("                            drawPoints: true, \n");
2846                                         
2847                                         //stacked graph
2848                                         wholeScript.append("                            stackedGraph: false, \n");
2849                                         
2850                                         dct = null; 
2851                                 for (Iterator iter = l.iterator(); iter.hasNext();) {
2852                                     dct = (DataColumnType) iter.next();
2853                                     if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) {
2854                                         if(!AppUtils.nvl(dct.getDisplayName()).toLowerCase().equals("anomaly_text")) {
2855                                         if(dct.getChartSeq()!=null && dct.getChartSeq() >=0) {
2856                                                 wholeScript.append("                            '"+ dct.getDisplayName() + "': {\n");
2857                                                 if(AppUtils.nvl(dct.getChartLineType()).length()>0)
2858                                                         wholeScript.append("                                    strokePattern: Dygraph.DASHED_LINE,\n");
2859                                                 if(dct.isIsRangeAxisFilled()!=null && dct.isIsRangeAxisFilled().booleanValue()) {
2860                                                         wholeScript.append("                                    fillGraph: true\n");
2861                                                 }
2862                                                 wholeScript.append("                            },\n");
2863                                         }
2864                                         }
2865                                     }
2866                                 }
2867                                 
2868 /*                                      //each labels
2869                                         wholeScript.append("                            'Forecast': {\n");
2870                                         
2871                                         //if dashed line
2872                                         wholeScript.append("                                    strokePattern: Dygraph.DASHED_LINE,\n");
2873                                         
2874                                         //if fillable
2875                                         wholeScript.append("                                    fillGraph: true\n");
2876                                         
2877                                         // close each labels
2878                                         wholeScript.append("                            }\n");
2879 */                                      
2880                                         // callback method
2881                                 if(anomalyRec > 0) {
2882                                                 wholeScript.append("                            drawCallback: function(g, is_initial) { \n");
2883                                                 wholeScript.append("                                    if (is_initial) { \n");
2884                                                 wholeScript.append("                                            graph_initialized = true; \n");
2885                                                 wholeScript.append("                                            if (anns.length > 0) { \n");
2886                                                 wholeScript.append("                                                    g.setAnnotations(anns); \n");
2887                                                 wholeScript.append("                                            }\n");
2888                                                 wholeScript.append("                                    }\n");
2889                                                 
2890                                                 wholeScript.append("                            var anns1 = g.annotations();\n");
2891                                                 //wholeScript.append("                          var html = \"\";\n");
2892                                                 wholeScript.append("                var html = \"<select id='x' size='1' style='width: "+ widthInt +"px; font-family : courier; font-size:8pt; font-weight:bold;'>\";\n");
2893                                                 wholeScript.append("                            for (var i = anns1.length-1; i >= 0 ; i--) {\n");
2894                                                 wholeScript.append("                                    var name = nameAnnotation(anns1[i]);\n");
2895                                                 //wholeScript.append("                                  html += \"<span id='\" + name + \"'>\"\n");
2896                                                 wholeScript.append("                                    if(i==anns1.length-1)\n");                                        
2897                                                 wholeScript.append("                            html += \"<option value='\" + name + \"' selected ><font size=1>\" \n");
2898                                                 wholeScript.append("                    else \n");                      
2899                                                 wholeScript.append("                    html += \"<option value='\" + name + \"'><font size=1>\" \n");
2900                                                 wholeScript.append("                    html += name \n");
2901                                                 //wholeScript.append("                                  html += name + \": \" + (anns1[i].shortText || '(icon)')\n");
2902                                                 //wholeScript.append("                                  html += \" -> \" + anns1[i].text + \"</span><br/>\";\n");
2903                                                 wholeScript.append("                                    html += \"&nbsp;:&nbsp;\" + anns1[i].text + \"</font></option>\";\n");
2904                                                 wholeScript.append("                            }\n");
2905                                                 wholeScript.append("               html += \"</select>\" \n");
2906                                                 wholeScript.append("                            document.getElementById(\"list"+reportRuntime.getReportID()+"\").innerHTML = html;\n");
2907                                                 wholeScript.append("                            }\n");
2908                                 
2909                                         
2910                                         wholeScript.append("                    }\n");
2911                                         wholeScript.append("          )\n");
2912                                         
2913                                         //push annotations
2914                                         wholeScript.append(annotationsStrBuf.toString());
2915                                         
2916                                         wholeScript.append("      if (graph_initialized) {\n");
2917                                         wholeScript.append("            g.setAnnotations(anns);\n");
2918                                         wholeScript.append("      }     \n");
2919                                         //upate handler script
2920
2921                                         wholeScript.append("     var saveBg = '';\n");
2922                                         wholeScript.append("     var num = 0;\n");
2923                                         wholeScript.append("      g.updateOptions( {\n");
2924                                         wholeScript.append("            annotationMouseOverHandler: function(ann) { \n");
2925                                         //wholeScript.append("          document.getElementById(nameAnnotation(ann)).style.fontWeight = 'bold';\n");
2926                                         //wholeScript.append("          saveBg = ann.div.style.backgroundColor;\n");
2927                                         //wholeScript.append("          ann.div.style.backgroundColor = '#ddd';\n");
2928                                         wholeScript.append("            var selectobject = document.getElementById(\"x\");\n");
2929                                         wholeScript.append("            for(var i=0; i<selectobject.length;i++) {\n ");
2930                                         wholeScript.append("                    if(selectobject.options[i].value == nameAnnotation(ann)) {\n ");
2931                                         wholeScript.append("                      selectobject.options[i].selected = true; \n ");
2932                                         wholeScript.append("                    } ");
2933                                         wholeScript.append("            } ");
2934                                         
2935                                         wholeScript.append("       },\n");
2936                                         wholeScript.append("       annotationMouseOutHandler: function(ann) {\n");
2937                                         //wholeScript.append("     document.getElementById(nameAnnotation(ann)).style.fontWeight = 'normal';\n");
2938                                         wholeScript.append("            ann.div.style.backgroundColor = saveBg;\n");
2939                                         //wholeScript.append("          var selectobject = document.getElementById(\"x\");\n");
2940                                         //wholeScript.append("          for(var i=0; i<selectobject.length;i++) {\n ");
2941                                         //wholeScript.append("                  if(selectobject.options[i].value == nameAnnotation(ann)) {\n ");
2942                                         //wholeScript.append("                    selectobject.options[i].selected = false; \n ");
2943                                         //wholeScript.append("                          } ");
2944                                         //wholeScript.append("                  } ");
2945                                         
2946                                         wholeScript.append("      }\n");
2947                                 }
2948                                         wholeScript.append("      });\n");
2949                                         
2950                                         
2951                                         wholeScript.append("} \n");
2952                                 //}
2953                                         wholeScript.append("} else {\n");
2954                                         wholeScript.append("document.getElementById(\"message"+ reportRuntime.getReportID()+"\").display = \"none\";\n");
2955                                         wholeScript.append("document.getElementById(\"labelDiv"+ reportRuntime.getReportID()+"\").display=\"none\";\n");
2956                                         wholeScript.append("document.getElementById(\"div_g"+reportRuntime.getReportID()+"\").display=\"none\";\n");
2957
2958                                         wholeScript.append("document.getElementById(\"div_g"+reportRuntime.getReportID()+"\").innerHTML = \"<div id='noData'><b>No Data Available</b></div>\";\n");
2959                                         wholeScript.append("document.getElementById(\"div_g"+reportRuntime.getReportID()+"\").className=\"nodatadiv\";\n");
2960                                         wholeScript.append("document.getElementById(\"nodata\").className=\"nodatainner\";\n");
2961                                         if(!timeCharts)
2962                                                 wholeScript.append("document.getElementById(\"list"+reportRuntime.getReportID()+"\").display=\"none\";\n");
2963                                         wholeScript.append("}\n");
2964                                         wholeScript.append("     </script>\n");
2965                                         wholeScript.append("  </body>\n");
2966                                         wholeScript.append("</html>");
2967                                         
2968
2969                                 } else if (chartType.equals(AppConstants.GT_SCATTER)) {
2970
2971                                         wholeScript.append("<link href=\""+ chartScriptsPath +"d3/css/nv.d3.css\" rel=\"stylesheet\" type=\"text/css\">\n");
2972                                         wholeScript.append("<style>\n   " +
2973                                                                                 " body { \n" +
2974                                                                                 "       overflow-y:scroll; \n" +
2975                                                                                 "       } \n" +
2976                                                                                 " text { \n" +
2977                                                                                 "       font: 12px sans-serif; \n" +
2978                                                                                 " } \n" +
2979                                                                                 " tr.z-row-over > td.z-row-inner, tr.z-row-over > .z-cell {" +
2980                                                                                 " background-color: rgb(255, 255, 255); "+
2981                                                                                 "} "+
2982                                                                                 " svg {   display: block; } " + 
2983                                                                                 " #chart1 svg { \n" +
2984                                                                                 " height: 420px; \n" +
2985                                                                                 " width: 800px; \n" +
2986                                                                                 " min-width: 100px; \n" +
2987                                                                                 " min-height: 100px; \n" +
2988                                                                                 " } \n" +
2989                                                                                 
2990                                                                                 " </style> \n" );
2991                                         wholeScript.append("<body> \n");
2992                                         wholeScript.append("<div id=\"chart1\"><svg></svg></div>");
2993                                         //js files
2994                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/d3.v2.js\"></script>\n");
2995                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/nv.d3.js\"></script> \n");
2996                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/tooltip.js\"></script> \n");
2997                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/utils.js\"></script> \n");
2998                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/legend.js\"></script> \n");
2999                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/axis.js\"></script> \n");
3000                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/distribution.js\"></script> \n");
3001                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/scatter.js\"></script> \n");
3002                                         wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/scatterChart.js\"></script> \n");
3003                                         wholeScript.append("<script> \n");
3004                                         wholeScript.append("nv.addGraph(function() { \n" +
3005                                                 " var width1=900, height1=220; \n" +
3006                                                         " var chart = nv.models.scatterChart() \n" +
3007                                                         "                       .showDistX(true) \n" +
3008                                                         "                       .showDistY(true) \n" +
3009                                                         "                       .useVoronoi(true) \n" +         
3010                                                         "           .color(d3.scale.category10().range()); \n" +
3011 /*                                                      "                       .width(width1) \n" +
3012                                                         "                       .height(height1); \n" +         
3013 */                                                      " chart.xAxis\n" +
3014                                                         "       .axisLabel('" +legendColumnName + "')\n" +
3015                                                         "               .tickFormat(d3.format('.02f'));\n" +                    
3016                                                         " chart.yAxis\n" +
3017                                                         "       .axisLabel('" + chartLeftAxisLabel + "')\n" +
3018                                                         "               .tickFormat(d3.format('.02f'));\n" +                    
3019                                                         " d3.select('#chart1 svg') \n" +
3020                                                         "  .datum(getData()) \n" );
3021                                                         if(animation)
3022                                                                 wholeScript.append("  .transition().duration(1200) \n" );
3023 /*                                                      "   .attr(\"width\", width1) \n" +
3024                                                         "   .attr(\"height\", height1) \n" +
3025 */                                                      wholeScript.append("  .call(chart); \n" +
3026                                                         " nv.utils.windowResize(chart.update);\n"+  
3027                                                         "return chart; \n" +
3028                                                         "}); \n");
3029                                         
3030                                         String dateStr = "";
3031                                 Object uniqueElements [] = null;
3032                                 TreeSet ts = new TreeSet();        
3033                                 for (int i = 0; i < ds.getRowCount(); i++) {
3034                                     dateStr = ds.getString(i, 2);
3035                                     if(dateStr.length()>0)
3036                                         ts.add(dateStr);
3037                                 }                                       
3038                                 SortedSet s = Collections.synchronizedSortedSet(ts);
3039                                 uniqueElements = s.toArray();
3040                                 
3041                                         wholeScript.append(" function getData() { \n " +
3042                                                    "  var data = [];\n ");
3043                                         for (int i = 0; i < uniqueElements.length; i++) {
3044                                                 wholeScript.append(" data.push( {key:'"+ uniqueElements[i]+ "', values:[]})\n");
3045                                         }
3046                                                   
3047
3048                                 for (int i = 0; i < ds.getRowCount(); i++) {
3049                                                 for (int k = 0; k < uniqueElements.length; k++) {
3050                                                         if(ds.getString(i, 2).equals(uniqueElements[k])) {
3051                                                                 wholeScript.append("data["+k+"].values.push({x:"+ ds.getString(i, 1) +",y:"+ds.getString(i, 3) + ", size: Math.random() });\n");
3052                                                         }
3053                                                 }
3054                                         }
3055                                          
3056                                         wholeScript.append("return data; } </script></body>\n");
3057                                 } else if (chartType.equals(AppConstants.GT_HIERARCHICAL_SUNBURST)) {
3058                                         
3059                                         StringBuffer dataStr = new StringBuffer("");
3060                                         StringBuffer groupBuffer = new StringBuffer("");
3061                                         StringBuffer s = new StringBuffer("");
3062                                         dataStr.append("{");
3063                                         dataStr.append("        \"ss4262\":{\n");
3064                                         String mid = "";
3065                                         String mid_old = "";
3066                                         String level = "-1";
3067                                         String level_old = "-1";                
3068                                         String eid = "";
3069                                         for (int i = 0; i < ds.getRowCount(); i++) {
3070                                                  mid  = ds.getString(i, "mid");
3071                                                 level = ds.getString(i, "level1");
3072                                                 eid = ds.getString(i, "eid");
3073                                 if(mid.equals(mid_old)) {
3074                                         dataStr.append("\""+ eid +"\": 9956,\n");
3075                                 } else {
3076                                         if(dataStr.lastIndexOf(",")!= -1)
3077                                                 dataStr.deleteCharAt(dataStr.lastIndexOf(","));
3078                                         //if(Integer.parseInt(level_old)==Integer.parseInt(level))
3079                                                 //dataStr.append("},\n");
3080                                         if (Integer.parseInt(level_old)<Integer.parseInt(level))
3081                                                 dataStr.append("},\n");
3082                                                     dataStr.append("\""+ mid +"\": { \n");
3083                                                 }
3084                                                 
3085                                                  mid_old = mid;
3086                                                 level_old = level;
3087                                         }
3088                                         if(dataStr.toString().endsWith(","))
3089                                                 dataStr.deleteCharAt(dataStr.lastIndexOf(","));
3090                                         dataStr.append("}\n");
3091                                         dataStr.append("}\n");
3092                                 try {
3093                                         String formattedReportName = new HtmlStripper().stripSpecialCharacters(reportRuntime.getReportName());
3094                                 String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new java.util.Date());
3095                                         String filename=formattedReportName+formattedDate+user_id+".json";
3096                                         String filenamepath = AppUtils.getExcelTemplatePath()+"../../json/"+filename;
3097                                         System.out.println("filenamepath " + filenamepath);
3098                                         BufferedWriter out = new BufferedWriter(new FileWriter(filenamepath));
3099                                         out.write(dataStr.toString());
3100                                         out.close();
3101                                         request.getSession().setAttribute("jsonFileName", filename);
3102                                 } catch (IOException e) { 
3103                                         e.printStackTrace();
3104                                         System.out.println("Exception ");
3105                                 }                                               
3106                                 } else if (chartType.equals(AppConstants.GT_HIERARCHICAL)) {
3107                                         
3108                                         StringBuffer dataStr = new StringBuffer("");
3109                                         StringBuffer groupBuffer = new StringBuffer("");
3110                                         StringBuffer s = new StringBuffer("");
3111                                         dataStr.append("{");
3112                                         dataStr.append("        \"groups\":[");
3113                                         
3114                                         for (int i = 0; i < ds.getRowCount(); i++) {
3115                                 if(ds.getString(i,"group_ind").equals("Y")) {
3116                                         groupBuffer.append("    { \"name\": \""+ ds.getString(i,"ei1") +"\" },\n");
3117                                 }
3118                                                 
3119                                         }
3120                                         groupBuffer.deleteCharAt(groupBuffer.lastIndexOf(","));
3121                                         dataStr.append(groupBuffer.toString());
3122                                         dataStr.append("],");
3123                                         dataStr.append("\"nodes\":[");
3124                                         int rowCount = ds.getRowCount();
3125                                         for (int i = 0; i < ds.getRowCount(); i++) {
3126                                                 s.append("{ \"name\": \""+ ds.getString(i,"ei1") +"\" , \"group\":"+ ds.getString(i,"groups") +", \"level\":2   }");
3127                                                 if (i < (rowCount-1)) s.append(",");
3128                                                 dataStr.append(s);
3129                                                 s = new StringBuffer("");
3130                                         }
3131                                         
3132                                 dataStr.append("],");
3133                                 dataStr.append("\"links\":[");
3134                                         for (int i = 0; i < ds.getRowCount(); i++) {
3135                                                 s.append("{ \"source\": "+ ds.getString(i,"source") +" , \"target\":"+ ds.getString(i,"target") +", \"value\":2   }");
3136                                         if (i < (rowCount-1)) s.append(",");
3137                                                 dataStr.append(s);
3138                                                 s = new StringBuffer("");
3139                                         }
3140                                 dataStr.append("]}");
3141                                 try {
3142                                         String formattedReportName = new HtmlStripper().stripSpecialCharacters(reportRuntime.getReportName());
3143                                 String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new java.util.Date());
3144                                         String filename=formattedReportName+formattedDate+user_id+".json";
3145                                         String filenamepath = AppUtils.getExcelTemplatePath()+"../../json/"+filename;
3146                                         System.out.println("filenamepath " + filenamepath);
3147                                         BufferedWriter out = new BufferedWriter(new FileWriter(filenamepath));
3148                                         out.write(dataStr.toString());
3149                                         out.close();
3150                                         request.getSession().setAttribute("jsonFileName", filename);
3151                                 } catch (IOException e) { 
3152                                         e.printStackTrace();
3153                                         System.out.println("Exception ");
3154                                 }                                               
3155                                 }
3156                                 
3157                         }
3158                 }
3159                 try {
3160                         BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));
3161                         out.write(wholeScript.toString());
3162                         out.close();
3163                 } catch (IOException e) { 
3164                         e.printStackTrace();
3165                         System.out.println("Exception ");
3166                 }
3167                 return wholeScript.toString();
3168         }
3169                 
3170                 public String nvl(String s) {
3171                         return (s == null) ? "" : s;
3172                 }
3173                 
3174                 public String nvl(String s, String sDefault) {
3175                         return nvl(s).equals("") ? sDefault : s;
3176                 }
3177
3178                 public static String nvls(String s) {
3179                         return (s == null) ? "" : s;
3180                 }
3181
3182                 public static String nvls(String s, String sDefault) {
3183                         return nvls(s).equals("") ? sDefault : s;
3184                 }
3185                 
3186                 public boolean getFlagInBoolean(String s) {
3187                         return nvl(s).toUpperCase().startsWith("Y") || nvl(s).toLowerCase().equals("true");
3188                 }
3189                 
3190                 public DataSet loadChartData(String userId, HttpServletRequest request) throws RaptorException {
3191                         if (nvl(getChartType()).length() == 0)
3192                                 return null;
3193                         //TODO: display chart function to be added. 
3194                         //if (!getDisplayChart())
3195                         //      return null;
3196
3197                 String sql = null;
3198             sql = generateChartSQL(userId, request);
3199             logger.debug(EELFLoggerDelegate.debugLogger, ("SQL generated " + sql));
3200                         String dbInfo = reportRuntime.getDBInfo();
3201                         DataSet ds = ConnectionUtils.getDataSet(sql, dbInfo);
3202                         if(ds.getRowCount()<=0) {
3203                                 logger.debug(EELFLoggerDelegate.debugLogger, ("********************************************************************************"));
3204                                 logger.debug(EELFLoggerDelegate.debugLogger, (getChartType().toUpperCase()+" - " + "Report ID : " + reportRuntime.getReportID() + " DATA IS EMPTY" ));
3205                                 logger.debug(EELFLoggerDelegate.debugLogger, ("QUERY - " + sql));
3206                                 logger.debug(EELFLoggerDelegate.debugLogger, ("********************************************************************************"));
3207                         }
3208
3209                         return ds;
3210                 } // loadChartData      
3211                 
3212                 public String generateChartSQL(String userId, HttpServletRequest request ) throws RaptorException  {
3213                         List reportCols = reportRuntime.getAllColumns();
3214                         List chartValueCols = getChartValueColumnsList(AppConstants.CHART_ALL_COLUMNS, null); // parameter is 0 has this requires all columns. 
3215                         String reportSQL = reportRuntime.getWholeSQL();
3216                         
3217                         //Add order by clause
3218                         Pattern re1 = Pattern.compile("(^[\r\n]*|([\\s]))[Oo][Rr][Dd][Ee][Rr](.*?[^\r\n]*)[Bb][Yy]",Pattern.DOTALL);
3219                         //Pattern re1 = Pattern.compile("order(.*?[^\r\n]*)by", Pattern.DOTALL);
3220                         Matcher matcher = re1.matcher(reportSQL);
3221                         //Pattern re1 = Pattern.compile("(^[\r\n]*|([\\s]))[Oo][Rr][Dd][Ee][Rr][Tt](.*?[^\r\n]*)[Bb][Yy]",Pattern.DOTALL);
3222                         //int startPoint = sql.length()-30;
3223                         
3224                         reportSQL = reportSQL + " ";
3225                         reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ss][Ee][Ll][Ee][Cc][Tt]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" SELECT ");
3226                         //reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ff][Rr][Oo][Mm]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" FROM ");
3227                         reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Rr][Ee]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" WHERE ");
3228                         reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Nn]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" WHEN ");
3229                         reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Aa][Nn][Dd]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" AND ");
3230                         
3231                         if(!reportRuntime.getReportType().equals(AppConstants.RT_HIVE)) {
3232                                 int startPoint = reportSQL.lastIndexOf(" FROM ");
3233                                 if(startPoint <= 0) {
3234                                         startPoint = reportSQL.lastIndexOf(" from ");
3235                                 } 
3236                                 if(startPoint <= 0) {
3237                                         startPoint = reportSQL.lastIndexOf("from ");
3238                                 }
3239                                 if(startPoint <= 0) {
3240                                         startPoint = reportSQL.lastIndexOf("FROM ");
3241                                 }
3242                                 
3243                                 if (!matcher.find(startPoint)) {
3244                                         reportSQL = reportSQL + " ORDER BY 1" ;
3245                                 }
3246                         }
3247                         reportRuntime.setWholeSQL(reportSQL);                   
3248                         
3249                         logger.debug(EELFLoggerDelegate.debugLogger, (" *************************************************************************************** "));
3250                         logger.debug(EELFLoggerDelegate.debugLogger, ("WHOLE_SQL" + reportSQL));
3251                         logger.debug(EELFLoggerDelegate.debugLogger, (" *************************************************************************************** "));
3252                         
3253                         if (reportRuntime.getFormFieldList() != null) {
3254                                 for (Iterator iter = reportRuntime.getFormFieldList().getFormField().iterator(); iter.hasNext();) {
3255                                         FormFieldType fft = (FormFieldType) iter.next();
3256                                         String fieldId = fft.getFieldId();
3257                                         String fieldDisplay = reportRuntime.getFormFieldDisplayName(fft);
3258                                         String formfield_value = "";
3259                                         formfield_value = AppUtils.getRequestNvlValue(request, fieldId);
3260                         String paramValue = nvl(formfield_value);
3261                                 if(paramValue.length()>0) {
3262                                         /*sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl(
3263                                             paramValue, "NULL"));*/
3264                                         reportSQL = Utils.replaceInString(reportSQL,  fieldDisplay, nvl(
3265                                             paramValue, "NULL"));
3266                                 }
3267                                     /*sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl(
3268                                             paramValue, "NULL"));*/
3269                                 reportSQL = Utils.replaceInString(reportSQL, "'" + fieldDisplay + "'", nvl(
3270                                         paramValue, "NULL"));                                           
3271                                 reportSQL = Utils.replaceInString(reportSQL,  fieldDisplay , nvl(
3272                                             paramValue, "NULL"));
3273                                 }
3274                         }                       
3275                 logger.debug(EELFLoggerDelegate.debugLogger, ("SQL " + reportSQL));
3276                         String legendCol = "1 a";
3277                         // String valueCol = "1";
3278                         StringBuffer groupCol = new StringBuffer();
3279                         StringBuffer seriesCol = new StringBuffer();
3280                         StringBuffer valueCols = new StringBuffer();
3281                         
3282                         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3283                                 DataColumnType dc = (DataColumnType) iter.next();
3284                                 String colName = getColumnSelectStr(dc, request);
3285                                 if (nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND))
3286                                         legendCol = getSelectExpr(dc, colName)+" " + dc.getColId();
3287                                 // if(dc.getChartSeq()>0)
3288                                 // valueCol = "NVL("+colName+", 0) "+dc.getColId();
3289                                 if ((!nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND))
3290                                                 && (dc.getChartSeq()!=null &&  dc.getChartSeq().intValue() <= 0) && dc.isGroupBreak()) {
3291                                         groupCol.append(", ");
3292                                         groupCol.append(colName + " " +  dc.getColId());
3293                                 }
3294                         } // for
3295                         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3296                                 DataColumnType dc = (DataColumnType) iter.next();
3297                                 if(dc.isChartSeries()!=null && dc.isChartSeries().booleanValue()) {
3298                                         //System.out.println("*****************, "+ " " +getColumnSelectStr(dc, paramValues)+ " "+ getSelectExpr(dc,getColumnSelectStr(dc, paramValues)));
3299                                         seriesCol.append(", "+ getSelectExpr(dc,getColumnSelectStr(dc, request))+ " " +  dc.getColId());
3300                                 } 
3301                         }
3302
3303                         /*for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3304                                 DataColumnType dc = (DataColumnType) iter.next();
3305                                 if(!dc.isChartSeries() && !(nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND))) {
3306                                         //System.out.println("*****************, "+ " " +getColumnSelectStr(dc, paramValues)+ " "+ getSelectExpr(dc,getColumnSelectStr(dc, paramValues)));
3307                                         seriesCol.append(", "+ formatChartColumn(getSelectExpr(dc,getColumnSelectStr(dc, paramValues)))+ " " +  dc.getColId());
3308                         }
3309                         }*/
3310                         
3311                         for (Iterator iter = chartValueCols.iterator(); iter.hasNext();) {
3312                                 DataColumnType dc = (DataColumnType) iter.next();
3313                                 String colName = getColumnSelectStr(dc, request);
3314                                 String paramValue = "";
3315                                 if(AppUtils.nvl(colName).startsWith("[")) {
3316                                         if (reportRuntime.getFormFieldList() != null) {
3317                                                 for (Iterator iterC = reportRuntime.getFormFieldList().getFormField().iterator(); iterC.hasNext();) {
3318                                                         FormFieldType fft = (FormFieldType) iterC.next();
3319                                                         String fieldId = fft.getFieldId();
3320                                                         String fieldDisplay = reportRuntime.getFormFieldDisplayName(fft);
3321                                                         String formfield_value = "";
3322                                                         if(AppUtils.nvl(fieldDisplay).equals(colName)) {
3323                                                                 formfield_value = AppUtils.getRequestNvlValue(request, fieldId);
3324                                                                 paramValue = nvl(formfield_value);
3325                                                         }
3326                                                 }
3327
3328                                         }
3329                                         
3330                                         seriesCol.append("," + (AppUtils.nvl(paramValue).length()>0? paramValue:"null") + " " + dc.getColId());
3331                                 } else {
3332                                 //valueCols.append(", NVL(" + formatChartColumn(colName) + ",0) " + dc.getColId());
3333                                  seriesCol.append("," + (AppUtils.nvl(paramValue).length()>0? paramValue:formatChartColumn(colName)) + " " + dc.getColId());
3334                                 }
3335                         } // for
3336
3337                         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3338                                 DataColumnType dc = (DataColumnType) iter.next();
3339                                 String colName = dc.getDisplayName();
3340                                 String colValue = getColumnSelectStr(dc, request);
3341                                 //String colName = getColumnSelectStr(dc, formGrid);
3342                                 if(colName.equals(AppConstants.RI_CHART_TOTAL_COL))
3343                                         seriesCol.append(", " + AppConstants.RI_CHART_TOTAL_COL + " " + AppConstants.RI_CHART_TOTAL_COL );
3344                                 if (colName.equals(AppConstants.RI_CHART_COLOR))
3345                                         seriesCol.append(", " + colValue + " " + AppConstants.RI_CHART_COLOR );
3346                                 if(colName.equals(AppConstants.RI_CHART_MARKER_START))
3347                                         seriesCol.append(", " + AppConstants.RI_CHART_MARKER_START + " " + AppConstants.RI_CHART_MARKER_START );
3348                                 if(colName.equals(AppConstants.RI_CHART_MARKER_END))
3349                                         seriesCol.append(", " + AppConstants.RI_CHART_MARKER_END + " " + AppConstants.RI_CHART_MARKER_END );
3350                                 if(colName.equals(AppConstants.RI_CHART_MARKER_TEXT_LEFT))
3351                                         seriesCol.append(", " + AppConstants.RI_CHART_MARKER_TEXT_LEFT + " " + AppConstants.RI_CHART_MARKER_TEXT_LEFT );
3352                                 if(colName.equals(AppConstants.RI_CHART_MARKER_TEXT_RIGHT))
3353                                         seriesCol.append(", " + AppConstants.RI_CHART_MARKER_TEXT_RIGHT + " " + AppConstants.RI_CHART_MARKER_TEXT_RIGHT );
3354                                 //if(colName.equals(AppConstants.RI_ANOMALY_TEXT))
3355                                         //seriesCol.append(", " + AppConstants.RI_ANOMALY_TEXT + " " + AppConstants.RI_ANOMALY_TEXT );
3356                         }
3357                         
3358                  //debugLogger.debug("ReportSQL Chart " + reportSQL );
3359                         /*for (Iterator iter = chartValueCols.iterator(); iter.hasNext();) {
3360                                 DataColumnType dc = (DataColumnType) iter.next();
3361                                 String colName = getColumnSelectStr(dc, paramValues);
3362                                 //valueCols.append(", NVL(" + formatChartColumn(colName) + ",0) " + dc.getColId());
3363                                 valueCols.append("," + formatChartColumn(colName) + " " + dc.getColId());
3364                         } // for
3365                         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3366                                 DataColumnType dc = (DataColumnType) iter.next();
3367                                 String colName = getColumnSelectStr(dc, paramValues);
3368                                 //if(colName.equals(AppConstants.RI_CHART_TOTAL_COL) || colName.equals(AppConstants.RI_CHART_COLOR)) {
3369                                         if(colName.equals(AppConstants.RI_CHART_TOTAL_COL))
3370                                                 valueCols.append(", " + AppConstants.RI_CHART_TOTAL_COL + " " + AppConstants.RI_CHART_TOTAL_COL );
3371                                         if (colName.equals(AppConstants.RI_CHART_COLOR))
3372                                                 valueCols.append(", " + AppConstants.RI_CHART_COLOR + " " + AppConstants.RI_CHART_COLOR );
3373                                         if (colName.equals(AppConstants.RI_CHART_INCLUDE))
3374                                                 valueCols.append(", " + AppConstants.RI_CHART_INCLUDE + " " + AppConstants.RI_CHART_INCLUDE );
3375                                 //}
3376                         }*/
3377                 String final_sql = "";
3378                 reportSQL = Utils.replaceInString(reportSQL, " from ", " FROM ");
3379                 reportSQL = Utils.replaceInString(reportSQL, " From ", " FROM ");
3380                 reportSQL = Utils.replaceInString(reportSQL, " select ", " SELECT ");
3381                 reportSQL = Utils.replaceInString(reportSQL, " union ", " UNION ");
3382                 //reportSQL = reportSQL.replaceAll("[\\s]*\\(", "(");  
3383 //              if(reportSQL.indexOf("UNION") != -1) {
3384 //                  if(reportSQL.indexOf("FROM(")!=-1)
3385 //                      final_sql += " "+reportSQL.substring(reportSQL.indexOf("FROM(") );
3386 //                  else if (reportSQL.indexOf("FROM (")!=-1)
3387 //                      final_sql += " "+reportSQL.substring(reportSQL.indexOf("FROM (") );
3388 //                  //TODO ELSE THROW ERROR
3389 //              }
3390 //              else {
3391 //                  final_sql += " "+reportSQL.substring(reportSQL.toUpperCase().indexOf(" FROM "));
3392 //              }
3393                 int pos = 0;
3394                 int pos_first_select = 0;
3395                 int pos_dup_select = 0;
3396                 int pos_prev_select = 0;
3397                 int pos_last_select = 0;
3398                 if (reportSQL.indexOf("FROM", pos)!=-1) {
3399                     pos = reportSQL.indexOf("FROM", pos);
3400                     pos_dup_select = reportSQL.lastIndexOf("SELECT",pos);
3401                     pos_first_select = reportSQL.indexOf("SELECT");//,pos);
3402                     logger.debug(EELFLoggerDelegate.debugLogger, ("pos_select " + pos_first_select + " " + pos_dup_select));
3403                     if(pos_dup_select > pos_first_select) {
3404                         logger.debug(EELFLoggerDelegate.debugLogger, ("********pos_dup_select ********" + pos_dup_select));
3405                         //pos_dup_select1 =  pos_dup_select;
3406                         pos_prev_select = pos_first_select;
3407                         pos_last_select = pos_dup_select;
3408                         while (pos_last_select > pos_prev_select) {
3409                             logger.debug(EELFLoggerDelegate.debugLogger, ("pos_last , pos_prev " + pos_last_select + " " + pos_prev_select));
3410                             pos = reportSQL.indexOf("FROM", pos+2);
3411                             pos_prev_select = pos_last_select;
3412                             pos_last_select = reportSQL.lastIndexOf("SELECT",pos);
3413                             logger.debug(EELFLoggerDelegate.debugLogger, ("in WHILE LOOP LAST " + pos_last_select));
3414                         }
3415                      }
3416                     
3417                   }
3418                  final_sql += " "+reportSQL.substring(pos);
3419                  logger.debug(EELFLoggerDelegate.debugLogger, ("Final SQL " + final_sql));
3420                  String sql =  "SELECT " + legendCol + ", " + legendCol+"_1" + seriesCol.toString()+ nvl(valueCols.toString(), ", 1")
3421                                         + groupCol.toString()
3422                                         + final_sql;
3423                  logger.debug(EELFLoggerDelegate.debugLogger, ("Final sql in generateChartSQL " +sql));
3424
3425                 return sql;
3426                 } // generateChartSQL           
3427
3428                 private String getColumnSelectStr(DataColumnType dc, HttpServletRequest request) {
3429                         //String colName = dc.isCalculated() ? dc.getColName()
3430                                 //      : ((nvl(dc.getTableId()).length() > 0) ? (dc.getTableId() + "." + dc
3431                                         //              .getColName()) : dc.getColName());
3432                         String colName = dc.getColName();
3433                         String paramValue = null;
3434                         //if (dc.isCalculated()) {
3435                         if (reportRuntime.getFormFieldList() != null) {
3436                                 for (Iterator iter = reportRuntime.getFormFieldList().getFormField().iterator(); iter.hasNext();) {
3437                                         FormFieldType fft = (FormFieldType) iter.next();
3438                                         String fieldId = fft.getFieldId();
3439                                         String fieldDisplay = reportRuntime.getFormFieldDisplayName(fft);
3440                                         String formfield_value = "";
3441                                         formfield_value = AppUtils.getRequestNvlValue(request, fieldId);
3442                         paramValue = nvl(formfield_value);
3443                                 if(paramValue.length()>0) {
3444                                         /*sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl(
3445                                             paramValue, "NULL"));*/
3446                                                         colName = Utils.replaceInString(colName, "'" + fieldDisplay + "'", "'"+nvl(
3447                                              paramValue, "NULL")+"'");
3448                                                         colName = Utils.replaceInString(colName,  fieldDisplay, nvl(
3449                                                                                         paramValue, "NULL"));   
3450                                 }
3451                                 }
3452                                 return colName;
3453                         }                                               
3454                 //}
3455                         return colName;
3456                 } // getColumnSelectStr
3457                 
3458
3459                 
3460                 public String getSelectExpr(DataColumnType dct) {
3461                         // String colName =
3462                         // dct.isCalculated()?dct.getColName():((nvl(dct.getTableId()).length()>0)?(dct.getTableId()+"."+dct.getColName()):dct.getColName());
3463                         return getSelectExpr(dct, dct.getColName() /* colName */);
3464                 } // getSelectExpr
3465
3466                 private String getSelectExpr(DataColumnType dct, String colName) {
3467                         String colType = dct.getColType();
3468                         if (colType.equals(AppConstants.CT_CHAR)
3469                                         || ((nvl(dct.getColFormat()).length() == 0) && (!colType
3470                                                         .equals(AppConstants.CT_DATE))))
3471                                 return colName;
3472                         else
3473                                 return "DATE_FORMAT(" + colName + ", '"
3474                                                 + nvl(dct.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT) + "')";
3475                 } // getSelectExpr
3476                 
3477             private String formatChartColumn(String colName) {
3478                 logger.debug(EELFLoggerDelegate.debugLogger, ("Format Chart Column Input colName " + colName));
3479                 colName =  colName.trim();
3480                 colName = Utils.replaceInString(colName, "TO_CHAR", "to_char");
3481                 colName = Utils.replaceInString(colName, "to_number", "TO_NUMBER");
3482                 //reportSQL = reportSQL.replaceAll("[\\s]*\\(", "(");
3483                 colName = colName.replaceAll(",[\\s]*\\(", ",(");
3484                 StringBuffer colNameBuf = new StringBuffer(colName);
3485                 int pos = 0, posFormatStart = 0, posFormatEnd = 0;
3486                 String format = "";
3487
3488                 if(colNameBuf.indexOf("999")==-1 && colNameBuf.indexOf("990")==-1) {
3489                         logger.debug(EELFLoggerDelegate.debugLogger, (" return colName " + colNameBuf.toString()));
3490                     return colNameBuf.toString();
3491                 }
3492                 
3493                 while (colNameBuf.indexOf("to_char")!=-1) {
3494                     if(colNameBuf.indexOf("999")!=-1 || colNameBuf.indexOf("990")!=-1) {
3495                         pos = colNameBuf.indexOf("to_char");
3496                         colNameBuf.insert(pos, " TO_NUMBER ( CR_RAPTOR.SAFE_TO_NUMBER (");
3497                         pos = colNameBuf.indexOf("to_char");
3498                         colNameBuf.replace(pos, pos+7, "TO_CHAR");
3499                         //colName = Utils.replaceInString(colNameBuf.toString(), "to_char", " TO_NUMBER ( CR_RAPTOR.SAFE_TO_NUMBER ( TO_CHAR ");
3500                         logger.debug(EELFLoggerDelegate.debugLogger, ("After adding to_number " + colNameBuf.toString()));
3501                         //posFormatStart = colNameBuf.lastIndexOf(",'")+1;
3502                         posFormatStart = colNameBuf.indexOf(",'", pos)+1;
3503                         posFormatEnd = colNameBuf.indexOf(")",posFormatStart);
3504                         logger.debug(EELFLoggerDelegate.debugLogger, (posFormatStart + " " + posFormatEnd + " "+ pos));
3505                         format = colNameBuf.substring(posFormatStart, posFormatEnd);
3506                         //posFormatEnd = colNameBuf.indexOf(")",posFormatEnd);
3507                         colNameBuf.insert(posFormatEnd+1, " ," + format + ") , "+ format + ")");
3508                         logger.debug(EELFLoggerDelegate.debugLogger, ("colNameBuf " + colNameBuf.toString()));
3509                     }
3510                 }
3511                 logger.debug(EELFLoggerDelegate.debugLogger, (" return colName " + colNameBuf.toString()));
3512                 return colNameBuf.toString();
3513             }
3514
3515                 public List getChartValueColumnsList( int filter, HashMap formValues) { /*filter; all=0;create without new chart =1; createNewChart=2 */
3516                         List reportCols = reportRuntime.getAllColumns();
3517
3518                         ArrayList chartValueCols = new ArrayList();
3519                         int flag = 0;
3520                         for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
3521                                 flag = 0;
3522                                 DataColumnType dc = (DataColumnType) iter.next();
3523 //                          if(filter == 2 || filter == 1) {
3524                                 flag = reportRuntime.getDependsOnFormFieldFlag(dc, formValues);
3525                                 
3526                                 if( (dc.getChartSeq()!=null &&  dc.getChartSeq()> 0) && flag == 0 && !(nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND))) {
3527                                         if(nvl(dc.getChartGroup()).length()<=0) {
3528                                                 if( filter == 2 && (dc.isCreateInNewChart()!=null && dc.isCreateInNewChart().booleanValue())) {
3529                                                         chartValueCols.add(dc);
3530                                                 } else if (filter == 1 && (dc.isCreateInNewChart()==null || !dc.isCreateInNewChart().booleanValue())) {
3531                                                         chartValueCols.add(dc);
3532                                                 }
3533                                                 else if(filter == 0) chartValueCols.add(dc);
3534                                         } else chartValueCols.add(dc);
3535                                 }
3536 //                              } else
3537 //                                      chartValueCols.add(dc); 
3538                         } // for
3539                         Collections.sort(chartValueCols, new ChartSeqComparator());
3540                         return chartValueCols;
3541                 } // getChartValueColumnsList
3542                  
3543                 public String parseTitle(String title, HashMap formValues) {
3544                         Set set = formValues.entrySet();
3545                         for(Iterator iter = set.iterator(); iter.hasNext(); ) {
3546                                 Map.Entry entry = (Entry<String,String>) iter.next();
3547                                 if(title.indexOf("["+ entry.getKey() + "]")!= -1) {
3548                                         title = Utils.replaceInString(title, "["+entry.getKey()+"]", nvl(
3549                             (String) entry.getValue(), ""));
3550                                 }
3551                         }
3552                         return title;
3553                 }
3554                 
3555        public java.util.Date getDateFromDateStr(String dateStr) {
3556                                 SimpleDateFormat MMDDYYYYFormat                         = new SimpleDateFormat("MM/dd/yyyy");
3557                         SimpleDateFormat EEEMMDDYYYYFormat                      = new SimpleDateFormat("EEE, MM/dd/yyyy"); //2012-11-01 00:00:00
3558                         SimpleDateFormat YYYYMMDDFormat                         = new SimpleDateFormat("yyyy/MM/dd");
3559                         SimpleDateFormat MONYYYYFormat                          = new SimpleDateFormat("MMM yyyy");
3560                         SimpleDateFormat MMYYYYFormat                           = new SimpleDateFormat("MM/yyyy");
3561                         SimpleDateFormat MMMMMDDYYYYFormat                      = new SimpleDateFormat("MMMMM dd, yyyy");
3562                         SimpleDateFormat timestampFormat                        = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
3563                         SimpleDateFormat timestampHrFormat              = new SimpleDateFormat("yyyy-MM-dd HH"); 
3564                         SimpleDateFormat timestampDayFormat             = new SimpleDateFormat("yyyy-MM-dd"); 
3565                         SimpleDateFormat DDMONYYYYFormat                = new SimpleDateFormat("dd-MMM-yyyy");
3566                         SimpleDateFormat MONTHYYYYFormat                = new SimpleDateFormat("MMMMM, yyyy");
3567                         SimpleDateFormat MMDDYYYYHHFormat               = new SimpleDateFormat("MM/dd/yyyy HH");
3568                         SimpleDateFormat MMDDYYYYHHMMSSFormat           = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
3569                         SimpleDateFormat MMDDYYYYHHMMFormat             = new SimpleDateFormat("MM/dd/yyyy HH:mm");        
3570                         SimpleDateFormat YYYYMMDDHHMMSSFormat           = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
3571                         SimpleDateFormat YYYYMMDDHHMMFormat             = new SimpleDateFormat("yyyy/MM/dd HH:mm");
3572                         SimpleDateFormat DDMONYYYYHHMMSSFormat          = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
3573                         SimpleDateFormat DDMONYYYYHHMMFormat            = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
3574                         SimpleDateFormat MMDDYYFormat                           = new SimpleDateFormat("MM/dd/yy");        
3575                         SimpleDateFormat MMDDYYHHMMFormat               = new SimpleDateFormat("MM/dd/yy HH:mm");
3576                         SimpleDateFormat MMDDYYHHMMSSFormat             = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
3577                         SimpleDateFormat timestampFormat1               = new SimpleDateFormat("yyyy-M-d.HH.mm. s. S");
3578                         SimpleDateFormat timestamp_W_dash                       = new SimpleDateFormat("yyyyMMddHHmmss");
3579                         SimpleDateFormat MMDDYYYYHHMMZFormat            = new SimpleDateFormat("MM/dd/yyyy HH:mm z");
3580                         SimpleDateFormat YYYYFormat                             = new SimpleDateFormat("yyyy");                                 
3581                                 java.util.Date date = null;
3582                                 
3583                         int formatFlag = 0;
3584                         
3585                         final int YEARFLAG = 1;
3586                         final int MONTHFLAG = 2;
3587                         final int DAYFLAG = 3;
3588                         final int HOURFLAG = 4;
3589                         final int MINFLAG = 5;
3590                         final int SECFLAG = 6;
3591                         final int MILLISECFLAG = 7;
3592                         final int DAYOFTHEWEEKFLAG = 8;
3593                         final int FLAGDATE = 9;
3594                                 /*int yearFlag                  = 1;
3595                         int monthFlag           = 2;
3596                         int dayFlag             = 3;
3597                         int hourFlag            = 4;
3598                         int minFlag             = 5;
3599                         int secFlag             = 6;
3600                         int milliSecFlag        = 7;
3601                         int dayoftheweekFlag  = 8;                                      
3602                                 int flagDate        = 10;
3603                                 */
3604
3605                                 date = MMDDYYYYHHMMSSFormat.parse(dateStr, new ParsePosition(0));
3606                     if(date!=null) formatFlag = SECFLAG;
3607                     if(date==null) {
3608                         date = EEEMMDDYYYYFormat.parse(dateStr, new ParsePosition(0));
3609                         if(date!=null) formatFlag = DAYOFTHEWEEKFLAG;
3610                     }
3611                     if(date==null) {
3612                         date = MMDDYYYYHHMMFormat.parse(dateStr, new ParsePosition(0));
3613                         if(date!=null) formatFlag = MINFLAG;
3614                     }
3615                     if(date==null) {
3616                         //MMDDYYYYHHFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
3617                         date = MMDDYYYYHHFormat.parse(dateStr, new ParsePosition(0));
3618                         if(date!=null) formatFlag = HOURFLAG;
3619                     }            
3620                     if(date==null) {
3621                         date = MMDDYYYYFormat.parse(dateStr, new ParsePosition(0));
3622                         if(date!=null) formatFlag = DAYFLAG;
3623                     }
3624                     if(date==null) {
3625                         date = YYYYMMDDFormat.parse(dateStr, new ParsePosition(0));
3626                         if(date!=null) formatFlag = DAYFLAG;
3627                     }
3628                     if(date==null) {
3629                         date = timestampFormat.parse(dateStr, new ParsePosition(0));
3630                         if(date!=null) formatFlag = SECFLAG;
3631                     }
3632                     if(date==null) {
3633                         date = timestampHrFormat.parse(dateStr, new ParsePosition(0));
3634                         if(date!=null) formatFlag = HOURFLAG;
3635                     }
3636                     if(date==null) {
3637                         date = timestampDayFormat.parse(dateStr, new ParsePosition(0));
3638                         if(date!=null) formatFlag = DAYFLAG;
3639                     }
3640                     
3641                     if(date==null) { 
3642                         date = MONYYYYFormat.parse(dateStr, new ParsePosition(0));
3643                         if(date!=null) formatFlag = MONTHFLAG;
3644                     }
3645                     if(date==null) { 
3646                         date = MMYYYYFormat.parse(dateStr, new ParsePosition(0));
3647                         if(date!=null) formatFlag = MONTHFLAG;
3648                     }
3649                     if(date==null) { 
3650                         date = MMMMMDDYYYYFormat.parse(dateStr, new ParsePosition(0));
3651                         if(date!=null) formatFlag = DAYFLAG;
3652                     }
3653                     if(date==null) { 
3654                         date = MONTHYYYYFormat.parse(dateStr, new ParsePosition(0));
3655                         if(date!=null) formatFlag = MONTHFLAG;
3656                     }
3657                     
3658                     if(date==null) { 
3659                         date = YYYYMMDDHHMMSSFormat.parse(dateStr, new ParsePosition(0));
3660                         if(date!=null) formatFlag = SECFLAG;
3661                     }
3662                     
3663                     if(date==null) { 
3664                         date = YYYYMMDDHHMMFormat.parse(dateStr, new ParsePosition(0));
3665                         if(date!=null) formatFlag = MINFLAG;
3666                     }
3667                     
3668                     if(date==null) { 
3669                         date = DDMONYYYYHHMMSSFormat.parse(dateStr, new ParsePosition(0));
3670                         if(date!=null) formatFlag = SECFLAG;
3671                     }
3672                     
3673                     if(date==null) { 
3674                         date = DDMONYYYYHHMMFormat.parse(dateStr, new ParsePosition(0));
3675                         if(date!=null) formatFlag = MINFLAG;
3676                     }
3677                     
3678                     if(date==null) { 
3679                         date = DDMONYYYYFormat.parse(dateStr, new ParsePosition(0));
3680                         if(date!=null) formatFlag = DAYFLAG;
3681                     }
3682                     
3683                     if(date==null) { 
3684                         date = MMDDYYHHMMSSFormat.parse(dateStr, new ParsePosition(0));
3685                         if(date!=null) formatFlag = SECFLAG;
3686                     }
3687                     
3688                     if(date==null) { 
3689                         date = MMDDYYHHMMFormat.parse(dateStr, new ParsePosition(0));
3690                         if(date!=null) formatFlag = MINFLAG;
3691                     }
3692                     
3693                     if(date==null) { 
3694                         date = MMDDYYFormat.parse(dateStr, new ParsePosition(0));
3695                         if(date!=null) formatFlag = DAYFLAG;
3696                     }
3697                     
3698                     if(date==null) { 
3699                         date = timestampFormat1.parse(dateStr, new ParsePosition(0));
3700                         if(date!=null) formatFlag = SECFLAG;
3701                     }
3702                     
3703                     if(date==null) {
3704                         date = MMDDYYYYHHMMZFormat.parse(dateStr, new ParsePosition(0));            
3705                         if(date!=null) formatFlag = MINFLAG;
3706                     }
3707                     
3708                     if(date==null) {
3709                         date = YYYYFormat.parse(dateStr, new ParsePosition(0));
3710                         /* Some random numbers should not satisfy this year format. */
3711                         if(dateStr.length()>4) date = null;
3712                         if(date!=null) formatFlag = YEARFLAG;
3713                     }
3714                     if(date==null) {
3715                         date = timestamp_W_dash.parse(dateStr, new ParsePosition(0));            
3716                         if(date!=null) formatFlag = SECFLAG;
3717                     }
3718                     if(date==null)
3719                         date = null;
3720                return date;  
3721        }
3722
3723        public int getFlagFromDateStr(String dateStr) {
3724                                 SimpleDateFormat MMDDYYYYFormat                         = new SimpleDateFormat("MM/dd/yyyy");
3725                         SimpleDateFormat EEEMMDDYYYYFormat                      = new SimpleDateFormat("EEE, MM/dd/yyyy"); //2012-11-01 00:00:00
3726                         SimpleDateFormat YYYYMMDDFormat                         = new SimpleDateFormat("yyyy/MM/dd");
3727                         SimpleDateFormat MONYYYYFormat                          = new SimpleDateFormat("MMM yyyy");
3728                         SimpleDateFormat MMYYYYFormat                           = new SimpleDateFormat("MM/yyyy");
3729                         SimpleDateFormat MMMMMDDYYYYFormat                      = new SimpleDateFormat("MMMMM dd, yyyy");
3730                         SimpleDateFormat timestampFormat                        = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
3731                         SimpleDateFormat timestampHrFormat              = new SimpleDateFormat("yyyy-MM-dd HH");
3732                         SimpleDateFormat timestampDayFormat             = new SimpleDateFormat("yyyy-MM-dd"); 
3733                         SimpleDateFormat DDMONYYYYFormat                = new SimpleDateFormat("dd-MMM-yyyy");
3734                         SimpleDateFormat MONTHYYYYFormat                = new SimpleDateFormat("MMMMM, yyyy");
3735                         SimpleDateFormat MMDDYYYYHHFormat               = new SimpleDateFormat("MM/dd/yyyy HH");
3736                         SimpleDateFormat MMDDYYYYHHMMSSFormat           = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
3737                         SimpleDateFormat MMDDYYYYHHMMFormat             = new SimpleDateFormat("MM/dd/yyyy HH:mm");        
3738                         SimpleDateFormat YYYYMMDDHHMMSSFormat           = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
3739                         SimpleDateFormat YYYYMMDDHHMMFormat             = new SimpleDateFormat("yyyy/MM/dd HH:mm");
3740                         SimpleDateFormat DDMONYYYYHHMMSSFormat          = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
3741                         SimpleDateFormat DDMONYYYYHHMMFormat            = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
3742                         SimpleDateFormat MMDDYYFormat                           = new SimpleDateFormat("MM/dd/yy");        
3743                         SimpleDateFormat MMDDYYHHMMFormat               = new SimpleDateFormat("MM/dd/yy HH:mm");
3744                         SimpleDateFormat MMDDYYHHMMSSFormat             = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
3745                         SimpleDateFormat timestampFormat1               = new SimpleDateFormat("yyyy-M-d.HH.mm. s. S");
3746                         SimpleDateFormat timestamp_W_dash                       = new SimpleDateFormat("yyyyMMddHHmmss");
3747                         SimpleDateFormat MMDDYYYYHHMMZFormat            = new SimpleDateFormat("MM/dd/yyyy HH:mm z");
3748                         SimpleDateFormat YYYYFormat                             = new SimpleDateFormat("yyyy");                                 
3749                                 java.util.Date date = null;
3750                                 
3751                         int formatFlag = 0;
3752                         
3753                         final int YEARFLAG = 1;
3754                         final int MONTHFLAG = 2;
3755                         final int DAYFLAG = 3;
3756                         final int HOURFLAG = 4;
3757                         final int MINFLAG = 5;
3758                         final int SECFLAG = 6;
3759                         final int MILLISECFLAG = 7;
3760                         final int DAYOFTHEWEEKFLAG = 8;
3761                         final int FLAGDATE = 9;
3762                                 /*int yearFlag                  = 1;
3763                         int monthFlag           = 2;
3764                         int dayFlag             = 3;
3765                         int hourFlag            = 4;
3766                         int minFlag             = 5;
3767                         int secFlag             = 6;
3768                         int milliSecFlag        = 7;
3769                         int dayoftheweekFlag  = 8;                                      
3770                                 int flagDate        = 10;
3771                                 */
3772
3773                                 date = MMDDYYYYHHMMSSFormat.parse(dateStr, new ParsePosition(0));
3774                     if(date!=null) formatFlag = SECFLAG;
3775                     if(date==null) {
3776                         date = EEEMMDDYYYYFormat.parse(dateStr, new ParsePosition(0));
3777                         if(date!=null) formatFlag = DAYOFTHEWEEKFLAG;
3778                     }
3779                     if(date==null) {
3780                         date = MMDDYYYYHHMMFormat.parse(dateStr, new ParsePosition(0));
3781                         if(date!=null) formatFlag = MINFLAG;
3782                     }
3783                     if(date==null) {
3784                         //MMDDYYYYHHFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
3785                         date = MMDDYYYYHHFormat.parse(dateStr, new ParsePosition(0));
3786                         if(date!=null) formatFlag = HOURFLAG;
3787                     }            
3788                     if(date==null) {
3789                         date = MMDDYYYYFormat.parse(dateStr, new ParsePosition(0));
3790                         if(date!=null) formatFlag = DAYFLAG;
3791                     }
3792                     if(date==null) {
3793                         date = YYYYMMDDFormat.parse(dateStr, new ParsePosition(0));
3794                         if(date!=null) formatFlag = DAYFLAG;
3795                     }
3796                     if(date==null) {
3797                         date = timestampFormat.parse(dateStr, new ParsePosition(0));
3798                         if(date!=null) formatFlag = SECFLAG;
3799                     }
3800                     if(date==null) {
3801                         date = timestampHrFormat.parse(dateStr, new ParsePosition(0));
3802                         if(date!=null) formatFlag = HOURFLAG;
3803                     }
3804                     if(date==null) {
3805                         date = timestampDayFormat.parse(dateStr, new ParsePosition(0));
3806                         if(date!=null) formatFlag = DAYFLAG;
3807                     }
3808                     if(date==null) { 
3809                         date = MONYYYYFormat.parse(dateStr, new ParsePosition(0));
3810                         if(date!=null) formatFlag = MONTHFLAG;
3811                     }
3812                     if(date==null) { 
3813                         date = MMYYYYFormat.parse(dateStr, new ParsePosition(0));
3814                         if(date!=null) formatFlag = MONTHFLAG;
3815                     }
3816                     if(date==null) { 
3817                         date = MMMMMDDYYYYFormat.parse(dateStr, new ParsePosition(0));
3818                         if(date!=null) formatFlag = DAYFLAG;
3819                     }
3820                     if(date==null) { 
3821                         date = MONTHYYYYFormat.parse(dateStr, new ParsePosition(0));
3822                         if(date!=null) formatFlag = MONTHFLAG;
3823                     }
3824                     
3825                     if(date==null) { 
3826                         date = YYYYMMDDHHMMSSFormat.parse(dateStr, new ParsePosition(0));
3827                         if(date!=null) formatFlag = SECFLAG;
3828                     }
3829                     
3830                     if(date==null) { 
3831                         date = YYYYMMDDHHMMFormat.parse(dateStr, new ParsePosition(0));
3832                         if(date!=null) formatFlag = MINFLAG;
3833                     }
3834                     
3835                     if(date==null) { 
3836                         date = DDMONYYYYHHMMSSFormat.parse(dateStr, new ParsePosition(0));
3837                         if(date!=null) formatFlag = SECFLAG;
3838                     }
3839                     
3840                     if(date==null) { 
3841                         date = DDMONYYYYHHMMFormat.parse(dateStr, new ParsePosition(0));
3842                         if(date!=null) formatFlag = MINFLAG;
3843                     }
3844                     
3845                     if(date==null) { 
3846                         date = DDMONYYYYFormat.parse(dateStr, new ParsePosition(0));
3847                         if(date!=null) formatFlag = DAYFLAG;
3848                     }
3849                     
3850                     if(date==null) { 
3851                         date = MMDDYYHHMMSSFormat.parse(dateStr, new ParsePosition(0));
3852                         if(date!=null) formatFlag = SECFLAG;
3853                     }
3854                     
3855                     if(date==null) { 
3856                         date = MMDDYYHHMMFormat.parse(dateStr, new ParsePosition(0));
3857                         if(date!=null) formatFlag = MINFLAG;
3858                     }
3859                     
3860                     if(date==null) { 
3861                         date = MMDDYYFormat.parse(dateStr, new ParsePosition(0));
3862                         if(date!=null) formatFlag = DAYFLAG;
3863                     }
3864                     
3865                     if(date==null) { 
3866                         date = timestampFormat1.parse(dateStr, new ParsePosition(0));
3867                         if(date!=null) formatFlag = SECFLAG;
3868                     }
3869                     
3870                     if(date==null) {
3871                         date = MMDDYYYYHHMMZFormat.parse(dateStr, new ParsePosition(0));            
3872                         if(date!=null) formatFlag = MINFLAG;
3873                     }
3874                     
3875                     if(date==null) {
3876                         date = YYYYFormat.parse(dateStr, new ParsePosition(0));
3877                         /* Some random numbers should not satisfy this year format. */
3878                         if(dateStr.length()>4) date = null;
3879                         if(date!=null) formatFlag = YEARFLAG;
3880                     }
3881                     if(date==null) {
3882                         date = timestamp_W_dash.parse(dateStr, new ParsePosition(0));            
3883                         if(date!=null) formatFlag = SECFLAG;
3884                     }
3885                     if(date==null)
3886                         date = null;
3887                return formatFlag;  
3888        }
3889
3890        public static String[] reverse(String[] arr) {
3891            List<String> list = Arrays.asList(arr);
3892            Collections.reverse(list);
3893            return (String[])list.toArray();
3894        }
3895        
3896        public int getNumberOfDecimalPlaces(double num) {
3897            Double d = num;
3898            String[] splitter = d.toString().split("\\.");
3899            splitter[0].length();   // Before Decimal Count
3900            splitter[1].length();   // After  Decimal Count
3901            return splitter[1].length();
3902        }
3903        
3904        public boolean getBooleanValue(String s) {
3905          return getBooleanValue(s,null);
3906        }
3907
3908        public boolean getBooleanValue(String s, Boolean defaultValue) {
3909            s = nvl(s);
3910            if(s.length()<=0 && defaultValue!=null) return defaultValue.booleanValue();
3911            else if(s.length()<=0) return false;
3912            else {
3913            if(s.toUpperCase().startsWith("Y") || s.toLowerCase().equals("true"))
3914               return true;
3915            else
3916                    return false;
3917            }
3918        }
3919        
3920        
3921        public String IntToLetter(int Int) {
3922             if (Int<27){
3923               return Character.toString((char)(Int+96));
3924             } else {
3925               if (Int%26==0) {
3926                 return IntToLetter((Int/26)-1)+IntToLetter((Int%26)+1);
3927               } else {
3928                 return IntToLetter(Int/26)+IntToLetter(Int%26);
3929               }
3930             }
3931           }
3932        
3933
3934     
3935        
3936         private void clearReportRuntimeBackup(HttpServletRequest request) {
3937                 //Session sess = Sessions.getCurrent(true)getCurrent();
3938         //HttpSession session = (HttpSession)sess.getNativeSession();
3939         HttpSession session = request.getSession();
3940                 session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST);
3941                 request.removeAttribute(AppConstants.DRILLDOWN_INDEX);
3942                 session.removeAttribute(AppConstants.DRILLDOWN_INDEX);
3943                 request.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX);
3944                 session.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX);
3945                 Enumeration<String> enum1 = session.getAttributeNames();
3946                 String attributeName = "";
3947                 while(enum1.hasMoreElements()) {
3948                         attributeName = enum1.nextElement();
3949                         if(attributeName.startsWith("parent_")) {
3950                                 session.removeAttribute(attributeName);
3951                         }
3952                 }
3953         session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST);
3954                 session.removeAttribute(AppConstants.SI_BACKUP_FOR_REP_ID);
3955                 session.removeAttribute(AppConstants.SI_COLUMN_LOOKUP);
3956         session.removeAttribute(AppConstants.SI_DASHBOARD_REP_ID);
3957         session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP);
3958         session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME);
3959         session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP);
3960         session.removeAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP);
3961                 session.removeAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP);
3962         session.removeAttribute(AppConstants.SI_DATA_SIZE_FOR_TEXTFIELD_POPUP);
3963         session.removeAttribute(AppConstants.SI_MAP);
3964                 session.removeAttribute(AppConstants.SI_MAP_OBJECT);
3965         session.removeAttribute(AppConstants.SI_REPORT_DEFINITION);                     
3966         session.removeAttribute(AppConstants.SI_REPORT_RUNTIME);                        
3967                 session.removeAttribute(AppConstants.SI_REPORT_RUN_BACKUP);
3968         session.removeAttribute(AppConstants.SI_REPORT_SCHEDULE);
3969         session.removeAttribute(AppConstants.RI_REPORT_DATA);
3970         session.removeAttribute(AppConstants.RI_CHART_DATA);
3971         session.removeAttribute(AppConstants.SI_FORMFIELD_INFO);
3972         session.removeAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO);
3973         
3974         } // clearReportRuntimeBackup
3975         
3976         
3977     public static synchronized java.util.HashMap getRequestParametersMap(ReportRuntime rr, HttpServletRequest request)
3978     {
3979         HashMap valuesMap = new HashMap();
3980         
3981                 ReportFormFields rff = rr.getReportFormFields();
3982                 
3983                 int idx = 0;
3984                 FormField ff = null;
3985                 
3986                 Map fieldNameMap = new HashMap();
3987                 int countOfFields = 0 ;
3988                 
3989
3990                 for(rff.resetNext(); rff.hasNext(); idx++) { 
3991                          ff = rff.getNext();
3992                          fieldNameMap.put(ff.getFieldName(), ff.getFieldDisplayName());
3993                          countOfFields++;
3994                 }
3995
3996                 List formParameter = new ArrayList();
3997                 String formField = "";
3998                 for(int i = 0 ; i < rff.size(); i++) {
3999                         ff = ((FormField)rff.getFormField(i));
4000                         formField = ff.getFieldName();
4001                         boolean isMultiValue = false;
4002                         isMultiValue = ff.getFieldType().equals(FormField.FFT_CHECK_BOX)
4003                         || ff.getFieldType().equals(FormField.FFT_LIST_MULTI);
4004                         boolean isTextArea = (ff.getFieldType().equals(FormField.FFT_TEXTAREA) && rr.getReportDefType()
4005                                         .equals(AppConstants.RD_SQL_BASED));
4006
4007                         if(request.getParameterValues(formField) != null && isMultiValue ) {
4008                                         String[] vals = request.getParameterValues(formField);
4009                                         StringBuffer value = new StringBuffer("");
4010                                         if(!AppUtils.getRequestFlag(request, AppConstants.RI_RESET_ACTION)) {
4011
4012                                                 if ( isMultiValue ) {
4013                                                         value.append("(");
4014                                                 }
4015                                                 for(int j = 0 ; j < vals.length; j++) {
4016                                                         if(isMultiValue) value.append("'");
4017                                                         try {
4018                                                                 if(vals[j] !=null && vals[j].length() > 0) {
4019                                                                         vals[j] = Utils.oracleSafe(vals[j]);
4020                                                                         value.append(java.net.URLDecoder.decode(vals[j], "UTF-8"));// + ",";
4021                                                                 }
4022                                                                 else
4023                                                                         value.append(vals[j]);
4024                                                         } catch (UnsupportedEncodingException ex) {value.append(vals[j]);}
4025                                                         catch (IllegalArgumentException ex1){value.append(vals[j]);} 
4026                                                         catch (Exception ex2){
4027                                                                 value.append(vals[j]);
4028                                                         }
4029                 
4030                 
4031                                                         if(isMultiValue) value.append("'"); 
4032                                                         
4033                                                         if(j != vals.length -1) {
4034                                                                 value.append(",");
4035                                                         }
4036                                                 }
4037                                                 if(vals.length > 0) {
4038                                                         value.append(")");
4039                                                 }
4040                                         }
4041                                         
4042                                         //value = value.substring(0 , value.length());  
4043                                  
4044                                  valuesMap.put(fieldNameMap.get(formField), value.toString());
4045                                  value = new StringBuffer("");
4046                     } else if(request.getParameter(formField) != null) {
4047                         if(isTextArea) {
4048                                 String value = "";
4049                                 value = request.getParameter(formField);
4050                                                         
4051                                 value = Utils.oracleSafe(value);
4052                                 value = "('" + Utils.replaceInString(value, ",", "'|'") + "')";
4053                                 value = Utils.replaceInString(value, "|", ",");
4054                                 valuesMap.put(fieldNameMap.get(formField), value);
4055                                 value = "";
4056                         } else { 
4057                                         String value = "";
4058                                         if(!AppUtils.getRequestFlag(request, AppConstants.RI_RESET_ACTION))
4059                                                 value = request.getParameter(formField);
4060                                         valuesMap.put(fieldNameMap.get(formField), Utils.oracleSafe(value));
4061                         }
4062                         
4063                 } else {
4064                         valuesMap.put(fieldNameMap.get(formField), "" );
4065                 }
4066                         
4067         }
4068                 
4069                 return valuesMap;
4070
4071         }       
4072        
4073 }