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