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