/* * ================LICENSE_START========================================== * ONAP Portal SDK * ======================================================================= * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. * ======================================================================= * * Unless otherwise specified, all software contained herein is licensed * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * * https://creativecommons.org/licenses/by/4.0/ * * Unless required by applicable law or agreed to in writing, documentation * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ================LICENSE_END============================================ * * */ package org.onap.portalsdk.analytics.model.runtime; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import java.util.TimeZone; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.lang.time.DateUtils; import org.onap.portalsdk.analytics.error.RaptorException; import org.onap.portalsdk.analytics.model.base.ChartSeqComparator; import org.onap.portalsdk.analytics.system.AppUtils; import org.onap.portalsdk.analytics.system.ConnectionUtils; import org.onap.portalsdk.analytics.system.Globals; import org.onap.portalsdk.analytics.util.AppConstants; import org.onap.portalsdk.analytics.util.DataSet; import org.onap.portalsdk.analytics.util.HtmlStripper; import org.onap.portalsdk.analytics.util.Utils; import org.onap.portalsdk.analytics.xmlobj.DataColumnType; import org.onap.portalsdk.analytics.xmlobj.FormFieldType; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.web.support.UserUtils; public class ChartD3Helper { private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ChartD3Helper.class); private ReportRuntime reportRuntime; private String chartType; public static final long HOUR = 3600l*1000l; public static final long DAY = 3600l*1000l*24l; public static final long MONTH = 3600l*1000l*24l*31l; public static final long YEAR = 3600l*1000l*24l*365l; private static final String REPORT_ID = "Report ID : "; private static final String QUERY = "QUERY - "; public ChartD3Helper() { } public ChartD3Helper(ReportRuntime rr) { this.reportRuntime = rr; } private void printDebugLogSeparatorLine() { logger.debug(EELFLoggerDelegate.debugLogger, ("********************************************************************************")); } /** * @return the chartType */ public String getChartType() { return chartType; } /** * @param chartType the chartType to set */ public void setChartType(String chartType) { this.chartType = chartType; } public String createVisualization(ReportRuntime reportRuntime, Map chartOptionsMap, HttpServletRequest request) { boolean isEmbedded = false; if(request.getParameter("embedded")!=null) { isEmbedded = true; } String width = chartOptionsMap.get("width"); String height = chartOptionsMap.get("height"); boolean animation = getBooleanValue(chartOptionsMap.get("animation"), true); String rotateLabels = chartOptionsMap.get("rotateLabels"); boolean staggerLabels = getBooleanValue(chartOptionsMap.get("staggerLabels")); boolean showMaxMin = getBooleanValue(chartOptionsMap.get("showMaxMin"), false); boolean showLegend = getBooleanValue(chartOptionsMap.get("showLegend"), true); boolean showControls = getBooleanValue(chartOptionsMap.get("showControls"), true); String topMargin = chartOptionsMap.get("topMargin"); String bottomMargin = chartOptionsMap.get("bottomMargin"); String leftMargin = chartOptionsMap.get("leftMargin"); String rightMargin = chartOptionsMap.get("rightMargin"); boolean showTitle = getBooleanValue(chartOptionsMap.get("showTitle"), true); String subType = chartOptionsMap.get("subType"); boolean stacked = getBooleanValue(chartOptionsMap.get("stacked"), false); boolean horizontalBar = getBooleanValue(chartOptionsMap.get("horizontalBar"), false); boolean barRealTimeAxis = getBooleanValue(chartOptionsMap.get("barRealTimeAxis"), true); boolean barReduceXAxisLabels= getBooleanValue(chartOptionsMap.get("barReduceXAxisLabels"), false); boolean timeAxis = getBooleanValue(chartOptionsMap.get("timeAxis"), true); boolean logScale = getBooleanValue(chartOptionsMap.get("logScale"), false); int precision = 2; try { precision = Integer.parseInt(chartOptionsMap.get("precision")); } catch (NumberFormatException ex) { logger.debug(EELFLoggerDelegate.debugLogger, ex.getMessage()); } final Long user_id = new Long((long) UserUtils.getUserId(request)); String chartType = reportRuntime.getChartType(); List l = reportRuntime.getAllColumns(); String chartLeftAxisLabel = reportRuntime.getFormFieldFilled(nvl(reportRuntime.getChartLeftAxisLabel())); String chartRightAxisLabel = reportRuntime.getFormFieldFilled(nvl(reportRuntime.getChartRightAxisLabel())); boolean multipleSeries = reportRuntime.isMultiSeries(); java.util.HashMap formValues = null; formValues = getRequestParametersMap(reportRuntime, request); String legendColumnName = (reportRuntime.getChartLegendColumn()!=null)?reportRuntime.getChartLegendColumn().getDisplayName():"Legend Column"; boolean displayChart = (nvl(chartType).length()>0)&&reportRuntime.getDisplayChart(); StringBuilder wholeScript = new StringBuilder(""); String title = reportRuntime.getReportTitle(); //Assigning reportName as title in case of title is blank or null if(title == null || "".equalsIgnoreCase(title)) { title = reportRuntime.getReportName(); } if(title != null) { title = parseTitle(title, formValues); }else { logger.debug(EELFLoggerDelegate.debugLogger, "Report Title is NULL."); } String chartScriptsPath = (isEmbedded?AppUtils.getChartScriptsPath(""):AppUtils.getChartScriptsPath()); if(displayChart) { DataSet ds = null; try { if (!(chartType.equals(AppConstants.GT_HIERARCHICAL) || chartType.equals(AppConstants.GT_HIERARCHICAL_SUNBURST) || chartType.equals(AppConstants.GT_ANNOTATION_CHART))) { ds = loadChartData(Long.toString(user_id), request); } else if(chartType.equals(AppConstants.GT_ANNOTATION_CHART)) { String reportSQL = reportRuntime.getWholeSQL(); String dbInfo = reportRuntime.getDBInfo(); ds = ConnectionUtils.getDataSet(reportSQL, dbInfo); if(ds.getRowCount()<=0) { printDebugLogSeparatorLine(); logger.debug(EELFLoggerDelegate.debugLogger, (chartType.toUpperCase()+" - " + REPORT_ID + reportRuntime.getReportID() + " DATA IS EMPTY")); logger.debug(EELFLoggerDelegate.debugLogger, (QUERY + reportSQL)); printDebugLogSeparatorLine(); } } else if(chartType.equals(AppConstants.GT_HIERARCHICAL)||chartType.equals(AppConstants.GT_HIERARCHICAL_SUNBURST)) { String reportSQL = reportRuntime.getWholeSQL(); String dbInfo = reportRuntime.getDBInfo(); ds = ConnectionUtils.getDataSet(reportSQL, dbInfo); } } catch (RaptorException ex) { printDebugLogSeparatorLine(); logger.error(EELFLoggerDelegate.debugLogger, (chartType.toUpperCase()+" - " + REPORT_ID + reportRuntime.getReportID() + " ERROR THROWN FOR GIVEN QUERY ")); logger.error(EELFLoggerDelegate.debugLogger, (QUERY + reportRuntime.getWholeSQL())); logger.error(EELFLoggerDelegate.debugLogger, ("ERROR STACK TRACE" + ex.getMessage())); printDebugLogSeparatorLine(); } if(ds==null) { if(chartType.equals(AppConstants.GT_ANNOTATION_CHART)) ds = new DataSet(); else displayChart = false; } if(displayChart) { if (chartType.equals(AppConstants.GT_BAR_3D)) { // get category if not give the column name for the data column use this to develop series. boolean hasCategoryAxis = reportRuntime.hasSeriesColumn(); boolean hasCustomizedChartColor = false; int flag = 0; flag = hasCategoryAxis?1:0; Object[] uniqueElements = null; ArrayList uniqueElementsList = new ArrayList(); Object[] uniqueXAxisElements = null; ArrayList ts = new ArrayList(); ArrayList ts1 = new ArrayList(); HashMap columnMap = new HashMap(); String uniqueXAxisStr = ""; if(!timeAxis){ for (int i = 0; i < ds.getRowCount(); i++) { uniqueXAxisStr = ds.getString(i, 0); ts1.add(uniqueXAxisStr); } } uniqueElementsList.addAll(ts1); uniqueXAxisElements = ts1.toArray(); if(flag == 1) { StringBuilder catStr; String color=""; for (int i = 0; i < ds.getRowCount(); i++) { catStr = new StringBuilder(""); catStr.append(ds.getString(i, 2)); try { if(ds.getString(i, "chart_color")!=null) { color = ds.getString(i, "chart_color"); hasCustomizedChartColor = true; catStr.append("|"+color); } } catch (ArrayIndexOutOfBoundsException ex) { logger.debug(EELFLoggerDelegate.debugLogger, ex.getMessage()); } if(catStr.length()>0) { //duplicates are avoided if(!ts.contains(catStr.toString())) ts.add(catStr.toString()); } /* Get Chart LeftAxis Label even from Range Axis definition. */ DataColumnType dct = null; for (Iterator iter = l.iterator(); iter.hasNext();) { dct = (DataColumnType) iter.next(); if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) { if(nvl(chartLeftAxisLabel).length()<=0) { chartLeftAxisLabel = nvl(dct.getYAxis()); chartLeftAxisLabel = (chartLeftAxisLabel.indexOf("|")!=-1)?chartLeftAxisLabel.substring(0,chartLeftAxisLabel.indexOf("|")):""; } } } } uniqueElements = ts.toArray(); } else { DataColumnType dct = null; List yTextSeries = reportRuntime.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues); for (Iterator iter = l.iterator(); iter.hasNext();) { dct = (DataColumnType) iter.next(); if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) { if((dct.isChartSeries()!=null && dct.isChartSeries().booleanValue()) || (dct.getChartSeq()!=null && dct.getChartSeq()>0) ) { if(nvl(dct.getChartColor()).length()>0) hasCustomizedChartColor = true; if(hasCustomizedChartColor) { //duplicates are avoided if(!ts.contains(dct.getDisplayName()+"|"+nvl(dct.getChartColor()))) ts.add(dct.getDisplayName()+"|"+nvl(dct.getChartColor())); } else { //duplicates are avoided if(!ts.contains(dct.getDisplayName())) ts.add(dct.getDisplayName()); } if(nvl(chartLeftAxisLabel).length()<=0) { chartLeftAxisLabel = nvl(dct.getYAxis()); chartLeftAxisLabel = (chartLeftAxisLabel.indexOf("|")!=-1)?chartLeftAxisLabel.substring(0,chartLeftAxisLabel.indexOf("|")):""; } columnMap.put(dct.getDisplayName(), dct.getColId()); } } } uniqueElements = ts.toArray(); } wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append("\n"); //wholeScript.append("") wholeScript.append(" \n" ); wholeScript.append(" \n"); if(showTitle) wholeScript.append("

" + title +"

"); wholeScript.append("
\n"); //js files wholeScript.append(""); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); //json wholeScript.append(" \n"); } else if (chartType.equals(AppConstants.GT_TIME_SERIES)) { // get category if not give the column name for the data column use this to develop series. boolean hasCategoryAxis = reportRuntime.hasSeriesColumn(); final int YEARFLAG = 1; final int MONTHFLAG = 2; final int DAYFLAG = 3; final int HOURFLAG = 4; final int MINFLAG = 5; final int SECFLAG = 6; final int MILLISECFLAG = 7; final int DAYOFTHEWEEKFLAG = 8; final int FLAGDATE = 9; int flag = 0; flag = hasCategoryAxis?1:0; String uniqueElements [] = null; ArrayList ts = new ArrayList(); HashMap columnMap = new HashMap(); //check timeAxis String dateStr = null; java.util.Date date = null; if( ds.getRowCount() > 0) { dateStr = ds.getString(0, 1); if(!timeAxis) { date = getDateFromDateStr(dateStr); if(date!=null) { reportRuntime.setTimeAxis(true); timeAxis = reportRuntime.isTimeAxis(); } } } ArrayList ts1 = new ArrayList(); ArrayList uniqueElementsList = new ArrayList(); Object uniqueXAxisElements[] = null; String uniqueXAxisStr = ""; if(!timeAxis){ for (int i = 0; i < ds.getRowCount(); i++) { uniqueXAxisStr = ds.getString(i, 0); ts1.add(uniqueXAxisStr); } } uniqueElementsList.addAll(ts1); uniqueXAxisElements = ts1.toArray(); //test start //test end boolean hasCustomizedChartColor = false; if(flag == 1) { StringBuffer catStr = new StringBuffer(""); String color=""; for (int i = 0; i < ds.getRowCount(); i++) { catStr = new StringBuffer(""); catStr.append(ds.getString(i, 2)); try { if(ds.getString(i, "chart_color")!=null) { color = ds.getString(i, "chart_color"); hasCustomizedChartColor = true; catStr.append("|"+color); } } catch (ArrayIndexOutOfBoundsException ex) { } if(catStr.length()>0) { //duplicates are avoided if(!ts.contains(catStr.toString())) ts.add(catStr.toString()); } } DataColumnType dct = null; List yTextSeries = reportRuntime.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues); if(yTextSeries.size()==1) { for (Iterator iter = l.iterator(); iter.hasNext();) { dct = (DataColumnType) iter.next(); if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) { if(nvl(chartLeftAxisLabel).length()<=0) { chartLeftAxisLabel = nvl(dct.getYAxis()); chartLeftAxisLabel = (chartLeftAxisLabel.indexOf("|")!=-1)?chartLeftAxisLabel.substring(0,chartLeftAxisLabel.indexOf("|")):""; } } } } Object tempArray[] = ts.toArray(); uniqueElements = Arrays.copyOf(tempArray, tempArray.length, String[].class); } else { DataColumnType dct = null; List yTextSeries = reportRuntime.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues); int dctIndex = 0; for (Iterator iter = l.iterator(); iter.hasNext();) { dct = (DataColumnType) iter.next(); if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) { if(yTextSeries.contains((String)dct.getDisplayName())) { if(nvl(dct.getChartColor()).length()>0) hasCustomizedChartColor = true; if(hasCustomizedChartColor) { //duplicates are avoided if(!ts.contains(dct.getDisplayName()+"|"+nvl(dct.getChartColor()))) ts.add(dct.getDisplayName()+"|"+nvl(dct.getChartColor())); } else { //duplicates are avoided if(!ts.contains(dct.getDisplayName())) ts.add(dct.getDisplayName()); } if(nvl(chartLeftAxisLabel).length()<=0) { chartLeftAxisLabel = nvl(dct.getYAxis()); chartLeftAxisLabel = (chartLeftAxisLabel.indexOf("|")!=-1)?chartLeftAxisLabel.substring(0,chartLeftAxisLabel.indexOf("|")):""; } if(nvl(chartRightAxisLabel).length()>0) { String dctYAxis = nvl(dct.getYAxis()); String yAxis = (dctYAxis.indexOf("|")!=-1)?dctYAxis.substring(0,dctYAxis.indexOf("|")):dctYAxis; if(chartRightAxisLabel.equals(yAxis)) { if(ts.contains(dct.getDisplayName())) { if(hasCustomizedChartColor) { ts.set(dctIndex, dct.getDisplayName()+"|R|"+nvl(dct.getChartColor())); } else { ts.set(dctIndex, dct.getDisplayName()+"|R"); } } } } columnMap.put(dct.getDisplayName(), dct.getColId()); } dctIndex++; } } Object tempArray[] = ts.toArray(); uniqueElements = Arrays.copyOf(tempArray, tempArray.length, String[].class); } wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append(" \n" ); wholeScript.append(" \n"); if(showTitle) wholeScript.append("

" + title +"

"); wholeScript.append("
\n"); //js files wholeScript.append("\n"); wholeScript.append(" \n"); wholeScript.append(" \n"); //json wholeScript.append(" \n"); } else if (chartType.equals(AppConstants.GT_PIE) || chartType.equals(AppConstants.GT_PIE_3D)) { wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append(" \n" ); wholeScript.append(" \n"); if(showTitle) wholeScript.append("

" + title +"

"); wholeScript.append("
"); //"\n"); //js files wholeScript.append("\n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); } else if (chartType.equals(AppConstants.GT_ANNOTATION_CHART) || chartType.equals(AppConstants.GT_FLEX_TIME_CHARTS)) { boolean timeCharts = chartType.equals(AppConstants.GT_FLEX_TIME_CHARTS); String dateStr = null; java.util.Date date = null; final int YEARFLAG = 1; final int MONTHFLAG = 2; final int DAYFLAG = 3; final int HOURFLAG = 4; final int MINFLAG = 5; final int SECFLAG = 6; final int MILLISECFLAG = 7; final int DAYOFTHEWEEKFLAG = 8; final int FLAGDATE = 9; int flagNoDate = 0; int MAXNUM = 0; int YAXISNUM = 0; int flagNull = 0; double YAXISDOUBLENUM = 0.0; double MAXDOUBLENUM = 0.0; int MAXNUMDECIMALPLACES = 0; int formatFlag = 0; TreeSet dateStrList = new TreeSet<>(); // added to store all date elements SortedSet sortSet = new TreeSet<>(); int count = 0; int flag = 0; boolean hasCategoryAxis = reportRuntime.hasSeriesColumn(); flag = hasCategoryAxis?1:0; String anomalyText = ""; StringBuffer dataStrBuf = new StringBuffer(""); StringBuffer annotationsStrBuf = new StringBuffer(""); String xAxisLabel = (reportRuntime.getChartLegendColumn()!=null)?reportRuntime.getChartLegendColumn().getDisplayName():""; //finding actual string String actualText = ""; DataColumnType dct = null; for (Iterator iter = l.iterator(); iter.hasNext();) { dct = (DataColumnType) iter.next(); if((dct.getChartSeq()!=null && dct.getChartSeq() >=0) && !AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND)) { //if(AppUtils.nvl(dct.getDisplayName()).toLowerCase().contains("actual")) { actualText = dct.getDisplayName(); break; //} } } int anomalyRec = 0; int columnIndex = 1; ArrayList columnNames = new ArrayList(); ArrayList columnValues = new ArrayList(); Set set = null; String columnName = ""; String columnValue = ""; long minDate = 0L; long maxDate = 0L; StringBuffer seriesBuffer = new StringBuffer(""); for (int i = 0; i < ds.getRowCount(); i++) { columnNames = new ArrayList(); columnValues = new ArrayList(); columnName = ""; columnValue = ""; columnIndex = 1; anomalyText = ""; dateStr = ds.getString(i, 0); date = getDateFromDateStr(dateStr); if(date.getTime() > maxDate ) maxDate = date.getTime(); formatFlag = getFlagFromDateStr(dateStr); for (;columnIndex=0) && !AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND)) { if((!timeCharts && !AppUtils.nvl(dct.getColId()).toLowerCase().equals("anomaly_text")) && AppUtils.nvl(dct.getColId()).toLowerCase().equals(columnName.toLowerCase())) { dataStrBuf.append(","+columnValue); break; } else if(timeCharts && AppUtils.nvl(dct.getColId()).toLowerCase().equals(columnName.toLowerCase())){ dataStrBuf.append(","+columnValue); //break; } } } } dataStrBuf.append("],\n"); if(!timeCharts) { if(AppUtils.nvl(anomalyText).length()>0) { ++anomalyRec; annotationsStrBuf.append("anns.push( {\n"); annotationsStrBuf.append(" series: '"+actualText+"',\n"); annotationsStrBuf.append(" x: moment(\""+dateStr+"\"),\n"); annotationsStrBuf.append(" shortText: '"+ IntToLetter(anomalyRec).toUpperCase() +"',\n"); annotationsStrBuf.append(" text: '"+ anomalyText + "'\n"); annotationsStrBuf.append("});\n"); //anomalyRec++; } } } minDate = maxDate - (new Long(reportRuntime.getZoomIn()).longValue()*60*60*1000); System.out.println(new java.util.Date(maxDate) + " " + new java.util.Date(minDate) + " " + reportRuntime.getZoomIn()); if(dataStrBuf.lastIndexOf(",")!= -1) dataStrBuf.deleteCharAt(dataStrBuf.lastIndexOf(",")); wholeScript = new StringBuilder(""); wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append(" \n"); wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append("\n "); wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append(" \n"); /* if(showTitle) wholeScript.append("

" + (AppUtils.nvl(reportRuntime.getReportTitle()).length()>0?reportRuntime.getReportTitle():reportRuntime.getReportName()) + "

\n"); */ wholeScript.append(" \n"); if(showTitle) { wholeScript.append(" \n "); wholeScript.append(" \n "); } wholeScript.append(" \n "); wholeScript.append(" \n "); wholeScript.append(" \n "); wholeScript.append(" \n "); wholeScript.append(" \n"); wholeScript.append(" \n"); if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) { wholeScript.append(" \n"); } wholeScript.append(" \n"); if(anomalyRec > 0) { wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); } wholeScript.append("
\n "); wholeScript.append("
"+title+"
\n"); wholeScript.append("
\n "); if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()<=0 || reportRuntime.getLegendPosition().equals("top")) { wholeScript.append("
\n"); } wholeScript.append("
\n"); wholeScript.append("
\n"); int heightInt = 0; if(nvl(height).length() > 0) { try { heightInt = new Integer(height).intValue(); heightInt -= 50; } catch(Exception ex) { if(height.endsWith("px")) { try { heightInt = new Integer(height.substring(0, height.indexOf("px"))); heightInt -= 50; } catch (Exception ex1) { heightInt = 420; } } else { heightInt = 420; } } } else heightInt = 420; if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) { wholeScript.append("
\n"); wholeScript.append("
\n"); wholeScript.append("
\n"); wholeScript.append("
\n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n" ); wholeScript.append(" \n"); wholeScript.append("
Anomaly Description
\n"); wholeScript.append("
\n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(""); } else if (chartType.equals(AppConstants.GT_SCATTER)) { wholeScript.append("\n"); wholeScript.append(" \n" ); wholeScript.append(" \n"); wholeScript.append("
"); //js files wholeScript.append("\n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append(" \n"); wholeScript.append("\n"); } else if (chartType.equals(AppConstants.GT_HIERARCHICAL_SUNBURST)) { StringBuilder dataStr = new StringBuilder(""); StringBuilder groupBuffer = new StringBuilder(""); StringBuilder s = new StringBuilder(""); dataStr.append("{"); dataStr.append(" \"xxxxxx\":{\n"); String mid = ""; String midOld = ""; String level = "-1"; String levelOld = "-1"; String eid = ""; for (int i = 0; i < ds.getRowCount(); i++) { mid = ds.getString(i, "mid"); level = ds.getString(i, "level1"); eid = ds.getString(i, "eid"); if(mid.equals(midOld)) { dataStr.append("\""+ eid +"\": 9956,\n"); } else { if(dataStr.lastIndexOf(",")!= -1) dataStr.deleteCharAt(dataStr.lastIndexOf(",")); //if(Integer.parseInt(levelOld)==Integer.parseInt(level)) //dataStr.append("},\n"); if (Integer.parseInt(levelOld) 0) { out.write(wholeScript.toString()); }else { wholeScript = new StringBuilder(""); wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append(" \n"); wholeScript.append("\n"); wholeScript.append("\n"); wholeScript.append(" \n"); wholeScript.append("

No Chart has been configured. Kindly go to Chart Wizard and configure your Chart.

"); wholeScript.append(" \n"); out.write(wholeScript.toString()); } } catch (IOException e) { e.printStackTrace(); System.out.println("Exception "); } return wholeScript.toString(); } public String nvl(String s) { return (s == null) ? "" : s; } public String nvl(String s, String sDefault) { return nvl(s).equals("") ? sDefault : s; } public static String nvls(String s) { return (s == null) ? "" : s; } public static String nvls(String s, String sDefault) { return nvls(s).equals("") ? sDefault : s; } public boolean getFlagInBoolean(String s) { return nvl(s).toUpperCase().startsWith("Y") || nvl(s).toLowerCase().equals("true"); } public DataSet loadChartData(String userId, HttpServletRequest request) throws RaptorException { if (nvl(getChartType()).length() == 0) return null; //TODO: display chart function to be added. //if (!getDisplayChart()) // return null; String sql = null; sql = generateChartSQL(userId, request); logger.debug(EELFLoggerDelegate.debugLogger, ("SQL generated " + sql)); String dbInfo = reportRuntime.getDBInfo(); DataSet ds = ConnectionUtils.getDataSet(sql, dbInfo); if(ds.getRowCount()<=0) { printDebugLogSeparatorLine(); logger.debug(EELFLoggerDelegate.debugLogger, (getChartType().toUpperCase()+" - " + REPORT_ID + reportRuntime.getReportID() + " DATA IS EMPTY" )); logger.debug(EELFLoggerDelegate.debugLogger, (QUERY + sql)); printDebugLogSeparatorLine(); } return ds; } // loadChartData public String generateChartSQL(String userId, HttpServletRequest request ) throws RaptorException { List reportCols = reportRuntime.getAllColumns(); List chartValueCols = getChartValueColumnsList(AppConstants.CHART_ALL_COLUMNS, null); // parameter is 0 has this requires all columns. String reportSQL = reportRuntime.getWholeSQL(); //Add order by clause Pattern re1 = Pattern.compile("(^[\r\n]*|([\\s]))[Oo][Rr][Dd][Ee][Rr](.*?[^\r\n]*)[Bb][Yy]",Pattern.DOTALL); //Pattern re1 = Pattern.compile("order(.*?[^\r\n]*)by", Pattern.DOTALL); Matcher matcher = re1.matcher(reportSQL); //Pattern re1 = Pattern.compile("(^[\r\n]*|([\\s]))[Oo][Rr][Dd][Ee][Rr][Tt](.*?[^\r\n]*)[Bb][Yy]",Pattern.DOTALL); //int startPoint = sql.length()-30; reportSQL = reportSQL + " "; reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ss][Ee][Ll][Ee][Cc][Tt]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" SELECT "); //reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ff][Rr][Oo][Mm]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" FROM "); reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Rr][Ee]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" WHERE "); reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Nn]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" WHEN "); reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Aa][Nn][Dd]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" AND "); if(!reportRuntime.getReportType().equals(AppConstants.RT_HIVE)) { int startPoint = reportSQL.lastIndexOf(" FROM "); if(startPoint <= 0) { startPoint = reportSQL.lastIndexOf(" from "); } if(startPoint <= 0) { startPoint = reportSQL.lastIndexOf("from "); } if(startPoint <= 0) { startPoint = reportSQL.lastIndexOf("FROM "); } if (!matcher.find(startPoint)) { reportSQL = reportSQL + " ORDER BY 1" ; } } reportRuntime.setWholeSQL(reportSQL); printDebugLogSeparatorLine(); logger.debug(EELFLoggerDelegate.debugLogger, ("WHOLE_SQL" + reportSQL)); printDebugLogSeparatorLine(); if (reportRuntime.getFormFieldList() != null) { for (Iterator iter = reportRuntime.getFormFieldList().getFormField().iterator(); iter.hasNext();) { FormFieldType fft = (FormFieldType) iter.next(); String fieldId = fft.getFieldId(); String fieldDisplay = reportRuntime.getFormFieldDisplayName(fft); String formfield_value = ""; formfield_value = AppUtils.getRequestNvlValue(request, fieldId); String paramValue = nvl(formfield_value); if(paramValue.length()>0) { /*sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl( paramValue, "NULL"));*/ reportSQL = Utils.replaceInString(reportSQL, fieldDisplay, nvl( paramValue, "NULL")); } /*sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl( paramValue, "NULL"));*/ reportSQL = Utils.replaceInString(reportSQL, "'" + fieldDisplay + "'", nvl( paramValue, "NULL")); reportSQL = Utils.replaceInString(reportSQL, fieldDisplay , nvl( paramValue, "NULL")); } } logger.debug(EELFLoggerDelegate.debugLogger, ("SQL " + reportSQL)); String legendCol = "1 a"; // String valueCol = "1"; StringBuilder groupCol = new StringBuilder(); StringBuilder seriesCol = new StringBuilder(); StringBuilder valueCols = new StringBuilder(); for (Iterator iter = reportCols.iterator(); iter.hasNext();) { DataColumnType dc = (DataColumnType) iter.next(); String colName = getColumnSelectStr(dc, request); if (nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND)) legendCol = getSelectExpr(dc, colName)+" " + dc.getColId(); // if(dc.getChartSeq()>0) // valueCol = "NVL("+colName+", 0) "+dc.getColId(); if ((!nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND)) && (dc.getChartSeq()!=null && dc.getChartSeq().intValue() <= 0) && dc.isGroupBreak()) { groupCol.append(", "); groupCol.append(colName + " " + dc.getColId()); } } // for for (Iterator iter = reportCols.iterator(); iter.hasNext();) { DataColumnType dc = (DataColumnType) iter.next(); if(dc.isChartSeries()!=null && dc.isChartSeries().booleanValue()) { //System.out.println("*****************, "+ " " +getColumnSelectStr(dc, paramValues)+ " "+ getSelectExpr(dc,getColumnSelectStr(dc, paramValues))); seriesCol.append(", "+ getSelectExpr(dc,getColumnSelectStr(dc, request))+ " " + dc.getColId()); } } /*for (Iterator iter = reportCols.iterator(); iter.hasNext();) { DataColumnType dc = (DataColumnType) iter.next(); if(!dc.isChartSeries() && !(nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND))) { //System.out.println("*****************, "+ " " +getColumnSelectStr(dc, paramValues)+ " "+ getSelectExpr(dc,getColumnSelectStr(dc, paramValues))); seriesCol.append(", "+ formatChartColumn(getSelectExpr(dc,getColumnSelectStr(dc, paramValues)))+ " " + dc.getColId()); } }*/ for (Iterator iter = chartValueCols.iterator(); iter.hasNext();) { DataColumnType dc = (DataColumnType) iter.next(); String colName = getColumnSelectStr(dc, request); String paramValue = ""; if(AppUtils.nvl(colName).startsWith("[")) { if (reportRuntime.getFormFieldList() != null) { for (Iterator iterC = reportRuntime.getFormFieldList().getFormField().iterator(); iterC.hasNext();) { FormFieldType fft = (FormFieldType) iterC.next(); String fieldId = fft.getFieldId(); String fieldDisplay = reportRuntime.getFormFieldDisplayName(fft); String formfield_value = ""; if(AppUtils.nvl(fieldDisplay).equals(colName)) { formfield_value = AppUtils.getRequestNvlValue(request, fieldId); paramValue = nvl(formfield_value); } } } seriesCol.append("," + (AppUtils.nvl(paramValue).length()>0? paramValue:"null") + " " + dc.getColId()); } else { //valueCols.append(", NVL(" + formatChartColumn(colName) + ",0) " + dc.getColId()); seriesCol.append("," + (AppUtils.nvl(paramValue).length()>0? paramValue:formatChartColumn(colName)) + " " + dc.getColId()); } } // for for (Iterator iter = reportCols.iterator(); iter.hasNext();) { DataColumnType dc = (DataColumnType) iter.next(); String colName = dc.getDisplayName(); String colValue = getColumnSelectStr(dc, request); //String colName = getColumnSelectStr(dc, formGrid); if(colName.equals(AppConstants.RI_CHART_TOTAL_COL)) seriesCol.append(", " + AppConstants.RI_CHART_TOTAL_COL + " " + AppConstants.RI_CHART_TOTAL_COL ); if (colName.equals(AppConstants.RI_CHART_COLOR)) seriesCol.append(", " + colValue + " " + AppConstants.RI_CHART_COLOR ); if(colName.equals(AppConstants.RI_CHART_MARKER_START)) seriesCol.append(", " + AppConstants.RI_CHART_MARKER_START + " " + AppConstants.RI_CHART_MARKER_START ); if(colName.equals(AppConstants.RI_CHART_MARKER_END)) seriesCol.append(", " + AppConstants.RI_CHART_MARKER_END + " " + AppConstants.RI_CHART_MARKER_END ); if(colName.equals(AppConstants.RI_CHART_MARKER_TEXT_LEFT)) seriesCol.append(", " + AppConstants.RI_CHART_MARKER_TEXT_LEFT + " " + AppConstants.RI_CHART_MARKER_TEXT_LEFT ); if(colName.equals(AppConstants.RI_CHART_MARKER_TEXT_RIGHT)) seriesCol.append(", " + AppConstants.RI_CHART_MARKER_TEXT_RIGHT + " " + AppConstants.RI_CHART_MARKER_TEXT_RIGHT ); //if(colName.equals(AppConstants.RI_ANOMALY_TEXT)) //seriesCol.append(", " + AppConstants.RI_ANOMALY_TEXT + " " + AppConstants.RI_ANOMALY_TEXT ); } //debugLogger.debug("ReportSQL Chart " + reportSQL ); /*for (Iterator iter = chartValueCols.iterator(); iter.hasNext();) { DataColumnType dc = (DataColumnType) iter.next(); String colName = getColumnSelectStr(dc, paramValues); //valueCols.append(", NVL(" + formatChartColumn(colName) + ",0) " + dc.getColId()); valueCols.append("," + formatChartColumn(colName) + " " + dc.getColId()); } // for for (Iterator iter = reportCols.iterator(); iter.hasNext();) { DataColumnType dc = (DataColumnType) iter.next(); String colName = getColumnSelectStr(dc, paramValues); //if(colName.equals(AppConstants.RI_CHART_TOTAL_COL) || colName.equals(AppConstants.RI_CHART_COLOR)) { if(colName.equals(AppConstants.RI_CHART_TOTAL_COL)) valueCols.append(", " + AppConstants.RI_CHART_TOTAL_COL + " " + AppConstants.RI_CHART_TOTAL_COL ); if (colName.equals(AppConstants.RI_CHART_COLOR)) valueCols.append(", " + AppConstants.RI_CHART_COLOR + " " + AppConstants.RI_CHART_COLOR ); if (colName.equals(AppConstants.RI_CHART_INCLUDE)) valueCols.append(", " + AppConstants.RI_CHART_INCLUDE + " " + AppConstants.RI_CHART_INCLUDE ); //} }*/ String final_sql = ""; reportSQL = Utils.replaceInString(reportSQL, " from ", " FROM "); reportSQL = Utils.replaceInString(reportSQL, " From ", " FROM "); reportSQL = Utils.replaceInString(reportSQL, " select ", " SELECT "); reportSQL = Utils.replaceInString(reportSQL, " union ", " UNION "); //reportSQL = reportSQL.replaceAll("[\\s]*\\(", "("); // if(reportSQL.indexOf("UNION") != -1) { // if(reportSQL.indexOf("FROM(")!=-1) // final_sql += " "+reportSQL.substring(reportSQL.indexOf("FROM(") ); // else if (reportSQL.indexOf("FROM (")!=-1) // final_sql += " "+reportSQL.substring(reportSQL.indexOf("FROM (") ); // //TODO ELSE THROW ERROR // } // else { // final_sql += " "+reportSQL.substring(reportSQL.toUpperCase().indexOf(" FROM ")); // } int pos = 0; int pos_first_select = 0; int pos_dup_select = 0; int pos_prev_select = 0; int pos_last_select = 0; if (reportSQL.indexOf("FROM", pos)!=-1) { pos = reportSQL.indexOf("FROM", pos); pos_dup_select = reportSQL.lastIndexOf("SELECT",pos); pos_first_select = reportSQL.indexOf("SELECT");//,pos); logger.debug(EELFLoggerDelegate.debugLogger, ("pos_select " + pos_first_select + " " + pos_dup_select)); if(pos_dup_select > pos_first_select) { logger.debug(EELFLoggerDelegate.debugLogger, ("********pos_dup_select ********" + pos_dup_select)); //pos_dup_select1 = pos_dup_select; pos_prev_select = pos_first_select; pos_last_select = pos_dup_select; while (pos_last_select > pos_prev_select) { logger.debug(EELFLoggerDelegate.debugLogger, ("pos_last , pos_prev " + pos_last_select + " " + pos_prev_select)); pos = reportSQL.indexOf("FROM", pos+2); pos_prev_select = pos_last_select; pos_last_select = reportSQL.lastIndexOf("SELECT",pos); logger.debug(EELFLoggerDelegate.debugLogger, ("in WHILE LOOP LAST " + pos_last_select)); } } } final_sql += " "+reportSQL.substring(pos); logger.debug(EELFLoggerDelegate.debugLogger, ("Final SQL " + final_sql)); String sql = "SELECT " + legendCol + ", " + legendCol+"_1" + seriesCol.toString()+ nvl(valueCols.toString(), ", 1") + groupCol.toString() + final_sql; logger.debug(EELFLoggerDelegate.debugLogger, ("Final sql in generateChartSQL " +sql)); return sql; } // generateChartSQL private String getColumnSelectStr(DataColumnType dc, HttpServletRequest request) { //String colName = dc.isCalculated() ? dc.getColName() // : ((nvl(dc.getTableId()).length() > 0) ? (dc.getTableId() + "." + dc // .getColName()) : dc.getColName()); String colName = dc.getColName(); String paramValue = null; //if (dc.isCalculated()) { if (reportRuntime.getFormFieldList() != null) { for (Iterator iter = reportRuntime.getFormFieldList().getFormField().iterator(); iter.hasNext();) { FormFieldType fft = (FormFieldType) iter.next(); String fieldId = fft.getFieldId(); String fieldDisplay = reportRuntime.getFormFieldDisplayName(fft); String formfield_value = ""; formfield_value = AppUtils.getRequestNvlValue(request, fieldId); paramValue = nvl(formfield_value); if(paramValue.length()>0) { /*sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl( paramValue, "NULL"));*/ colName = Utils.replaceInString(colName, "'" + fieldDisplay + "'", "'"+nvl( paramValue, "NULL")+"'"); colName = Utils.replaceInString(colName, fieldDisplay, nvl( paramValue, "NULL")); } } return colName; } //} return colName; } // getColumnSelectStr public String getSelectExpr(DataColumnType dct) { // String colName = // dct.isCalculated()?dct.getColName():((nvl(dct.getTableId()).length()>0)?(dct.getTableId()+"."+dct.getColName()):dct.getColName()); return getSelectExpr(dct, dct.getColName() /* colName */); } // getSelectExpr private String getSelectExpr(DataColumnType dct, String colName) { String colType = dct.getColType(); if (colType.equals(AppConstants.CT_CHAR) || ((nvl(dct.getColFormat()).length() == 0) && (!colType .equals(AppConstants.CT_DATE)))) return colName; else return "DATE_FORMAT(" + colName + ", '" + nvl(dct.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT) + "')"; } // getSelectExpr private String formatChartColumn(String colName) { logger.debug(EELFLoggerDelegate.debugLogger, ("Format Chart Column Input colName " + colName)); colName = colName.trim(); colName = Utils.replaceInString(colName, "TO_CHAR", "to_char"); colName = Utils.replaceInString(colName, "to_number", "TO_NUMBER"); //reportSQL = reportSQL.replaceAll("[\\s]*\\(", "("); colName = colName.replaceAll(",[\\s]*\\(", ",("); StringBuilder colNameBuf = new StringBuilder(colName); int pos = 0, posFormatStart = 0, posFormatEnd = 0; String format = ""; if(colNameBuf.indexOf("999")==-1 && colNameBuf.indexOf("990")==-1) { logger.debug(EELFLoggerDelegate.debugLogger, (" return colName " + colNameBuf.toString())); return colNameBuf.toString(); } while (colNameBuf.indexOf("to_char")!=-1) { if(colNameBuf.indexOf("999")!=-1 || colNameBuf.indexOf("990")!=-1) { pos = colNameBuf.indexOf("to_char"); colNameBuf.insert(pos, " TO_NUMBER ( CR_RAPTOR.SAFE_TO_NUMBER ("); pos = colNameBuf.indexOf("to_char"); colNameBuf.replace(pos, pos+7, "TO_CHAR"); //colName = Utils.replaceInString(colNameBuf.toString(), "to_char", " TO_NUMBER ( CR_RAPTOR.SAFE_TO_NUMBER ( TO_CHAR "); logger.debug(EELFLoggerDelegate.debugLogger, ("After adding to_number " + colNameBuf.toString())); //posFormatStart = colNameBuf.lastIndexOf(",'")+1; posFormatStart = colNameBuf.indexOf(",'", pos)+1; posFormatEnd = colNameBuf.indexOf(")",posFormatStart); logger.debug(EELFLoggerDelegate.debugLogger, (posFormatStart + " " + posFormatEnd + " "+ pos)); format = colNameBuf.substring(posFormatStart, posFormatEnd); //posFormatEnd = colNameBuf.indexOf(")",posFormatEnd); colNameBuf.insert(posFormatEnd+1, " ," + format + ") , "+ format + ")"); logger.debug(EELFLoggerDelegate.debugLogger, ("colNameBuf " + colNameBuf.toString())); } } logger.debug(EELFLoggerDelegate.debugLogger, (" return colName " + colNameBuf.toString())); return colNameBuf.toString(); } public List getChartValueColumnsList( int filter, HashMap formValues) { /*filter; all=0;create without new chart =1; createNewChart=2 */ List reportCols = reportRuntime.getAllColumns(); ArrayList chartValueCols = new ArrayList(); int flag = 0; for (Iterator iter = reportCols.iterator(); iter.hasNext();) { flag = 0; DataColumnType dc = (DataColumnType) iter.next(); // if(filter == 2 || filter == 1) { flag = reportRuntime.getDependsOnFormFieldFlag(dc, formValues); if( (dc.getChartSeq()!=null && dc.getChartSeq()> 0) && flag == 0 && !(nvl(dc.getColOnChart()).equals(AppConstants.GC_LEGEND))) { if(nvl(dc.getChartGroup()).length()<=0) { if( filter == 2 && (dc.isCreateInNewChart()!=null && dc.isCreateInNewChart().booleanValue())) { chartValueCols.add(dc); } else if (filter == 1 && (dc.isCreateInNewChart()==null || !dc.isCreateInNewChart().booleanValue())) { chartValueCols.add(dc); } else if(filter == 0) chartValueCols.add(dc); } else chartValueCols.add(dc); } // } else // chartValueCols.add(dc); } // for Collections.sort(chartValueCols, new ChartSeqComparator()); return chartValueCols; } // getChartValueColumnsList public String parseTitle(String title, HashMap formValues) { Set set = formValues.entrySet(); for(Iterator iter = set.iterator(); iter.hasNext(); ) { Map.Entry entry = (Entry) iter.next(); if(title.indexOf("["+ entry.getKey() + "]")!= -1) { title = Utils.replaceInString(title, "["+entry.getKey()+"]", nvl( (String) entry.getValue(), "")); } } return title; } public java.util.Date timezoneConversion(SimpleDateFormat sdf, String dateStr) { // sdf.setTimeZone(TimeZone.getTimeZone("GMT")); return sdf.parse(dateStr, new ParsePosition(0)); } public java.util.Date getDateFromDateStr(String dateStr) { SimpleDateFormat MMDDYYYYFormat = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateFormat EEEMMDDYYYYFormat = new SimpleDateFormat("EEE, MM/dd/yyyy"); //2012-11-01 00:00:00 SimpleDateFormat YYYYMMDDFormat = new SimpleDateFormat("yyyy/MM/dd"); SimpleDateFormat MONYYYYFormat = new SimpleDateFormat("MMM yyyy"); SimpleDateFormat MMYYYYFormat = new SimpleDateFormat("MM/yyyy"); SimpleDateFormat MMMMMDDYYYYFormat = new SimpleDateFormat("MMMMM dd, yyyy"); SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat timestampHrFormat = new SimpleDateFormat("yyyy-MM-dd HH"); SimpleDateFormat timestampDayFormat = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat DDMONYYYYFormat = new SimpleDateFormat("dd-MMM-yyyy"); SimpleDateFormat MONTHYYYYFormat = new SimpleDateFormat("MMMMM, yyyy"); SimpleDateFormat MMDDYYYYHHFormat = new SimpleDateFormat("MM/dd/yyyy HH"); SimpleDateFormat MMDDYYYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); SimpleDateFormat MMDDYYYYHHMMFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm"); SimpleDateFormat YYYYMMDDHHMMSSFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); SimpleDateFormat YYYYMMDDHHMMFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); SimpleDateFormat DDMONYYYYHHMMSSFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); SimpleDateFormat DDMONYYYYHHMMFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm"); SimpleDateFormat MMDDYYFormat = new SimpleDateFormat("MM/dd/yy"); SimpleDateFormat MMDDYYHHMMFormat = new SimpleDateFormat("MM/dd/yy HH:mm"); SimpleDateFormat MMDDYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yy HH:mm:ss"); SimpleDateFormat timestampFormat1 = new SimpleDateFormat("yyyy-M-d.HH.mm. s. S"); SimpleDateFormat timestamp_W_dash = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat MMDDYYYYHHMMZFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm z"); SimpleDateFormat YYYYFormat = new SimpleDateFormat("yyyy"); java.util.Date date = null; int formatFlag = 0; final int YEARFLAG = 1; final int MONTHFLAG = 2; final int DAYFLAG = 3; final int HOURFLAG = 4; final int MINFLAG = 5; final int SECFLAG = 6; final int MILLISECFLAG = 7; final int DAYOFTHEWEEKFLAG = 8; final int FLAGDATE = 9; /*int yearFlag = 1; int monthFlag = 2; int dayFlag = 3; int hourFlag = 4; int minFlag = 5; int secFlag = 6; int milliSecFlag = 7; int dayoftheweekFlag = 8; int flagDate = 10; */ date = timezoneConversion(MMDDYYYYHHMMSSFormat, dateStr); if(date!=null) formatFlag = SECFLAG; if(date==null) { date = timezoneConversion(EEEMMDDYYYYFormat, dateStr); if(date!=null) formatFlag = DAYOFTHEWEEKFLAG; } if(date==null) { date = timezoneConversion(MMDDYYYYHHMMFormat, dateStr); if(date!=null) formatFlag = MINFLAG; } if(date==null) { date = timezoneConversion(MMDDYYYYHHFormat, dateStr); if(date!=null) formatFlag = HOURFLAG; } if(date==null) { date = timezoneConversion(MMDDYYYYFormat, dateStr); if(date!=null) formatFlag = DAYFLAG; } if(date==null) { date = timezoneConversion(YYYYMMDDFormat, dateStr); if(date!=null) formatFlag = DAYFLAG; } if(date==null) { date = timezoneConversion(timestampFormat, dateStr); if(date!=null) formatFlag = SECFLAG; } if(date==null) { date = timezoneConversion(timestampHrFormat, dateStr); if(date!=null) formatFlag = HOURFLAG; } if(date==null) { date = timezoneConversion(timestampDayFormat, dateStr); if(date!=null) formatFlag = DAYFLAG; } if(date==null) { date = timezoneConversion(MONYYYYFormat, dateStr); if(date!=null) formatFlag = MONTHFLAG; } if(date==null) { date = timezoneConversion(MMYYYYFormat, dateStr); if(date!=null) formatFlag = MONTHFLAG; } if(date==null) { date = timezoneConversion(MMMMMDDYYYYFormat, dateStr); if(date!=null) formatFlag = DAYFLAG; } if(date==null) { date = timezoneConversion(MONTHYYYYFormat, dateStr); if(date!=null) formatFlag = MONTHFLAG; } if(date==null) { date = timezoneConversion(YYYYMMDDHHMMSSFormat, dateStr); if(date!=null) formatFlag = SECFLAG; } if(date==null) { date = timezoneConversion(YYYYMMDDHHMMFormat, dateStr); if(date!=null) formatFlag = MINFLAG; } if(date==null) { date = timezoneConversion(DDMONYYYYHHMMSSFormat, dateStr); if(date!=null) formatFlag = SECFLAG; } if(date==null) { date = timezoneConversion(DDMONYYYYHHMMFormat, dateStr); if(date!=null) formatFlag = MINFLAG; } if(date==null) { date = timezoneConversion(DDMONYYYYFormat, dateStr); if(date!=null) formatFlag = DAYFLAG; } if(date==null) { date = timezoneConversion(MMDDYYHHMMSSFormat, dateStr); if(date!=null) formatFlag = SECFLAG; } if(date==null) { date = timezoneConversion(MMDDYYHHMMFormat, dateStr); if(date!=null) formatFlag = MINFLAG; } if(date==null) { date = timezoneConversion(MMDDYYFormat, dateStr); if(date!=null) formatFlag = DAYFLAG; } if(date==null) { date = timezoneConversion(timestampFormat1, dateStr); if(date!=null) formatFlag = SECFLAG; } if(date==null) { date = timezoneConversion(MMDDYYYYHHMMZFormat, dateStr); if(date!=null) formatFlag = MINFLAG; } if(date==null) { date = timezoneConversion(YYYYFormat, dateStr); /* Some random numbers should not satisfy this year format. */ if(dateStr.length()>4) date = null; if(date!=null) formatFlag = YEARFLAG; } if(date==null) { date = timezoneConversion(timestamp_W_dash, dateStr); if(date!=null) formatFlag = SECFLAG; } if(date==null) date = null; return date; } public int getFlagFromDateStr(String dateStr) { SimpleDateFormat MMDDYYYYFormat = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateFormat EEEMMDDYYYYFormat = new SimpleDateFormat("EEE, MM/dd/yyyy"); //2012-11-01 00:00:00 SimpleDateFormat YYYYMMDDFormat = new SimpleDateFormat("yyyy/MM/dd"); SimpleDateFormat MONYYYYFormat = new SimpleDateFormat("MMM yyyy"); SimpleDateFormat MMYYYYFormat = new SimpleDateFormat("MM/yyyy"); SimpleDateFormat MMMMMDDYYYYFormat = new SimpleDateFormat("MMMMM dd, yyyy"); SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat timestampHrFormat = new SimpleDateFormat("yyyy-MM-dd HH"); SimpleDateFormat timestampDayFormat = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat DDMONYYYYFormat = new SimpleDateFormat("dd-MMM-yyyy"); SimpleDateFormat MONTHYYYYFormat = new SimpleDateFormat("MMMMM, yyyy"); SimpleDateFormat MMDDYYYYHHFormat = new SimpleDateFormat("MM/dd/yyyy HH"); SimpleDateFormat MMDDYYYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); SimpleDateFormat MMDDYYYYHHMMFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm"); SimpleDateFormat YYYYMMDDHHMMSSFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); SimpleDateFormat YYYYMMDDHHMMFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); SimpleDateFormat DDMONYYYYHHMMSSFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); SimpleDateFormat DDMONYYYYHHMMFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm"); SimpleDateFormat MMDDYYFormat = new SimpleDateFormat("MM/dd/yy"); SimpleDateFormat MMDDYYHHMMFormat = new SimpleDateFormat("MM/dd/yy HH:mm"); SimpleDateFormat MMDDYYHHMMSSFormat = new SimpleDateFormat("MM/dd/yy HH:mm:ss"); SimpleDateFormat timestampFormat1 = new SimpleDateFormat("yyyy-M-d.HH.mm. s. S"); SimpleDateFormat timestamp_W_dash = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat MMDDYYYYHHMMZFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm z"); SimpleDateFormat YYYYFormat = new SimpleDateFormat("yyyy"); java.util.Date date = null; int formatFlag = 0; final int YEARFLAG = 1; final int MONTHFLAG = 2; final int DAYFLAG = 3; final int HOURFLAG = 4; final int MINFLAG = 5; final int SECFLAG = 6; final int MILLISECFLAG = 7; final int DAYOFTHEWEEKFLAG = 8; final int FLAGDATE = 9; date = MMDDYYYYHHMMSSFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = SECFLAG; if(date==null) { date = EEEMMDDYYYYFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = DAYOFTHEWEEKFLAG; } if(date==null) { date = MMDDYYYYHHMMFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = MINFLAG; } if(date==null) { date = MMDDYYYYHHFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = HOURFLAG; } if(date==null) { date = MMDDYYYYFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = DAYFLAG; } if(date==null) { date = YYYYMMDDFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = DAYFLAG; } if(date==null) { date = timestampFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = SECFLAG; } if(date==null) { date = timestampHrFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = HOURFLAG; } if(date==null) { date = timestampDayFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = DAYFLAG; } if(date==null) { date = MONYYYYFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = MONTHFLAG; } if(date==null) { date = MMYYYYFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = MONTHFLAG; } if(date==null) { date = MMMMMDDYYYYFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = DAYFLAG; } if(date==null) { date = MONTHYYYYFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = MONTHFLAG; } if(date==null) { date = YYYYMMDDHHMMSSFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = SECFLAG; } if(date==null) { date = YYYYMMDDHHMMFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = MINFLAG; } if(date==null) { date = DDMONYYYYHHMMSSFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = SECFLAG; } if(date==null) { date = DDMONYYYYHHMMFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = MINFLAG; } if(date==null) { date = DDMONYYYYFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = DAYFLAG; } if(date==null) { date = MMDDYYHHMMSSFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = SECFLAG; } if(date==null) { date = MMDDYYHHMMFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = MINFLAG; } if(date==null) { date = MMDDYYFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = DAYFLAG; } if(date==null) { date = timestampFormat1.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = SECFLAG; } if(date==null) { date = MMDDYYYYHHMMZFormat.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = MINFLAG; } if(date==null) { date = YYYYFormat.parse(dateStr, new ParsePosition(0)); /* Some random numbers should not satisfy this year format. */ if(dateStr.length()>4) date = null; if(date!=null) formatFlag = YEARFLAG; } if(date==null) { date = timestamp_W_dash.parse(dateStr, new ParsePosition(0)); if(date!=null) formatFlag = SECFLAG; } if(date==null) date = null; return formatFlag; } public static String[] reverse(String[] arr) { List list = Arrays.asList(arr); Collections.reverse(list); return (String[])list.toArray(); } public int getNumberOfDecimalPlaces(double num) { Double d = num; String[] splitter = d.toString().split("\\."); splitter[0].length(); // Before Decimal Count splitter[1].length(); // After Decimal Count return splitter[1].length(); } public boolean getBooleanValue(String s) { return getBooleanValue(s,null); } public boolean getBooleanValue(String s, Boolean defaultValue) { s = nvl(s); if(s.length()<=0 && defaultValue!=null) return defaultValue.booleanValue(); else if(s.length()<=0) return false; else { if(s.toUpperCase().startsWith("Y") || s.toLowerCase().equals("true")) return true; else return false; } } public String IntToLetter(int Int) { if (Int<27){ return Character.toString((char)(Int+96)); } else { if (Int%26==0) { return IntToLetter((Int/26)-1)+IntToLetter((Int%26)+1); } else { return IntToLetter(Int/26)+IntToLetter(Int%26); } } } private void clearReportRuntimeBackup(HttpServletRequest request) { HttpSession session = request.getSession(); session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST); request.removeAttribute(AppConstants.DRILLDOWN_INDEX); session.removeAttribute(AppConstants.DRILLDOWN_INDEX); request.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX); session.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX); Enumeration enum1 = session.getAttributeNames(); String attributeName = ""; while(enum1.hasMoreElements()) { attributeName = enum1.nextElement(); if(attributeName.startsWith("parent_")) { session.removeAttribute(attributeName); } } session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST); session.removeAttribute(AppConstants.SI_BACKUP_FOR_REP_ID); session.removeAttribute(AppConstants.SI_COLUMN_LOOKUP); session.removeAttribute(AppConstants.SI_DASHBOARD_REP_ID); session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP); session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME); session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP); session.removeAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP); session.removeAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP); session.removeAttribute(AppConstants.SI_DATA_SIZE_FOR_TEXTFIELD_POPUP); session.removeAttribute(AppConstants.SI_MAP); session.removeAttribute(AppConstants.SI_MAP_OBJECT); session.removeAttribute(AppConstants.SI_REPORT_DEFINITION); session.removeAttribute(AppConstants.SI_REPORT_RUNTIME); session.removeAttribute(AppConstants.SI_REPORT_RUN_BACKUP); session.removeAttribute(AppConstants.SI_REPORT_SCHEDULE); session.removeAttribute(AppConstants.RI_REPORT_DATA); session.removeAttribute(AppConstants.RI_CHART_DATA); session.removeAttribute(AppConstants.SI_FORMFIELD_INFO); session.removeAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO); } // clearReportRuntimeBackup public static synchronized java.util.HashMap getRequestParametersMap(ReportRuntime rr, HttpServletRequest request) { HashMap valuesMap = new HashMap(); ReportFormFields rff = rr.getReportFormFields(); int idx = 0; FormField ff = null; Map fieldNameMap = new HashMap(); int countOfFields = 0 ; for(rff.resetNext(); rff.hasNext(); idx++) { ff = rff.getNext(); fieldNameMap.put(ff.getFieldName(), ff.getFieldDisplayName()); countOfFields++; } List formParameter = new ArrayList(); String formField = ""; for(int i = 0 ; i < rff.size(); i++) { ff = ((FormField)rff.getFormField(i)); formField = ff.getFieldName(); boolean isMultiValue = false; isMultiValue = ff.getFieldType().equals(FormField.FFT_CHECK_BOX) || ff.getFieldType().equals(FormField.FFT_LIST_MULTI); boolean isTextArea = (ff.getFieldType().equals(FormField.FFT_TEXTAREA) && rr.getReportDefType() .equals(AppConstants.RD_SQL_BASED)); if(request.getParameterValues(formField) != null && isMultiValue ) { String[] vals = request.getParameterValues(formField); StringBuilder value = new StringBuilder(""); if(!AppUtils.getRequestFlag(request, AppConstants.RI_RESET_ACTION)) { if ( isMultiValue ) { value.append("("); } for(int j = 0 ; j < vals.length; j++) { if(isMultiValue) value.append("'"); try { if(vals[j] !=null && vals[j].length() > 0) { vals[j] = Utils.oracleSafe(vals[j]); value.append(java.net.URLDecoder.decode(vals[j], "UTF-8")); } else value.append(vals[j]); } catch (UnsupportedEncodingException ex) {value.append(vals[j]);} catch (IllegalArgumentException ex1){value.append(vals[j]);} catch (Exception ex2){ value.append(vals[j]); } if(isMultiValue) value.append("'"); if(j != vals.length -1) { value.append(","); } } if(vals.length > 0) { value.append(")"); } } valuesMap.put(fieldNameMap.get(formField), value.toString()); } else if(request.getParameter(formField) != null) { if(isTextArea) { String value = ""; value = request.getParameter(formField); value = Utils.oracleSafe(value); value = "('" + Utils.replaceInString(value, ",", "'|'") + "')"; value = Utils.replaceInString(value, "|", ","); valuesMap.put(fieldNameMap.get(formField), value); value = ""; } else { String value = ""; if(!AppUtils.getRequestFlag(request, AppConstants.RI_RESET_ACTION)) value = request.getParameter(formField); valuesMap.put(fieldNameMap.get(formField), Utils.oracleSafe(value)); } } else { valuesMap.put(fieldNameMap.get(formField), "" ); } } return valuesMap; } public static int getCurrentTimezoneOffset() { TimeZone tz = TimeZone.getDefault(); java.util.Calendar cal = GregorianCalendar.getInstance(tz); int offsetInMillis = tz.getOffset(cal.getTimeInMillis()); int hourOffset = Math.abs(offsetInMillis / 3600000) * 60; boolean isDST = tz.inDaylightTime(new java.util.Date()); if(isDST){ hourOffset += 60; } int offset = hourOffset + Math.abs((offsetInMillis / 60000) % 60); if (offsetInMillis > 0) offset *= -1; return Globals.getTimezoneOffset(); } }