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