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