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