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