diff options
Diffstat (limited to 'ecomp-sdk/epsdk-analytics/src')
36 files changed, 5029 insertions, 7008 deletions
diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/AntBuild.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/AntBuild.java index 3e106ab9..7f1c7433 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/AntBuild.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/AntBuild.java @@ -65,9 +65,6 @@ public class AntBuild { URL manifestUrl = new URL("jar:" + classContainer + "!/META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(manifestUrl.openStream()); - //JarFile jar = new JarFile("../lib/raptor_classes.jar"); - //Manifest manifest = jar.getManifest(); - Attributes attribs = manifest.getMainAttributes(); Iterator it = attribs.entrySet().iterator(); while(it.hasNext()) { diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/config/ConfigLoader.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/config/ConfigLoader.java index a21400ca..de62b738 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/config/ConfigLoader.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/config/ConfigLoader.java @@ -49,8 +49,6 @@ import org.onap.portalsdk.analytics.controller.ActionMapping; import org.onap.portalsdk.analytics.util.Log; public class ConfigLoader { - // public static final String RAPTOR_ACTION_MAP = - // "raptor_action_map.properties"; private static final String P_FILE_EXTENSION = ".properties"; @@ -189,8 +187,6 @@ public class ConfigLoader { ActionMapping actionMapping = new ActionMapping(); String pLine = null; - // BufferedReader pFile = new BufferedReader(new - // InputStreamReader(servletContext.getResourceAsStream(internalFilesPath+RAPTOR_ACTION_MAP))); BufferedReader pFile = new BufferedReader(new StringReader(raptorActionMapString)); while ((pLine = pFile.readLine()) != null) if (pLine.trim().length() > 0) diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/controller/Action.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/controller/Action.java index a3a5c60f..81ed950b 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/controller/Action.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/controller/Action.java @@ -63,7 +63,6 @@ public class Action extends org.onap.portalsdk.analytics.RaptorObject { Action a = new Action(); StringTokenizer st = new StringTokenizer(configFileEntry, "| \t", false); - // if(st.hasMoreTokens()) a.setAction(st.nextToken()); a.setControllerClass(st.nextToken()); a.setControllerMethod(st.nextToken()); diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/controller/ActionHandler.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/controller/ActionHandler.java index 0846efda..1cc75b5e 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/controller/ActionHandler.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/controller/ActionHandler.java @@ -488,11 +488,9 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REP_ID, reportID); // get dashboard HTML from report runtime. getListOfReportsFromDashBoardHTML String strHTML = rr.getDashboardLayoutHTML(); - //System.out.println("StrHTML " + strHTML); // call getListOfReportsFromDashBoardHTML returns HashMap TreeMap treeMap = getListOfReportsFromDashBoardHTML(strHTML); - //System.out.println("Size " + hashMap.size()); Set set = treeMap.entrySet(); String value = ""; @@ -566,30 +564,21 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { if(buildReportdata) { reportDataMap.put(new Integer(entry.getKey().toString()), rd); reportChartDataMap.put(new Integer(entry.getKey().toString()), ds); - //reportDisplayTypeMap.put(new Integer(entry.getKey().toString()), entry.getValue().toString().substring(0,1)); } } - /*if(widthFlag ==1) request.getSession().setAttribute("extendedWidth", "Y"); - else request.getSession().removeAttribute("extendedWidth"); - if(heightFlag ==1) request.getSession().setAttribute("extendedHeight", "Y"); - else request.getSession().removeAttribute("extendedHeight"); - */ request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP, new TreeMap(reportsRuntimeMap)); request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); //changing session to request if(buildReportdata) { request.getSession().setAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP, new TreeMap(reportDisplayTypeMap)); request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP, new TreeMap(reportDataMap)); request.getSession().setAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP, new TreeMap(reportChartDataMap)); - } - //request.setAttribute(AppConstants.SI_REPORT_RUNTIME, rr1); - //return nextPage; + } } else { // Ends -// debugLogger.debug("Action Handler *****************" + new java.util.Date()+ " " + isGoBackAction); ReportHandler rh = new ReportHandler(); //rr = null; // COMMENT THIS LINE boolean resetParams = AppUtils.getRequestFlag(request, @@ -608,42 +597,18 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { } return nextPage; } - - /*if (isGoBackAction) { -// debugLogger.debug("Report back in action handler " + ((ReportRuntime) request.getSession().getAttribute( -// AppConstants.SI_REPORT_RUN_BACKUP))!=null?((ReportRuntime) request.getSession().getAttribute( -// AppConstants.SI_REPORT_RUN_BACKUP)).getReportID():((ReportRuntime) request.getSession().getAttribute( -// AppConstants.SI_REPORT_RUN_BACKUP))); - rr = null; - rr = getReportRuntimeFromBackup(request); - if (rr == null) - throw new Exception("[ActionHandler.reportRun] Report backup not found"); - reportID = rr.getReportID(); - } else {*/ logger.debug(EELFLoggerDelegate.debugLogger, ("Ocurring during Schedule ")); //TODO differentiate Schedule with other actions -// if(isEmailAttachment) { -// -// } else { -// -// } + rr = rh.loadReportRuntime(request, reportID); //setParamValues called for Drilldown to display formfield - //rr.setParamValues(request, false,true); //} // else ArrayList aL = (ArrayList)request.getSession().getAttribute(AppConstants.DRILLDOWN_REPORTS_LIST); ReportRuntime aLR = null; if(aL != null) { -// for (int i = 1; i < aL.size(); i++) { -// aLR = (ReportRuntime) aL.get(i); -// if (!aLR.getReportID().equals(reportID)) { -// request.setAttribute(AppConstants.RI_SHOW_BACK_BTN, "Y"); -// } -// } -// if(reportID.equals(reportIDFromSession)) { aLR = (ReportRuntime) aL.get(0); if (aLR!=null && !aLR.getReportID().equals(reportID)) { request.setAttribute(AppConstants.RI_SHOW_BACK_BTN, "Y"); @@ -683,7 +648,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { String limit = nvl(request.getParameter("download_limit"),"1000"); downloadLimit = Integer.parseInt(limit); } - //if (action.startsWith("mobile")) rr.setPageSize(5); long reportTime = System.currentTimeMillis(); if (!rr.getReportType().equals(AppConstants.RT_HIVE)) rd = rr.loadReportData(pageNo, userId, downloadLimit,request,false /*download*/); @@ -692,12 +656,9 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] ------->Time Taken for the loading report data --- " + (System.currentTimeMillis() - reportTime))); ReportData rd_whole = null; boolean hideReportMap = rr.isDisplayOptionHideMap()||AppUtils.getRequestNvlValue(request, "noMap").equals("Y"); -/* if (Globals.getMapAllowedYN().equals("Y") && !hideReportMap && rr.getReportMap()!=null){ - rd_whole = rr.loadReportData(-1, userId, downloadLimit,request); - } -*/ + + request.getSession().setAttribute(AppConstants.RI_REPORT_DATA, rd); - //if (Globals.getMapAllowedYN().equals("Y") && !hideReportMap && (rr.getReportMap()!=null && rr.getReportMap().getLatColumn()!=null && rr.getReportMap().getLongColumn()!=null)) { if(rr!=null && rr.getReportType().equals(AppConstants.RT_LINEAR)) { String sqlWhole = rr.getReportDataSQL(userId, downloadLimit, request); request.setAttribute(AppConstants.RI_REPORT_SQL_WHOLE, sqlWhole); @@ -742,7 +703,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_DOWNLOAD_TEXT, formFields); } else { - //rr.logReportRun(userId, String.valueOf(totalTime),formFields); if(rd!=null && !action.equals("report.run.container")) rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_EXECUTION_TIME, formFields); } @@ -751,12 +711,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { rr.logReportExecutionTimeFromLogList(userId, String.valueOf(totalTime),formFields); } -/* if((String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!=null) { - reportID = (String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID); - ReportRuntime rrDash = rh1.loadReportRuntime(request, reportID, true, 1); - request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rrDash); - } -*/ if(rr.isDrillDownURLInPopupPresent()) { request.getSession().setAttribute(PARENT+rr.getReportID()+"_rr", rr); request.getSession().setAttribute(PARENT+rr.getReportID()+"_rd", rd); @@ -798,8 +752,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { ReportJSONRuntime reportJSONRuntime = rr.createReportJSONRuntime(request, rd); ObjectMapper mapper = new ObjectMapper(); - //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); - //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE)); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String jsonInString = ""; @@ -829,8 +781,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { errorJSONRuntime.setErrormessage(e.getMessage()); errorJSONRuntime.setStacktrace(getStackTrace(e)); ObjectMapper mapper = new ObjectMapper(); - //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); - //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE)); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String jsonInString = ""; @@ -853,8 +803,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { errorJSONRuntime.setErrormessage(ex.getMessage()); errorJSONRuntime.setStacktrace(getStackTrace(ex)); ObjectMapper mapper = new ObjectMapper(); - //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); - //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE)); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String jsonInString = ""; @@ -865,7 +813,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { } return jsonInString; } - //nextPage = (new ErrorHandler()).processFatalError(request, e); } catch (Exception t) { logger.error(EELFLoggerDelegate.errorLogger,t.getMessage(), t); @@ -879,8 +826,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { errorJSONRuntime.setErrormessage(t.toString()); errorJSONRuntime.setStacktrace(getStackTrace(t)); ObjectMapper mapper = new ObjectMapper(); - //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); - //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE)); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String jsonInString = ""; @@ -893,7 +838,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { return jsonInString; } - //return nextPage; } // reportRun public static String getStackTrace(Throwable aThrowable) { @@ -1141,17 +1085,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { /****Remove Report Data from Session when Javascript throw error on onSubmit***/ public String removeReportDataFromSession (HttpServletRequest request, String nextPage) { HttpSession session = request.getSession(false); -/* if (session.getAttribute(AppConstants.RI_REPORT_DATA)!=null) - request.getSession().removeAttribute(AppConstants.RI_REPORT_DATA); - if (request.getAttribute(AppConstants.RI_REPORT_DATA)!=null) - request.removeAttribute(AppConstants.RI_REPORT_DATA); - if (session.getAttribute(AppConstants.RI_CHART_DATA)!=null) - request.getSession().removeAttribute(AppConstants.RI_CHART_DATA); - if (request.getAttribute(AppConstants.RI_CHART_DATA)!=null) - request.removeAttribute(AppConstants.RI_CHART_DATA); -*/ /*if (session.getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null) - request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);*/ - //request.setAttribute(AppConstants.RI_RESET_ACTION, "Y"); return nextPage; } // processScheduleDelete @@ -1216,10 +1149,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( AppConstants.SI_REPORT_DEFINITION); WizardSequence ws = rdef.getWizardSequence(); - //debugLogger.debug("Step Count " + ws.getStepCount()); - //debugLogger.debug("Dashboard " + ((ws instanceof WizardSequenceDashboard) ? ws.getStepCount(): "Not a Dashboard")); - //debugLogger.debug("GO TO STEP LENGTH " + goToStep.length()); - //debugLogger.debug("NumDash Cols in Action Handler " + AppUtils.getRequestNvlValue(request, "numDashCols")); if (goToStep.length() > 0) ws.performGoToStep(goToStep); else @@ -1236,7 +1165,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { } // reportWizard public String refreshCache ( HttpServletRequest request, String nextPage ) { - //DataCache.refreshReportTableSources(); removeVariablesFromSession(request); DataCache.refreshAll(); Globals.getAppUtils().resetUserCache(); @@ -1249,8 +1177,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { ReportDefinition rdef = ReportDefinition.createBlank(request); request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef); - // request.setAttribute(AppConstants.RI_CUR_STEP, - // AppConstants.WS_DEFINITION); DataCache.refreshReportTableSources(); request.getSession().removeAttribute("remoteDB"); } catch (RaptorException e) { @@ -1293,8 +1219,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { rdef.getWizardSequence().performGoToStep(AppConstants.WS_DEFINITION); request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef); - // request.setAttribute(AppConstants.RI_CUR_STEP, - // AppConstants.WS_DEFINITION); } catch (RaptorException e) { nextPage = (new ErrorHandler()).processFatalError(request, e); } @@ -1325,12 +1249,10 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { ReportLoader.deleteReportRecord(reportID); return "{\"deleted\":true}"; - //nextPage = reportSearchExecute(request, nextPage); } catch (RaptorException e) { nextPage = (new ErrorHandler()).processFatalError(request, e); } - //return nextPage; return "{\"deleted\":false}"; } // reportDelete @@ -1419,7 +1341,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { lookup = new IdNameSql(-1,SQL,lu.getDefaultSQL()); lookup.setOldSql(oldSQL); } - //lookup.loadData("0"); } if(lookup instanceof IdNameSql) ((IdNameSql)lookup).setDataSizeUsedinPopup(-3); // -3 indicates to run the count sql for pagination. } @@ -1611,8 +1532,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { request.setAttribute("msg_align", " align=center"); request.setAttribute(AppConstants.RI_PAGE_TITLE, "Test Scheduler Condition"); - // request.setAttribute(AppConstants.RI_PAGE_SUBTITLE, ...); - //String query = "SELECT 1 FROM DUAL WHERE EXISTS (" + sql + ")"; String query = Globals.getTestSchedCondPopup(); query = query.replace("[sql]", sql); @@ -1622,13 +1541,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { String remoteDbPrefix = (remoteDb != null && !remoteDb.equalsIgnoreCase("null")) ? remoteDb : rdef.getDBInfo(); ds = ConnectionUtils.getDataSet(sql, remoteDbPrefix); - // if ( (remoteDbPrefix!=null) && - // (!remoteDbPrefix.equals(AppConstants.DB_LOCAL))) { - // Globals.getRDbUtils().setDBPrefix(remoteDbPrefix); - // ds = RemDbUtils.executeQuery(query); - // } - // else - // ds = DbUtils.executeQuery(query); if (ds.getRowCount() == 0) request .setAttribute(AppConstants.RI_FORMATTED_SQL, @@ -1638,7 +1550,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { .setAttribute(AppConstants.RI_FORMATTED_SQL, "<br><b>Condition satisfied</b> - email notification will be send.<br><br>"); } catch (Exception e) { - // nextPage = (new ErrorHandler()).processFatalError(request, e); request.setAttribute(AppConstants.RI_FORMATTED_SQL, "<br><b>SQL ERROR</b> " + e.getMessage() + "<br>Email notification will NOT be send.<br><br>"); } @@ -1669,13 +1580,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { FormFieldType fft = (FormFieldType) iter.next(); String fieldId = fft.getFieldId(); String fieldDisplay = rdef.getFormFieldDisplayName(fft); - /* - * if(paramValues.isParameterMultiValue(fieldId)) - * generatedSQL = Utils.replaceInString(generatedSQL, - * fieldDisplay, nvl(formatListValue((String) - * paramValues.get(fieldId), null, false, false, null), - * "NULL")); else - */ sql = Utils.replaceInString(sql, fieldDisplay, "NULL"); } // for } // if @@ -1699,25 +1603,13 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { } if(session != null ) { for (int i = 0; i < sessionParameters.length; i++) { - //if(!sessionParameters[i].startsWith("ff")) - //sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i].toUpperCase()) ); - //else { logger.debug(EELFLoggerDelegate.debugLogger, (" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i]))); sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) ); - //} } } logger.debug(EELFLoggerDelegate.debugLogger, ("After testRunSQL " + sql)); ds = ConnectionUtils.getDataSet(sql, remoteDbPrefix, true); - // if ( (remoteDbPrefix!=null) && - // (!remoteDbPrefix.equals(AppConstants.DB_LOCAL))) { - // Globals.getRDbUtils().setDBPrefix(remoteDbPrefix); - // ds = RemDbUtils.executeQuery(sql, - // Globals.getDefaultPageSize()+1); - // } - // else - // ds = DbUtils.executeQuery(sql, Globals.getDefaultPageSize()+1); if (chkFormFieldSQL && ds.getRowCount() > 0) { String id = ds.getString(0, "id"); String name = ds.getString(0, "name"); @@ -1783,12 +1675,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { if(isFromSchedule) { String reportID = null; String report_email_sent_log_id = AppUtils.getRequestValue(request, "log_id"); - /*String query = "Select user_id, rep_id from CR_REPORT_EMAIL_SENT_LOG" + - " where rownum = 1" + - " and gen_key='"+pdfAttachmentKey.trim()+"'" + - " and log_id ="+report_email_sent_log_id.trim() + - " and (sysdate - sent_date) < 1 ";*/ - String query = Globals.getDownloadAllEmailSent(); query = query.replace("[pdfAttachmentKey.trim()]", pdfAttachmentKey.trim()); query = query.replace("[report_email_sent_log_id.trim()]", report_email_sent_log_id.trim()); @@ -1813,7 +1699,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { String d_sql = Globals.getDownloadAllGenKey(); d_sql = d_sql.replace("[pdfAttachmentKey]", pdfAttachmentKey); - //ds = DbUtils.executeQuery("select schedule_id from cr_report_email_sent_log u where U.GEN_KEY = '"+ pdfAttachmentKey + "'"); ds = DbUtils.executeQuery(d_sql); for (int i = 0; i < ds.getRowCount(); i++) { @@ -1824,13 +1709,9 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { String fileName = FilenameUtils.normalize(rr.getReportID()+"_"+userId+"_"+timestamp); boolean flag = false; logger.debug(EELFLoggerDelegate.debugLogger, (""+Utils.isDownloadFileExists(rr.getReportID()+"_"+userId+"_"+dateStr))); - // if(Utils.isDownloadFileExists(rr.getReportID()+"_"+userId+"_"+dateStr)) { - // flag = true; - // } if(flag){ String strFileName = Utils.getLatestDownloadableFile(rr.getReportID()+"_"+userId+"_"+dateStr); - //debugLogger.debug("File Name " + strFileName); StringBuffer messageBuffer = new StringBuffer(""); messageBuffer.append("Download data file using the following link<BR>"); messageBuffer.append("<a href=\"" + request.getContextPath() + "/raptor/dwnld/data/" + @@ -1867,8 +1748,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { logger.debug(EELFLoggerDelegate.debugLogger, ("************************")); logger.debug(EELFLoggerDelegate.debugLogger, (rr.parseReportSQL(rr.getWholeSQL()))); xmlOut.println(rr.parseReportSQL(rr.getWholeSQL())); - //xmlOut.println("******************"); - //xmlOut.println(rr.getWholeSQL()); xmlOut.flush(); xmlOut.close(); } catch (IOException e) {logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), e);} @@ -1885,7 +1764,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { logger.debug(EELFLoggerDelegate.debugLogger, ("Command " + command)); Process downloadProcess = runtime.exec(command.toString()); logger.debug(EELFLoggerDelegate.debugLogger, ("Command Executed ")); - //Connection connection = DbUtils.getConnection(); Enumeration enum1 = rr.getParamKeys(); String value = ""; String paramStr = ""; @@ -1902,26 +1780,9 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { StringBuffer retrieveUserEmailQry = null; ArrayList userEmailList = new ArrayList(); if(nvl(scheduleId).length()>0) { - /*retrieveUserEmailQry = new StringBuffer(); - retrieveUserEmailQry.append(" SELECT "); - retrieveUserEmailQry.append(" au.user_id "); - retrieveUserEmailQry.append(" FROM "); - retrieveUserEmailQry.append(" (SELECT rs.schedule_id, rs.rep_id FROM cr_report_schedule rs WHERE rs.enabled_yn='Y' AND rs.run_date IS NOT NULL "); - retrieveUserEmailQry.append(" AND rs.schedule_id = " + scheduleId + " ) x, cr_report r, app_user au "); - retrieveUserEmailQry.append(" WHERE "); - retrieveUserEmailQry.append("x.rep_id = r.rep_id "); - retrieveUserEmailQry.append(" AND au.user_id IN (SELECT rsu.user_id FROM cr_report_schedule_users rsu WHERE rsu.schedule_id = x.schedule_id and rsu.schedule_id = " + scheduleId ); - retrieveUserEmailQry.append(" UNION "); - retrieveUserEmailQry.append(" SELECT ur.user_id FROM fn_user_role ur "); - retrieveUserEmailQry.append(" WHERE ur.role_id IN "); - retrieveUserEmailQry.append(" (SELECT rsu2.role_id FROM cr_report_schedule_users rsu2 "); - retrieveUserEmailQry.append(" WHERE rsu2.schedule_id = x.schedule_id and "); - retrieveUserEmailQry.append(" rsu2.schedule_id = "+ scheduleId + ")) ");*/ String r_sql = Globals.getDownloadAllRetrieve(); r_sql = r_sql.replace("[scheduleId]", scheduleId); - - // DataSet ds = DbUtils.executeQuery(retrieveUserEmailQry.toString()); DataSet ds = DbUtils.executeQuery(r_sql); for (int i = 0; i < ds.getRowCount(); i++) { @@ -1929,7 +1790,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { } } - // String insertQry = "insert into cr_report_dwnld_log (user_id,rep_id,file_name,dwnld_start_time,filter_params) values (?,?,?,?,?)"; String insertQry = Globals.getDownloadAllInsert(); @@ -1962,30 +1822,6 @@ public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject { } catch (Exception ex) { throw new RaptorException (ex); } - //DbUtils.commitTransaction(connection); - //DbUtils.clearConnection(connection); - - - -// debugLogger.debug("|"+downloadProcess.toString() + "|"); -// if (downloadProcess == null) -// throw new Exception("unable to create a process for command:" + -// command); -// int retCode= 1; -// try { -// retCode= downloadProcess.waitFor(); -// } catch (InterruptedException e){ -// e.printStackTrace(); -// } -// debugLogger.debug("retCode " + retCode); -// Process child = rtime.exec("/bin/bash"); -// BufferedWriter outCommand = new BufferedWriter(new -// OutputStreamWriter(child.getOutputStream())); -// outCommand.write(Globals.getShellScriptName()); -// outCommand.flush(); -// int retCode = child.waitFor(); -// debugLogger.debug("RetCode " + retCode); - //request.setAttribute(MESSAGE, "Shell Script is running in the background. You'll get an email once it is done"); } return nextPage; diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/ReportHandler.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/ReportHandler.java index 2729ebb0..12842f50 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/ReportHandler.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/ReportHandler.java @@ -33,31 +33,38 @@ * * ============LICENSE_END============================================ * - * + * */ /* =========================================================================================== - * This class is part of <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I> + * This class is part of <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I> * Raptor : This tool is used to generate different kinds of reports with lot of utilities * =========================================================================================== * * ------------------------------------------------------------------------------------------- - * ReportHandler.java - This class is used to generate reports in Excel using POI and also to + * ReportHandler.java - This class is used to generate reports in Excel using POI and also to * create ReportRuntime and ReportDefinition object using report id. * ------------------------------------------------------------------------------------------- * * * Changes * ------- - * 18-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL> + * 18-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL> * 14-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Signature for generating excel method has been changed to add the report name as sheet name. </LI> * <LI> Dashboard reports can be downloaded with each report as a separate sheet. </LI> - * </UL> - * 08-Jun-2009 : Version 8.3 (Sundar); <UL><LI> Short datatype is replaced with default integer datatype to create - * row as short is not expoting more than 32768 rows. </LI></UL> + * </UL> + * 08-Jun-2009 : Version 8.3 (Sundar); <UL><LI> Short datatype is replaced with default integer datatype to create + * row as short is not expoting more than 32768 rows. </LI></UL> * */ package org.onap.portalsdk.analytics.model; +import com.lowagie.text.Document; +import com.lowagie.text.Paragraph; +import com.lowagie.text.html.simpleparser.HTMLWorker; +import com.lowagie.text.html.simpleparser.StyleSheet; +import com.lowagie.text.pdf.PdfPTable; + +import java.awt.Font; import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.File; @@ -102,18 +109,10 @@ import java.util.concurrent.TimeoutException; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; - import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; - -import com.lowagie.text.Document; -import com.lowagie.text.Paragraph; -import com.lowagie.text.html.simpleparser.HTMLWorker; -import com.lowagie.text.html.simpleparser.StyleSheet; -import com.lowagie.text.pdf.PdfPTable; - import org.apache.commons.io.FilenameUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; @@ -130,6 +129,7 @@ import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.FillPatternType; +import org.apache.poi.ss.usermodel.Footer; import org.apache.poi.ss.usermodel.Header; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IndexedColors; @@ -142,6 +142,7 @@ import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbookType; import org.onap.portalsdk.analytics.controller.ErrorHandler; import org.onap.portalsdk.analytics.error.RaptorException; import org.onap.portalsdk.analytics.error.ReportSQLException; @@ -178,68 +179,69 @@ import org.owasp.esapi.ESAPI; public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { - private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportHandler.class); - - public ReportHandler() { - } - - private String SHEET_NAME = ""; - private static final String XML_ENCODING = "UTF-8"; - private static int font_size = 10; - private static int font_header_title_size = 12; - private static int font_header_descr_size = 9; - private static int font_footer_size = 9; - - - private HashMap loadStyles(ReportRuntime rr, HSSFWorkbook wb) { - HSSFCellStyle styleDefault = wb.createCellStyle(); - // Style default will be normal with no background - HSSFFont fontDefault = wb.createFont(); - // The default will be plain . - fontDefault.setColor((short) HSSFFont.COLOR_NORMAL); - fontDefault.setFontHeight((short) (font_size / 0.05)); - fontDefault.setFontName("Tahoma"); - - styleDefault.setAlignment(HorizontalAlignment.CENTER ); - styleDefault.setBorderBottom(BorderStyle.THIN); - styleDefault.setBorderTop(BorderStyle.THIN); - styleDefault.setBorderLeft(BorderStyle.THIN); - styleDefault.setBorderRight(BorderStyle.THIN); - - styleDefault.setFillPattern(FillPatternType.NO_FILL); - styleDefault.setFont(fontDefault); - - HSSFCellStyle styleRed = wb.createCellStyle(); - styleRed.cloneStyleFrom(styleDefault); - styleRed.setFillForegroundColor((short)HSSFColor.RED.index); - styleRed.setFillPattern(FillPatternType.SOLID_FOREGROUND ); - HSSFFont fontRed = wb.createFont(); - fontRed.setColor((short) HSSFColor.WHITE.index); - fontRed.setFontHeight((short) (font_size / 0.05)); - fontRed.setFontName("Tahoma"); - styleRed.setFont(fontRed); - - HSSFCellStyle styleYellow = wb.createCellStyle(); - styleYellow.cloneStyleFrom(styleDefault); - styleYellow.setFillForegroundColor((short)HSSFColor.YELLOW.index); - styleYellow.setFillPattern(FillPatternType.SOLID_FOREGROUND ); - HSSFFont fontYellow = wb.createFont(); - fontYellow.setColor((short) HSSFColor.BLACK.index); - fontYellow.setFontHeight((short) (font_size / 0.05)); - fontYellow.setFontName("Tahoma"); - styleYellow.setFont(fontYellow); - - HSSFCellStyle styleGreen = wb.createCellStyle(); - styleGreen.cloneStyleFrom(styleDefault); - styleGreen.setFillForegroundColor((short)HSSFColor.GREEN.index); - styleGreen.setFillPattern(FillPatternType.SOLID_FOREGROUND ); - HSSFFont fontGreen = wb.createFont(); - fontGreen.setColor((short) HSSFColor.WHITE.index); - fontGreen.setFontHeight((short) (font_size / 0.05)); - fontGreen.setFontName("Tahoma"); - styleGreen.setFont(fontGreen); - - + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportHandler.class); + + public ReportHandler() {} + + private String sheetName = ""; + private static final String XML_ENCODING = "UTF-8"; + private static final int FONT_SIZE = 10; + private static final int FONT_HEADER_TITLE_SIZE = 12; + private static final int FONT_HEADER_DESCR_SIZE = 9; + private static final int FONT_FOOTER_SIZE = 9; + private static final String DEFAULT = "default"; + private static final String YELLOW = "yellow"; + private static final String GREEN = "green"; + private static final String RED = "red"; + private static final String RUNTIME_PARAMETERS = "Run-time Parameters"; + private static final String FONT_TAHOMA = "Tahoma"; + FillPatternType fillPattern = null; + + private HashMap loadStyles(ReportRuntime rr, XSSFWorkbook wb) { + XSSFCellStyle styleDefault = wb.createCellStyle(); + XSSFFont fontDefault = wb.createFont(); + fontDefault.setColor((short) HSSFFont.COLOR_NORMAL); + fontDefault.setFontHeight((short) (FONT_SIZE / 0.05)); + fontDefault.setFontName(FONT_TAHOMA); + + styleDefault.setAlignment(HorizontalAlignment.CENTER); + styleDefault.setBorderBottom(BorderStyle.THIN); + styleDefault.setBorderTop(BorderStyle.THIN); + styleDefault.setBorderLeft(BorderStyle.THIN); + styleDefault.setBorderRight(BorderStyle.THIN); + styleDefault.setFillPattern(fillPattern.NO_FILL); + styleDefault.setFont(fontDefault); + + XSSFCellStyle styleRed = wb.createCellStyle(); + styleRed.cloneStyleFrom(styleDefault); + styleRed.setFillForegroundColor((short) HSSFColor.RED.index); + styleRed.setFillPattern(fillPattern.SOLID_FOREGROUND); + XSSFFont fontRed = wb.createFont(); + fontRed.setColor((short) HSSFColor.WHITE.index); + fontRed.setFontHeight((short) (FONT_SIZE / 0.05)); + fontRed.setFontName(FONT_TAHOMA); + styleRed.setFont(fontRed); + + XSSFCellStyle styleYellow = wb.createCellStyle(); + styleYellow.cloneStyleFrom(styleDefault); + styleYellow.setFillForegroundColor((short) HSSFColor.YELLOW.index); + styleYellow.setFillPattern(fillPattern.SOLID_FOREGROUND); + XSSFFont fontYellow = wb.createFont(); + fontYellow.setColor((short) HSSFColor.BLACK.index); + fontYellow.setFontHeight((short) (FONT_SIZE / 0.05)); + fontYellow.setFontName(FONT_TAHOMA); + styleYellow.setFont(fontYellow); + + XSSFCellStyle styleGreen = wb.createCellStyle(); + styleGreen.cloneStyleFrom(styleDefault); + styleGreen.setFillForegroundColor((short) HSSFColor.GREEN.index); + styleGreen.setFillPattern(fillPattern.SOLID_FOREGROUND); + XSSFFont fontGreen = wb.createFont(); + fontGreen.setColor((short) HSSFColor.WHITE.index); + fontGreen.setFontHeight((short) (FONT_SIZE / 0.05)); + fontGreen.setFontName(FONT_TAHOMA); + styleGreen.setFont(fontGreen); + ArrayList semColumnList = new ArrayList(); List dsList = rr.getDataSourceList().getDataSource(); for (Iterator iter = dsList.iterator(); iter.hasNext();) { @@ -248,2544 +250,2033 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { for (Iterator iterator = dcList.iterator(); iterator.hasNext();) { DataColumnType element1 = (DataColumnType) iterator.next(); semColumnList.add(element1.getSemaphoreId()); - + } } - SemaphoreList semList = rr.getSemaphoreList(); - HashMap hashMapStyles = new HashMap(); - HashMap hashMapFonts = new HashMap(); - hashMapFonts.put("default", fontDefault); - hashMapFonts.put("red", fontRed); - hashMapFonts.put("yellow", fontYellow); - hashMapFonts.put("green", fontGreen); - hashMapStyles.put("default", styleDefault); - hashMapStyles.put("red", styleRed); - hashMapStyles.put("yellow", styleYellow); - hashMapStyles.put("green", styleGreen); - HSSFCellStyle cellStyle = null; - if (semList == null || semList.getSemaphore() == null) { - return hashMapStyles; - } else { - for (Iterator iter = semList.getSemaphore().iterator(); iter.hasNext();) { - SemaphoreType sem = (SemaphoreType) iter.next(); - if(!semColumnList.contains(sem.getSemaphoreId())) - continue; - FormatList fList = sem.getFormatList(); - List formatList = fList.getFormat(); - for (Iterator fIter = formatList.iterator(); fIter.hasNext();) { - FormatType fmt = (FormatType) fIter.next(); - if(fmt!=null){ - cellStyle = wb.createCellStyle(); - HSSFFont cellFont = wb.createFont(); - if (nvl(fmt.getBgColor()).length() > 0) { - cellStyle.setFillForegroundColor(ExcelColorDef.getExcelColor(fmt - .getBgColor())); - cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND ); - } - if (nvl(fmt.getFontColor()).length() > 0) { - cellFont.setColor(ExcelColorDef.getExcelColor(fmt.getFontColor())); - } else - cellFont.setColor((short) HSSFFont.COLOR_NORMAL); - if (fmt.isBold()) - cellFont.setBold(true); - if (fmt.isItalic()) - cellFont.setItalic(true); - if (fmt.isUnderline()) - cellFont.setUnderline(HSSFFont.U_SINGLE); - if(nvl(fmt.getFontFace()).length()>0) - cellFont.setFontName(fmt.getFontFace()); - else - cellFont.setFontName("Tahoma"); - - if(nvl(fmt.getFontSize()).length()>0) { - try { - cellFont.setFontHeight((short) (font_size/0.05)); - } catch(NumberFormatException e){ - cellFont.setFontHeight((short) (font_size / 0.05));//10 - } - } - else - cellFont.setFontHeight((short) (font_size / 0.05)); - cellStyle.setFont(cellFont); - cellStyle.setAlignment(HorizontalAlignment.CENTER); - cellStyle.setBorderBottom(BorderStyle.THIN); - cellStyle.setBorderTop(BorderStyle.THIN); - cellStyle.setBorderLeft(BorderStyle.THIN); - cellStyle.setBorderRight(BorderStyle.THIN); - hashMapStyles.put(fmt.getFormatId(), cellStyle); - } else { - // hashMapStyles.put(fmt.getFormatId(), styleDefault); //fmt is null here - hashMapStyles.put("default", styleDefault); - } - } - - } - } - return hashMapStyles; - } - - private void paintExcelParams(final HSSFWorkbook wb, int rowNum, final int col, final List paramsList, - final String customizedParamInfo, final HSSFSheet sheet, final String reportTitle, final String reportDescr) - throws IOException { + SemaphoreList semList = rr.getSemaphoreList(); + HashMap hashMapStyles = new HashMap(); + HashMap hashMapFonts = new HashMap(); + hashMapFonts.put(DEFAULT, fontDefault); + hashMapFonts.put(RED, fontRed); + hashMapFonts.put(YELLOW, fontYellow); + hashMapFonts.put(GREEN, fontGreen); + hashMapStyles.put(DEFAULT, styleDefault); + hashMapStyles.put(RED, styleRed); + hashMapStyles.put(YELLOW, styleYellow); + hashMapStyles.put(GREEN, styleGreen); + XSSFCellStyle cellStyle = null; + if (semList == null || semList.getSemaphore() == null) { + return hashMapStyles; + } else { + for (Iterator iter = semList.getSemaphore().iterator(); iter.hasNext();) { + SemaphoreType sem = (SemaphoreType) iter.next(); + if (!semColumnList.contains(sem.getSemaphoreId())) + continue; + FormatList fList = sem.getFormatList(); + List formatList = fList.getFormat(); + for (Iterator fIter = formatList.iterator(); fIter.hasNext();) { + FormatType fmt = (FormatType) fIter.next(); + if (fmt != null) { + cellStyle = wb.createCellStyle(); + XSSFFont cellFont = wb.createFont(); + if (nvl(fmt.getBgColor()).length() > 0) { + cellStyle.setFillForegroundColor(ExcelColorDef.getExcelColor(fmt + .getBgColor())); + cellStyle.setFillPattern(fillPattern.SOLID_FOREGROUND); + } + if (nvl(fmt.getFontColor()).length() > 0) { + cellFont.setColor(ExcelColorDef.getExcelColor(fmt.getFontColor())); + } else + cellFont.setColor((short) HSSFFont.COLOR_NORMAL); + if (fmt.isBold()) + cellFont.setBold(true); + if (fmt.isItalic()) + cellFont.setItalic(true); + if (fmt.isUnderline()) + cellFont.setUnderline(HSSFFont.U_SINGLE); + if (nvl(fmt.getFontFace()).length() > 0) + cellFont.setFontName(fmt.getFontFace()); + else + cellFont.setFontName(FONT_TAHOMA); + + if (nvl(fmt.getFontSize()).length() > 0) { + try { + // cellFont.setFontHeight((short) (Integer.parseInt(fmt.getFontSize()) / 0.05)); + cellFont.setFontHeight((short) (FONT_SIZE / 0.05)); + } catch (NumberFormatException e) { + cellFont.setFontHeight((short) (FONT_SIZE / 0.05));// 10 + } + } else + cellFont.setFontHeight((short) (FONT_SIZE / 0.05)); + cellStyle.setFont(cellFont); + cellStyle.setAlignment(HorizontalAlignment.CENTER); + cellStyle.setBorderBottom(BorderStyle.THIN); + cellStyle.setBorderTop(BorderStyle.THIN); + cellStyle.setBorderLeft(BorderStyle.THIN); + cellStyle.setBorderRight(BorderStyle.THIN); + hashMapStyles.put(fmt.getFormatId(), cellStyle); + } else { + hashMapStyles.put(DEFAULT, styleDefault); + } + } + + } + } + return hashMapStyles; + } + + private void paintExcelParams(final XSSFWorkbook wb, int rowNum, final int col, final List paramsList, + final String customizedParamInfo, final XSSFSheet sheet, final String reportTitle, final String reportDescr) + throws IOException { int cellNum = 0; - HSSFRow row = null; - short s1 = 0, s2 = (short) 1; - HtmlStripper strip = new HtmlStripper(); - // Name Style - HSSFCellStyle styleName = wb.createCellStyle(); + XSSFRow row = null; + short s1 = 0; + short s2 = (short) 1; + XSSFCellStyle styleName = wb.createCellStyle(); styleName.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); styleName.setAlignment(HorizontalAlignment.CENTER); styleName.setBorderBottom(BorderStyle.THIN); styleName.setBorderTop(BorderStyle.THIN); styleName.setBorderRight(BorderStyle.THIN); styleName.setBorderLeft(BorderStyle.THIN); - styleName.setDataFormat((short)0); - HSSFFont font = wb.createFont(); - font.setFontHeight((short) (font_size / 0.05)); - font.setFontName("Tahoma"); + styleName.setDataFormat((short) 0); + XSSFFont font = wb.createFont(); + font.setFontHeight((short) (FONT_SIZE / 0.05)); + font.setFontName(FONT_TAHOMA); font.setColor(HSSFColor.BLACK.index); font.setBold(true); styleName.setFont(font); - //Data Style - - // Create some fonts. - HSSFFont fontDefault = wb.createFont(); - // Initialize the styles & fonts. - // The default will be plain . + + XSSFFont fontDefault = wb.createFont(); + fontDefault.setColor((short) HSSFFont.COLOR_NORMAL); - fontDefault.setFontHeight((short) (font_size / 0.05)); - fontDefault.setFontName("Tahoma"); + fontDefault.setFontHeight((short) (FONT_SIZE / 0.05)); + fontDefault.setFontName(FONT_TAHOMA); fontDefault.setItalic(true); - // Style default will be normal with no background - HSSFCellStyle styleValue = wb.createCellStyle(); - styleValue.setDataFormat((short)0); + XSSFCellStyle styleValue = wb.createCellStyle(); + styleValue.setDataFormat((short) 0); styleValue.setAlignment(HorizontalAlignment.CENTER); styleValue.setBorderBottom(BorderStyle.THIN); styleValue.setBorderTop(BorderStyle.THIN); styleValue.setBorderLeft(BorderStyle.THIN); styleValue.setBorderRight(BorderStyle.THIN); - styleValue.setFillPattern(FillPatternType.NO_FILL); + // styleValue.setFillForegroundColor(HSSFColor.YELLOW.index); + styleValue.setFillPattern(fillPattern.NO_FILL); styleValue.setFont(fontDefault); - HSSFCell cell = null; - HSSFCellStyle styleDescription = wb.createCellStyle(); - styleDescription.setAlignment(HorizontalAlignment.CENTER); - HSSFFont fontDescr = wb.createFont(); - fontDescr.setFontHeight((short) (font_size / 0.05)); //14 - fontDescr.setFontName("Tahoma"); + XSSFCell cell = null; + XSSFCellStyle styleDescription = wb.createCellStyle(); + styleDescription.setAlignment(HorizontalAlignment.CENTER); + + XSSFFont fontDescr = wb.createFont(); + fontDescr.setFontHeight((short) (FONT_SIZE / 0.05)); // 14 + fontDescr.setFontName(FONT_TAHOMA); fontDescr.setColor(HSSFColor.BLACK.index); fontDescr.setBold(true); styleDescription.setFont(font); - HSSFCell cellDescr = null; + XSSFCell cellDescr = null; int paramSeq = 0; - HSSFHeader header = sheet.getHeader(); - StringBuffer strBuf = new StringBuffer(); - if(!Globals.customizeFormFieldInfo() || customizedParamInfo.length()<=0) { - for (Iterator iter = paramsList.iterator(); iter.hasNext();) { - IdNameValue value = (IdNameValue) iter.next(); - if(nvl(value.getId()).trim().length()>0 && (!nvl(value.getId()).trim().equals("BLANK"))) { - paramSeq += 1; - if(paramSeq <= 1) { - row = sheet.createRow(++rowNum); - cell = row.createCell((short) 0); - sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); - cellDescr = row.createCell((short) 0); - cellDescr.setCellValue("Run-time Parameters"); - cellDescr.setCellStyle(styleDescription); - - - strBuf.append(reportTitle+"\n"); - } - row = sheet.createRow(++rowNum); - cellNum = 0; - cell = row.createCell((short) cellNum); - cell.setCellValue(value.getId()); - cell.setCellStyle(styleName); - cellNum += 1; - cell = row.createCell((short) cellNum); - cell.setCellValue(value.getName().replaceAll("~",",")); - cell.setCellStyle(styleValue); - } - } //for + Header header = sheet.getHeader(); + StringBuilder strBuf = new StringBuilder(); + if (!Globals.customizeFormFieldInfo() || customizedParamInfo.length() <= 0) { + for (Iterator iter = paramsList.iterator(); iter.hasNext();) { + IdNameValue value = (IdNameValue) iter.next(); + if (nvl(value.getId()).trim().length() > 0 && (!nvl(value.getId()).trim().equals("BLANK"))) { + paramSeq += 1; + if (paramSeq <= 1) { + row = sheet.createRow(++rowNum); + cell = row.createCell((short) 0); + sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); + cellDescr = row.createCell((short) 0); + cellDescr.setCellValue(RUNTIME_PARAMETERS); + cellDescr.setCellStyle(styleDescription); + + strBuf.append(reportTitle + "\n"); + } + row = sheet.createRow(++rowNum); + cellNum = 0; + cell = row.createCell((short) cellNum); + cell.setCellValue(value.getId()); + cell.setCellStyle(styleName); + cellNum += 1; + cell = row.createCell((short) cellNum); + cell.setCellValue(value.getName().replaceAll("~", ",")); + cell.setCellStyle(styleValue); + + } + } // for } else { - strBuf.append(reportTitle+"\n"); - Document document = new Document(); - document.open(); + strBuf.append(reportTitle + "\n"); + Document document = new Document(); + document.open(); HTMLWorker worker = new HTMLWorker(document); - StyleSheet style = new StyleSheet(); - style.loadTagStyle("body", "leading", "16,0"); - ArrayList p = HTMLWorker.parseToList(new StringReader(customizedParamInfo), style); - String name = ""; - String token = ""; - String value = ""; - String s = ""; - PdfPTable pdfTable = null; - for (int k = 0; k < p.size(); ++k){ - if(p.get(k) instanceof Paragraph) - s = ((Paragraph)p.get(k)).toString(); - else { /*if ((p.get(k) instanceof PdfPTable))*/ - pdfTable = ((PdfPTable)p.get(k)); - } - //todo: Logic for parsing pdfTable should be added after upgrading to iText 5.0.0 - //s = Utils.replaceInString(s, ",", "|"); - s = s.replaceAll(",", "|"); - s = s.replaceAll("~", ","); - if(s.indexOf(":")!= -1) { - row = sheet.createRow(++rowNum); + StyleSheet style = new StyleSheet(); + style.loadTagStyle("body", "leading", "16,0"); + ArrayList p = HTMLWorker.parseToList(new StringReader(customizedParamInfo), style); + String name = ""; + String token = ""; + String value = ""; + String s = ""; + PdfPTable pdfTable = null; + for (int k = 0; k < p.size(); ++k) { + if (p.get(k) instanceof Paragraph) + s = ((Paragraph) p.get(k)).toString(); + else { + pdfTable = ((PdfPTable) p.get(k)); + } + + s = s.replaceAll(",", "|"); + s = s.replaceAll("~", ","); + if (s.indexOf(":") != -1) { + row = sheet.createRow(++rowNum); cell = row.createCell((short) 0); sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); cellDescr = row.createCell((short) 0); - cellDescr.setCellValue("Run-time Parameters"); - cellDescr.setCellStyle(styleDescription); - - StringTokenizer st = new StringTokenizer(s.trim(), "|"); - while(st.hasMoreTokens()) { - token = st.nextToken(); - token = token.trim(); - if (!(token.trim().equals("|") || token.trim().equals("]]") || token.trim().equals("]") || token.trim().equals("[") )) { - if(token.endsWith(":")) { - name = token; - name = name.substring(0, name.length()-1); - if(name.startsWith("[")) - name = name.substring(1); - value = st.nextToken(); - if(nvl(value).endsWith("]")){ - value = nvl(value).substring(0, nvl(value).length()-1); - } - } /*else if(name != null && name.length() > 0) { - value = st.nextToken(); - if(value.endsWith("]]"))value = value.substring(0, value.length()-1); - }*/ - if(name!=null && name.trim().length()>0) { - row = sheet.createRow((short) ++rowNum); - cellNum = 0; - cell = row.createCell((short) cellNum); - cell.setCellValue(name.trim()); - cell.setCellStyle(styleName); - cellNum += 1; - cell = row.createCell((short) cellNum); - cell.setCellValue(value.trim()); - cell.setCellStyle(styleValue); - } -/* if(token.endsWith(":") && (value!=null && value.trim().length()<=0) && (name!=null && name.trim().length()>0 && name.endsWith(":"))) { - name = name.substring(0, name.indexOf(":")+1); - //value = token.substring(token.indexOf(":")+1); - row = sheet.createRow((short) ++rowNum); - cellNum = 0; - cell = row.createCell((short) cellNum); - cell.setCellValue(name.trim()); - cell.setCellStyle(styleName); - cellNum += 1; - cell = row.createCell((short) cellNum); - cell.setCellValue(value.trim()); - cell.setCellStyle(styleValue); - - //strBuf.append(name.trim()+": "+ value.trim()+"\n"); - value = ""; - name = ""; - } -*/ } - //int cw = 0; - //cw = name.trim().length() + 12; - // if(i!=cellWidth.size()-1) - if(name!=null && (sheet.getColumnWidth((short)0)< (short) name.trim().length())){ - sheet.setColumnWidth((short)0, (short) name.trim().length()); - } - if(sheet.getColumnWidth((short)1)< (short) value.trim().length()){ - sheet.setColumnWidth((short)1, (short) value.trim().length()); - } - name = ""; - value = ""; - - } - - try { - SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss"); - Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime()); - SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern()); - - row = sheet.createRow((short) ++rowNum); - cellNum = 0; - cell = row.createCell((short) cellNum); - cell.setCellValue("Report Date/Time"); - cell.setCellStyle(styleName); - cellNum += 1; - cell = row.createCell((short) cellNum); - - cell.setCellValue(dtimestamp.format(sysdate)+" "+Globals.getTimeZone()); - cell.setCellStyle(styleValue); - - } catch(Exception ex) { - //ex.printStackTrace(); - } - - - } - } - - -/* Iterator iter1 = paramsList.iterator(); - s1 = 0; s2 = (short)10; - if(iter1.hasNext()) { - row = sheet.createRow((short) ++rowNum); - cellNum = 0; - cell = row.createCell((short) cellNum); - sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); - cell.setCellValue(strip.stripHtml(customizedParamInfo)); - } -*/ -/* rowNum += 2; - row = sheet.createRow(rowNum);*/ - } // if + cellDescr.setCellValue(RUNTIME_PARAMETERS); + cellDescr.setCellStyle(styleDescription); + + StringTokenizer st = new StringTokenizer(s.trim(), "|"); + while (st.hasMoreTokens()) { + token = st.nextToken(); + token = token.trim(); + if (!(token.trim().equals("|") || token.trim().equals("]]") || token.trim().equals("]") + || token.trim().equals("["))) { + if (token.endsWith(":")) { + name = token; + name = name.substring(0, name.length() - 1); + if (name.startsWith("[")) + name = name.substring(1); + value = st.nextToken(); + if (nvl(value).endsWith("]")) + value = nvl(value).substring(0, nvl(value).length() - 1); + } + if (name != null && name.trim().length() > 0) { + row = sheet.createRow((short) ++rowNum); + cellNum = 0; + cell = row.createCell((short) cellNum); + cell.setCellValue(name.trim()); + cell.setCellStyle(styleName); + cellNum += 1; + cell = row.createCell((short) cellNum); + cell.setCellValue(value.trim()); + cell.setCellStyle(styleValue); + } + if (name != null && (sheet.getColumnWidth((short) 0) < (short) name.trim().length())) { + sheet.setColumnWidth((short) 0, (short) name.trim().length()); + } + if (sheet.getColumnWidth((short) 1) < (short) value.trim().length()) { + sheet.setColumnWidth((short) 1, (short) value.trim().length()); + } + name = ""; + value = ""; + + } + + try { + SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss"); + Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime()); + SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern()); + + row = sheet.createRow((short) ++rowNum); + cellNum = 0; + cell = row.createCell((short) cellNum); + cell.setCellValue("Report Date/Time"); + cell.setCellStyle(styleName); + cellNum += 1; + cell = row.createCell((short) cellNum); + + cell.setCellValue(dtimestamp.format(sysdate) + " " + Globals.getTimeZone()); + cell.setCellStyle(styleValue); + + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "Excetion in paintExcelParams", ex); + } + } + } + + } // if Iterator iterCheck = paramsList.iterator(); - if(iterCheck.hasNext()) { + if (iterCheck.hasNext()) { rowNum += 2; row = sheet.createRow(rowNum); } - header.setCenter(HSSFHeader.font("Tahoma", "")+ HSSFHeader.fontSize((short) 9)+" " + strBuf.toString()); - HSSFFooter footer = sheet.getFooter(); - footer.setLeft(HSSFFooter.font("Tahoma", "")+ HSSFFooter.fontSize((short) 9)+ "Page " + HSSFFooter.page() - + " of " + HSSFFooter.numPages() ); - footer.setCenter(HSSFFooter.font("Tahoma", "")+ HSSFFooter.fontSize((short) 9)+Globals.getFooterFirstLine()+"\n"+Globals.getFooterSecondLine()); - + header.setCenter(HSSFHeader.font(FONT_TAHOMA, "") + HSSFHeader.fontSize((short) 9) + " " + strBuf.toString()); + Footer footer = sheet.getFooter(); + footer.setLeft(HSSFFooter.font(FONT_TAHOMA, "") + HSSFFooter.fontSize((short) 9) + "Page " + HSSFFooter.page() + + " of " + HSSFFooter.numPages()); + footer.setCenter( + HSSFFooter.font(FONT_TAHOMA, "") + HSSFFooter.fontSize((short) 9) + Globals.getFooterFirstLine() + + "\n" + Globals.getFooterSecondLine()); + } } - private int paintExcelData(final HSSFWorkbook wb, int rowNum, final ReportData rd, final Map styles, - final ReportRuntime rr, final HSSFSheet sheet, final String sql_whole, - final HttpServletRequest request) throws RaptorException { - int mb = 1024*1024; - Runtime runtime = Runtime.getRuntime(); - int returnValue = 0; - HSSFCellStyle styleDefault = wb.createCellStyle(); - HSSFCellStyle styleNumber = wb.createCellStyle(); - HSSFCellStyle styleDecimalNumber = wb.createCellStyle(); - HSSFCellStyle styleCurrencyNumber = wb.createCellStyle(); - HSSFCellStyle styleCurrencyDecimalNumber = wb.createCellStyle(); - HSSFCellStyle styleDate = wb.createCellStyle(); + private int paintExcelData(final XSSFWorkbook wb, int rowNum, final ReportData rd, final Map styles, + final ReportRuntime rr, final XSSFSheet sheet, final String sql_whole, + final HttpServletRequest request) throws RaptorException { + int mb = 1024 * 1024; + Runtime runtime = Runtime.getRuntime(); + int returnValue = 0; + XSSFCellStyle styleDefault = wb.createCellStyle(); + XSSFCellStyle styleNumber = wb.createCellStyle(); + XSSFCellStyle styleDecimalNumber = wb.createCellStyle(); + XSSFCellStyle styleCurrencyNumber = wb.createCellStyle(); + XSSFCellStyle styleCurrencyDecimalNumber = wb.createCellStyle(); + XSSFCellStyle styleDate = wb.createCellStyle(); HtmlStripper strip = new HtmlStripper(); - HSSFCellStyle styleDataHeader = wb.createCellStyle(); - styleDataHeader.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index); - styleDataHeader.setFillPattern(FillPatternType.SOLID_FOREGROUND ); - styleDataHeader.setAlignment(HorizontalAlignment.CENTER); - styleDataHeader.setBorderBottom(BorderStyle.THIN); - styleDataHeader.setBorderTop(BorderStyle.THIN); - styleDataHeader.setBorderRight(BorderStyle.THIN); - styleDataHeader.setBorderLeft(BorderStyle.THIN); - HSSFFont font = wb.createFont(); - font.setFontHeight((short) (font_size / 0.05)); - font.setFontName("Tahoma"); - font.setColor(HSSFColor.BLACK.index); - styleDataHeader.setFont(font); - // Column Header - boolean firstPass = true; - ArrayList cellWidth = new ArrayList(); - java.util.HashMap dataTypeMap = new java.util.HashMap(); - int cellNum = 0; - rowNum += 0; - ColumnHeaderRow chr = null; - String title = ""; - - int columnRows = rr.getVisibleColumnCount() - 1; - - HttpSession session = request.getSession(); - String drilldown_index = (String) session.getAttribute("drilldown_index"); - int index = 0; - try { - index = Integer.parseInt(drilldown_index); - } catch (NumberFormatException ex) { - index = 0; - } - String header = (String) session.getAttribute("TITLE_"+index); - String subtitle = (String) session.getAttribute("SUBTITLE_"+index); - if(nvl(header).length()>0) { - header = Utils.replaceInString(header, "<BR/>", " "); - header = Utils.replaceInString(header, "<br/>", " "); - header = Utils.replaceInString(header, "<br>", " "); - header = strip.stripHtml(nvl(header).trim()); - subtitle = Utils.replaceInString(subtitle, "<BR/>", " "); - subtitle = Utils.replaceInString(subtitle, "<br/>", " "); - subtitle = Utils.replaceInString(subtitle, "<br>", " "); - subtitle = strip.stripHtml(nvl(subtitle).trim()); - HSSFRow row = sheet.createRow(rowNum); - cellNum = 0; - row.createCell((short) cellNum).setCellValue(header); - sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, (short) cellNum, (short) (columnRows))); - rowNum += 1; - row = sheet.createRow(rowNum); - cellNum = 0; - row.createCell((short) cellNum).setCellValue(subtitle); - sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, (short) cellNum, (short) (columnRows))); - rowNum += 1; - } - - for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { - HSSFRow row = sheet.createRow(rowNum); - cellNum = -1; - /*if(rd.reportTotalRowHeaderCols!=null) { - cellNum +=1; - row.createCell((short) cellNum).setCellValue("Total"); - row.createCell((short) cellNum).setCellStyle(styleDataHeader); - //row.getCell((short) cellNum).setCellStyle(styleDataHeader); - }*/ - chr = rd.reportColumnHeaderRows.getNext(); - - if(nvl(sql_whole).length() <= 0 || (!rr.getReportType().equals(AppConstants.RT_LINEAR))) { - if(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) - rd.reportRowHeaderCols.resetNext(0); - else - rd.reportRowHeaderCols.resetNext(1); - - for (; rd.reportRowHeaderCols.hasNext();) { - cellNum += 1; - RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); - - if (firstPass) { - title = rhc.getColumnTitle(); - title = Utils.replaceInString(title,"_nl_", " \n"); - row.createCell((short) cellNum).setCellValue(title); - //commented after bug reported by EPAT 01/17/2015 - //sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum+columnRows, (short) cellNum, (short) (cellNum))); - //System.out.println(" **************** Row Header Title " + rhc.getColumnTitle() + " " + cellNum + " " ); - //System.out.println(cellNum + " " + cellWidth.size()); - if (cellWidth.size() > 0 && cellWidth.size() > cellNum) { - if (((Integer) cellWidth.get(cellNum)).intValue() < rhc - .getColumnTitle().length()) - cellWidth.set(cellNum, new Integer(title.length())); - } else - cellWidth.add(cellNum, new Integer(title.length())); - row.getCell((short) cellNum).setCellStyle(styleDataHeader); - } - - - } // for - - } - - firstPass = false; - -/* for(chr.resetNext(); chr.hasNext(); ) { - ColumnHeader ch = chr.getNext(); - if(ch.isVisible()) { - cellNum += 1; - row.createCell((short) cellNum).setCellValue(ch.getColumnTitle()); -// <td align="center"<%= ch.getColumnWidthHtml() %><%= ch.getColSpanHtml() %><%= ch.getRowSpanHtml() %>> -// <b class=rtableheader><%= ch.getColumnTitleHtml() %></b> -// </td> - } // if - } // for -*/ + XSSFCellStyle styleDataHeader = wb.createCellStyle(); + styleDataHeader.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); + styleDataHeader.setFillPattern(fillPattern.SOLID_FOREGROUND); + styleDataHeader.setAlignment(HorizontalAlignment.CENTER); + styleDataHeader.setBorderBottom(BorderStyle.THIN); + styleDataHeader.setBorderTop(BorderStyle.THIN); + styleDataHeader.setBorderRight(BorderStyle.THIN); + styleDataHeader.setBorderLeft(BorderStyle.THIN); + XSSFFont font = wb.createFont(); + font.setFontHeight((short) (FONT_SIZE / 0.05)); + font.setFontName(FONT_TAHOMA); + font.setBold(true); + font.setColor(HSSFColor.BLACK.index); + styleDataHeader.setFont(font); + boolean firstPass = true; + ArrayList cellWidth = new ArrayList(); + java.util.HashMap dataTypeMap = new java.util.HashMap(); + int cellNum = 0; + rowNum += 0; + ColumnHeaderRow chr = null; + String title = ""; + + int columnRows = rr.getVisibleColumnCount() - 1; + + HttpSession session = request.getSession(); + String drilldown_index = (String) session.getAttribute("drilldown_index"); + int index = 0; + try { + index = Integer.parseInt(drilldown_index); + } catch (NumberFormatException ex) { + index = 0; + } + String header = (String) session.getAttribute("TITLE_" + index); + String subtitle = (String) session.getAttribute("SUBTITLE_" + index); + if (nvl(header).length() > 0) { + header = Utils.replaceInString(header, "<BR/>", " "); + header = Utils.replaceInString(header, "<br/>", " "); + header = Utils.replaceInString(header, "<br>", " "); + header = strip.stripHtml(nvl(header).trim()); + subtitle = Utils.replaceInString(subtitle, "<BR/>", " "); + subtitle = Utils.replaceInString(subtitle, "<br/>", " "); + subtitle = Utils.replaceInString(subtitle, "<br>", " "); + subtitle = strip.stripHtml(nvl(subtitle).trim()); + XSSFRow row = sheet.createRow(rowNum); + cellNum = 0; + row.createCell((short) cellNum).setCellValue(header); + sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, (short) cellNum, (short) (columnRows))); + rowNum += 1; + row = sheet.createRow(rowNum); + cellNum = 0; + row.createCell((short) cellNum).setCellValue(subtitle); + sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, (short) cellNum, (short) (columnRows))); + rowNum += 1; + } + + for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { + XSSFRow row = sheet.createRow(rowNum); + cellNum = -1; - - for (chr.resetNext(); chr.hasNext();) { - ColumnHeader ch = chr.getNext(); - if(ch.isVisible()) { - cellNum += 1; - - int colSpan = ch.getColSpan()-1; - title = ch.getColumnTitle(); - title = Utils.replaceInString(title,"_nl_", " \n"); - row.createCell((short) cellNum).setCellValue(title); - if(colSpan > 0) { - for ( int k = 1; k <= colSpan; k++ ) { - row.createCell((short) cellNum+k); - } - sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, (short) cellNum, (short) (cellNum+colSpan))); - } - - - -/* if (cellWidth.size() > cellNum) { - if (((Integer) cellWidth.get(cellNum)).intValue() < ch - .getColumnTitle().length()) - cellWidth - .set((cellNum), new Integer(ch.getColumnTitle().length())); - } else - cellWidth.add((cellNum), new Integer(ch.getColumnTitle().length())); -*/ row.getCell((short) (cellNum)).setCellStyle(styleDataHeader); - for ( int k = 1; k <= colSpan; k++ ) { - row.getCell((short) (cellNum+k)).setCellStyle(styleDataHeader); - } - - if(colSpan > 0) - cellNum += colSpan; - } - } // for - -/* int cw = 0; - for (int i = 0; i < cellWidth.size(); i++) { - cw = ((Integer) cellWidth.get(i)).intValue() + 6; - sheet.setColumnWidth((short) (i), (short) ((cw * 8) / ((double) 1 / 20))); - } -*/ - rowNum += 1; - } // for - - - // Data - // Create some cell styles. - HSSFCellStyle styleCell = null; - - HSSFCellStyle styleTotal = wb.createCellStyle(); - HSSFCellStyle styleCurrencyTotal = wb.createCellStyle(); - HSSFCellStyle styleDefaultTotal = wb.createCellStyle(); - HSSFCellStyle styleCurrencyDecimalNumberTotal = wb.createCellStyle(); - HSSFCellStyle styleDecimalNumberTotal = wb.createCellStyle(); - HSSFCellStyle styleCurrencyNumberTotal = wb.createCellStyle(); - + chr = rd.reportColumnHeaderRows.getNext(); + + if (nvl(sql_whole).length() <= 0 || (!rr.getReportType().equals(AppConstants.RT_LINEAR))) { + if (rr.getReportType().equals(AppConstants.RT_CROSSTAB)) + rd.reportRowHeaderCols.resetNext(0); + else + rd.reportRowHeaderCols.resetNext(1); + + for (; rd.reportRowHeaderCols.hasNext();) { + cellNum += 1; + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + + if (firstPass) { + title = rhc.getColumnTitle(); + title = Utils.replaceInString(title, "_nl_", " \n"); + row.createCell((short) cellNum).setCellValue(title); + if (cellWidth.size() > 0 && cellWidth.size() > cellNum) { + if (((Integer) cellWidth.get(cellNum)).intValue() < rhc + .getColumnTitle().length()) + cellWidth.set(cellNum, new Integer(title.length())); + } else + cellWidth.add(cellNum, new Integer(title.length())); + row.getCell((short) cellNum).setCellStyle(styleDataHeader); + } + + } // for + + } + + firstPass = false; + + + for (chr.resetNext(); chr.hasNext();) { + ColumnHeader ch = chr.getNext(); + if (ch.isVisible()) { + cellNum += 1; + + int colSpan = ch.getColSpan() - 1; + title = ch.getColumnTitle(); + title = Utils.replaceInString(title, "_nl_", " \n"); + row.createCell((short) cellNum).setCellValue(title); + if (colSpan > 0) { + for (int k = 1; k <= colSpan; k++) { + row.createCell((short) cellNum + k); + } + sheet.addMergedRegion( + new CellRangeAddress(rowNum, rowNum, (short) cellNum, (short) (cellNum + colSpan))); + } + row.getCell((short) (cellNum)).setCellStyle(styleDataHeader); + for (int k = 1; k <= colSpan; k++) { + row.getCell((short) (cellNum + k)).setCellStyle(styleDataHeader); + } - // Create some fonts. - HSSFFont fontDefault = wb.createFont(); - HSSFFont fontBold = wb.createFont(); - // Initialize the styles & fonts. - // The default will be plain . - fontDefault.setColor((short) HSSFFont.COLOR_NORMAL); - fontDefault.setFontHeight((short) (font_size / 0.05)); - fontDefault.setFontName("Tahoma"); - - // The default will be bold black tachoma 10pt text. - fontBold.setColor((short) HSSFFont.COLOR_NORMAL); - fontBold.setFontHeight((short) (font_size / 0.05)); - fontBold.setFontName("Tahoma"); - fontBold.setBold(true); - // Style default will be normal with no background - styleDefault.setAlignment(HorizontalAlignment.CENTER); - styleDefault.setBorderBottom(BorderStyle.THIN); - styleDefault.setBorderTop(BorderStyle.THIN); - styleDefault.setBorderLeft(BorderStyle.THIN); - styleDefault.setBorderRight(BorderStyle.THIN); - styleDefault.setFillPattern(FillPatternType.NO_FILL); - styleDefault.setFont(fontDefault); - styleDefault.setWrapText(true); - //Number - styleNumber.setAlignment(HorizontalAlignment.CENTER); - styleNumber.setBorderBottom(BorderStyle.THIN); - styleNumber.setBorderTop(BorderStyle.THIN); - styleNumber.setBorderLeft(BorderStyle.THIN); - styleNumber.setBorderRight(BorderStyle.THIN); - styleNumber.setFillPattern(FillPatternType.NO_FILL); - styleNumber.setFont(fontDefault); - try { - styleNumber.setDataFormat((short)0x26); - } catch (Exception e) { - - } - //Decimal Number + if (colSpan > 0) + cellNum += colSpan; + } + } + rowNum += 1; + } + XSSFCellStyle styleCell = null; + + XSSFCellStyle styleTotal = wb.createCellStyle(); + XSSFCellStyle styleCurrencyTotal = wb.createCellStyle(); + XSSFCellStyle styleDefaultTotal = wb.createCellStyle(); + XSSFCellStyle styleCurrencyDecimalNumberTotal = wb.createCellStyle(); + XSSFCellStyle styleDecimalNumberTotal = wb.createCellStyle(); + XSSFCellStyle styleCurrencyNumberTotal = wb.createCellStyle(); + XSSFFont fontDefault = wb.createFont(); + XSSFFont fontBold = wb.createFont(); + fontDefault.setColor((short) HSSFFont.COLOR_NORMAL); + fontDefault.setFontHeight((short) (FONT_SIZE / 0.05)); + fontDefault.setFontName(FONT_TAHOMA); + + fontBold.setColor((short) HSSFFont.COLOR_NORMAL); + fontBold.setFontHeight((short) (FONT_SIZE / 0.05)); + fontBold.setFontName(FONT_TAHOMA); + fontBold.setBold(true); + styleDefault.setAlignment(HorizontalAlignment.CENTER); + styleDefault.setBorderBottom(BorderStyle.THIN); + styleDefault.setBorderTop(BorderStyle.THIN); + styleDefault.setBorderLeft(BorderStyle.THIN); + styleDefault.setBorderRight(BorderStyle.THIN); + styleDefault.setFillPattern(fillPattern.NO_FILL); + styleDefault.setFont(fontDefault); + styleDefault.setWrapText(true); + styleNumber.setAlignment(HorizontalAlignment.CENTER); + styleNumber.setBorderBottom(BorderStyle.THIN); + styleNumber.setBorderTop(BorderStyle.THIN); + styleNumber.setBorderLeft(BorderStyle.THIN); + styleNumber.setBorderRight(BorderStyle.THIN); + styleNumber.setFillPattern(fillPattern.NO_FILL); + styleNumber.setFont(fontDefault); + try { + styleNumber.setDataFormat((short) 0x26);// HSSFDataFormat.getBuiltinFormat("(#,##0_);[Red](#,##0)")); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Excetion in setDataFormat", e); + } styleDecimalNumber.setAlignment(HorizontalAlignment.CENTER); styleDecimalNumber.setBorderBottom(BorderStyle.THIN); styleDecimalNumber.setBorderTop(BorderStyle.THIN); styleDecimalNumber.setBorderLeft(BorderStyle.THIN); styleDecimalNumber.setBorderRight(BorderStyle.THIN); - styleDecimalNumber.setFillPattern(FillPatternType.NO_FILL); + styleDecimalNumber.setFillPattern(fillPattern.NO_FILL); styleDecimalNumber.setFont(fontDefault); - styleDecimalNumber.setDataFormat((short)0x27); + styleDecimalNumber.setDataFormat((short) 0x27);// HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); - //Decimal Number styleDecimalNumberTotal.setAlignment(HorizontalAlignment.CENTER); styleDecimalNumberTotal.setBorderBottom(BorderStyle.THIN); styleDecimalNumberTotal.setBorderTop(BorderStyle.THIN); styleDecimalNumberTotal.setBorderLeft(BorderStyle.THIN); styleDecimalNumberTotal.setBorderRight(BorderStyle.THIN); - styleDecimalNumberTotal.setFillPattern(FillPatternType.NO_FILL); + styleDecimalNumberTotal.setFillPattern(fillPattern.NO_FILL); styleDecimalNumberTotal.setFont(fontBold); - styleDecimalNumberTotal.setDataFormat((short)0x27);//HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); - - //CurrencyNumber - styleCurrencyDecimalNumber.setAlignment(HorizontalAlignment.CENTER); - styleCurrencyDecimalNumber.setBorderBottom(BorderStyle.THIN); - styleCurrencyDecimalNumber.setBorderTop(BorderStyle.THIN); - styleCurrencyDecimalNumber.setBorderLeft(BorderStyle.THIN); - styleCurrencyDecimalNumber.setBorderRight(BorderStyle.THIN); - styleCurrencyDecimalNumber.setFillPattern(FillPatternType.NO_FILL); - styleCurrencyDecimalNumber.setFont(fontDefault); - styleCurrencyDecimalNumber.setDataFormat((short)8); - - //currency number bold - styleCurrencyDecimalNumberTotal.setAlignment(HorizontalAlignment.CENTER); - styleCurrencyDecimalNumberTotal.setBorderBottom(BorderStyle.THIN); - styleCurrencyDecimalNumberTotal.setBorderTop(BorderStyle.THIN); - styleCurrencyDecimalNumberTotal.setBorderLeft(BorderStyle.THIN); - styleCurrencyDecimalNumberTotal.setBorderRight(BorderStyle.THIN); - styleCurrencyDecimalNumberTotal.setFillPattern(FillPatternType.NO_FILL); - styleCurrencyDecimalNumberTotal.setFont(fontBold); - styleCurrencyDecimalNumberTotal.setDataFormat((short)8);//HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); - - - //CurrencyNumber + styleDecimalNumberTotal.setDataFormat((short) 0x27);// HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); + + styleCurrencyDecimalNumber.setAlignment(HorizontalAlignment.CENTER); + styleCurrencyDecimalNumber.setBorderBottom(BorderStyle.THIN); + styleCurrencyDecimalNumber.setBorderTop(BorderStyle.THIN); + styleCurrencyDecimalNumber.setBorderLeft(BorderStyle.THIN); + styleCurrencyDecimalNumber.setBorderRight(BorderStyle.THIN); + styleCurrencyDecimalNumber.setFillPattern(fillPattern.NO_FILL); + styleCurrencyDecimalNumber.setFont(fontDefault); + styleCurrencyDecimalNumber.setDataFormat((short) 8);// HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); + + styleCurrencyDecimalNumberTotal.setAlignment(HorizontalAlignment.CENTER); + styleCurrencyDecimalNumberTotal.setBorderBottom(BorderStyle.THIN); + styleCurrencyDecimalNumberTotal.setBorderTop(BorderStyle.THIN); + styleCurrencyDecimalNumberTotal.setBorderLeft(BorderStyle.THIN); + styleCurrencyDecimalNumberTotal.setBorderRight(BorderStyle.THIN); + styleCurrencyDecimalNumberTotal.setFillPattern(fillPattern.NO_FILL); + styleCurrencyDecimalNumberTotal.setFont(fontBold); + styleCurrencyDecimalNumberTotal.setDataFormat((short) 8);// HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); + styleCurrencyNumber.setAlignment(HorizontalAlignment.CENTER); styleCurrencyNumber.setBorderBottom(BorderStyle.THIN); styleCurrencyNumber.setBorderTop(BorderStyle.THIN); styleCurrencyNumber.setBorderLeft(BorderStyle.THIN); styleCurrencyNumber.setBorderRight(BorderStyle.THIN); - // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); - styleCurrencyNumber.setFillPattern(FillPatternType.NO_FILL); + styleCurrencyNumber.setFillPattern(fillPattern.NO_FILL); styleCurrencyNumber.setFont(fontDefault); - styleCurrencyNumber.setDataFormat((short) 6); - + styleCurrencyNumber.setDataFormat((short) 6);// HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); - //CurrencyNumber styleCurrencyNumberTotal.setAlignment(HorizontalAlignment.CENTER); styleCurrencyNumberTotal.setBorderBottom(BorderStyle.THIN); styleCurrencyNumberTotal.setBorderTop(BorderStyle.THIN); styleCurrencyNumberTotal.setBorderLeft(BorderStyle.THIN); styleCurrencyNumberTotal.setBorderRight(BorderStyle.THIN); - // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); - styleCurrencyNumberTotal.setFillPattern(FillPatternType.NO_FILL); + styleCurrencyNumberTotal.setFillPattern(fillPattern.NO_FILL); styleCurrencyNumberTotal.setFont(fontBold); - styleCurrencyNumberTotal.setDataFormat((short) 6); - - //Date - styleDate.setAlignment(HorizontalAlignment.CENTER); - styleDate.setBorderBottom(BorderStyle.THIN); - styleDate.setBorderTop(BorderStyle.THIN); - styleDate.setBorderLeft(BorderStyle.THIN); - styleDate.setBorderRight(BorderStyle.THIN); - styleDate.setFillPattern(FillPatternType.NO_FILL); - styleDate.setFont(fontDefault); - styleDate.setDataFormat((short)0xe);//HSSFDataFormat.getBuiltinFormat("m/d/yy")); - - // Style for Total will be Bold with normal font with no background - styleTotal.setAlignment(HorizontalAlignment.CENTER); - styleTotal.setBorderBottom(BorderStyle.THIN); - styleTotal.setBorderTop(BorderStyle.THIN); - styleTotal.setBorderLeft(BorderStyle.THIN); - styleTotal.setBorderRight(BorderStyle.THIN); - styleTotal.setFillPattern(FillPatternType.NO_FILL); - styleTotal.setDataFormat((short)0x28); - styleTotal.setFont(fontBold); + styleCurrencyNumberTotal.setDataFormat((short) 6);// HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); + + styleDate.setAlignment(HorizontalAlignment.CENTER); + styleDate.setBorderBottom(BorderStyle.THIN); + styleDate.setBorderTop(BorderStyle.THIN); + styleDate.setBorderLeft(BorderStyle.THIN); + styleDate.setBorderRight(BorderStyle.THIN); + styleDate.setFillPattern(fillPattern.NO_FILL); + styleDate.setFont(fontDefault); + styleDate.setDataFormat((short) 0xe);// HSSFDataFormat.getBuiltinFormat("m/d/yy")); + + styleTotal.setAlignment(HorizontalAlignment.CENTER); + styleTotal.setBorderBottom(BorderStyle.THIN); + styleTotal.setBorderTop(BorderStyle.THIN); + styleTotal.setBorderLeft(BorderStyle.THIN); + styleTotal.setBorderRight(BorderStyle.THIN); + styleTotal.setFillPattern(fillPattern.NO_FILL); + styleTotal.setDataFormat((short) 0x28);// HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); + styleTotal.setFont(fontBold); styleCurrencyTotal.setAlignment(HorizontalAlignment.CENTER); styleCurrencyTotal.setBorderBottom(BorderStyle.THIN); styleCurrencyTotal.setBorderTop(BorderStyle.THIN); styleCurrencyTotal.setBorderLeft(BorderStyle.THIN); styleCurrencyTotal.setBorderRight(BorderStyle.THIN); - styleCurrencyTotal.setFillPattern(FillPatternType.NO_FILL); - styleCurrencyTotal.setDataFormat((short)8); - styleCurrencyTotal.setFont(fontBold); - + styleCurrencyTotal.setFillPattern(fillPattern.NO_FILL); + styleCurrencyTotal.setDataFormat((short) 8);// HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); + styleCurrencyTotal.setFont(fontBold); + styleDefaultTotal.setAlignment(HorizontalAlignment.CENTER); styleDefaultTotal.setBorderBottom(BorderStyle.THIN); styleDefaultTotal.setBorderTop(BorderStyle.THIN); styleDefaultTotal.setBorderLeft(BorderStyle.THIN); styleDefaultTotal.setBorderRight(BorderStyle.THIN); - styleDefaultTotal.setFillPattern(FillPatternType.NO_FILL); - styleDefaultTotal.setDataFormat((short)0x28); - styleDefaultTotal.setFont(fontBold); - - firstPass = true; - // Declare a row object reference. - HSSFRow row = null; - // Declare a cell object reference. - HSSFCell cell = null; - //HSSFCell cellNumber = null; - //HSSFCell cellCurrencyNumber = null; - //HSSFCell cellDate = null; - - //All the possible combinations of date format - SimpleDateFormat MMDDYYYYFormat = new SimpleDateFormat("MM/dd/yyyy"); - SimpleDateFormat YYYYMMDDFormat = new SimpleDateFormat("yyyy/MM/dd"); - SimpleDateFormat MONYYYYFormat = new SimpleDateFormat("MMM yyyy"); - SimpleDateFormat MMYYYYFormat = new SimpleDateFormat("MM/yyyy"); + styleDefaultTotal.setFillPattern(fillPattern.NO_FILL); + styleDefaultTotal.setDataFormat((short) 0x28); + styleDefaultTotal.setFont(fontBold); + + firstPass = true; + XSSFRow row = null; + XSSFCell cell = null; + + SimpleDateFormat MMDDYYYYFormat = new SimpleDateFormat("MM/dd/yyyy"); + 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 YYYYMMDDDASHFormat = new SimpleDateFormat("yyyy-MM-dd"); - SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - SimpleDateFormat DDMONYYYYFormat = new SimpleDateFormat("dd-MMM-yyyy"); - SimpleDateFormat MONTHYYYYFormat = new SimpleDateFormat("MMMMM, yyyy"); - 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 DDMONYYHHMMFormat = new SimpleDateFormat("dd-MMM-yy 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 MMDDYYYYHHMMZFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm z"); - SimpleDateFormat MMMMMDDYYYYHHMMSS = new SimpleDateFormat("MMMMM-dd-yyyy HH:mm:ss"); - - + SimpleDateFormat YYYYMMDDDASHFormat = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + SimpleDateFormat DDMONYYYYFormat = new SimpleDateFormat("dd-MMM-yyyy"); + SimpleDateFormat MONTHYYYYFormat = new SimpleDateFormat("MMMMM, yyyy"); + 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 DDMONYYHHMMFormat = new SimpleDateFormat("dd-MMM-yy 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 MMDDYYYYHHMMZFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm z"); + SimpleDateFormat MMMMMDDYYYYHHMMSS = new SimpleDateFormat("MMMMM-dd-yyyy HH:mm:ss"); + ResultSetMetaData rsmd = null; CreationHelper createHelper = wb.getCreationHelper(); - if(nvl(sql_whole).length() >0 && rr.getReportType().equals(AppConstants.RT_LINEAR)) { - try(Connection conn = ConnectionUtils.getConnection(rr.getDbInfo()); - Statement st = conn.createStatement(); - ResultSet rs = st.executeQuery(sql_whole)) { - System.out.println("************* Map Whole SQL *************"); - System.out.println(sql_whole); - System.out.println("*****************************************"); - rsmd = rs.getMetaData(); - int numberOfColumns = rsmd.getColumnCount(); - HashMap colHash = new HashMap(); - DataRow dr = null; - int j = 0; - int rowCount = 0; - while(rs.next()) { - rowCount++; - row = sheet.createRow(rowNum); - cellNum = -1; - colHash = new HashMap(); - for (int i = 1; i <= numberOfColumns; i++) { - colHash.put(rsmd.getColumnLabel(i).toUpperCase(), strip.stripHtml(rs.getString(i))); - } - rd.reportDataRows.resetNext(); - dr = rd.reportDataRows.getNext(); - j = 0; - - /*if(rd.reportTotalRowHeaderCols!=null) { - //cellNum = -1; - //for (rd.reportRowHeaderCols.resetNext(); rd.reportRowHeaderCols.hasNext();) { - cellNum += 1; - //RowHeaderCol rhc = rd.reportRowHeaderCols.getRowHeaderCol(0); - //if (firstPass) - // rhc.resetNext(); - //RowHeader rh = rhc.getRowHeader(rowCount-1); - row.createCell((short) cellNum).setCellValue(rowCount); - row.getCell((short) cellNum).setCellStyle(styleDefault); - if (firstPass) - cellWidth.add(cellNum, new Integer((rowCount+"").length())); - else - cellWidth.set(cellNum, new Integer((rowCount+"").length())); - - //} // for - }*/ - firstPass = false; - for (dr.resetNext(); dr.hasNext();j++) { - styleCell = null; - DataValue dv = dr.getNext(); - HtmlFormatter htmlFormat = dv.getCellFormatter(); - if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) - styleCell = (HSSFCellStyle) styles.get(nvl(dr.getFormatId(),"default")); - if (htmlFormat != null && dv.getFormatId() != null && styles != null) - styleCell = (HSSFCellStyle) styles.get(nvl(dv.getFormatId(),"default")); - String value = nvl((String)colHash.get(dv.getColId().toUpperCase())); - - boolean bold = false; - - if(dv.isVisible()) { - cellNum += 1; - cell = row.createCell((short) cellNum); - //cell.setCellValue(strip.stripHtml(dv.getDisplayValue())); - String dataType = (String) (dataTypeMap.get(dv.getColId())); - //System.out.println("Value " + value + " " + (( dataType !=null && dataType.equals("DATE")) || (dv.getColName()!=null && dv.getColName().toLowerCase().endsWith("date"))) ); - if (dataType!=null && dataType.equals("NUMBER")){ - int zInt = 0; - if (value.equals("null")){ - cell.setCellValue(zInt); - }else{ - - if ((value.indexOf("."))!= -1){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - - String tempDollar = dv.getDisplayValue().trim(); - tempDollar = tempDollar.replaceAll(" ", "").substring(0); - tempDollar = tempDollar.replaceAll("\\$", "").substring(0); - if ((tempDollar.indexOf(","))!= -1){ - tempDollar = tempDollar.replaceAll(",", ""); - } - //System.out.println("The final string 1 is "+tempDollar); - double tempDoubleDollar = 0.0; - try { - tempDoubleDollar = Double.parseDouble(tempDollar); - if(styleCell!=null) { - styleCell.setDataFormat((short) 8);//HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleCurrencyDecimalNumber); - cell.setCellValue(tempDoubleDollar); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - //cell.setCellStyle(styleDefault); - cell.setCellValue(tempDollar); - } - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - double tempDouble = 0.0; - try { - tempDouble = Double.parseDouble(value); - if(styleCell!=null) { - styleCell.setDataFormat((short)0x28);//HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDecimalNumber); - cell.setCellValue(tempDouble); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(value); - } - - } - }else { - if (!(value.equals(""))){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - //if (dv.getDisplayValue().startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempInt = value.trim(); - tempInt = tempInt.replaceAll(" ", "").substring(0); - tempInt = tempInt.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempInt); - //System.out.println("Before copy Value |" + tempInt); - //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); - //System.out.println("After copy Value |" + tempInt); - if ((tempInt.indexOf(","))!= -1){ - tempInt = tempInt.replaceAll(",", ""); - } - //System.out.println("The final string INT is "+tempInt); - Long tempIntDollar = 0L; - try { - tempIntDollar = Long.parseLong(tempInt); - if(styleCell!=null) { - styleCell.setDataFormat((short) 6);//HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleCurrencyNumber); - cell.setCellValue(tempIntDollar); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempInt); - } - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - String tempStr = value.trim(); - if ((tempStr.indexOf(","))!= -1){ - tempStr = tempStr.replaceAll(",", ""); - } - Long temp = 0L; - - try { - temp = Long.parseLong(tempStr); - if(styleCell!=null) { - styleCell.setDataFormat((short) 0x26);//HSSFDataFormat.getBuiltinFormat("(#,##0_);[Red](#,##0)")); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleNumber); - cell.setCellValue(temp); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempStr); - } - - - } - //int temp = Integer.parseInt(value.trim()); - // cell.setCellValue(temp); - //}else{ - // cell.setCellValue(strip.stripHtml(value)); - //} - } - } - } - - }else if ( ( dataType !=null && dataType.equals("DATE")) || (dv.getDisplayName()!=null && dv.getDisplayName().toLowerCase().endsWith("date")) || - (dv.getColId()!=null && dv.getColId().toLowerCase().endsWith("date")) || - (dv.getColName()!=null && dv.getColName().toLowerCase().endsWith("date")) ) { - //cellDate = row.createCell((short) cellNum); - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("mm/dd/yy")); - - if(styleCell!=null) { - styleCell.setDataFormat((short) 0xe);//HSSFDataFormat.getBuiltinFormat("m/d/yy")); - cell.setCellStyle(styleCell); + if (nvl(sql_whole).length() > 0 && rr.getReportType().equals(AppConstants.RT_LINEAR)) { + try (Connection conn = ConnectionUtils.getConnection(rr.getDbInfo()); + Statement st = conn.createStatement(); + ResultSet rs = st.executeQuery(sql_whole)) { + System.out.println("************* Map Whole SQL *************"); + System.out.println(sql_whole); + System.out.println("*****************************************"); + rsmd = rs.getMetaData(); + int numberOfColumns = rsmd.getColumnCount(); + HashMap colHash = new HashMap(); + DataRow dr = null; + int j = 0; + int rowCount = 0; + while (rs.next()) { + rowCount++; + row = sheet.createRow(rowNum); + cellNum = -1; + colHash = new HashMap(); + for (int i = 1; i <= numberOfColumns; i++) { + colHash.put(rsmd.getColumnLabel(i).toUpperCase(), strip.stripHtml(rs.getString(i))); + } + rd.reportDataRows.resetNext(); + dr = rd.reportDataRows.getNext(); + j = 0; + + firstPass = false; + for (dr.resetNext(); dr.hasNext(); j++) { + styleCell = null; + DataValue dv = dr.getNext(); + HtmlFormatter htmlFormat = dv.getCellFormatter(); + if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) + styleCell = (XSSFCellStyle) styles.get(nvl(dr.getFormatId(), DEFAULT)); + if (htmlFormat != null && dv.getFormatId() != null && styles != null) + styleCell = (XSSFCellStyle) styles.get(nvl(dv.getFormatId(), DEFAULT)); + String value = nvl((String) colHash.get(dv.getColId().toUpperCase())); + + boolean bold = false; + + if (dv.isVisible()) { + cellNum += 1; + cell = row.createCell((short) cellNum); + String dataType = (String) (dataTypeMap.get(dv.getColId())); + if (dataType != null && dataType.equals("NUMBER")) { + int zInt = 0; + if (value.equals("null")) { + cell.setCellValue(zInt); + } else { + + if ((value.indexOf(".")) != -1) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + + String tempDollar = dv.getDisplayValue().trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + if ((tempDollar.indexOf(",")) != -1) { + tempDollar = tempDollar.replaceAll(",", ""); + } + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if (styleCell != null) { + styleCell.setDataFormat((short) 8);// HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyDecimalNumber); + cell.setCellValue(tempDoubleDollar); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempDollar); + } + } else { + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(value); + if (styleCell != null) { + styleCell.setDataFormat((short) 0x28);// HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDecimalNumber); + cell.setCellValue(tempDouble); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(value); + } + + } + } else { + if (!(value.equals(""))) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + if ((tempInt.indexOf(",")) != -1) { + tempInt = tempInt.replaceAll(",", ""); + } + Long tempIntDollar = 0L; + try { + tempIntDollar = Long.parseLong(tempInt); + if (styleCell != null) { + styleCell.setDataFormat((short) 6);// HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyNumber); + cell.setCellValue(tempIntDollar); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempInt); + } + } else { + String tempStr = value.trim(); + if ((tempStr.indexOf(",")) != -1) { + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if (styleCell != null) { + styleCell.setDataFormat((short) 0x26);// HSSFDataFormat.getBuiltinFormat("(#,##0_);[Red](#,##0)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleNumber); + cell.setCellValue(temp); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempStr); + } + + } + } + } + } + + } else if ((dataType != null && dataType.equals("DATE")) + || (dv.getDisplayName() != null + && dv.getDisplayName().toLowerCase().endsWith("date")) + || + (dv.getColId() != null && dv.getColId().toLowerCase().endsWith("date")) || + (dv.getColName() != null && dv.getColName().toLowerCase().endsWith("date"))) { + if (styleCell != null) { + styleCell.setDataFormat((short) 0xe);// HSSFDataFormat.getBuiltinFormat("m/d/yy")); + cell.setCellStyle(styleCell); } else - cell.setCellStyle(styleDate); - //String MY_DATE_FORMAT = "yyyy-MM-dd"; - //value = nvl(value).length()<=0?nvl(dv.getDisplayValue()):value; - Date date = null; - int flag = 0; - date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); - flag = 1; - } - if(date==null) - date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy h:mm")); - flag = 1; - } - if(date==null) - date = MMDDYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy")); - flag = 1; - } - if(date==null) - date = MMDDYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yyyy h:mm:ss")); - flag = 1; - } - if(date==null) - date = MMDDYYYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); - flag = 1; - } - if(date==null) - date = MMDDYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yyyy")); - flag = 1; - } - if(date==null) - date = YYYYMMDDFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("yyyy/m/d")); - flag = 1; - } - if(date==null) - date = timestampFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("yyyy-m-d h:mm:ss")); //yyyy-MM-dd HH:mm:ss - flag = 1; - } - if(date==null) - date = MONYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("mmm yyyy")); - flag = 1; - } - if(date==null) - date = MMYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/yyyy")); - flag = 1; - } - if(date==null) - date = MMMMMDDYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("mmm/d/yyyy")); - flag = 1; - } - if(date==null) - date = MONTHYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("mmm/yyyy")); - flag = 1; - } - if(date==null) - date = YYYYMMDDHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("yyyy/m/d h:mm:ss")); - flag = 1; - } - if(date==null) - date = YYYYMMDDDASHFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("yyyy-m-d")); - flag = 1; - } - if(date==null) - date = YYYYMMDDHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("yyyy/m/d h:mm")); - flag = 1; - } - if(date==null) - date = DDMONYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("d-mmm-yyyy h:mm:ss")); - flag = 1; - } - if(date==null) - date = DDMONYYYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("d-mmm-yyyy h:mm")); - flag = 1; - } - if(date==null) - date = DDMONYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("d-mmm-yy h:mm")); - flag = 1; - } - if(date==null) - date = DDMONYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("d-mmm-yyyy")); - flag = 1; - } - if(date==null) - date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); - flag = 1; - } - if(date==null) - date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy h:mm")); - flag = 1; - } - if(date==null) - date = MMDDYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy")); - flag = 1; - } - if(date==null) - date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy h:mm")); - flag = 1; - } - if(date==null) - date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); - flag = 1; - } - if(date==null) - date = MMDDYYYYHHMMZFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); - flag = 1; - } - if(date==null) - date = MMMMMDDYYYYHHMMSS.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); - flag = 1; - } - - if(date!=null) { - //System.out.println("ExcelDate " + HSSFDateUtil.getExcelDate(date)); - cell.setCellValue(HSSFDateUtil.getExcelDate(date)); - try { - String str = cell.getStringCellValue(); - } catch (IllegalStateException ex) { /*cell.getCellStyle().setDataFormat((short)0);*/cell.setCellValue(value);} - } else { - /*cell.getCellStyle().setDataFormat((short)0);*/ - cell.setCellValue(value); - } - //cellDate.setCellValue(date); - //cellDate.setCellValue(value); //cellDate.setCellValue(date); - //cellDate.setCellValue(dv.getDisplayValue()); - - }else if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ - //cellNumber = row.createCell((short) cellNum); - //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); - //cellNumber.setCellValue(dv.getDisplayValue()); - cell = row.createCell((short) cellNum); - int zInt = 0; - if (value.equals("null")){ - cell.setCellValue(zInt); - }else{ - - if ((value.indexOf("."))!= -1){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - - //if (value.startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempDollar = value.trim(); - tempDollar = tempDollar.replaceAll(" ", "").substring(0); - tempDollar = tempDollar.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempDollar); - //System.out.println("Before copy Value |" + tempDollar); - //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); - //System.out.println("After copy Value |" + tempDollar); - if ((tempDollar.indexOf(","))!= -1){ - tempDollar = tempDollar.replaceAll(",", ""); - } - //System.out.println("The final string 2IF is "+tempDollar); - double tempDoubleDollar = 0.0; - try { - tempDoubleDollar = Double.parseDouble(tempDollar); - if(styleCell!=null) { - styleCell.setDataFormat((short) 8);//HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleCurrencyDecimalNumber); - cell.setCellValue(tempDoubleDollar); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempDollar); - } - - - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - String tempDoubleStr = value.trim(); - tempDoubleStr = tempDoubleStr.replaceAll(" ", "").substring(0); - if ((tempDoubleStr.indexOf(","))!= -1){ - tempDoubleStr = tempDoubleStr.replaceAll(",", ""); - } - double tempDouble = 0.0; - try { - tempDouble = Double.parseDouble(tempDoubleStr); - if(styleCell!=null) { - styleCell.setDataFormat((short)0x28 );//HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDecimalNumber); - cell.setCellValue(tempDouble); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempDoubleStr); - } - } - - }else { - if (!(value.equals(""))){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - //if (value.startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempInt = value.trim(); - tempInt = tempInt.replaceAll(" ", "").substring(0); - tempInt = tempInt.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempInt); - //System.out.println("Before copy Value |" + tempInt); - //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); - //System.out.println("After copy Value |" + tempInt); - if ((tempInt.indexOf(","))!= -1){ - tempInt = tempInt.replaceAll(",", ""); - } - //System.out.println("The final string INT 2 is "+tempInt); - - Long tempIntDollar = 0L; - - try { - tempIntDollar = Long.parseLong(tempInt); - if(styleCell!=null) { - styleCell.setDataFormat((short) 6);//HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleCurrencyNumber); - cell.setCellValue(tempIntDollar); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempInt); - } - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - String tempStr = value.trim(); - if ((tempStr.indexOf(","))!= -1){ - tempStr = tempStr.replaceAll(",", ""); - } - Long temp = 0L; - - try { - temp = Long.parseLong(tempStr); - if(styleCell!=null) { - styleCell.setDataFormat((short) 0x26);//HSSFDataFormat.getBuiltinFormat("(#,##0_);[Red](#,##0)")); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleNumber); - cell.setCellValue(temp); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempStr); - } - } - //int temp = Integer.parseInt(dv.getDisplayValue().trim()); - // cell.setCellValue(temp); - //}else{ - // cell.setCellValue(strip.stripHtml(dv.getDisplayValue())); - //} - } else { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - } - } - } - - - } - else { - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("General")); - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(strip.stripHtml(value)); - } - - //if (!(value.equals(""))){ - //int temp = Integer.parseInt(value.trim()); - //cell.setCellValue(temp); - //}else{ - // cell.setCellValue(strip.stripHtml(value)); - //} - //HSSFCellStyle styleFormat = null; - //HSSFCellStyle numberStyle = null; - //HSSFFont formatFont = null; - //short fgcolor = 0; - //short fillpattern = 0; - if (cellWidth.size() > cellNum) { - if (((Integer) cellWidth.get(cellNum)).intValue() < dv - .getDisplayValue().length()) - cellWidth.set((cellNum), - (value.length()<=Globals.getMaxCellWidthInExcel())?new Integer(value.length()):new Integer(Globals.getMaxCellWidthInExcel())); - } else - cellWidth.add((cellNum), (value.length()<=Globals.getMaxCellWidthInExcel())?new Integer(value.length()):new Integer(Globals.getMaxCellWidthInExcel())); - //System.out.println("1IF "+ (dv.isBold()) + " "+ value + " " + dv.getDisplayTotal() + " " + dv.getColName() ); - if (dv.isBold()) { - if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ - if (value!=null && (value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - cell.setCellStyle(styleCurrencyTotal); - } - else { - cell.setCellStyle(styleTotal); - } - } else { - cell.setCellStyle(styleDefaultTotal); - } - bold = true; - } - //System.out.println("2IF "+ (dr.isRowFormat()) + " " + (dv.isCellFormat()) + " " + (styles!=null)); - if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) { - //cell.setCellStyle((HSSFCellStyle) styles.get(nvl(dr.getFormatId(),"default"))); - continue; - } - //System.out.println("3IF "+ (htmlFormat != null) + " " + (dv.getFormatId() != null) + " " + (bold == false) + " "+ (styles != null)); - if (htmlFormat != null && dv.getFormatId() != null && bold == false - && styles != null) { - //cell.setCellStyle((HSSFCellStyle) styles.get(nvl(dv.getFormatId(),"default"))); - } //else if (bold == false) - //cell.setCellStyle(styleDefault); - } // dv.isVisible - } - rowNum += 1; - - } - - int cw = 0; - for (int i = 0; i < cellWidth.size(); i++) { - cw = ((Integer) cellWidth.get(i)).intValue() + 12; - // if(i!=cellWidth.size()-1) - sheet.setColumnWidth((short) (i), (short) ((cw * 8) / ((double) 1 / 20))); - // else - // sheet.setColumnWidth((short) (i + 1), (short) ((cw * 10) / - // ((double) 1 / 20))); - } - - // To Display Total Values for Linear report - if(rd.reportDataTotalRow!=null) { - row = sheet.createRow(rowNum); - cellNum = -1; - rd.reportTotalRowHeaderCols.resetNext(); - //for (rd.reportTotalRowHeaderCols.resetNext(); rd.reportTotalRowHeaderCols.hasNext();) { - cellNum += 1; - RowHeaderCol rhc = rd.reportTotalRowHeaderCols.getNext(); - RowHeader rh = rhc.getRowHeader(0); - row.createCell((short) cellNum).setCellValue(strip.stripHtml(rh.getRowTitle())); - row.getCell((short) cellNum).setCellStyle(styleDefaultTotal); - //} - - rd.reportDataTotalRow.resetNext(); - DataRow drTotal = rd.reportDataTotalRow.getNext(); - //cellNum = -1; - - drTotal.resetNext(); - drTotal.getNext(); - for (; drTotal.hasNext();) { - cellNum += 1; - cell = row.createCell((short) cellNum); - DataValue dv = drTotal.getNext(); - String value = dv.getDisplayValue(); - cell.setCellValue(value); - boolean bold = false; - if (dv.isBold()) { - if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ - if (value!=null && (value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - cell.setCellStyle(styleCurrencyTotal); - } else { - cell.setCellStyle(styleTotal); - } - } else { - cell.setCellStyle(styleDefaultTotal); - } - bold = true; - } - } - } - - } catch (SQLException ex) { - ex.printStackTrace(); - throw new RaptorException(ex); - } catch (ReportSQLException ex) { - throw new RaptorException(ex); - } catch (Exception ex) { - if(!(ex.getCause() instanceof java.net.SocketException) ) - throw new RaptorException (ex); - } - - /*if(Globals.getShowDisclaimer() && !Globals.disclaimerPositionedTopInCSVExcel()) { - rowNum += 1; - row = sheet.createRow(rowNum); - cellNum = 0; - String disclaimer = Globals.getFooterFirstLine() + " " + Globals.getFooterSecondLine(); - row.createCell((short) cellNum).setCellValue(disclaimer); - sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, (short) cellNum, (short) (columnRows))); - rowNum += 1; - }*/ - } else { - if(rr.getReportType().equals(AppConstants.RT_LINEAR)) { - int rowCount = 0; - for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) { - DataRow dr = rd.reportDataRows.getNext(); - //List l = rd.getReportDataList(); - //for (int dataRow = 0; dataRow < l.size(); dataRow++) { - rowCount++; - - - //DataRow dr = (DataRow) l.get(dataRow); - row = sheet.createRow(rowNum); - - cellNum = -1; - - if (rr.getReportType().equals(AppConstants.RT_LINEAR) && rd.reportTotalRowHeaderCols!=null) { - rd.reportRowHeaderCols.resetNext(0); - if(rd.reportTotalRowHeaderCols!=null) { - //cellNum = -1; - //for (rd.reportRowHeaderCols.resetNext(); rd.reportRowHeaderCols.hasNext();) { - //cellNum += 1; - //RowHeaderCol rhc = rd.reportRowHeaderCols.getRowHeaderCol(0); - //if (firstPass) - // rhc.resetNext(); - //RowHeader rh = rhc.getRowHeader(rowCount-1); - //row.createCell((short) cellNum).setCellValue(rowCount); - //row.getCell((short) cellNum).setCellStyle(styleDefault); - //if (firstPass) - //cellWidth.add(cellNum, new Integer((rowCount+"").length())); - //else - //cellWidth.set(cellNum, new Integer((rowCount+"").length())); - - //} // for - } - - } else { - rd.reportRowHeaderCols.resetNext(0); - } - for (; rd.reportRowHeaderCols.hasNext();) { - cellNum += 1; - RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); - if (firstPass) - rhc.resetNext(); - RowHeader rh = rhc.getNext(); - row.createCell((short) cellNum).setCellValue(strip.stripHtml(rh.getRowTitle())); - row.getCell((short) cellNum).setCellStyle(styleDefault); - if (cellWidth.size() > 0) { - if (((Integer) cellWidth.get(cellNum)).intValue() < rh.getRowTitle() - .length()) - cellWidth.set(cellNum, new Integer(rh.getRowTitle().length())); - } else - cellWidth.add(cellNum, new Integer(rh.getRowTitle().length())); - - } // for - firstPass = false; - //cellNum = -1; - int j = 0; - - for (dr.resetNext(); dr.hasNext();j++) { - DataValue dv = dr.getNext(); - styleCell = null; - boolean bold = false; - String value = nvl(dv.getDisplayValue()); - value = strip.stripHtml(value); - HtmlFormatter htmlFormat = dv.getCellFormatter(); - if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) - styleCell = (HSSFCellStyle) styles.get(nvl(dr.getFormatId(),"default")); - if (htmlFormat != null && dv.getFormatId() != null && styles != null) - styleCell = (HSSFCellStyle) styles.get(nvl(dv.getFormatId(),"default")); - - if(dv.isVisible()) { - cellNum += 1; - cell = row.createCell((short) cellNum); - //System.out.println("Stripping HTML 1"); - //cell.setCellValue(strip.stripHtml(value)); - String dataType = (String) (dataTypeMap.get(dv.getColId())); - //System.out.println(" The Display Value is ********"+value + " " + dv.getDisplayTotal() + " " + dv.getColName()); - - if (dataType!=null && dataType.equals("NUMBER")){ - //cellNumber = row.createCell((short) cellNum); - //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); - //cellNumber.setCellValue(value); - //cellCurrencyNumber = row.createCell((short) cellNum); - int zInt = 0; - if (value.equals("null")){ - cell.setCellValue(zInt); - }else{ - - if ((value.indexOf("."))!= -1){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - - //if (value.startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempDollar = value.trim(); - tempDollar = tempDollar.replaceAll(" ", "").substring(0); - tempDollar = tempDollar.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempDollar); - //System.out.println("Before copy Value |" + tempDollar); - //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); - //System.out.println("After copy Value |" + tempDollar); - if ((tempDollar.indexOf(","))!= -1){ - tempDollar = tempDollar.replaceAll(",", ""); - } - //System.out.println("The final string 1 is "+tempDollar); - double tempDoubleDollar = 0.0; - try { - tempDoubleDollar = Double.parseDouble(tempDollar); - if(styleCell!=null) { - styleCell.setDataFormat((short) 8);//HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleCurrencyDecimalNumber); - cell.setCellValue(tempDoubleDollar); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempDollar); - } - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - double tempDouble = 0.0; - try { - tempDouble = Double.parseDouble(value); - if(styleCell!=null) { - styleCell.setDataFormat((short) 0x28);//HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDecimalNumber); - cell.setCellValue(tempDouble); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(value); - } - - } - }else { - if (!(value.equals(""))){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - //if (value.startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempInt = value.trim(); - tempInt = tempInt.replaceAll(" ", "").substring(0); - tempInt = tempInt.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempInt); - //System.out.println("Before copy Value |" + tempInt); - //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); - //System.out.println("After copy Value |" + tempInt); - if ((tempInt.indexOf(","))!= -1){ - tempInt = tempInt.replaceAll(",", ""); - } - //System.out.println("The final string INT is "+tempInt); - Long tempIntDollar = 0L; - try { - tempIntDollar = Long.parseLong(tempInt); - if(styleCell!=null) { - styleCell.setDataFormat((short)6);//HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleCurrencyNumber); - cell.setCellValue(tempIntDollar); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempInt); - } - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - String tempStr = value.trim(); - if ((tempStr.indexOf(","))!= -1){ - tempStr = tempStr.replaceAll(",", ""); - } - Long temp = 0L; - - try { - temp = Long.parseLong(tempStr); - if(styleCell!=null) { - styleCell.setDataFormat((short)0x26);//HSSFDataFormat.getBuiltinFormat("(#,##0_);[Red](#,##0)")); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleNumber); - cell.setCellValue(temp); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempStr); - } - - - } - //int temp = Integer.parseInt(value.trim()); - // cell.setCellValue(temp); - //}else{ - // cell.setCellValue(strip.stripHtml(value)); - //} - } - } - } - - }else if ( ( dataType !=null && dataType.equals("DATE")) || (dv.getDisplayName()!=null && dv.getDisplayName().toLowerCase().endsWith("date")) || - (dv.getColId()!=null && dv.getColId().toLowerCase().endsWith("date")) || - (dv.getColName()!=null && dv.getColName().toLowerCase().endsWith("date")) ) { - //cellDate = row.createCell((short) cellNum); - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("mm/dd/yy")); - - if(styleCell!=null) { - styleCell.setDataFormat((short)0xe); //HSSFDataFormat.getBuiltinFormat("m/d/yy")); - cell.setCellStyle(styleCell); + cell.setCellStyle(styleDate); + Date date = null; + int flag = 0; + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); + flag = 1; + } + if (date == null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm")); + flag = 1; + } + if (date == null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy")); + flag = 1; + } + if (date == null) + date = MMDDYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm:ss")); + flag = 1; + } + if (date == null) + date = MMDDYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); + flag = 1; + } + if (date == null) + date = MMDDYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy")); + flag = 1; + } + if (date == null) + date = YYYYMMDDFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy/m/d")); + flag = 1; + } + if (date == null) + date = timestampFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy-m-d h:mm:ss")); // yyyy-MM-dd + // HH:mm:ss + flag = 1; + } + if (date == null) + date = MONYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("mmm yyyy")); + flag = 1; + } + if (date == null) + date = MMYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/yyyy")); + flag = 1; + } + if (date == null) + date = MMMMMDDYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("mmm/d/yyyy")); + flag = 1; + } + if (date == null) + date = MONTHYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("mmm/yyyy")); + flag = 1; + } + if (date == null) + date = YYYYMMDDHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy/m/d h:mm:ss")); + flag = 1; + } + if (date == null) + date = YYYYMMDDDASHFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy-m-d")); + flag = 1; + } + if (date == null) + date = YYYYMMDDHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy/m/d h:mm")); + flag = 1; + } + if (date == null) + date = DDMONYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yyyy h:mm:ss")); + flag = 1; + } + if (date == null) + date = DDMONYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yyyy h:mm")); + flag = 1; + } + if (date == null) + date = DDMONYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yy h:mm")); + flag = 1; + } + if (date == null) + date = DDMONYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yyyy")); + flag = 1; + } + if (date == null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); + flag = 1; + } + if (date == null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm")); + flag = 1; + } + if (date == null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy")); + flag = 1; + } + if (date == null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm")); + flag = 1; + } + if (date == null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); + flag = 1; + } + if (date == null) + date = MMDDYYYYHHMMZFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); + flag = 1; + } + if (date == null) + date = MMMMMDDYYYYHHMMSS.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); + flag = 1; + } + + if (date != null) { + cell.setCellValue(HSSFDateUtil.getExcelDate(date)); + try { + String str = cell.getStringCellValue(); + } catch (IllegalStateException ex) { + logger.error(EELFLoggerDelegate.errorLogger, "IllegalStateException occured", + ex); + cell.setCellValue(value); + } + } else { + cell.setCellValue(value); + } + + } else if ((dv.getDisplayTotal() != null && dv.getDisplayTotal().equals("SUM(")) + || (dv.getColName() != null && dv.getColName().indexOf("999") != -1)) { + cell = row.createCell((short) cellNum); + int zInt = 0; + if (value.equals("null")) { + cell.setCellValue(zInt); + } else { + + if ((value.indexOf(".")) != -1) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + + String tempDollar = value.trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + if ((tempDollar.indexOf(",")) != -1) { + tempDollar = tempDollar.replaceAll(",", ""); + } + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if (styleCell != null) { + styleCell.setDataFormat((short) 8);// HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyDecimalNumber); + cell.setCellValue(tempDoubleDollar); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempDollar); + } + + } else { + String tempDoubleStr = value.trim(); + tempDoubleStr = tempDoubleStr.replaceAll(" ", "").substring(0); + if ((tempDoubleStr.indexOf(",")) != -1) { + tempDoubleStr = tempDoubleStr.replaceAll(",", ""); + } + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(tempDoubleStr); + if (styleCell != null) { + styleCell.setDataFormat((short) 0x28);// HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDecimalNumber); + cell.setCellValue(tempDouble); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempDoubleStr); + } + } + + } else { + if (!(value.equals(""))) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + if ((tempInt.indexOf(",")) != -1) { + tempInt = tempInt.replaceAll(",", ""); + } + + Long tempIntDollar = 0L; + + try { + tempIntDollar = Long.parseLong(tempInt); + if (styleCell != null) { + styleCell.setDataFormat((short) 6);// HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyNumber); + cell.setCellValue(tempIntDollar); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempInt); + } + } else { + String tempStr = value.trim(); + if ((tempStr.indexOf(",")) != -1) { + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if (styleCell != null) { + styleCell.setDataFormat((short) 0x26);// HSSFDataFormat.getBuiltinFormat("(#,##0_);[Red](#,##0)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleNumber); + cell.setCellValue(temp); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempStr); + } + } + } else { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + } + } + } + + } else { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); } else - cell.setCellStyle(styleDate); - //String MY_DATE_FORMAT = "yyyy-MM-dd"; - Date date = null; - int flag = 0; - date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); - flag = 1; - } - if(date==null) - date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy h:mm")); - flag = 1; - } - if(date==null) - date = MMDDYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yyyy")); - flag = 1; - } - if(date==null) - date = MMDDYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yyyy h:mm:ss")); - flag = 1; - } - if(date==null) - date = MMDDYYYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); - flag = 1; - } - if(date==null) - date = MMDDYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy")); - flag = 1; - } - if(date==null) - date = YYYYMMDDFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("yyyy/m/d")); - flag = 1; - } - if(date==null) - date = timestampFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("yyyy-m-d h:mm:ss")); //yyyy-MM-dd HH:mm:ss - flag = 1; - } - if(date==null) - date = MONYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("mmm yyyy")); - flag = 1; - } - if(date==null) - date = MMYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/yyyy")); - flag = 1; - } - if(date==null) - date = MMMMMDDYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("mmm/d/yyyy")); - flag = 1; - } - if(date==null) - date = MONTHYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("mmm/yyyy")); - flag = 1; - } - if(date==null) - date = YYYYMMDDHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("yyyy/m/d h:mm:ss")); - flag = 1; - } - if(date==null) - date = YYYYMMDDDASHFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("yyyy-m-d")); - flag = 1; - } - if(date==null) - date = YYYYMMDDHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("yyyy/m/d h:mm")); - flag = 1; - } - if(date==null) - date = DDMONYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("d-mmm-yyyy h:mm:ss")); - flag = 1; - } - if(date==null) - date = DDMONYYYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("d-mmm-yyyy h:mm")); - flag = 1; - } - if(date==null) - date = DDMONYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("d-mmm-yy h:mm")); - flag = 1; - } - if(date==null) - date = DDMONYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("d-mmm-yyyy")); - flag = 1; - } - if(date==null) - date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); - flag = 1; - } - if(date==null) - date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy h:mm")); - flag = 1; - } - if(date==null) - date = MMDDYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy")); - flag = 1; - } - if(date==null) - date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy h:mm")); - flag = 1; - } - if(date==null) - date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); - flag = 1; - } - if(date==null) - date = MMDDYYYYHHMMZFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); - flag = 1; - } - if(date==null) - date = MMMMMDDYYYYHHMMSS.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cell.getCellStyle().setDataFormat( - createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); - flag = 1; - } - - if(date!=null) { - //System.out.println("ExcelDate " + HSSFDateUtil.getExcelDate(date)); - cell.setCellValue(HSSFDateUtil.getExcelDate(date)); - try { - String str = cell.getStringCellValue(); - } catch (IllegalStateException ex) { /*cell.getCellStyle().setDataFormat((short)0);*/cell.setCellValue(value);} - } else { - /*cell.getCellStyle().setDataFormat((short)0);*/ - cell.setCellValue(value); - } - //cellDate.setCellValue(date); - //cellDate.setCellValue(value); - - }else if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ - //cellNumber = row.createCell((short) cellNum); - //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); - //cellNumber.setCellValue(value); - cell = row.createCell((short) cellNum); - int zInt = 0; - if (value.equals("null")){ - cell.setCellValue(zInt); - }else{ - - if ((value.indexOf("."))!= -1){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - - //if (value.startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempDollar = value.trim(); - tempDollar = tempDollar.replaceAll(" ", "").substring(0); - tempDollar = tempDollar.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempDollar); - //System.out.println("Before copy Value |" + tempDollar); - //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); - //System.out.println("After copy Value |" + tempDollar); - if ((tempDollar.indexOf(","))!= -1){ - tempDollar = tempDollar.replaceAll(",", ""); - } - //System.out.println("The final string 2IF is "+tempDollar); - double tempDoubleDollar = 0.0; - try { - tempDoubleDollar = Double.parseDouble(tempDollar); - if(styleCell!=null) { - styleCell.setDataFormat((short)8);//HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleCurrencyDecimalNumber); - cell.setCellValue(tempDoubleDollar); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempDollar); - } - - - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - String tempDoubleStr = value.trim(); - tempDoubleStr = tempDoubleStr.replaceAll(" ", "").substring(0); - if ((tempDoubleStr.indexOf(","))!= -1){ - tempDoubleStr = tempDoubleStr.replaceAll(",", ""); - } - double tempDouble = 0.0; - try { - tempDouble = Double.parseDouble(tempDoubleStr); - if(styleCell!=null) { - styleCell.setDataFormat((short) 0x28); // for decimal - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDecimalNumber); - cell.setCellValue(tempDouble); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempDoubleStr); - } - } - - }else { - if (!(value.equals(""))){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - //if (value.startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempInt = value.trim(); - tempInt = tempInt.replaceAll(" ", "").substring(0); - tempInt = tempInt.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempInt); - //System.out.println("Before copy Value |" + tempInt); - //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); - //System.out.println("After copy Value |" + tempInt); - if ((tempInt.indexOf(","))!= -1){ - tempInt = tempInt.replaceAll(",", ""); - } - //System.out.println("The final string INT 2 is "+tempInt); - - Long tempIntDollar = 0L; - - try { - tempIntDollar = Long.parseLong(tempInt); - if(styleCell!=null) { - styleCell.setDataFormat((short) 6); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleCurrencyNumber); - cell.setCellValue(tempIntDollar); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempInt); - } - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - String tempStr = value.trim(); - if ((tempStr.indexOf(","))!= -1){ - tempStr = tempStr.replaceAll(",", ""); - } - Long temp = 0L; - - try { - temp = Long.parseLong(tempStr); - if(styleCell!=null) { - styleCell.setDataFormat((short) 0x26); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleNumber); - cell.setCellValue(temp); - } catch (NumberFormatException ne) { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempStr); - } - } - //int temp = Integer.parseInt(value.trim()); - // cell.setCellValue(temp); - //}else{ - // cell.setCellValue(strip.stripHtml(value)); - //} - } else { - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - } - } - } - - - } - else { - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("General")); - if(styleCell!=null) { - styleCell.setWrapText(true); - cell.setCellStyle(styleCell); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(strip.stripHtml(value)); - } - - //if (!(value.equals(""))){ - //int temp = Integer.parseInt(value.trim()); - //cell.setCellValue(temp); - //}else{ - // cell.setCellValue(strip.stripHtml(value)); - //} - //HSSFCellStyle styleFormat = null; - //HSSFCellStyle numberStyle = null; - //HSSFFont formatFont = null; - //short fgcolor = 0; - //short fillpattern = 0; - if (cellWidth.size() > cellNum) { - if (((Integer) cellWidth.get(cellNum)).intValue() < dv - .getDisplayValue().length()) - cellWidth.set((cellNum), - (value.length()<=Globals.getMaxCellWidthInExcel())?new Integer(value.length()):new Integer(Globals.getMaxCellWidthInExcel())); - } else - cellWidth.add((cellNum), (value.length()<=Globals.getMaxCellWidthInExcel())?new Integer(value.length()):new Integer(Globals.getMaxCellWidthInExcel())); - //System.out.println("1IF "+ (dv.isBold()) + " "+ value + " " + dv.getDisplayTotal() + " " + dv.getColName() ); - if (dv.isBold()) { - if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ - if (value!=null && (value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - cell.setCellStyle(styleCurrencyTotal); - } - else { - cell.setCellStyle(styleTotal); - } - } else { - cell.setCellStyle(styleDefaultTotal); - } - bold = true; - } - //System.out.println("2IF "+ (dr.isRowFormat()) + " " + (dv.isCellFormat()) + " " + (styles!=null)); - if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) { - //cell.setCellStyle((HSSFCellStyle) styles.get(nvl(dr.getFormatId(),"default"))); - continue; - } - //System.out.println("3IF "+ (htmlFormat != null) + " " + (dv.getFormatId() != null) + " " + (bold == false) + " "+ (styles != null)); - if (htmlFormat != null && dv.getFormatId() != null && bold == false - && styles != null) { - // cell.setCellStyle((HSSFCellStyle) styles.get(nvl(dv.getFormatId(),"default"))); - } //else if (bold == false) - //cell.setCellStyle(styleDefault); - } // if (dv.isVisible) - } // for - - /*for (int tmp=0; tmp<dataTypeMap.size(); tmp++){ - String dataTypeStr = (String)(dataTypeMap.get(tmp)); - if(dataTypeStr.equals("NUMBER")){ - cell.setCellStyle(styleNumber); - }else if (dataTypeStr.equals("VARCHAR2")){ - cell.setCellStyle(styleDefault); - - }else if (dataTypeStr.equals("DATE")){ - cell.setCellStyle(styleDate); - }else{ - - } - - }*/ - rowNum += 1; - int cw = 0; - for (int i = 0; i < cellWidth.size(); i++) { - cw = ((Integer) cellWidth.get(i)).intValue() + 12; - // if(i!=cellWidth.size()-1) - sheet.setColumnWidth((short) (i), (short) ((cw * 8) / ((double) 1 / 20))); - // else - // sheet.setColumnWidth((short) (i + 1), (short) ((cw * 10) / - // ((double) 1 / 20))); - } - - } // for - - // To Display Total Values for Linear report - if(rd.reportDataTotalRow!=null) { - row = sheet.createRow(rowNum); - cellNum = -1; - rd.reportTotalRowHeaderCols.resetNext(); - //for (rd.reportTotalRowHeaderCols.resetNext(); rd.reportTotalRowHeaderCols.hasNext();) { - cellNum += 1; - RowHeaderCol rhc = rd.reportTotalRowHeaderCols.getNext(); - RowHeader rh = rhc.getRowHeader(0); - row.createCell((short) cellNum).setCellValue(strip.stripHtml(rh.getRowTitle())); - row.getCell((short) cellNum).setCellStyle(styleDefaultTotal); - //} - - rd.reportDataTotalRow.resetNext(); - DataRow drTotal = rd.reportDataTotalRow.getNext(); - //cellNum = -1; - - drTotal.resetNext(); - drTotal.getNext(); - for (; drTotal.hasNext();) { - cellNum += 1; - cell = row.createCell((short) cellNum); - DataValue dv = drTotal.getNext(); - String value = dv.getDisplayValue(); - cell.setCellValue(value); - boolean bold = false; - if (dv.isBold()) { - if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ - if (value!=null && (value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - cell.setCellStyle(styleCurrencyTotal); - } else { - cell.setCellStyle(styleTotal); - } - } else { - cell.setCellStyle(styleDefaultTotal); - } - bold = true; - } - } - } - - /* - if (rr.getReportType().equals(AppConstants.RT_LINEAR) && rd.reportTotalRowHeaderCols!=null) { - - for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext();) { - rowCount++; - - - DataRow dr = rd.reportDataTotalRow.getNext(); - row = sheet.createRow(rowNum); - cellNum = -1; - int j = 0; - cellNum += 1; - cell = row.createCell((short) cellNum); - cell.setCellValue("Total"); - cell.setCellStyle(styleTotal); - - for (dr.resetNext(); dr.hasNext();j++) { - DataValue dv = dr.getNext(); - if(j==0 || !dv.isVisible()) continue; - cellNum += 1; - styleCell = null; - boolean bold = true; - String value = nvl(dv.getDisplayValue()); - //cellNumber = row.createCell((short) cellNum); - //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); - //cellNumber.setCellValue(dv.getDisplayValue()); - cell = row.createCell((short) cellNum); - int zInt = 0; - if (value.equals("null")){ - cell.setCellValue(zInt); - }else{ - - if ((value.indexOf("."))!= -1){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - - //if (value.startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempDollar = value.trim(); - tempDollar = tempDollar.replaceAll(" ", "").substring(0); - tempDollar = tempDollar.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempDollar); - //System.out.println("Before copy Value |" + tempDollar); - //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); - //System.out.println("After copy Value |" + tempDollar); - if ((tempDollar.indexOf(","))!= -1){ - tempDollar = tempDollar.replaceAll(",", ""); - } - //System.out.println("The final string 2IF is "+tempDollar); - double tempDoubleDollar = 0.0; - try { - tempDoubleDollar = Double.parseDouble(tempDollar); - if(styleTotal!=null) { - styleTotal.setDataFormat((short) 8);//HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); - cell.setCellStyle(styleTotal); - } else - cell.setCellStyle(styleCurrencyDecimalNumberTotal); - cell.setCellValue(tempDoubleDollar); - } catch (NumberFormatException ne) { - if(styleTotal!=null) { - styleTotal.setWrapText(true); - cell.setCellStyle(styleTotal); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempDollar); - } - - - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - String tempDoubleStr = value.trim(); - tempDoubleStr = tempDoubleStr.replaceAll(" ", "").substring(0); - if ((tempDoubleStr.indexOf(","))!= -1){ - tempDoubleStr = tempDoubleStr.replaceAll(",", ""); - } - double tempDouble = 0.0; - try { - tempDouble = Double.parseDouble(tempDoubleStr); - if(styleTotal!=null) { - styleTotal.setDataFormat((short)0x28 );//HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); - cell.setCellStyle(styleTotal); - } else - cell.setCellStyle(styleDecimalNumberTotal); - cell.setCellValue(tempDouble); - } catch (NumberFormatException ne) { - if(styleTotal!=null) { - styleTotal.setWrapText(true); - cell.setCellStyle(styleTotal); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempDoubleStr); - } - } - - }else { - if (!(value.equals(""))){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - //if (value.startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempInt = value.trim(); - tempInt = tempInt.replaceAll(" ", "").substring(0); - tempInt = tempInt.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempInt); - //System.out.println("Before copy Value |" + tempInt); - //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); - //System.out.println("After copy Value |" + tempInt); - if ((tempInt.indexOf(","))!= -1){ - tempInt = tempInt.replaceAll(",", ""); - } - //System.out.println("The final string INT 2 is "+tempInt); - - Long tempIntDollar = 0L; - - try { - tempIntDollar = Long.parseLong(tempInt); - if(styleTotal!=null) { - styleTotal.setDataFormat((short) 6);//HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); - cell.setCellStyle(styleTotal); - } else - cell.setCellStyle(styleCurrencyNumberTotal); - cell.setCellValue(tempIntDollar); - } catch (NumberFormatException ne) { - if(styleTotal!=null) { - styleTotal.setWrapText(true); - cell.setCellStyle(styleTotal); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempInt); - } - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - String tempStr = value.trim(); - if ((tempStr.indexOf(","))!= -1){ - tempStr = tempStr.replaceAll(",", ""); - } - Long temp = 0L; - - try { - temp = Long.parseLong(tempStr); - if(styleTotal!=null) { - styleTotal.setDataFormat((short) 0x26);//HSSFDataFormat.getBuiltinFormat("(#,##0_);[Red](#,##0)")); - cell.setCellStyle(styleTotal); - } else - cell.setCellStyle(styleNumber); - cell.setCellValue(temp); - } catch (NumberFormatException ne) { - if(styleTotal!=null) { - styleTotal.setWrapText(true); - cell.setCellStyle(styleTotal); - } else - cell.setCellStyle(styleDefault); - cell.setCellValue(tempStr); - } - } - //int temp = Integer.parseInt(dv.getDisplayValue().trim()); - // cell.setCellValue(temp); - //}else{ - // cell.setCellValue(strip.stripHtml(dv.getDisplayValue())); - //} - } else { - if(styleTotal!=null) { - styleTotal.setWrapText(true); - cell.setCellStyle(styleTotal); - } else - cell.setCellStyle(styleDefault); - } - } - } - - - - - } - } - } - */ - - - - } else if (rr.getReportType().equals(AppConstants.RT_CROSSTAB)) { // Linear - int rowCount = 0; - List l = rd.getReportDataList(); - boolean first = true; - for (int dataRow = 0; dataRow < l.size(); dataRow++) { - - - DataRow dr = (DataRow) l.get(dataRow); - row = sheet.createRow(rowNum); - - cellNum = -1; - first = true; - Vector<DataValue> rowNames = dr.getRowValues(); - for(dr.resetNext(); dr.hasNext(); rowCount++ ) { - if(first) { - if(rowNames!=null) { - for(int i=0; i<rowNames.size(); i++) { - DataValue dv = rowNames.get(i); - cellNum += 1; - row.createCell((short) cellNum).setCellValue(strip.stripHtml(dv.getDisplayValue())); - row.getCell((short) cellNum).setCellStyle(styleDefault); - } - } - } - first = false; - - DataValue dv = dr.getNext(); - if(dv.isVisible()) { - String value = dv.getDisplayValue(); - if(value.indexOf("|#")!=-1) - value = value.substring(0,value.indexOf("|")); - - if(dr.isRowFormat() || nvl(dv.getFormatId()).length()>0) { - cellNum += 1; - row.createCell((short) cellNum).setCellValue(strip.stripHtml(dv.getDisplayValue())); - //row.getCell((short) cellNum).setCellStyle(styleDefault); - if(nvl(dv.getFormatId()).length()>0) - row.getCell((short) cellNum).setCellStyle((HSSFCellStyle) styles.get(nvl(dv.getFormatId(),"default"))); - else - row.setRowStyle((HSSFCellStyle) styles.get(nvl(dr.getFormatId(),"default"))); - } else { - cellNum += 1; - row.createCell((short) cellNum).setCellValue(strip.stripHtml(value)); - row.getCell((short) cellNum).setCellStyle(styleDefault); - } // end - value = dv.getDisplayValue(); - if(value.indexOf("|#")!=-1) { - String color = value.substring(value.indexOf("|")+1); - if(color.equals("#FF0000")) - row.getCell((short) cellNum).setCellStyle((HSSFCellStyle) styles.get("red")); - else if (color.equals("#008000")) - row.getCell((short) cellNum).setCellStyle((HSSFCellStyle) styles.get("green")); - else if (color.equals("#FFFF00")) - row.getCell((short) cellNum).setCellStyle((HSSFCellStyle) styles.get("yellow")); - else { - row.getCell((short) cellNum).setCellStyle((HSSFCellStyle) styles.get("default")); - } - - } - } - } - rowNum += 1; - int cw = 0; - for (int i = 0; i < cellWidth.size(); i++) { - cw = ((Integer) cellWidth.get(i)).intValue() + 12; - // if(i!=cellWidth.size()-1) - sheet.setColumnWidth((short) (i), (short) ((cw * 8) / ((double) 1 / 20))); - // else - // sheet.setColumnWidth((short) (i + 1), (short) ((cw * 10) / - // ((double) 1 / 20))); - } - - - } // for - - } - - - } - - String footer = (String) session.getAttribute("FOOTER_"+index); - if(nvl(footer).length()>0) { - footer = Utils.replaceInString(footer, "<BR/>", " "); - footer = Utils.replaceInString(footer, "<br/>", " "); - footer = Utils.replaceInString(footer, "<br>", " "); - footer = strip.stripHtml(nvl(footer).trim()); - row = sheet.createRow(rowNum); - cellNum = 0; - row.createCell((short) cellNum).setCellValue(footer); - sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, (short) cellNum, (short) (columnRows))); - rowNum += 1; - } - - if(Globals.getShowDisclaimer() && !Globals.disclaimerPositionedTopInCSVExcel()) { - - rowNum += 1; - row = sheet.createRow(rowNum); - cellNum = 0; - String disclaimer = Globals.getFooterFirstLine() + " " + Globals.getFooterSecondLine(); - row.createCell((short) cellNum).setCellValue(disclaimer); - sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, (short) cellNum, (short) (columnRows))); - rowNum += 1; - } - - logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####")); - logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:" - + (runtime.maxMemory() - runtime.freeMemory()) / mb)); - logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:" - + runtime.freeMemory() / mb)); - logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb)); - logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb)); - return returnValue; + cell.setCellStyle(styleDefault); + cell.setCellValue(strip.stripHtml(value)); + } + + if (cellWidth.size() > cellNum) { + if (((Integer) cellWidth.get(cellNum)).intValue() < dv + .getDisplayValue().length()) + cellWidth.set((cellNum), + (value.length() <= Globals.getMaxCellWidthInExcel()) + ? new Integer(value.length()) + : new Integer(Globals.getMaxCellWidthInExcel())); + } else + cellWidth.add((cellNum), + (value.length() <= Globals.getMaxCellWidthInExcel()) + ? new Integer(value.length()) + : new Integer(Globals.getMaxCellWidthInExcel())); + if (dv.isBold()) { + if ((dv.getDisplayTotal() != null && dv.getDisplayTotal().equals("SUM(")) + || (dv.getColName() != null && dv.getColName().indexOf("999") != -1)) { + if (value != null && (value.trim().startsWith("$")) + || (value.trim().startsWith("-$"))) { + cell.setCellStyle(styleCurrencyTotal); + } else { + cell.setCellStyle(styleTotal); + } + } else { + cell.setCellStyle(styleDefaultTotal); + } + bold = true; + } + if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) { + continue; + } + if (htmlFormat != null && dv.getFormatId() != null && bold == false + && styles != null) { + } + } + } + rowNum += 1; + + } + + int cw = 0; + for (int i = 0; i < cellWidth.size(); i++) { + cw = ((Integer) cellWidth.get(i)).intValue() + 12; + + sheet.setColumnWidth((short) (i), (short) ((cw * 8) / ((double) 1 / 20))); + } + + if (rd.reportDataTotalRow != null) { + row = sheet.createRow(rowNum); + cellNum = -1; + rd.reportTotalRowHeaderCols.resetNext(); + cellNum += 1; + RowHeaderCol rhc = rd.reportTotalRowHeaderCols.getNext(); + RowHeader rh = rhc.getRowHeader(0); + row.createCell((short) cellNum).setCellValue(strip.stripHtml(rh.getRowTitle())); + row.getCell((short) cellNum).setCellStyle(styleDefaultTotal); + + rd.reportDataTotalRow.resetNext(); + DataRow drTotal = rd.reportDataTotalRow.getNext(); + + drTotal.resetNext(); + drTotal.getNext(); + for (; drTotal.hasNext();) { + cellNum += 1; + cell = row.createCell((short) cellNum); + DataValue dv = drTotal.getNext(); + String value = dv.getDisplayValue(); + cell.setCellValue(value); + boolean bold = false; + if (dv.isBold()) { + if ((dv.getDisplayTotal() != null && dv.getDisplayTotal().equals("SUM(")) + || (dv.getColName() != null && dv.getColName().indexOf("999") != -1)) { + if (value != null && (value.trim().startsWith("$")) + || (value.trim().startsWith("-$"))) { + cell.setCellStyle(styleCurrencyTotal); + } else { + cell.setCellStyle(styleTotal); + } + } else { + cell.setCellStyle(styleDefaultTotal); + } + bold = true; + } + } + } + + } catch (SQLException ex) { + logger.error(EELFLoggerDelegate.errorLogger, "SQLException occured ", ex); + throw new RaptorException(ex); + } catch (ReportSQLException ex) { + logger.error(EELFLoggerDelegate.errorLogger, "ReportSQLException occured ", ex); + throw new RaptorException(ex); + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occured ", ex); + if (!(ex.getCause() instanceof java.net.SocketException)) + throw new RaptorException(ex); + } + - } + } else { + if (rr.getReportType().equals(AppConstants.RT_LINEAR)) { + int rowCount = 0; + for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) { + DataRow dr = rd.reportDataRows.getNext(); + rowCount++; - private void paintExcelHeader(HSSFWorkbook wb, int rowNum, int col, String reportTitle, - String reportDescr, HSSFSheet sheet) { - short s1 = 0, s2 = (short) (col-1); - rowNum += 1; - sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); - HSSFRow row = null, row1 = null; - - row = sheet.createRow(rowNum); - // Header Style - HSSFCellStyle styleHeader = wb.createCellStyle(); - styleHeader.setAlignment(HorizontalAlignment.CENTER); - HSSFFont font = wb.createFont(); - font.setFontHeight((short) (font_header_title_size / 0.05)); //14 - font.setFontName("Tahoma"); - font.setColor(HSSFColor.BLACK.index); - styleHeader.setFont(font); - - HSSFCell cell = row.createCell((short) 0); - cell.setCellValue(reportTitle); - cell.setCellStyle(styleHeader); - HSSFHeader header = sheet.getHeader(); - header.setCenter(HSSFHeader.font("Tahoma", "")+ HSSFHeader.fontSize((short) 9)+" " + reportTitle); - - //header.setCenter(HSSFHeader.font("Tahoma", "")+ HSSFHeader.fontSize((short) 9)+reportTitle+"\n"+((Globals.getShowDescrAtRuntime() && nvl(reportDescr).length() > 0)?reportDescr:"")); - - // Report Description - if (Globals.getShowDescrAtRuntime() && nvl(reportDescr).length() > 0) { - rowNum += 1; - sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); - HSSFCellStyle styleDescription = wb.createCellStyle(); - styleDescription.setAlignment(HorizontalAlignment.CENTER); - HSSFFont fontDescr = wb.createFont(); - fontDescr.setFontHeight((short) font_header_descr_size); - fontDescr.setFontName("Tahoma"); - fontDescr.setColor(HSSFColor.BLACK.index); - styleDescription.setFont(fontDescr); - HSSFCell cellDescr = row.createCell((short) 0); - cellDescr.setCellValue(reportDescr); - cellDescr.setCellStyle(styleHeader); - } - - if(Globals.disclaimerPositionedTopInCSVExcel()) { - rowNum += 1; - row = sheet.createRow(rowNum); - sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); - HSSFCellStyle styleDescription = wb.createCellStyle(); - styleDescription.setAlignment(HorizontalAlignment.CENTER); - HSSFFont fontDescr = wb.createFont(); - fontDescr.setFontHeight((short) (font_size / 0.05)); //14 - fontDescr.setFontName("Tahoma"); - fontDescr.setColor(HSSFColor.BLACK.index); - fontDescr.setBold(true); - styleDescription.setFont(fontDescr); - HSSFCell cellDescr = row.createCell((short) 0); - String disclaimer = Globals.getFooterFirstLine() + " " + Globals.getFooterSecondLine(); - cellDescr.setCellValue(disclaimer); - cellDescr.setCellStyle(styleDescription); - } + row = sheet.createRow(rowNum); - rowNum += 1; - row = sheet.createRow(rowNum); - // System.out.println(" Last Row " + wb.getSheetAt(0).getLastRowNum()); - } + cellNum = -1; - private void paintExcelFooter(HSSFWorkbook wb, int rowNum, int col, HSSFSheet sheet) { - logger.debug(EELFLoggerDelegate.debugLogger, ("excel footer")); - //HSSFSheet sheet = wb.getSheet(getSheetName()); - HSSFFooter footer = sheet.getFooter(); - footer.setLeft(HSSFFooter.font("Tahoma", "")+ HSSFFooter.fontSize((short) font_footer_size)+ "Page " + HSSFFooter.page() - + " of " + HSSFFooter.numPages() ); - footer.setCenter(HSSFFooter.font("Tahoma", "")+ HSSFFooter.fontSize((short) font_footer_size)+Globals.getFooterFirstLine()+"\n"+Globals.getFooterSecondLine()); - //footer.setCenter(HSSFFooter.font("Tahoma", "Italic")+ HSSFFooter.fontSize((short) 16))+Globals.getFooterSecondLine()); -/* footer.font("Tahoma"); - short s1 = 0, s2 = (short) (col-1); + if (rr.getReportType().equals(AppConstants.RT_LINEAR) && rd.reportTotalRowHeaderCols != null) { + rd.reportRowHeaderCols.resetNext(0); + if (rd.reportTotalRowHeaderCols != null) { + } + + } else { + rd.reportRowHeaderCols.resetNext(0); + } + for (; rd.reportRowHeaderCols.hasNext();) { + cellNum += 1; + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + if (firstPass) + rhc.resetNext(); + RowHeader rh = rhc.getNext(); + row.createCell((short) cellNum).setCellValue(strip.stripHtml(rh.getRowTitle())); + row.getCell((short) cellNum).setCellStyle(styleDefault); + if (cellWidth.size() > 0) { + if (((Integer) cellWidth.get(cellNum)).intValue() < rh.getRowTitle() + .length()) + cellWidth.set(cellNum, new Integer(rh.getRowTitle().length())); + } else + cellWidth.add(cellNum, new Integer(rh.getRowTitle().length())); + + } // for + firstPass = false; + int j = 0; + + for (dr.resetNext(); dr.hasNext(); j++) { + DataValue dv = dr.getNext(); + styleCell = null; + boolean bold = false; + String value = nvl(dv.getDisplayValue()); + value = strip.stripHtml(value); + HtmlFormatter htmlFormat = dv.getCellFormatter(); + if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) + styleCell = (XSSFCellStyle) styles.get(nvl(dr.getFormatId(), DEFAULT)); + if (htmlFormat != null && dv.getFormatId() != null && styles != null) + styleCell = (XSSFCellStyle) styles.get(nvl(dv.getFormatId(), DEFAULT)); + + if (dv.isVisible()) { + cellNum += 1; + cell = row.createCell((short) cellNum); + String dataType = (String) (dataTypeMap.get(dv.getColId())); + + if (dataType != null && dataType.equals("NUMBER")) { + int zInt = 0; + if (value.equals("null")) { + cell.setCellValue(zInt); + } else { + + if ((value.indexOf(".")) != -1) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + + String tempDollar = value.trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + if ((tempDollar.indexOf(",")) != -1) { + tempDollar = tempDollar.replaceAll(",", ""); + } + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if (styleCell != null) { + styleCell.setDataFormat((short) 8);// HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyDecimalNumber); + cell.setCellValue(tempDoubleDollar); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempDollar); + } + } else { + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(value); + if (styleCell != null) { + styleCell.setDataFormat((short) 0x28);// HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDecimalNumber); + cell.setCellValue(tempDouble); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(value); + } + + } + } else { + if (!(value.equals(""))) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + if ((tempInt.indexOf(",")) != -1) { + tempInt = tempInt.replaceAll(",", ""); + } + Long tempIntDollar = 0L; + try { + tempIntDollar = Long.parseLong(tempInt); + if (styleCell != null) { + styleCell.setDataFormat((short) 6);// HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyNumber); + cell.setCellValue(tempIntDollar); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempInt); + } + } else { + String tempStr = value.trim(); + if ((tempStr.indexOf(",")) != -1) { + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if (styleCell != null) { + styleCell.setDataFormat((short) 0x26);// HSSFDataFormat.getBuiltinFormat("(#,##0_);[Red](#,##0)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleNumber); + cell.setCellValue(temp); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempStr); + } + + } + + } + } + } + + } else if ((dataType != null && dataType.equals("DATE")) + || (dv.getDisplayName() != null + && dv.getDisplayName().toLowerCase().endsWith("date")) + || + (dv.getColId() != null && dv.getColId().toLowerCase().endsWith("date")) || + (dv.getColName() != null && dv.getColName().toLowerCase().endsWith("date"))) { + + if (styleCell != null) { + styleCell.setDataFormat((short) 0xe); // HSSFDataFormat.getBuiltinFormat("m/d/yy")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDate); + Date date = null; + int flag = 0; + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); + flag = 1; + } + if (date == null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm")); + flag = 1; + } + if (date == null) + date = MMDDYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy")); + flag = 1; + } + if (date == null) + date = MMDDYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm:ss")); + flag = 1; + } + if (date == null) + date = MMDDYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); + flag = 1; + } + if (date == null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy")); + flag = 1; + } + if (date == null) + date = YYYYMMDDFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy/m/d")); + flag = 1; + } + if (date == null) + date = timestampFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy-m-d h:mm:ss")); // yyyy-MM-dd + // HH:mm:ss + flag = 1; + } + if (date == null) + date = MONYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("mmm yyyy")); + flag = 1; + } + if (date == null) + date = MMYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/yyyy")); + flag = 1; + } + if (date == null) + date = MMMMMDDYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("mmm/d/yyyy")); + flag = 1; + } + if (date == null) + date = MONTHYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("mmm/yyyy")); + flag = 1; + } + if (date == null) + date = YYYYMMDDHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy/m/d h:mm:ss")); + flag = 1; + } + if (date == null) + date = YYYYMMDDDASHFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy-m-d")); + flag = 1; + } + if (date == null) + date = YYYYMMDDHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("yyyy/m/d h:mm")); + flag = 1; + } + if (date == null) + date = DDMONYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yyyy h:mm:ss")); + flag = 1; + } + if (date == null) + date = DDMONYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yyyy h:mm")); + flag = 1; + } + if (date == null) + date = DDMONYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yy h:mm")); + flag = 1; + } + if (date == null) + date = DDMONYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("d-mmm-yyyy")); + flag = 1; + } + if (date == null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); + flag = 1; + } + if (date == null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm")); + flag = 1; + } + if (date == null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy")); + flag = 1; + } + if (date == null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm")); + flag = 1; + } + if (date == null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yy h:mm:ss")); + flag = 1; + } + if (date == null) + date = MMDDYYYYHHMMZFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); + flag = 1; + } + if (date == null) + date = MMMMMDDYYYYHHMMSS.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cell.getCellStyle().setDataFormat( + createHelper.createDataFormat().getFormat("m/d/yyyy h:mm")); + flag = 1; + } + + if (date != null) { + cell.setCellValue(HSSFDateUtil.getExcelDate(date)); + try { + String str = cell.getStringCellValue(); + } catch (IllegalStateException ex) { + logger.error(EELFLoggerDelegate.errorLogger, "IllegalStateException occured", + ex); + cell.setCellValue(value); + } + } else { + cell.setCellValue(value); + } + } else if ((dv.getDisplayTotal() != null && dv.getDisplayTotal().equals("SUM(")) + || (dv.getColName() != null && dv.getColName().indexOf("999") != -1)) { + cell = row.createCell((short) cellNum); + int zInt = 0; + if (value.equals("null")) { + cell.setCellValue(zInt); + } else { + + if ((value.indexOf(".")) != -1) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + + String tempDollar = value.trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + if ((tempDollar.indexOf(",")) != -1) { + tempDollar = tempDollar.replaceAll(",", ""); + } + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if (styleCell != null) { + styleCell.setDataFormat((short) 8);// HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)")); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyDecimalNumber); + cell.setCellValue(tempDoubleDollar); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempDollar); + } + + } else { + String tempDoubleStr = value.trim(); + tempDoubleStr = tempDoubleStr.replaceAll(" ", "").substring(0); + if ((tempDoubleStr.indexOf(",")) != -1) { + tempDoubleStr = tempDoubleStr.replaceAll(",", ""); + } + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(tempDoubleStr); + if (styleCell != null) { + styleCell.setDataFormat((short) 0x28); // for decimal + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDecimalNumber); + cell.setCellValue(tempDouble); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempDoubleStr); + } + } + + } else { + if (!(value.equals(""))) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + if ((tempInt.indexOf(",")) != -1) { + tempInt = tempInt.replaceAll(",", ""); + } + + Long tempIntDollar = 0L; + + try { + tempIntDollar = Long.parseLong(tempInt); + if (styleCell != null) { + styleCell.setDataFormat((short) 6); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleCurrencyNumber); + cell.setCellValue(tempIntDollar); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempInt); + } + } else { + // styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + String tempStr = value.trim(); + if ((tempStr.indexOf(",")) != -1) { + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if (styleCell != null) { + styleCell.setDataFormat((short) 0x26); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleNumber); + cell.setCellValue(temp); + } catch (NumberFormatException ne) { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(tempStr); + } + } + + } else { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + } + } + } + + } else { + if (styleCell != null) { + styleCell.setWrapText(true); + cell.setCellStyle(styleCell); + } else + cell.setCellStyle(styleDefault); + cell.setCellValue(strip.stripHtml(value)); + } + + if (cellWidth.size() > cellNum) { + if (((Integer) cellWidth.get(cellNum)).intValue() < dv + .getDisplayValue().length()) + cellWidth.set((cellNum), + (value.length() <= Globals.getMaxCellWidthInExcel()) + ? new Integer(value.length()) + : new Integer(Globals.getMaxCellWidthInExcel())); + } else + cellWidth.add((cellNum), + (value.length() <= Globals.getMaxCellWidthInExcel()) + ? new Integer(value.length()) + : new Integer(Globals.getMaxCellWidthInExcel())); + + if (dv.isBold()) { + if ((dv.getDisplayTotal() != null && dv.getDisplayTotal().equals("SUM(")) + || (dv.getColName() != null && dv.getColName().indexOf("999") != -1)) { + if (value != null && (value.trim().startsWith("$")) + || (value.trim().startsWith("-$"))) { + cell.setCellStyle(styleCurrencyTotal); + } else { + cell.setCellStyle(styleTotal); + } + } else { + cell.setCellStyle(styleDefaultTotal); + } + bold = true; + } + if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) { + continue; + } + if (htmlFormat != null && dv.getFormatId() != null && bold == false + && styles != null) { + } + } + } // for + + + rowNum += 1; + int cw = 0; + for (int i = 0; i < cellWidth.size(); i++) { + cw = ((Integer) cellWidth.get(i)).intValue() + 12; + sheet.setColumnWidth((short) (i), (short) ((cw * 8) / ((double) 1 / 20))); + + } + + } // for + + // To Display Total Values for Linear report + if (rd.reportDataTotalRow != null) { + row = sheet.createRow(rowNum); + cellNum = -1; + rd.reportTotalRowHeaderCols.resetNext(); + cellNum += 1; + RowHeaderCol rhc = rd.reportTotalRowHeaderCols.getNext(); + RowHeader rh = rhc.getRowHeader(0); + row.createCell((short) cellNum).setCellValue(strip.stripHtml(rh.getRowTitle())); + row.getCell((short) cellNum).setCellStyle(styleDefaultTotal); + + rd.reportDataTotalRow.resetNext(); + DataRow drTotal = rd.reportDataTotalRow.getNext(); + + drTotal.resetNext(); + drTotal.getNext(); + for (; drTotal.hasNext();) { + cellNum += 1; + cell = row.createCell((short) cellNum); + DataValue dv = drTotal.getNext(); + String value = dv.getDisplayValue(); + cell.setCellValue(value); + boolean bold = false; + if (dv.isBold()) { + if ((dv.getDisplayTotal() != null && dv.getDisplayTotal().equals("SUM(")) + || (dv.getColName() != null && dv.getColName().indexOf("999") != -1)) { + if (value != null && (value.trim().startsWith("$")) + || (value.trim().startsWith("-$"))) { + cell.setCellStyle(styleCurrencyTotal); + } else { + cell.setCellStyle(styleTotal); + } + } else { + cell.setCellStyle(styleDefaultTotal); + } + bold = true; + } + } + } + + + + } else if (rr.getReportType().equals(AppConstants.RT_CROSSTAB)) { // Linear + int rowCount = 0; + List l = rd.getReportDataList(); + boolean first = true; + for (int dataRow = 0; dataRow < l.size(); dataRow++) { + + DataRow dr = (DataRow) l.get(dataRow); + row = sheet.createRow(rowNum); + + cellNum = -1; + first = true; + Vector<DataValue> rowNames = dr.getRowValues(); + for (dr.resetNext(); dr.hasNext(); rowCount++) { + if (first) { + if (rowNames != null) { + for (int i = 0; i < rowNames.size(); i++) { + DataValue dv = rowNames.get(i); + cellNum += 1; + row.createCell((short) cellNum).setCellValue(strip.stripHtml(dv.getDisplayValue())); + row.getCell((short) cellNum).setCellStyle(styleDefault); + } + } + } + first = false; + + DataValue dv = dr.getNext(); + if (dv.isVisible()) { + String value = dv.getDisplayValue(); + if (value.indexOf("|#") != -1) + value = value.substring(0, value.indexOf("|")); + + if (dr.isRowFormat() || nvl(dv.getFormatId()).length() > 0) { + cellNum += 1; + row.createCell((short) cellNum).setCellValue(strip.stripHtml(dv.getDisplayValue())); + if (nvl(dv.getFormatId()).length() > 0) + row.getCell((short) cellNum) + .setCellStyle((HSSFCellStyle) styles.get(nvl(dv.getFormatId(), DEFAULT))); + else + row.setRowStyle((HSSFCellStyle) styles.get(nvl(dr.getFormatId(), DEFAULT))); + } else { + cellNum += 1; + row.createCell((short) cellNum).setCellValue(strip.stripHtml(value)); + row.getCell((short) cellNum).setCellStyle(styleDefault); + } // end + value = dv.getDisplayValue(); + if (value.indexOf("|#") != -1) { + String color = value.substring(value.indexOf("|") + 1); + if (color.equals("#FF0000")) + row.getCell((short) cellNum).setCellStyle((HSSFCellStyle) styles.get(RED)); + else if (color.equals("#008000")) + row.getCell((short) cellNum).setCellStyle((HSSFCellStyle) styles.get(GREEN)); + else if (color.equals("#FFFF00")) + row.getCell((short) cellNum).setCellStyle((HSSFCellStyle) styles.get(YELLOW)); + else { + row.getCell((short) cellNum).setCellStyle((HSSFCellStyle) styles.get(DEFAULT)); + } + + } + } + } + rowNum += 1; + int cw = 0; + for (int i = 0; i < cellWidth.size(); i++) { + cw = ((Integer) cellWidth.get(i)).intValue() + 12; + sheet.setColumnWidth((short) (i), (short) ((cw * 8) / ((double) 1 / 20))); + + } + + } // for + + } + + } + + String footer = (String) session.getAttribute("FOOTER_" + index); + if (nvl(footer).length() > 0) { + footer = Utils.replaceInString(footer, "<BR/>", " "); + footer = Utils.replaceInString(footer, "<br/>", " "); + footer = Utils.replaceInString(footer, "<br>", " "); + footer = strip.stripHtml(nvl(footer).trim()); + row = sheet.createRow(rowNum); + cellNum = 0; + row.createCell((short) cellNum).setCellValue(footer); + sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, (short) cellNum, (short) (columnRows))); + rowNum += 1; + } + + if (Globals.getShowDisclaimer() && !Globals.disclaimerPositionedTopInCSVExcel()) { + + rowNum += 1; + row = sheet.createRow(rowNum); + cellNum = 0; + String disclaimer = Globals.getFooterFirstLine() + " " + Globals.getFooterSecondLine(); + row.createCell((short) cellNum).setCellValue(disclaimer); + sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, (short) cellNum, (short) (columnRows))); + rowNum += 1; + } + + logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####")); + logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:" + + (runtime.maxMemory() - runtime.freeMemory()) / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:" + + runtime.freeMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb)); + return returnValue; + + } + + private void paintExcelHeader(XSSFWorkbook wb, int rowNum, int col, String reportTitle, + String reportDescr, XSSFSheet sheet) { + short shrt_one = 0, shrt_two = (short) (col - 1); rowNum += 1; - sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); - HSSFRow row = null, row1 = null; - + if(shrt_two != 0) + sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, shrt_one, shrt_two)); + XSSFRow row = null; + HSSFRow row1 = null; + row = sheet.createRow(rowNum); // Header Style - HSSFCellStyle styleFooter = wb.createCellStyle(); - styleFooter.setAlignment(HorizontalAlignment.CENTER); - HSSFFont font = wb.createFont(); - font.setFontHeight((short) (10 / 0.05)); - font.setFontName("Tahoma"); + XSSFCellStyle styleHeader = wb.createCellStyle(); + styleHeader.setAlignment(HorizontalAlignment.CENTER); + XSSFFont font = wb.createFont(); + font.setFontHeight((short) (FONT_HEADER_TITLE_SIZE / 0.05)); // 14 + font.setFontName(FONT_TAHOMA); font.setColor(HSSFColor.BLACK.index); - font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); - styleFooter.setFont(font); + styleHeader.setFont(font); - HSSFCell cell = row.createCell((short) 0); - debugLogger.debug(Globals.getFooterFirstLine()); - cell.setCellValue(Globals.getFooterFirstLine()); - cell.setCellStyle(styleFooter); - - rowNum += 1; - sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); + XSSFCell cell = row.createCell((short) 0); + cell.setCellValue(reportTitle); + cell.setCellStyle(styleHeader); + Header header = sheet.getHeader(); + header.setCenter(HSSFHeader.font(FONT_TAHOMA, "") + HSSFHeader.fontSize((short) 9) + " " + reportTitle); + + if (Globals.getShowDescrAtRuntime() && nvl(reportDescr).length() > 0) { + rowNum += 1; + if(shrt_two != 0) + sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, shrt_one, shrt_two)); + XSSFCellStyle styleDescription = wb.createCellStyle(); + styleDescription.setAlignment(HorizontalAlignment.CENTER); + XSSFFont fontDescr = wb.createFont(); + fontDescr.setFontHeight((short) FONT_HEADER_DESCR_SIZE); + fontDescr.setFontName(FONT_TAHOMA); + fontDescr.setColor(HSSFColor.BLACK.index); + styleDescription.setFont(fontDescr); + XSSFCell cellDescr = row.createCell((short) 0); + cellDescr.setCellValue(reportDescr); + cellDescr.setCellStyle(styleHeader); + } + + if (Globals.disclaimerPositionedTopInCSVExcel()) { + rowNum += 1; + row = sheet.createRow(rowNum); + if(shrt_two != 0) + sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, shrt_one, shrt_two)); + XSSFCellStyle styleDescription = wb.createCellStyle(); + styleDescription.setAlignment(HorizontalAlignment.CENTER); + XSSFFont fontDescr = wb.createFont(); + fontDescr.setFontHeight((short) (FONT_SIZE / 0.05)); // 14 + fontDescr.setFontName(FONT_TAHOMA); + fontDescr.setColor(HSSFColor.BLACK.index); + fontDescr.setBold(true); + styleDescription.setFont(fontDescr); + XSSFCell cellDescr = row.createCell((short) 0); + String disclaimer = Globals.getFooterFirstLine() + " " + Globals.getFooterSecondLine(); + cellDescr.setCellValue(disclaimer); + cellDescr.setCellStyle(styleDescription); + } + + rowNum += 1; row = sheet.createRow(rowNum); - cell = row.createCell((short) 0); - debugLogger.debug(Globals.getFooterSecondLine()); - cell.setCellValue(Globals.getFooterSecondLine()); - cell.setCellStyle(styleFooter); -*/ + } + + private void paintExcelFooter(XSSFWorkbook wb, int rowNum, int col, XSSFSheet sheet) { + logger.debug(EELFLoggerDelegate.debugLogger, ("excel footer")); + Footer footer = sheet.getFooter(); + footer.setLeft(HSSFFooter.font(FONT_TAHOMA, "") + HSSFFooter.fontSize((short) FONT_FOOTER_SIZE) + "Page " + + HSSFFooter.page() + + " of " + HSSFFooter.numPages()); + footer.setCenter(HSSFFooter.font(FONT_TAHOMA, "") + HSSFFooter.fontSize((short) FONT_FOOTER_SIZE) + + Globals.getFooterFirstLine() + "\n" + Globals.getFooterSecondLine()); + logger.debug(EELFLoggerDelegate.debugLogger, ("Done")); } - public String saveAsExcelFile(HttpServletRequest request, ReportData rd, - ArrayList reportParamNameValues, String reportTitle, String reportDescr) { - return saveAsExcelFile(request, rd, reportParamNameValues, reportTitle, reportDescr, 2); //2 denotes ReportRuntime object should be taken from session. - } - public String saveAsExcelFile(HttpServletRequest request, ReportData rd, - ArrayList reportParamNameValues, String reportTitle, String reportDescr, int requestFlag) { - setSheetName(Globals.getSheetName()); - try { - ReportRuntime rr; - if(requestFlag == 2) - rr = (ReportRuntime) request.getSession().getAttribute( - AppConstants.SI_REPORT_RUNTIME); - else - rr = (ReportRuntime) request.getAttribute( - AppConstants.SI_REPORT_RUNTIME); - HSSFWorkbook wb = new HSSFWorkbook(); - HashMap styles = new HashMap(); - String xlsFName=""; - if (rr != null){ - styles = loadStyles(rr, wb); - xlsFName = AppUtils.generateUniqueFileName(request, rr.getReportName(), AppConstants.FT_XLS); - } - logger.debug(EELFLoggerDelegate.debugLogger, ("Xls File name " + - AppUtils.getTempFolderPath() - + xlsFName)); - try(FileOutputStream xlsOut = new FileOutputStream(FilenameUtils.normalize(AppUtils.getTempFolderPath() - + xlsFName))){ - // BufferedWriter xlsOut = new BufferedWriter(new - // FileWriter(AppUtils - // .getTempFolderPath() - // + xlsFName)); - - int col = 0; - //System.out.println("Row Header Count " + rd.reportRowHeaderCols.getRowCount()); - //System.out.println("Total Count " + rd.getTotalColumnCount()); + public String saveAsExcelFile(HttpServletRequest request, ReportData rd, + ArrayList reportParamNameValues, String reportTitle, String reportDescr) { + return saveAsExcelFile(request, rd, reportParamNameValues, reportTitle, reportDescr, 2); // 2 denotes + // ReportRuntime object + // should be taken from + // session. + } + + public String saveAsExcelFile(HttpServletRequest request, ReportData rd, + ArrayList reportParamNameValues, String reportTitle, String reportDescr, int requestFlag) { + setSheetName(Globals.getSheetName()); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + ReportRuntime rr; + if (requestFlag == 2) + rr = (ReportRuntime) request.getSession().getAttribute( + AppConstants.SI_REPORT_RUNTIME); + else + rr = (ReportRuntime) request.getAttribute( + AppConstants.SI_REPORT_RUNTIME); + + HashMap styles = new HashMap(); + String xlsFName = ""; + if (rr != null) { + styles = loadStyles(rr, wb); + xlsFName = AppUtils.generateUniqueFileName(request, rr.getReportName(), AppConstants.FT_XLS); + } + logger.debug(EELFLoggerDelegate.debugLogger, ("Xls File name " + + AppUtils.getTempFolderPath() + + xlsFName)); + try (FileOutputStream xlsOut = new FileOutputStream(FilenameUtils.normalize(AppUtils.getTempFolderPath() + + xlsFName))) { - if (!rd.reportRowHeaderCols.hasNext()) - col = rd.getTotalColumnCount(); - else - col = rd.getTotalColumnCount(); - int rowNum = 0; - HSSFSheet sheet = wb.createSheet(getSheetName()); - - if (Globals.getPrintTitleInDownload()&& reportTitle != null ) { - paintExcelHeader(wb, rowNum, col, reportTitle, reportDescr, sheet); + int col = 0; + + if (!rd.reportRowHeaderCols.hasNext()) + col = rd.getTotalColumnCount(); + else + col = rd.getTotalColumnCount(); + int rowNum = 0; + XSSFSheet sheet = wb.createSheet(getSheetName()); + + if (Globals.getPrintTitleInDownload() && reportTitle != null) { + paintExcelHeader(wb, rowNum, col, reportTitle, reportDescr, sheet); + rowNum = sheet.getLastRowNum(); + } else + rowNum = 0; + if (Globals.getPrintParamsInDownload() && rr != null + && rr.getParamNameValuePairsforPDFExcel(request, 1) != null) { + paintExcelParams(wb, rowNum, col, rr.getParamNameValuePairsforPDFExcel(request, 1), + rr.getFormFieldComments(request), sheet, reportTitle, reportDescr); + } // if rowNum = sheet.getLastRowNum(); - } else - rowNum = 0; - if (Globals.getPrintParamsInDownload() && rr.getParamNameValuePairsforPDFExcel(request, 1) != null) { - paintExcelParams(wb,rowNum,col,rr.getParamNameValuePairsforPDFExcel(request, 1), rr.getFormFieldComments(request), sheet, reportTitle, reportDescr); - } // if - rowNum = sheet.getLastRowNum(); - //System.out.println(" rowNum after Params " + rowNum); - paintExcelData(wb, rowNum, rd, styles,rr, sheet, "", request); - if (Globals.getPrintFooterInDownload() ) { - rowNum = sheet.getLastRowNum(); - rowNum += 2; - paintExcelFooter(wb, rowNum, col, sheet); + paintExcelData(wb, rowNum, rd, styles, rr, sheet, "", request); + if (Globals.getPrintFooterInDownload()) { + rowNum = sheet.getLastRowNum(); + rowNum += 2; + paintExcelFooter(wb, rowNum, col, sheet); + } + // response.setContentType("application/vnd.ms-excel"); + // response.setHeader("Content-disposition", "attachment;filename=download_all_" + // + user_id + ".xls"); + wb.write(xlsOut); + xlsOut.flush(); } - //response.setContentType("application/vnd.ms-excel"); - //response.setHeader("Content-disposition", "attachment;filename=download_all_" - // + user_id + ".xls"); - wb.write(xlsOut); - xlsOut.flush(); - } - return xlsFName; - } catch (Exception e) { - e.printStackTrace(); - (new ErrorHandler()).processError(request, "Exception saving data to EXCEL file: " - + e.getMessage()); - return null; - } - } // saveAsExcelFile + return xlsFName; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Excetion in saveAsExcelFile", e); + (new ErrorHandler()).processError(request, "Exception saving data to EXCEL file: " + + e.getMessage()); + return null; + } + } // saveAsExcelFile public void createExcelFileContent(final Writer out, ReportData rd, final ReportRuntime rr, - final HttpServletRequest request, final HttpServletResponse response, final String user_id, final int type) - throws IOException, RaptorException { + final HttpServletRequest request, final HttpServletResponse response, final String user_id, final int type) + throws IOException, RaptorException { // Adding utility for downloading Dashboard reports. Map styles = new HashMap(); final HttpSession session = request.getSession(); - HSSFWorkbook wb = null; + XSSFWorkbook wb = null; int returnValue = 0; final boolean isDashboard = (session.getAttribute(AppConstants.SI_DASHBOARD_REP_ID) != null) && - (((String) session.getAttribute(AppConstants.SI_DASHBOARD_REP_ID)).equals(rr.getReportID())); + (((String) session.getAttribute(AppConstants.SI_DASHBOARD_REP_ID)).equals(rr.getReportID())); if (isDashboard) { final String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date()); - final String xlsFName = "dashboard" + formattedDate + user_id + ".xls"; + final String xlsFName = "./Dashboard.xlsx"; try { FileInputStream xlsIn = null; final Map reportRuntimeMap = (TreeMap) request.getSession() - .getAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP); + .getAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP); final Map reportDataMap = (TreeMap) request.getSession() - .getAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP); + .getAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP); if (reportRuntimeMap != null) { final Set setReportRuntime = reportRuntimeMap.entrySet(); final Set setReportDataMap = reportDataMap.entrySet(); final Iterator iter2 = setReportDataMap.iterator(); int count = 0; - for (Iterator iter = setReportRuntime.iterator(); iter.hasNext(); ) { + for (Iterator iter = setReportRuntime.iterator(); iter.hasNext();) { count++; try { xlsIn = - new FileInputStream(FilenameUtils.normalize(AppUtils.getTempFolderPath() + xlsFName)); + new FileInputStream(xlsFName); } catch (final FileNotFoundException e) { - System.out.println("File not found in the specified path."); + logger.error(EELFLoggerDelegate.errorLogger, "File not found in the specified path.", e); } if (xlsIn != null) { - final POIFSFileSystem fileSystem = new POIFSFileSystem(xlsIn); - wb = new HSSFWorkbook(fileSystem); + wb = new XSSFWorkbook(xlsIn); } else { - wb = new HSSFWorkbook(); + wb = new XSSFWorkbook(); } final Map.Entry entryData = (Entry) iter2.next(); @@ -2794,29 +2285,33 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { final ReportData rdDashRep = (ReportData) entryData.getValue(); int col = 0; final String reportTitle = (nvl(rrDashRep.getReportTitle()).length() > 0 ? rrDashRep - .getReportTitle() - : rrDashRep.getReportName()); + .getReportTitle() + : rrDashRep.getReportName()); final String reportDescr = rrDashRep.getReportDescr(); - if (!rdDashRep.reportRowHeaderCols.hasNext()) { - col = rdDashRep.getTotalColumnCount(); - } else { - col = rdDashRep.getTotalColumnCount(); - } + if (rdDashRep != null) { + if (!rdDashRep.reportRowHeaderCols.hasNext()) { + col = rdDashRep.getTotalColumnCount(); + } else { + col = rdDashRep.getTotalColumnCount(); + } + }else { + continue; + } if (col == 0) { col = 10; } int rowNum = 0; final String formattedReportName = - new HtmlStripper().stripSpecialCharacters(rrDashRep.getReportName()); + new HtmlStripper().stripSpecialCharacters(rrDashRep.getReportName()); - HSSFSheet sheet = null; + XSSFSheet sheet = null; try { sheet = wb.createSheet(formattedReportName); sheet.getPrintSetup().setLandscape(true); styles = loadStyles(rrDashRep, wb); } catch (final IllegalArgumentException ex) { - try (final FileOutputStream xlsOut = new FileOutputStream( - FilenameUtils.normalize(AppUtils.getTempFolderPath() + xlsFName))) { + logger.warn("IllegalArgumentException occured", ex); + try (final FileOutputStream xlsOut = new FileOutputStream(xlsFName)) { wb.write(xlsOut); xlsOut.flush(); } catch (final IOException e) { @@ -2831,33 +2326,32 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { } else { rowNum = 0; } - //getting ReportRuntime object from session + // getting ReportRuntime object from session if (Globals.getPrintParamsInDownload() - && rrDashRep.getParamNameValuePairsforPDFExcel(request, 1) != null) { + && rrDashRep.getParamNameValuePairsforPDFExcel(request, 1) != null) { if (count > 1 && Globals.showParamsInAllDashboardReports()) { paintExcelParams(wb, rowNum, col, - rrDashRep.getParamNameValuePairsforPDFExcel(request, 1), - rrDashRep.getFormFieldComments(request), sheet, reportTitle, reportDescr); + rrDashRep.getParamNameValuePairsforPDFExcel(request, 1), + rrDashRep.getFormFieldComments(request), sheet, reportTitle, reportDescr); } else if (count == 1) { paintExcelParams(wb, rowNum, col, - rrDashRep.getParamNameValuePairsforPDFExcel(request, 1), - rrDashRep.getFormFieldComments(request), sheet, reportTitle, reportDescr); + rrDashRep.getParamNameValuePairsforPDFExcel(request, 1), + rrDashRep.getFormFieldComments(request), sheet, reportTitle, reportDescr); } } // if rowNum = sheet.getLastRowNum(); final String sql_whole = rrDashRep.getWholeSQL(); returnValue = paintExcelData(wb, rowNum, rdDashRep, styles, rrDashRep, sheet, sql_whole, - request); + request); if (returnValue == 0) { if (Globals.getPrintFooterInDownload()) { rowNum = sheet.getLastRowNum(); rowNum += 2; paintExcelFooter(wb, rowNum, col, sheet); } - try (final FileOutputStream xlsOut = new FileOutputStream( - FilenameUtils.normalize(AppUtils.getTempFolderPath() + xlsFName))) { + try (final FileOutputStream xlsOut = new FileOutputStream(xlsFName)) { wb.write(xlsOut); - //TODO Remove comment + // TODO Remove comment xlsOut.flush(); } catch (final IOException e) { logger.warn("Failed to open FileOutputStream", e); @@ -2867,17 +2361,17 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { } response.reset(); - response.setContentType("application/vnd.ms-excel"); + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-disposition", - "attachment;filename=" + "dashboard" + formattedDate + user_id + ".xls"); + "attachment;filename=" + "dashboard" + formattedDate + user_id + ".xlsx"); - xlsIn = new FileInputStream(AppUtils.getTempFolderPath() + xlsFName); + xlsIn = new FileInputStream(xlsFName); int readBytes = 0; final byte[] bOut = new byte[4096]; try (final BufferedInputStream buf = new BufferedInputStream(xlsIn); - final ServletOutputStream sos = response.getOutputStream();) { - //read from the file; write to the ServletOutputStream + final ServletOutputStream sos = response.getOutputStream();) { + // read from the file; write to the ServletOutputStream while ((readBytes = buf.read(bOut, 0, 4096)) > 0) { buf.available(); sos.write(bOut, 0, readBytes); @@ -2891,25 +2385,25 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { throw ex; } - final File f = new File(AppUtils.getTempFolderPath() + xlsFName); + final File f = new File(xlsFName); if (f.exists()) { f.delete(); } } else { - wb = new HSSFWorkbook(); + wb = new XSSFWorkbook (); setSheetName(Globals.getSheetName()); if (rr != null) { styles = loadStyles(rr, wb); } final String reportTitle = (nvl(rr.getReportTitle()).length() > 0 ? rr.getReportTitle() - : rr.getReportName()); + : rr.getReportName()); final String reportDescr = rr.getReportDescr(); final int col = getColumnCountForDownloadFile(rr, rd); int rowNum = 0; - final HSSFSheet sheet = wb.createSheet(getSheetName()); + final XSSFSheet sheet = wb.createSheet(getSheetName()); sheet.getPrintSetup().setLandscape(true); if (Globals.getPrintTitleInDownload() && reportTitle != null) { @@ -2925,19 +2419,18 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { } paintExcelParams(wb, rowNum, col, paramsList, rr.getFormFieldComments(request), sheet, reportTitle, - reportDescr); + reportDescr); } // if rowNum = sheet.getLastRowNum(); final String formattedReportName = new HtmlStripper().stripSpecialCharacters(rr.getReportName()); final String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date()); response.reset(); - response.setContentType("application/vnd.ms-excel"); + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-disposition", - "attachment;filename=" + formattedReportName + formattedDate + user_id + ".xls"); - - if (type == 3 && rr.getSemaphoreList() == null && !(rr.getReportType() - .equals(AppConstants.RT_CROSSTAB))) { //type = 3 is whole + "attachment;filename=" + formattedReportName + formattedDate + user_id + ".xlsx"); + if (type == 3 && rr.getSemaphoreList() == null && !(rr.getReportType() + .equals(AppConstants.RT_CROSSTAB))) { // type = 3 is whole String sql_whole = ""; sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); @@ -2948,38 +2441,42 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { sql_whole = rr.getReportSQL(); } } - + if(rr.isSinglePageDownload()) + sql_whole = rr.getCachedSQL(); returnValue = paintExcelData(wb, rowNum, rd, styles, rr, sheet, sql_whole, request); + rr.setSinglePageDownload(false); } else if (type == 2) { returnValue = paintExcelData(wb, rowNum, rd, styles, rr, sheet, "", request); } else { int downloadLimit = - (rr.getMaxRowsInExcelDownload() > 0) ? rr.getMaxRowsInExcelDownload() : Globals.getDownloadLimit(); - String action = request.getParameter(AppConstants.RI_ACTION); - if (!(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) && !action.endsWith("session")) { - rd = rr.loadReportData(-1, AppUtils.getUserID(request), downloadLimit, request, false /*download*/); - } - if (rr.getSemaphoreList() != null) { - if (rr.getReportType().equals(AppConstants.RT_CROSSTAB)) { - returnValue = paintExcelData(wb, rowNum, rd, styles, rr, sheet, "", request); - } else { - rd = rr.loadReportData(-1, AppUtils.getUserID(request), downloadLimit, request, true); - returnValue = paintExcelData(wb, rowNum, rd, styles, rr, sheet, "", request); - } - } else { - String sql_whole = ""; - sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); - - if (sql_whole == null) { - if (!rr.getReportType().equals(AppConstants.RT_HIVE)) { - sql_whole = rr.getWholeSQL(); - } else { - sql_whole = rr.getReportSQL(); + (rr.getMaxRowsInExcelDownload() > 0) ? rr.getMaxRowsInExcelDownload() + : Globals.getDownloadLimit(); + String action = request.getParameter(AppConstants.RI_ACTION); + if (!(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) && !action.endsWith("session")) { + rd = rr.loadReportData(-1, AppUtils.getUserID(request), downloadLimit, request, + false /* download */); } - } + if (rr.getSemaphoreList() != null) { + if (rr.getReportType().equals(AppConstants.RT_CROSSTAB)) { + returnValue = paintExcelData(wb, rowNum, rd, styles, rr, sheet, "", request); + } else { + rd = rr.loadReportData(-1, AppUtils.getUserID(request), downloadLimit, request, true); + returnValue = paintExcelData(wb, rowNum, rd, styles, rr, sheet, "", request); + } + } else { + String sql_whole = ""; + sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); + + if (sql_whole == null) { + if (!rr.getReportType().equals(AppConstants.RT_HIVE)) { + sql_whole = rr.getWholeSQL(); + } else { + sql_whole = rr.getReportSQL(); + } + } - returnValue = paintExcelData(wb, rowNum, rd, styles, rr, sheet, sql_whole, request); - } + returnValue = paintExcelData(wb, rowNum, rd, styles, rr, sheet, sql_whole, request); + } } if (returnValue == 0) { if (Globals.getPrintFooterInDownload()) { @@ -2987,15 +2484,15 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { rowNum += 2; paintExcelFooter(wb, rowNum, col, sheet); } - //Alternatively: + // Alternatively: wb.setPrintArea( - 0, //sheet index - 0, //start column - col, //end column - 0, //start row - rowNum //end row - ); - //TODO Remove comment + 0, // sheet index + 0, // start column + col, // end column + 0, // start row + rowNum // end row + ); + // TODO Remove comment try (final ServletOutputStream sos = response.getOutputStream();) { wb.write(sos); sos.flush(); @@ -3006,466 +2503,439 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { } } } - + public void createFlatFileContent(Writer out, ReportData rd, ReportRuntime rr, HttpServletRequest request, HttpServletResponse response, String user_id) - throws IOException, Exception { + throws IOException, Exception { ReportHandler rephandler = new ReportHandler(); String reportID = rr.getReportID(); rr = rephandler.loadReportRuntime(request, reportID); String query = rr.getWholeSQL(); String dbInfo = rr.getDbInfo(); - //File f = new File(request.(arg0)("/")); DataSet ds = ConnectionUtils.getDataSet(query, dbInfo); - - //Writing Column names to the file + + // Writing Column names to the file List l = rr.getAllColumns(); StringBuffer allColumnsBuffer = new StringBuffer(); DataColumnType dct = null; - + for (Iterator iter = l.iterator(); iter.hasNext();) { dct = (DataColumnType) iter.next(); allColumnsBuffer.append(dct.getDisplayName()); - if(iter.hasNext()) - allColumnsBuffer.append("|"); + if (iter.hasNext()) + allColumnsBuffer.append("|"); } - rd = rr.loadReportData(-1, user_id, -1,request, true); - //PrintWriter txtOut = new PrintWriter(out); - //response.setContentType("application/notepad"); - //response.setHeader("Content-disposition", "attachment;filename=download_all_"+AppUtils.getUserID(request)+".txt"); + rd = rr.loadReportData(-1, user_id, -1, request, true); + ServletOutputStream sos = response.getOutputStream(); - - //No Report Title for flat file. -// if (Globals.getPrintTitleInDownload() && reportTitle != null) { -// txtOut.println(); -// txtOut.println("\"" + reportTitle + "\""); -// txtOut.println(); -// if (Globals.getShowDescrAtRuntime() && nvl(reportDescr).length() > 0) { -// txtOut.println("\"" + reportDescr + "\""); -// txtOut.println(); -// } -// } // if - // No Params either -// int count = 0; -// if (Globals.getPrintParamsInDownload() && reportParamNameValues != null) { -// for (Iterator iter = reportParamNameValues.iterator(); iter.hasNext();) { -// count += 1; -// if(count == 1) txtOut.println(); -// IdNameValue value = (IdNameValue) iter.next(); -// txtOut.println(value.getId() + " = " + value.getName()); -// if(!iter.hasNext()) txtOut.println(); -// } // for -// } // if - - - - boolean firstPass = true; - for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) { - DataRow dr = rd.reportDataRows.getNext(); - for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { - RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); - if (firstPass) - rhc.resetNext(); - RowHeader rh = rhc.getNext(); - - sos.print(rh.getRowTitle()); - if(rhc.hasNext()) sos.print("|"); - } // for - firstPass = false; - - for (dr.resetNext(); dr.hasNext();) { - DataValue dv = dr.getNext(); - - sos.print( dv.getDisplayValue()); - if(dr.hasNext()) sos.print("|"); - } // for - - sos.println(); - } // for - //sos.flush(); - sos.close(); - } // createFlatFileContent + boolean firstPass = true; + for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) { + DataRow dr = rd.reportDataRows.getNext(); + for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + if (firstPass) + rhc.resetNext(); + RowHeader rh = rhc.getNext(); + + sos.print(rh.getRowTitle()); + if (rhc.hasNext()) + sos.print("|"); + } // for + firstPass = false; + + for (dr.resetNext(); dr.hasNext();) { + DataValue dv = dr.getNext(); + + sos.print(dv.getDisplayValue()); + if (dr.hasNext()) + sos.print("|"); + } // for + + sos.println(); + } // for + sos.close(); + } // createFlatFileContent + public void createExcel2007FileContent(Writer out, ReportData rd, ReportRuntime rr, HttpServletRequest request, - HttpServletResponse response, String user_id, int type) - throws Exception { - + HttpServletResponse response, String user_id, int type) + throws Exception { + // to check performance - int mb = 1024*1024; - Runtime runtime = Runtime.getRuntime(); - - logger.debug(EELFLoggerDelegate.debugLogger, ("STARTING.EXCELX DOWNLOAD....")); - logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####")); - logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:" - + (runtime.totalMemory() - runtime.freeMemory()) / mb)); + int mb = 1024 * 1024; + Runtime runtime = Runtime.getRuntime(); + + logger.debug(EELFLoggerDelegate.debugLogger, ("STARTING.EXCELX DOWNLOAD....")); + logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####")); + logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:" + + (runtime.totalMemory() - runtime.freeMemory()) / mb)); logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:" - + runtime.freeMemory() / mb)); - logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb)); - logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb)); - logger.debug(EELFLoggerDelegate.debugLogger, ("##### END #####")); - - // Adding utility for downloading Dashboard reports. - - Map<String, XSSFCellStyle> styles = new HashMap<String, XSSFCellStyle>(); - HttpSession session = request.getSession(); - XSSFWorkbook wb = null; + + runtime.freeMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("##### END #####")); + + // Adding utility for downloading Dashboard reports. + + Map<String, XSSFCellStyle> styles = new HashMap<String, XSSFCellStyle>(); + HttpSession session = request.getSession(); + XSSFWorkbook wb = null; String formattedReportName = new HtmlStripper().stripSpecialCharacters(rr.getReportName()); String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date()); - //Sheet name to be filled is taken from property. How would this be called if it is Dashboard? - //commented out since application will create and leave it blank. - //setSheetName(Globals.getSheetName()); + // Sheet name to be filled is taken from property. How would this be called if it is Dashboard? + // commented out since application will create and leave it blank. boolean isDashboard = false; - if ((session.getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!=null) && ( ((String) session.getAttribute(AppConstants.SI_DASHBOARD_REP_ID)).equals(rr.getReportID())) ) { - isDashboard = true; + if ((session.getAttribute(AppConstants.SI_DASHBOARD_REP_ID) != null) + && (((String) session.getAttribute(AppConstants.SI_DASHBOARD_REP_ID)).equals(rr.getReportID()))) { + isDashboard = true; } - //boolean isDashboard = (session.getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!=null); ArrayList sheetArrayList = new ArrayList(); - - Map reportRuntimeMap = null; - Map reportDataMap = null; - - ArrayList reportIDList = new ArrayList(); - - //Map reportDisplayTypeMap = null; - if(isDashboard) { - reportRuntimeMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP); - reportDataMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP); - - if(reportRuntimeMap!=null) { - Set setReportRuntime = reportRuntimeMap.entrySet(); - for(Iterator iter = setReportRuntime.iterator(); iter.hasNext(); ) { - Map.Entry entry = (Entry) iter.next(); - ReportRuntime rrDashRep = (ReportRuntime) entry.getValue(); - reportIDList.add(rrDashRep.getReportID()); - } - } - } - - - - - int col = 0; - String reportTitle = (nvl(rr.getReportTitle()).length()>0?rr.getReportTitle():rr.getReportName()); - String reportDescr = rr.getReportDescr(); - - // Total Columns visible in excel - //col = getColumnCountForDownloadFile(rr, rd); - - int rowNum = 0; - - - XSSFSheet sheet = null; - //save the template + + Map reportRuntimeMap = null; + Map reportDataMap = null; + + ArrayList reportIDList = new ArrayList(); + + if (isDashboard) { + reportRuntimeMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP); + reportDataMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP); + + if (reportRuntimeMap != null) { + Set setReportRuntime = reportRuntimeMap.entrySet(); + for (Iterator iter = setReportRuntime.iterator(); iter.hasNext();) { + Map.Entry entry = (Entry) iter.next(); + ReportRuntime rrDashRep = (ReportRuntime) entry.getValue(); + reportIDList.add(rrDashRep.getReportID()); + } + } + } + + int col = 0; + String reportTitle = (nvl(rr.getReportTitle()).length() > 0 ? rr.getReportTitle() : rr.getReportName()); + String reportDescr = rr.getReportDescr(); + + int rowNum = 0; + + XSSFSheet sheet = null; + // save the template String filename = ""; String extension = ""; String sheetRef = null; - - File templateFile = null; - - if(isDashboard) { - if(reportRuntimeMap!=null) { - - FileInputStream readTemplate = null; - //Load customized styles - int count = 0; - - //If template supplied by Application - String templateFilename = rr.getTemplateFile(); - extension = templateFilename.substring(templateFilename.lastIndexOf(".")+1); - filename = formattedReportName+formattedDate+user_id; - - Set setReportRuntimeWB = reportRuntimeMap.entrySet(); - for(Iterator iter = setReportRuntimeWB.iterator(); iter.hasNext(); ) { - count++; - Map.Entry entry = (Entry) iter.next(); - ReportRuntime rrDashRep = (ReportRuntime) entry.getValue(); - try(FileOutputStream os = new FileOutputStream(AppUtils.getTempFolderPath()+ filename+"T."+ nvls(extension, "xlsx"))){ - - if(count==1) { - if(nvl(rr.getTemplateFile()).length()>0) { - readTemplate = new FileInputStream(org.onap.portalsdk.analytics.system.AppUtils.getExcelTemplatePath()+rr.getTemplateFile()); - wb=new XSSFWorkbook(readTemplate); - } else { - //copy the os file to new file and open new file in below line - wb=new XSSFWorkbook(); - } - } else { - readTemplate = new FileInputStream(AppUtils.getTempFolderPath()+ filename+"."+ nvls(extension, "xlsx")); - wb=new XSSFWorkbook(readTemplate); - } - String reportSheetName = ""; - if(rrDashRep!=null){ - styles = loadXSSFStyles(rrDashRep, wb, styles); - reportSheetName = new HtmlStripper().stripSpecialCharacters(rrDashRep.getReportName()); - } - if(nvl(reportSheetName).length()>28) - reportSheetName = reportSheetName.substring(0, 28); - sheet = wb.createSheet(count+"-"+reportSheetName); - if(!Globals.printExcelInLandscapeMode()) - sheet.getPrintSetup().setLandscape(false); - else - sheet.getPrintSetup().setLandscape(true); - wb.write(os); - os.flush(); - if(nvl(rr.getTemplateFile()).length()>0) { - readTemplate.close(); - } - - try(FileInputStream inF = new FileInputStream(AppUtils.getTempFolderPath()+ filename+"T."+ nvls(extension, "xlsx")); - FileOutputStream outStream = new FileOutputStream(AppUtils.getTempFolderPath()+ filename+"."+ nvls(extension, "xlsx"))){ - copyStream(inF, outStream); - outStream.flush(); - } - - } - } - FileInputStream xlsIn = null; - POIFSFileSystem fileSystem = null; - FileOutputStream xlsOut = null; - formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date()); - String xlsFName = "dashboard"+formattedDate+user_id+".xls"; - - Set setReportRuntime = reportRuntimeMap.entrySet(); - Set setReportDataMap = reportDataMap.entrySet(); - Iterator iter2 = setReportDataMap.iterator(); - - - //filename = templateFilename.substring(0, templateFilename.lastIndexOf("."))+"_"+formattedDate+user_id; - + + File templateFile = null; + + if (isDashboard) { + if (reportRuntimeMap != null) { + + FileInputStream readTemplate = null; + // Load customized styles + int count = 0; + + // If template supplied by Application + String templateFilename = rr.getTemplateFile(); + extension = templateFilename.substring(templateFilename.lastIndexOf(".") + 1); + filename = formattedReportName + formattedDate + user_id; + + Set setReportRuntimeWB = reportRuntimeMap.entrySet(); + for (Iterator iter = setReportRuntimeWB.iterator(); iter.hasNext();) { + count++; + Map.Entry entry = (Entry) iter.next(); + ReportRuntime rrDashRep = (ReportRuntime) entry.getValue(); + try (FileOutputStream os = new FileOutputStream( + AppUtils.getTempFolderPath() + filename + "T." + nvls(extension, "xlsx"))) { + + if (count == 1) { + if (nvl(rr.getTemplateFile()).length() > 0) { + readTemplate = new FileInputStream( + org.onap.portalsdk.analytics.system.AppUtils.getExcelTemplatePath() + + rr.getTemplateFile()); + wb = new XSSFWorkbook(readTemplate); + } else { + // copy the os file to new file and open new file in below line + wb = new XSSFWorkbook(); + } + } else { + readTemplate = new FileInputStream( + AppUtils.getTempFolderPath() + filename + "." + nvls(extension, "xlsx")); + wb = new XSSFWorkbook(readTemplate); + } + String reportSheetName = ""; + if (rrDashRep != null) { + styles = loadXSSFStyles(rrDashRep, wb, styles); + reportSheetName = new HtmlStripper().stripSpecialCharacters(rrDashRep.getReportName()); + } + if (nvl(reportSheetName).length() > 28) + reportSheetName = reportSheetName.substring(0, 28); + sheet = wb.createSheet(count + "-" + reportSheetName); + if (!Globals.printExcelInLandscapeMode()) + sheet.getPrintSetup().setLandscape(false); + else + sheet.getPrintSetup().setLandscape(true); + wb.write(os); + os.flush(); + if (nvl(rr.getTemplateFile()).length() > 0) { + readTemplate.close(); + } + + try (FileInputStream inF = new FileInputStream( + AppUtils.getTempFolderPath() + filename + "T." + nvls(extension, "xlsx")); + FileOutputStream outStream = new FileOutputStream( + AppUtils.getTempFolderPath() + filename + "." + nvls(extension, "xlsx"))) { + copyStream(inF, outStream); + outStream.flush(); + } + + } + } + FileInputStream xlsIn = null; + POIFSFileSystem fileSystem = null; + FileOutputStream xlsOut = null; + formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date()); + String xlsFName = "dashboard" + formattedDate + user_id + ".xls"; + + Set setReportRuntime = reportRuntimeMap.entrySet(); + Set setReportDataMap = reportDataMap.entrySet(); + Iterator iter2 = setReportDataMap.iterator(); + count = 0; - for(Iterator iter = setReportRuntime.iterator(); iter.hasNext(); ) { - count++; - - Map.Entry entry = (Entry) iter.next(); - Map.Entry entryData = (Entry) iter2.next(); - ReportRuntime rrDashRep = (ReportRuntime) entry.getValue(); - ReportData rdDashRep = (ReportData) entryData.getValue(); - - String reportSheetName = new HtmlStripper().stripSpecialCharacters(rrDashRep.getReportName()); - if(nvl(reportSheetName).length()>28) - reportSheetName = reportSheetName.substring(0, 28); - sheet = wb.getSheet(count+"-"+reportSheetName); - sheetRef = sheet.getPackagePart().getPartName().getName(); - - //Step 2. Generate XML file. - File tmp = File.createTempFile("sheet", ".xml"); - try(FileOutputStream fileOutTemp = new FileOutputStream(tmp); - Writer fw = new OutputStreamWriter(fileOutTemp, XML_ENCODING)){ - - String sql_whole = rrDashRep.getWholeSQL(); - - SpreadsheetWriter sw = new SpreadsheetWriter(fw); - sw.beginSheet(); - - - generate(wb, sw, styles, rdDashRep, sql_whole, rrDashRep, request, sheet); - - - sw.endSheet(); - - fw.flush(); - fileOutTemp.flush(); - } - - //Step 3. Substitute the template entry with the generated data - - try(FileOutputStream outF = new FileOutputStream(AppUtils.getTempFolderPath()+ filename+"."+ nvls(extension, "xlsx"))){ - templateFile = new File(AppUtils.getTempFolderPath()+ filename+"T."+ nvls(extension, "xlsx")); - substitute(templateFile, tmp, sheetRef.substring(1), outF); - outF.flush(); - } - - try(FileInputStream inF = new FileInputStream(AppUtils.getTempFolderPath()+ filename+"."+ nvls(extension, "xlsx")); - FileOutputStream outStream = new FileOutputStream(AppUtils.getTempFolderPath()+ filename+"T."+ nvls(extension, "xlsx"))){ - copyStream(inF, outStream); - outStream.flush(); - } - } - } - } else { - //If template supplied by Application - if(nvl(rr.getTemplateFile()).length()>0) { - String templateFilename = rr.getTemplateFile(); - extension = templateFilename.substring(templateFilename.lastIndexOf(".")+1); - filename = formattedReportName+formattedDate+user_id; - //filename = templateFilename.substring(0, templateFilename.lastIndexOf("."))+"_"+formattedDate+user_id; + for (Iterator iter = setReportRuntime.iterator(); iter.hasNext();) { + count++; + + Map.Entry entry = (Entry) iter.next(); + Map.Entry entryData = (Entry) iter2.next(); + ReportRuntime rrDashRep = (ReportRuntime) entry.getValue(); + ReportData rdDashRep = (ReportData) entryData.getValue(); + + String reportSheetName = new HtmlStripper().stripSpecialCharacters(rrDashRep.getReportName()); + if (nvl(reportSheetName).length() > 28) + reportSheetName = reportSheetName.substring(0, 28); + sheet = wb.getSheet(count + "-" + reportSheetName); + sheetRef = sheet.getPackagePart().getPartName().getName(); + + // Step 2. Generate XML file. + File tmp = File.createTempFile("sheet", ".xml"); + try (FileOutputStream fileOutTemp = new FileOutputStream(tmp); + Writer fw = new OutputStreamWriter(fileOutTemp, XML_ENCODING)) { + + String sql_whole = rrDashRep.getWholeSQL(); + + SpreadsheetWriter sw = new SpreadsheetWriter(fw); + sw.beginSheet(); + + generate(wb, sw, styles, rdDashRep, sql_whole, rrDashRep, request, sheet); + + sw.endSheet(); + + fw.flush(); + fileOutTemp.flush(); + } + + // Step 3. Substitute the template entry with the generated data + + try (FileOutputStream outF = new FileOutputStream( + AppUtils.getTempFolderPath() + filename + "." + nvls(extension, "xlsx"))) { + templateFile = + new File(AppUtils.getTempFolderPath() + filename + "T." + nvls(extension, "xlsx")); + substitute(templateFile, tmp, sheetRef.substring(1), outF); + outF.flush(); + } + + try (FileInputStream inF = new FileInputStream( + AppUtils.getTempFolderPath() + filename + "." + nvls(extension, "xlsx")); + FileOutputStream outStream = new FileOutputStream( + AppUtils.getTempFolderPath() + filename + "T." + nvls(extension, "xlsx"))) { + copyStream(inF, outStream); + outStream.flush(); + } + } + } } else { - filename = formattedReportName+formattedDate+user_id; - } + // If template supplied by Application + if (nvl(rr.getTemplateFile()).length() > 0) { + String templateFilename = rr.getTemplateFile(); + extension = templateFilename.substring(templateFilename.lastIndexOf(".") + 1); + filename = formattedReportName + formattedDate + user_id; + // filename = templateFilename.substring(0, + // templateFilename.lastIndexOf("."))+"_"+formattedDate+user_id; + } else { + filename = formattedReportName + formattedDate + user_id; + } - if(nvl(rr.getTemplateFile()).length()<=0) { - try(FileOutputStream os = new FileOutputStream(AppUtils.getTempFolderPath()+"template"+formattedDate+user_id+".xlsx")){ - wb=new XSSFWorkbook(); - //Load customized styles - if (rr != null) - styles = loadXSSFStyles(rr, wb, styles); - //create data sheet - if(isDashboard) { - - } else { - - } - String reportSheetName = new HtmlStripper().stripSpecialCharacters(rr.getReportName()); - if(nvl(reportSheetName).length()>28) - reportSheetName = reportSheetName.substring(0, 28); - sheet = wb.createSheet(reportSheetName); - - //customized mode - if(!Globals.printExcelInLandscapeMode()) - sheet.getPrintSetup().setLandscape(false); - else - sheet.getPrintSetup().setLandscape(true); - //get data sheet name - sheetRef = sheet.getPackagePart().getPartName().getName(); - wb.write(os); - os.flush(); - //wb = null; - } - - } else { - try(FileOutputStream os = new FileOutputStream(AppUtils.getTempFolderPath()+ filename+"T."+ nvls(extension, "xlsx")); - FileInputStream readTemplate = new FileInputStream(org.onap.portalsdk.analytics.system.AppUtils.getExcelTemplatePath()+rr.getTemplateFile());){ - wb=new XSSFWorkbook(readTemplate); - if (rr != null) - styles = loadXSSFStyles(rr, wb, styles); - sheet = wb.getSheetAt(0); - if(!Globals.printExcelInLandscapeMode()) - sheet.getPrintSetup().setLandscape(false); - else - sheet.getPrintSetup().setLandscape(true); - //sheet = wb.getSheet(getSheetName()); - sheetRef = sheet.getPackagePart().getPartName().getName(); - wb.write(os); - os.flush(); - //wb = null; - } - } - - //Step 2. Generate XML file. - File tmp = File.createTempFile("sheet", ".xml"); - try(FileOutputStream fileOutTemp = new FileOutputStream(tmp); - Writer fw = new OutputStreamWriter(fileOutTemp, XML_ENCODING)){ - - //String sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); - String sql_whole = ""; - sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); - - if(sql_whole==null) { - if (!rr.getReportType().equals(AppConstants.RT_HIVE)) - sql_whole = rr.getWholeSQL(); - else - sql_whole = rr.getReportSQL(); - } - - SpreadsheetWriter sw = new SpreadsheetWriter(fw); - - sw.beginSheet(); - - if((rd.getDataRowCount() >= rr.getReportDataSize()) && !rr.getReportType().equals(AppConstants.RT_HIVE)) { - sql_whole=""; - } - - generate(wb, sw, styles, rd, sql_whole, rr, request, sheet); - - sw.endSheet(); - - fw.flush(); - fileOutTemp.flush(); + if (nvl(rr.getTemplateFile()).length() <= 0) { + try (FileOutputStream os = new FileOutputStream( + AppUtils.getTempFolderPath() + "template" + formattedDate + user_id + ".xlsx")) { + wb = new XSSFWorkbook(); + // Load customized styles + if (rr != null) + styles = loadXSSFStyles(rr, wb, styles); + // create data sheet + if (isDashboard) { + + } else { + + } + String reportSheetName = new HtmlStripper().stripSpecialCharacters(rr.getReportName()); + if (nvl(reportSheetName).length() > 28) + reportSheetName = reportSheetName.substring(0, 28); + sheet = wb.createSheet(reportSheetName); + + // customized mode + if (!Globals.printExcelInLandscapeMode()) + sheet.getPrintSetup().setLandscape(false); + else + sheet.getPrintSetup().setLandscape(true); + // get data sheet name + sheetRef = sheet.getPackagePart().getPartName().getName(); + wb.write(os); + os.flush(); + // wb = null; + } + + } else { + try (FileOutputStream os = + new FileOutputStream(AppUtils.getTempFolderPath() + filename + "T." + nvls(extension, "xlsx")); + FileInputStream readTemplate = + new FileInputStream(org.onap.portalsdk.analytics.system.AppUtils.getExcelTemplatePath() + + rr.getTemplateFile());) { + wb = new XSSFWorkbook(readTemplate); + if (rr != null) + styles = loadXSSFStyles(rr, wb, styles); + sheet = wb.getSheetAt(0); + if (!Globals.printExcelInLandscapeMode()) + sheet.getPrintSetup().setLandscape(false); + else + sheet.getPrintSetup().setLandscape(true); + // sheet = wb.getSheet(getSheetName()); + sheetRef = sheet.getPackagePart().getPartName().getName(); + wb.write(os); + os.flush(); + // wb = null; + } } - //Step 3. Substitute the template entry with the generated data - - try(FileOutputStream outF = new FileOutputStream(AppUtils.getTempFolderPath()+ filename+"."+ nvls(extension, "xlsx"))){ - - if(nvl(rr.getTemplateFile()).length()>0) { - templateFile = new File(AppUtils.getTempFolderPath()+ filename+"T."+ nvls(extension, "xlsx")); - } else { - templateFile = new File(AppUtils.getTempFolderPath()+"template"+formattedDate+user_id+".xlsx"); - } - substitute(templateFile, tmp, sheetRef.substring(1), outF); - outF.flush(); - } - - } - //get servlet output stream - - - response.reset(); - try(BufferedInputStream buf = new BufferedInputStream(new FileInputStream(AppUtils.getTempFolderPath()+filename + "."+ nvls(extension, "xlsx"))); - ServletOutputStream sos = response.getOutputStream()){ - - String mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; - if(extension.equals("xlsm")) - mime_type = "application/vnd.ms-excel.sheet.macroEnabled.12"; - response.setContentType(mime_type); - - response.setHeader("Content-disposition", "attachment;filename="+filename+"."+ nvls(extension, "xlsx")); - - - int readBytes = 0; - - //read from the file; write to the ServletOutputStream - while ((readBytes = buf.read()) != -1) - sos.write(readBytes); - - - sos.flush(); - } - logger.debug(EELFLoggerDelegate.debugLogger, ("ENDING..DOWNLOADING XLSX...")); - logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####")); - logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:" - + (runtime.totalMemory() - runtime.freeMemory()) / mb)); - logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:" - + runtime.freeMemory() / mb)); - logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb)); - logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb)); - logger.debug(EELFLoggerDelegate.debugLogger, ("##### END #####")); + + // Step 2. Generate XML file. + File tmp = File.createTempFile("sheet", ".xml"); + try (FileOutputStream fileOutTemp = new FileOutputStream(tmp); + Writer fw = new OutputStreamWriter(fileOutTemp, XML_ENCODING)) { + + String sql_whole = ""; + sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); + + if (sql_whole == null) { + if (!rr.getReportType().equals(AppConstants.RT_HIVE)) + sql_whole = rr.getWholeSQL(); + else + sql_whole = rr.getReportSQL(); + } + + SpreadsheetWriter sw = new SpreadsheetWriter(fw); + + sw.beginSheet(); + + if ((rd.getDataRowCount() >= rr.getReportDataSize()) + && !rr.getReportType().equals(AppConstants.RT_HIVE)) { + sql_whole = ""; + } + + generate(wb, sw, styles, rd, sql_whole, rr, request, sheet); + + sw.endSheet(); + + fw.flush(); + fileOutTemp.flush(); + } + // Step 3. Substitute the template entry with the generated data + + try (FileOutputStream outF = + new FileOutputStream(AppUtils.getTempFolderPath() + filename + "." + nvls(extension, "xlsx"))) { + + if (nvl(rr.getTemplateFile()).length() > 0) { + templateFile = new File(AppUtils.getTempFolderPath() + filename + "T." + nvls(extension, "xlsx")); + } else { + templateFile = + new File(AppUtils.getTempFolderPath() + "template" + formattedDate + user_id + ".xlsx"); + } + substitute(templateFile, tmp, sheetRef.substring(1), outF); + outF.flush(); + } + + } + // get servlet output stream + + response.reset(); + try (BufferedInputStream buf = new BufferedInputStream( + new FileInputStream(AppUtils.getTempFolderPath() + filename + "." + nvls(extension, "xlsx"))); + ServletOutputStream sos = response.getOutputStream()) { + + String mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + if (extension.equals("xlsm")) + mime_type = "application/vnd.ms-excel.sheet.macroEnabled.12"; + response.setContentType(mime_type); + + response.setHeader("Content-disposition", + "attachment;filename=" + filename + "." + nvls(extension, "xlsx")); + + int readBytes = 0; + + // read from the file; write to the ServletOutputStream + while ((readBytes = buf.read()) != -1) + sos.write(readBytes); + + sos.flush(); + } + logger.debug(EELFLoggerDelegate.debugLogger, ("ENDING..DOWNLOADING XLSX...")); + logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####")); + logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:" + + (runtime.totalMemory() - runtime.freeMemory()) / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:" + + runtime.freeMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("##### END #####")); } - /** - * - * @param zipfile the template file - * @param tmpfile the XML file with the sheet data - * @param entry the name of the sheet entry to substitute, e.g. xl/worksheets/sheet1.xml - * @param out the stream to write the result to - */ - private static void substitute(File zipfile, File tmpfile, String entry, OutputStream out) throws IOException { - try(ZipFile zip = new ZipFile(zipfile); - ZipOutputStream zos = new ZipOutputStream(out)){ - - - - @SuppressWarnings("unchecked") - Enumeration<ZipEntry> en = (Enumeration<ZipEntry>) zip.entries(); - while (en.hasMoreElements()) { - ZipEntry ze = en.nextElement(); - if(!ze.getName().equals(entry)){ - zos.putNextEntry(new ZipEntry(ze.getName())); - try(InputStream is = zip.getInputStream(ze)){ - copyStream(is, zos); - } - } - } - zos.putNextEntry(new ZipEntry(entry)); - try(InputStream is = new FileInputStream(tmpfile)){ - copyStream(is, zos); - } - zos.flush(); - } - } - - private static void copyStream(InputStream in, OutputStream out) throws IOException { - byte[] chunk = new byte[1024]; - int count; - while ((count = in.read(chunk)) >=0 ) { - out.write(chunk,0,count); - } - } + /** + * + * @param zipfile the template file + * @param tmpfile the XML file with the sheet data + * @param entry the name of the sheet entry to substitute, e.g. xl/worksheets/sheet1.xml + * @param out the stream to write the result to + */ + private static void substitute(File zipfile, File tmpfile, String entry, OutputStream out) throws IOException { + try (ZipFile zip = new ZipFile(zipfile); + ZipOutputStream zos = new ZipOutputStream(out)) { + + @SuppressWarnings("unchecked") + Enumeration<ZipEntry> en = (Enumeration<ZipEntry>) zip.entries(); + while (en.hasMoreElements()) { + ZipEntry ze = en.nextElement(); + if (!ze.getName().equals(entry)) { + zos.putNextEntry(new ZipEntry(ze.getName())); + try (InputStream is = zip.getInputStream(ze)) { + copyStream(is, zos); + } + } + } + zos.putNextEntry(new ZipEntry(entry)); + try (InputStream is = new FileInputStream(tmpfile)) { + copyStream(is, zos); + } + zos.flush(); + } + } + private static void copyStream(InputStream in, OutputStream out) throws IOException { + byte[] chunk = new byte[1024]; + int count; + while ((count = in.read(chunk)) >= 0) { + out.write(chunk, 0, count); + } + } public void createCSVFileContent(final Writer out, final ReportData rd, final ReportRuntime rr, - final HttpServletRequest request, final HttpServletResponse response) throws RaptorException { + final HttpServletRequest request, final HttpServletResponse response) throws RaptorException { final String formattedReportName = new HtmlStripper().stripSpecialCharacters(rr.getReportName()); final String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date()); @@ -3481,13 +2951,13 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { final int mb = 1024 * 1024; try (final PrintWriter csvOut = - new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8")), - false);) { + new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8")), + false);) { final HtmlStripper strip = new HtmlStripper(); ColumnHeaderRow chr = null; if (!raw) { final String reportTitle = (nvl(rr.getReportTitle()).length() > 0 ? rr.getReportTitle() - : rr.getReportName()); + : rr.getReportName()); csvOut.println(); csvOut.print("\"" + reportTitle + "\","); csvOut.println(); @@ -3509,12 +2979,12 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { paramsList = (ArrayList) request.getSession().getAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO); } int paramSeq = 0; - for (final Iterator iter = paramsList.iterator(); iter.hasNext(); ) { + for (final Iterator iter = paramsList.iterator(); iter.hasNext();) { final IdNameValue value = (IdNameValue) iter.next(); if (nvl(value.getId()).trim().length() > 0 && (!"BLANK".equals(nvl(value.getId()).trim()))) { paramSeq += 1; if (paramSeq <= 1) { - csvOut.print("\"" + "Run-time Parameters" + "\""); + csvOut.print("\"" + RUNTIME_PARAMETERS + "\""); csvOut.println(); } csvOut.print("\"" + value.getId() + ":" + "\","); @@ -3524,14 +2994,15 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { } else { if (valueName.startsWith("(") && valueName.endsWith(")")) { csvOut.print( - "\"" + valueName.replaceAll("~", ",").substring(1, valueName.length() - 1) + "\","); + "\"" + valueName.replaceAll("~", ",").substring(1, valueName.length() - 1) + + "\","); } else { csvOut.print("\"" + valueName.replaceAll("~", ",") + "\","); } } csvOut.println(); } - } //for + } // for csvOut.println(); csvOut.println(); } @@ -3554,8 +3025,8 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { if (nvl(sql_whole).length() > 0) { try (final Connection conn = ConnectionUtils.getConnection(rr.getDbInfo()); - final Statement st = conn.createStatement(); - final ResultSet rs = st.executeQuery(sql_whole)) { + final Statement st = conn.createStatement(); + final ResultSet rs = st.executeQuery(sql_whole)) { System.out.println("************* Map Whole SQL *************"); System.out.println(sql_whole); @@ -3565,9 +3036,9 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { String title = ""; if (rd != null) { - for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext(); ) { + for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { chr = rd.reportColumnHeaderRows.getNext(); - for (chr.resetNext(); chr.hasNext(); ) { + for (chr.resetNext(); chr.hasNext();) { ColumnHeader ch = chr.getNext(); title = ch.getColumnTitle(); title = Utils.replaceInString(title, "_nl_", " \n"); @@ -3588,15 +3059,16 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { for (int i = 1; i <= numberOfColumns; i++) { colHash.put(rsmd.getColumnLabel(i).toUpperCase(), rs.getString(i)); } - for (chr.resetNext(); chr.hasNext(); ) { + for (chr.resetNext(); chr.hasNext();) { final ColumnHeader ch = chr.getNext(); title = ch.getColumnTitle(); title = Utils.replaceInString(title, "_nl_", " \n"); if (ch.isVisible() && nvl(title).length() > 0) { csvOut.print( - "\"" + strip - .stripCSVHtml(nvl((String) colHash.get(ch.getColId().toUpperCase()))) + "\"" + strip + .stripCSVHtml( + nvl((String) colHash.get(ch.getColId().toUpperCase()))) + "\","); } @@ -3605,12 +3077,12 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { } if (rd.reportDataTotalRow != null) { - for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext(); ) { + for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext();) { final DataRow dr = rd.reportDataTotalRow.getNext(); csvOut.print("\"" + "Total" + "\","); dr.resetNext(); dr.getNext(); - for (; dr.hasNext(); ) { + for (; dr.hasNext();) { final DataValue dv = dr.getNext(); if (dv.isVisible()) { csvOut.print("\"" + strip.stripCSVHtml(dv.getDisplayValue()) + "\","); @@ -3653,9 +3125,9 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { csvOut.print("\"" + "#" + "\","); } - for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext(); ) { + for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { chr = rd.reportColumnHeaderRows.getNext(); - for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext(); ) { + for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); if (firstPass) { @@ -3665,7 +3137,7 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { } // for firstPass = false; - for (chr.resetNext(); chr.hasNext(); ) { + for (chr.resetNext(); chr.hasNext();) { ColumnHeader ch = chr.getNext(); if (ch.isVisible()) { csvOut.print("\"" + ch.getColumnTitle() + "\","); @@ -3680,7 +3152,7 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { firstPass = true; int rowCount = 0; - for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext(); ) { + for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) { if (rd.reportDataTotalRow != null) { rowCount++; csvOut.print("\"" + rowCount + "\","); @@ -3688,7 +3160,7 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { final DataRow dr = rd.reportDataRows.getNext(); - for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext(); ) { + for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { final RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); if (firstPass) { rhc.resetNext(); @@ -3699,7 +3171,7 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { } // for firstPass = false; - for (dr.resetNext(); dr.hasNext(); ) { + for (dr.resetNext(); dr.hasNext();) { DataValue dv = dr.getNext(); if (dv.isVisible()) { csvOut.print("\"" + strip.stripCSVHtml(dv.getDisplayValue()) + "\","); @@ -3709,12 +3181,12 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { csvOut.println(); } // for if (rd.reportDataTotalRow != null) { - for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext(); ) { + for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext();) { DataRow dr = rd.reportDataTotalRow.getNext(); csvOut.print("\"" + "Total" + "\","); firstPass = false; - for (dr.resetNext(); dr.hasNext(); ) { + for (dr.resetNext(); dr.hasNext();) { DataValue dv = dr.getNext(); if (dv.isVisible()) { csvOut.print("\"" + strip.stripCSVHtml(dv.getDisplayValue()) + "\","); @@ -3748,8 +3220,8 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { if (!raw) { try (final ZipOutputStream zos = - new ZipOutputStream(new FileOutputStream(AppUtils.getTempFolderPath() + "" + zipFName)); - final FileInputStream fis = new FileInputStream(fileName)) { + new ZipOutputStream(new FileOutputStream(AppUtils.getTempFolderPath() + "" + zipFName)); + final FileInputStream fis = new FileInputStream(fileName)) { int size = 0; final byte[] buffer = new byte[1024]; @@ -3783,11 +3255,11 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { } try (final ServletOutputStream sos = response.getOutputStream(); - final FileInputStream fileIn = new FileInputStream(file); - final BufferedInputStream buf = new BufferedInputStream(fileIn);) { + final FileInputStream fileIn = new FileInputStream(file); + final BufferedInputStream buf = new BufferedInputStream(fileIn);) { final byte[] bOut = new byte[4096]; - //read from the file; write to the ServletOutputStream + // read from the file; write to the ServletOutputStream int readBytes = 0; while ((readBytes = buf.read(bOut, 0, 4096)) > 0) { buf.available(); @@ -3813,336 +3285,322 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { } // createCSVFileContent - public String saveXMLFile(HttpServletRequest request, String reportName, String reportXML) { - try { - String xmlFName = AppUtils.generateUniqueFileName(request, reportName, AppConstants.FT_XML); - - try(PrintWriter xmlOut = new PrintWriter(new BufferedWriter(new FileWriter(new File( - AppUtils.getTempFolderPath() + xmlFName))))){ - xmlOut.println(reportXML); - } + public String saveXMLFile(HttpServletRequest request, String reportName, String reportXML) { + try { + String xmlFName = AppUtils.generateUniqueFileName(request, reportName, AppConstants.FT_XML); + + try (PrintWriter xmlOut = new PrintWriter(new BufferedWriter(new FileWriter(new File( + AppUtils.getTempFolderPath() + xmlFName))))) { + xmlOut.println(reportXML); + } - //return AppUtils.getTempFolderURL() - // + java.net.URLEncoder.encode(java.net.URLDecoder.decode(xmlFName)); return java.net.URLEncoder.encode(java.net.URLDecoder.decode(xmlFName)); - - } catch (Exception e) { - (new ErrorHandler()).processError(request, - "Exception saving XML source to file system: " + e.getMessage()); - return null; - } - } // saveXMLFile - - public ReportRuntime loadReportRuntime(HttpServletRequest request, String reportID) - throws RaptorException { - return loadReportRuntime(request, reportID, true); - } // loadReportRuntime - - public ReportRuntime loadReportRuntime(HttpServletRequest request, String reportID, - boolean prepareForExecution) throws RaptorException { - return loadReportRuntime(request, reportID, true, 2); // where 2 is adding to session - } - public ReportRuntime loadReportRuntime(HttpServletRequest request, String reportID, - boolean prepareForExecution, int requestFlag) throws RaptorException { + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception in saveXMLFile", e); + (new ErrorHandler()).processError(request, + "Exception saving XML source to file system: " + e.getMessage()); + return null; + } + } // saveXMLFile + + public ReportRuntime loadReportRuntime(HttpServletRequest request, String reportID) + throws RaptorException { + return loadReportRuntime(request, reportID, true); + } // loadReportRuntime + + public ReportRuntime loadReportRuntime(HttpServletRequest request, String reportID, + boolean prepareForExecution) throws RaptorException { + return loadReportRuntime(request, reportID, true, 2); // where 2 is adding to session + } + + public ReportRuntime loadReportRuntime(HttpServletRequest request, String reportID, + boolean prepareForExecution, int requestFlag) throws RaptorException { boolean refresh = nvl(request.getParameter(AppConstants.RI_REFRESH)).toUpperCase().startsWith("Y"); - boolean rDisplayContent = AppUtils.getRequestFlag(request, - AppConstants.RI_DISPLAY_CONTENT) - || AppUtils.getRequestFlag(request, "noFormFields"); - - ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute( - AppConstants.SI_REPORT_RUNTIME); - boolean inSchedule = AppUtils.getRequestFlag(request, AppConstants.SCHEDULE_ACTION); - if (rr != null ) { - if(requestFlag == 7) { // DASH - String reportXML = ReportLoader.loadCustomReportXML(reportID); - logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Report [" + reportID + "]: XML loaded")); - rr = ReportRuntime.unmarshal(reportXML, reportID, request); - rr.setParamValues(request, false,refresh); - rr.setDisplayFlags(true, true); // show content even at the first time - return rr; - } else { - logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Load Report Runtime "+ reportID + " " +rr.getReportID() + " " + request.getParameter("refresh") )); - if (reportID.equals(rr.getReportID()) && (request.getParameter("refresh")==null || !request.getParameter("refresh").equals("Y"))) { - // The report runtime is already in the session - if (prepareForExecution) { - boolean resetParams = AppUtils.getRequestFlag(request, - AppConstants.RI_RESET_PARAMS); - rr.setParamValues(request, resetParams,refresh); - - if (resetParams) - rr.resetVisualSettings(); - rr.setDisplayFlags(nvl(request.getParameter(AppConstants.RI_SOURCE_PAGE)) - .length() == 0, rDisplayContent || rr.isDisplayOptionHideForm()); - } // if - - return rr; - } // if - } + boolean rDisplayContent = AppUtils.getRequestFlag(request, + AppConstants.RI_DISPLAY_CONTENT) + || AppUtils.getRequestFlag(request, "noFormFields"); + + ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute( + AppConstants.SI_REPORT_RUNTIME); + boolean inSchedule = AppUtils.getRequestFlag(request, AppConstants.SCHEDULE_ACTION); + if (rr != null) { + if (requestFlag == 7) { // DASH + String reportXML = ReportLoader.loadCustomReportXML(reportID); + logger.debug(EELFLoggerDelegate.debugLogger, + ("[DEBUG MESSAGE FROM RAPTOR] Report [" + reportID + "]: XML loaded")); + rr = ReportRuntime.unmarshal(reportXML, reportID, request); + rr.setParamValues(request, false, refresh); + rr.setDisplayFlags(true, true); // show content even at the first time + return rr; + } else { + logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Load Report Runtime " + + reportID + " " + rr.getReportID() + " " + request.getParameter("refresh"))); + if (reportID.equals(rr.getReportID()) + && (request.getParameter("refresh") == null || !request.getParameter("refresh").equals("Y"))) { + if (prepareForExecution) { + boolean resetParams = AppUtils.getRequestFlag(request, + AppConstants.RI_RESET_PARAMS); + rr.setParamValues(request, resetParams, refresh); + + if (resetParams) + rr.resetVisualSettings(); + rr.setDisplayFlags(nvl(request.getParameter(AppConstants.RI_SOURCE_PAGE)) + .length() == 0, rDisplayContent || rr.isDisplayOptionHideForm()); + } // if + + return rr; + } // if + } } - /* - * Cannot convert the definition => XML file not saved for preview also, - * commented code not maintained up to date ReportDefinition rdef = - * (ReportDefinition) - * request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION); - * if(rdef!=null) if(reportID.equals(rdef.getReportID())) { // The - * report definition is in the session => create report runtime from it - * rr = new ReportRuntime(rdef, request); if(prepareForExecution) { - * request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, - * rr); - * rr.setDisplayFlags(request.getParameter(AppConstants.RI_SOURCE_PAGE)==null); } // - * if return rr; } // if - */ - - // Report is NOT in the session => load from the database - String reportXML = ReportLoader.loadCustomReportXML(reportID); - logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Report [" + reportID + "]: XML loaded")); - - rr = ReportRuntime.unmarshal(reportXML, reportID, request); - if (prepareForExecution) { - String userID ; - int flag = 0; - if(request.getAttribute("schedule_email_userId") != null) { - userID = (String)request.getAttribute("schedule_email_userId"); - flag = 1; - } - else - userID = AppUtils.getUserID(request); - // If it is dashboard type then report can be viewed without specific privilege to report - String dashboardId = AppUtils.getRequestValue(request, AppConstants.RI_DASHBOARD_ID); - //System.out.println("USSSSSSSSSSSSERID " + userID); - //System.out.println("PDF " + AppUtils.getRequestNvlValue(request, "pdfAttachmentKey") ); - if(!rr.isDashboardType() && !(isReportAddedAsDashboard(request, dashboardId, rr.getReportID()))) { - if ( AppUtils.getRequestNvlValue(request, "pdfAttachmentKey").length()<=0 ) - if(flag == 1 )rr.checkUserReadAccess(request, userID); - else rr.checkUserReadAccess(request); + /* + * Cannot convert the definition => XML file not saved for preview also, commented code not + * maintained up to date ReportDefinition rdef = (ReportDefinition) + * request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION); if(rdef!=null) + * if(reportID.equals(rdef.getReportID())) { // The report definition is in the session => create + * report runtime from it rr = new ReportRuntime(rdef, request); if(prepareForExecution) { + * request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); + * rr.setDisplayFlags(request.getParameter(AppConstants.RI_SOURCE_PAGE)==null); } // if return rr; } + * // if + */ + + String reportXML = ReportLoader.loadCustomReportXML(reportID); + logger.debug(EELFLoggerDelegate.debugLogger, + ("[DEBUG MESSAGE FROM RAPTOR] Report [" + reportID + "]: XML loaded")); + + rr = ReportRuntime.unmarshal(reportXML, reportID, request); + if (prepareForExecution) { + String userID; + int flag = 0; + if (request.getAttribute("schedule_email_userId") != null) { + userID = (String) request.getAttribute("schedule_email_userId"); + flag = 1; + } else + userID = AppUtils.getUserID(request); + String dashboardId = AppUtils.getRequestValue(request, AppConstants.RI_DASHBOARD_ID); + if (!rr.isDashboardType() && !(isReportAddedAsDashboard(request, dashboardId, rr.getReportID()))) { + if (AppUtils.getRequestNvlValue(request, "pdfAttachmentKey").length() <= 0) + if (flag == 1) + rr.checkUserReadAccess(request, userID); + else + rr.checkUserReadAccess(request); } // TODO ON Demand - //rr.setXmlFileName(saveXMLFile(request, rr.getReportName(), reportXML)); - if (rDisplayContent) { - //System.out.println("In rDisplayContent "); - rr.setParamValues(request, false,true); - //if (requestFlag==2) - request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); - } - if(inSchedule) { - //System.out.println("In inSchedule "); - rr.setParamValues(request, false,false); - } - if( requestFlag == 7 ) { // DASH - rr.setDisplayFlags(true, true); - } else { - rr.setDisplayFlags(request.getParameter(AppConstants.RI_SOURCE_PAGE) == null, - rDisplayContent || rr.isDisplayOptionHideForm()); - } -// System.out.println("Report ID B4 Id in reportHandler " -// + ( request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null?((ReportRuntime)request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)).getReportID():"Not in session")); -// System.out.println("requestFlag " + requestFlag); - if(requestFlag==2 && !rDisplayContent) { - //System.out.println("In Request Flag "); - request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); - rr.setParamValues(request, false, false); + if (rDisplayContent) { + rr.setParamValues(request, false, true); + request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); + } + if (inSchedule) { + rr.setParamValues(request, false, false); + } + if (requestFlag == 7) { // DASH + rr.setDisplayFlags(true, true); + } else { + rr.setDisplayFlags(request.getParameter(AppConstants.RI_SOURCE_PAGE) == null, + rDisplayContent || rr.isDisplayOptionHideForm()); + } + + if (requestFlag == 2 && !rDisplayContent) { + // System.out.println("In Request Flag "); + request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); + rr.setParamValues(request, false, false); + } else if (requestFlag == 1) { + rr.setParamValues(request, false, refresh); + request.setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); + } - else if(requestFlag==1) { - rr.setParamValues(request, false,refresh); - request.setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); - - } -// System.out.println("Report ID B4 Id in reportHandler " -// + ( request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null?((ReportRuntime)request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)).getReportID():"Not in session")); - //request.setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); - } // if - - return rr; - } // loadReportRuntime - - private boolean isReportAddedAsDashboard(HttpServletRequest request, String dashboardId, String reportId)throws RaptorException { - if(nvl(dashboardId).length() <= 0) - return false; - String reportXML = ReportLoader.loadCustomReportXML(dashboardId); - ReportDefinition rdef = createReportDefinition(request, dashboardId, reportXML); - List l = rdef.getDashBoardReports().getReportsList(); + + } // if + + return rr; + } // loadReportRuntime + + private boolean isReportAddedAsDashboard(HttpServletRequest request, String dashboardId, String reportId) + throws RaptorException { + if (nvl(dashboardId).length() <= 0) + return false; + String reportXML = ReportLoader.loadCustomReportXML(dashboardId); + ReportDefinition rdef = createReportDefinition(request, dashboardId, reportXML); + List l = rdef.getDashBoardReports().getReportsList(); for (Iterator iterator = l.iterator(); iterator.hasNext();) { - Reports reports = (Reports) iterator.next(); - if(reports.getReportId().equals(reportId)) return true; - - } - return false; - } - - public ReportDefinition createReportDefinition(HttpServletRequest request, - String reportID, String reportXML) throws RaptorException { - ReportDefinition rdef = ReportDefinition.unmarshal(reportXML, reportID, request); - rdef.generateWizardSequence(request); - return rdef; - } // createReportDefinition - - public ReportDefinition loadReportDefinition(HttpServletRequest request, String reportID) - throws RaptorException { - //System.out.println("********* ReportID " + reportID); - boolean isReportIDBlank = (reportID.length() == 0 || reportID.equals("-1")); - String actionKey = nvl(request.getParameter(AppConstants.RI_ACTION), ""); - String wizardActionKey = nvl(request.getParameter(AppConstants.RI_WIZARD_ACTION), ""); - ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( - AppConstants.SI_REPORT_DEFINITION); - if(nvl(actionKey).equals("report.edit")) - rdef = null; - //ReportDefinition rdef = null; - if (rdef != null) - if (isReportIDBlank || reportID.equals(rdef.getReportID())) { - // The report definition is already in the session - return rdef; - } - - ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute( - AppConstants.SI_REPORT_RUNTIME); - if (rr != null) - if (isReportIDBlank || reportID.equals(rr.getReportID())) { - // The report runtime is in the session => create report - // definition from it - rdef = new ReportDefinition(rr, request); - String userID = AppUtils.getUserID(request); - rdef.generateWizardSequence(request); - // rdef.checkUserWriteAccess(userID); - - request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef); - return rdef; - } // if - - // Report is NOT in the session => load from the database - if (isReportIDBlank) - rdef = ReportDefinition.createBlank(request); - else { - String reportXML = ReportLoader.loadCustomReportXML(reportID); - logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Report [" + reportID + "]: XML loaded")); - rdef = createReportDefinition(request, reportID, reportXML); - } // else - - request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef); - return rdef; - } // loadReportDefinition - - public void setSheetName( String sheet_name ) { - SHEET_NAME = sheet_name; + Reports reports = (Reports) iterator.next(); + if (reports.getReportId().equals(reportId)) + return true; + + } + return false; } - + + public ReportDefinition createReportDefinition(HttpServletRequest request, + String reportID, String reportXML) throws RaptorException { + ReportDefinition rdef = ReportDefinition.unmarshal(reportXML, reportID, request); + rdef.generateWizardSequence(request); + return rdef; + } // createReportDefinition + + public ReportDefinition loadReportDefinition(HttpServletRequest request, String reportID) + throws RaptorException { + boolean isReportIDBlank = (reportID.length() == 0 || reportID.equals("-1")); + String actionKey = nvl(request.getParameter(AppConstants.RI_ACTION), ""); + String wizardActionKey = nvl(request.getParameter(AppConstants.RI_WIZARD_ACTION), ""); + ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute( + AppConstants.SI_REPORT_DEFINITION); + if (nvl(actionKey).equals("report.edit")) + rdef = null; + if (rdef != null) + if (isReportIDBlank || reportID.equals(rdef.getReportID())) { + return rdef; + } + + ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute( + AppConstants.SI_REPORT_RUNTIME); + if (rr != null) + if (isReportIDBlank || reportID.equals(rr.getReportID())) { + + rdef = new ReportDefinition(rr, request); + String userID = AppUtils.getUserID(request); + rdef.generateWizardSequence(request); + + request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef); + return rdef; + } // if + + if (isReportIDBlank) + rdef = ReportDefinition.createBlank(request); + else { + String reportXML = ReportLoader.loadCustomReportXML(reportID); + logger.debug(EELFLoggerDelegate.debugLogger, + ("[DEBUG MESSAGE FROM RAPTOR] Report [" + reportID + "]: XML loaded")); + rdef = createReportDefinition(request, reportID, reportXML); + } // else + + request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef); + return rdef; + } // loadReportDefinition + + public void setSheetName(String sheet_name) { + sheetName = sheet_name; + } + public String getSheetName() { - return SHEET_NAME; + return sheetName; } - /** - * Writes spreadsheet data in a Writer. - * (YK: in future it may evolve in a full-featured API for streaming data in Excel) - */ - public static class SpreadsheetWriter { - private final Writer _out; - private int _rownum; - - public SpreadsheetWriter(Writer out){ - _out = out; - } - - public void beginSheet() throws IOException { - _out.write("<?xml version=\"1.0\" encoding=\""+XML_ENCODING+"\"?>" + - "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">" ); - _out.write("<sheetData>\n"); - } - - public void endSheet() throws IOException { - _out.write("</sheetData>"); - _out.write("</worksheet>"); - } - - /** - * Insert a new row - * - * @param rownum 0-based row number - */ - public void insertRow(int rownum) throws IOException { - _out.write("<row r=\""+(rownum+1)+"\">\n"); - this._rownum = rownum; - } - - /** - * Insert row end marker - */ - public void endRow() throws IOException { - _out.write("</row>\n"); - } - - public void createCell(int columnIndex, String value, int styleIndex) throws IOException { - String ref = new CellReference(_rownum, columnIndex).formatAsString(); - _out.write("<c r=\""+ref+"\" t=\"inlineStr\""); - if(styleIndex != -1) _out.write(" s=\""+styleIndex+"\""); - _out.write(">"); - _out.write("<is><t>"+value+"</t></is>"); - _out.write("</c>"); - } - - public void createCell(int columnIndex, String value) throws IOException { - createCell(columnIndex, value, -1); - } - - public void createCell(int columnIndex, double value, int styleIndex) throws IOException { - String ref = new CellReference(_rownum, columnIndex).formatAsString(); - _out.write("<c r=\""+ref+"\" t=\"n\""); - if(styleIndex != -1) _out.write(" s=\""+styleIndex+"\""); - _out.write(">"); - _out.write("<v>"+value+"</v>"); - _out.write("</c>"); - } - - public void createCell(int columnIndex, double value) throws IOException { - createCell(columnIndex, value, -1); - } - - public void createCell(int columnIndex, Calendar value, int styleIndex) throws IOException { - createCell(columnIndex, DateUtil.getExcelDate(value, false), styleIndex); - } - } - - public int getColumnCountForDownloadFile(ReportRuntime rr, ReportData rd) { - int columnCount = 0; - for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { - ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext(); - for(chr.resetNext(); chr.hasNext(); ) { - ColumnHeader ch = chr.getNext(); - if(ch.isVisible()) { - columnCount++; - } - } - } - if(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) { - for (rd.reportRowHeaderCols.resetNext(); rd.reportRowHeaderCols.hasNext();) { - RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); - if(rhc.isVisible()) { - columnCount++; - } - } - } - return columnCount; - } - - private Map<String, XSSFCellStyle> loadXSSFStyles(ReportRuntime rr, XSSFWorkbook wb, Map<String, XSSFCellStyle> loadedStyles) { - XSSFCellStyle styleDefault = wb.createCellStyle(); - //System.out.println("Load Styles"); - // Style default will be normal with no background - XSSFFont fontDefault = wb.createFont(); - - XSSFDataFormat xssffmt = wb.createDataFormat(); - // The default will be plain . - fontDefault.setColor((short) HSSFFont.COLOR_NORMAL); - fontDefault.setFontHeight((short) (font_size / 0.05)); - fontDefault.setFontName("Tahoma"); - - styleDefault.setAlignment(HorizontalAlignment.CENTER); - styleDefault.setBorderBottom(BorderStyle.THIN); - styleDefault.setBorderTop(BorderStyle.THIN); - styleDefault.setBorderLeft(BorderStyle.THIN); - styleDefault.setBorderRight(BorderStyle.THIN); - // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); - styleDefault.setFillPattern(FillPatternType.NO_FILL); - styleDefault.setFont(fontDefault); + /** + * Writes spreadsheet data in a Writer. (YK: in future it may evolve in a full-featured API for + * streaming data in Excel) + */ + public static class SpreadsheetWriter { + private final Writer _out; + private int _rownum; + + public SpreadsheetWriter(Writer out) { + _out = out; + } + + public void beginSheet() throws IOException { + _out.write("<?xml version=\"1.0\" encoding=\"" + XML_ENCODING + "\"?>" + + "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">"); + _out.write("<sheetData>\n"); + } + + public void endSheet() throws IOException { + _out.write("</sheetData>"); + _out.write("</worksheet>"); + } + + /** + * Insert a new row + * + * @param rownum 0-based row number + */ + public void insertRow(int rownum) throws IOException { + _out.write("<row r=\"" + (rownum + 1) + "\">\n"); + this._rownum = rownum; + } + + /** + * Insert row end marker + */ + public void endRow() throws IOException { + _out.write("</row>\n"); + } + + public void createCell(int columnIndex, String value, int styleIndex) throws IOException { + String ref = new CellReference(_rownum, columnIndex).formatAsString(); + _out.write("<c r=\"" + ref + "\" t=\"inlineStr\""); + if (styleIndex != -1) + _out.write(" s=\"" + styleIndex + "\""); + _out.write(">"); + _out.write("<is><t>" + value + "</t></is>"); + _out.write("</c>"); + } + + public void createCell(int columnIndex, String value) throws IOException { + createCell(columnIndex, value, -1); + } + + public void createCell(int columnIndex, double value, int styleIndex) throws IOException { + String ref = new CellReference(_rownum, columnIndex).formatAsString(); + _out.write("<c r=\"" + ref + "\" t=\"n\""); + if (styleIndex != -1) + _out.write(" s=\"" + styleIndex + "\""); + _out.write(">"); + _out.write("<v>" + value + "</v>"); + _out.write("</c>"); + } + + public void createCell(int columnIndex, double value) throws IOException { + createCell(columnIndex, value, -1); + } + + public void createCell(int columnIndex, Calendar value, int styleIndex) throws IOException { + createCell(columnIndex, DateUtil.getExcelDate(value, false), styleIndex); + } + } + + public int getColumnCountForDownloadFile(ReportRuntime rr, ReportData rd) { + int columnCount = 0; + for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { + ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext(); + for (chr.resetNext(); chr.hasNext();) { + ColumnHeader ch = chr.getNext(); + if (ch.isVisible()) { + columnCount++; + } + } + } + if (rr.getReportType().equals(AppConstants.RT_CROSSTAB)) { + for (rd.reportRowHeaderCols.resetNext(); rd.reportRowHeaderCols.hasNext();) { + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + if (rhc.isVisible()) { + columnCount++; + } + } + } + return columnCount; + } + + private Map<String, XSSFCellStyle> loadXSSFStyles(ReportRuntime rr, XSSFWorkbook wb, + Map<String, XSSFCellStyle> loadedStyles) { + XSSFCellStyle styleDefault = wb.createCellStyle(); + + XSSFFont fontDefault = wb.createFont(); + + XSSFDataFormat xssffmt = wb.createDataFormat(); + fontDefault.setColor((short) HSSFFont.COLOR_NORMAL); + fontDefault.setFontHeight((short) (FONT_SIZE / 0.05)); + fontDefault.setFontName(FONT_TAHOMA); + + styleDefault.setAlignment(HorizontalAlignment.CENTER); + styleDefault.setBorderBottom(BorderStyle.THIN); + styleDefault.setBorderTop(BorderStyle.THIN); + styleDefault.setBorderLeft(BorderStyle.THIN); + styleDefault.setBorderRight(BorderStyle.THIN); + // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); + styleDefault.setFillPattern(fillPattern.NO_FILL); + styleDefault.setFont(fontDefault); ArrayList semColumnList = new ArrayList(); List dsList = rr.getDataSourceList().getDataSource(); for (Iterator iter = dsList.iterator(); iter.hasNext();) { @@ -4151,26 +3609,24 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { for (Iterator iterator = dcList.iterator(); iterator.hasNext();) { DataColumnType element1 = (DataColumnType) iterator.next(); semColumnList.add(element1.getSemaphoreId()); - + } } - SemaphoreList semList = rr.getSemaphoreList(); - Map<String, XSSFCellStyle> hashMapStyles = new HashMap<>();; - Map<String, XSSFFont> hashMapFonts = new HashMap<>(); - hashMapFonts.put("default", fontDefault); - hashMapStyles.put("default", styleDefault); - XSSFCellStyle styleLeftDefault = wb.createCellStyle(); - styleLeftDefault.setAlignment(HorizontalAlignment.LEFT); - styleLeftDefault.setBorderBottom(BorderStyle.THIN); - styleLeftDefault.setBorderTop(BorderStyle.THIN); - styleLeftDefault.setBorderLeft(BorderStyle.THIN); - styleLeftDefault.setBorderRight(BorderStyle.THIN); - // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); - styleLeftDefault.setFillPattern(FillPatternType.NO_FILL); - styleLeftDefault.setFont(fontDefault); - hashMapStyles.put("defaultLeft", styleLeftDefault); - - + SemaphoreList semList = rr.getSemaphoreList(); + Map<String, XSSFCellStyle> hashMapStyles = new HashMap<>();; + Map<String, XSSFFont> hashMapFonts = new HashMap<>(); + hashMapFonts.put(DEFAULT, fontDefault); + hashMapStyles.put(DEFAULT, styleDefault); + XSSFCellStyle styleLeftDefault = wb.createCellStyle(); + styleLeftDefault.setAlignment(HorizontalAlignment.LEFT); + styleLeftDefault.setBorderBottom(BorderStyle.THIN); + styleLeftDefault.setBorderTop(BorderStyle.THIN); + styleLeftDefault.setBorderLeft(BorderStyle.THIN); + styleLeftDefault.setBorderRight(BorderStyle.THIN); + styleLeftDefault.setFillPattern(fillPattern.NO_FILL); + styleLeftDefault.setFont(fontDefault); + hashMapStyles.put("defaultLeft", styleLeftDefault); + XSSFCellStyle styleDate = wb.createCellStyle(); styleDate.setAlignment(HorizontalAlignment.RIGHT); styleDate.setDataFormat(xssffmt.getFormat("d-mmm-yy")); @@ -4179,275 +3635,168 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { styleDate.setBorderTop(BorderStyle.THIN); styleDate.setBorderLeft(BorderStyle.THIN); styleDate.setBorderRight(BorderStyle.THIN); - // styleDefault.setFillForegroundColor(HSSFColor.YELLOW.index); - styleDate.setFillPattern(FillPatternType.NO_FILL); + styleDate.setFillPattern(fillPattern.NO_FILL); styleDate.setFont(fontDefault); hashMapStyles.put("date", styleDate); - - XSSFCellStyle rowHeaderStyle = wb.createCellStyle(); - XSSFFont headerFont = wb.createFont(); - headerFont.setBold(true); - rowHeaderStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - rowHeaderStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - rowHeaderStyle.setFont(headerFont); - rowHeaderStyle.setBorderTop(BorderStyle.THIN); - rowHeaderStyle.setBorderLeft(BorderStyle.THIN); - rowHeaderStyle.setBorderBottom(BorderStyle.THIN); - rowHeaderStyle.setBorderRight(BorderStyle.THIN); - hashMapStyles.put("header", rowHeaderStyle); - - - XSSFCellStyle boldStyle = wb.createCellStyle(); - //headerFont = wb.createFont(); - //headerFont.setBold(true); - boldStyle.setFont(headerFont); - boldStyle.setBorderTop(BorderStyle.THIN); - boldStyle.setBorderLeft(BorderStyle.THIN); - boldStyle.setBorderBottom(BorderStyle.THIN); - boldStyle.setBorderRight(BorderStyle.THIN); - boldStyle.setAlignment(HorizontalAlignment.CENTER); - hashMapStyles.put("title", boldStyle); - - XSSFCellStyle cellStyle = null; - if (semList == null || semList.getSemaphore() == null) { - hashMapStyles.put("default", styleDefault); - } /*else { - for (Iterator iter = semList.getSemaphore().iterator(); iter.hasNext();) { - SemaphoreType sem = (SemaphoreType) iter.next(); - if(!semColumnList.contains(sem.getSemaphoreId())) continue; - //System.out.println("SemphoreId ----> " + sem.getSemaphoreId()); - FormatList fList = sem.getFormatList(); - List formatList = fList.getFormat(); - for (Iterator fIter = formatList.iterator(); fIter.hasNext();) { - FormatType fmt = (FormatType) fIter.next(); - if(fmt!=null){ - //if (fmt.getLessThanValue().length() > 0) { - cellStyle = wb.createCellStyle(); - XSSFFont cellFont = wb.createFont(); - //System.out.println("Format Id " + fmt.getFormatId()); - if (nvl(fmt.getBgColor()).length() > 0) { -// System.out.println("Load Styles " + -// fmt.getFormatId() -// + " " +fmt.getBgColor() + " " + -// ExcelColorDef.getExcelColor(fmt.getBgColor())); - cellStyle.setFillForegroundColor(ExcelColorDef.getExcelColor(fmt - .getBgColor())); - cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND ); - } - if (nvl(fmt.getFontColor()).length() > 0) { - cellFont.setColor(ExcelColorDef.getExcelColor(fmt.getFontColor())); - } else - cellFont.setColor((short) HSSFFont.COLOR_NORMAL); - if (fmt.isBold()) - cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); - if (fmt.isItalic()) - cellFont.setItalic(true); - if (fmt.isUnderline()) - cellFont.setUnderline(HSSFFont.U_SINGLE); - if(nvl(fmt.getFontFace()).length()>0) - cellFont.setFontName(fmt.getFontFace()); - else - cellFont.setFontName("Tahoma"); - //cellFont.setFontHeight((short) (10 / 0.05)); - - if(nvl(fmt.getFontSize()).length()>0) { - try { - cellFont.setFontHeight((short) (Integer.parseInt(fmt.getFontSize()) / 0.05)); - } catch(NumberFormatException e){ - cellFont.setFontHeight((short) (font_size / 0.05)); - } - } - else - cellFont.setFontHeight((short) (font_size / 0.05)); - cellStyle.setFont(cellFont); - cellStyle.setAlignment(HorizontalAlignment.CENTER); - cellStyle.setBorderBottom(BorderStyle.THIN); - cellStyle.setBorderTop(BorderStyle.THIN); - cellStyle.setBorderLeft(BorderStyle.THIN); - cellStyle.setBorderRight(BorderStyle.THIN); - hashMapStyles.put(fmt.getFormatId(), cellStyle); - } else { - //hashMapStyles.put(fmt.getFormatId(), styleDefault); - hashMapStyles.put("default", styleDefault); - } - } - - } - }*/ - loadedStyles.putAll(hashMapStyles); - return loadedStyles; - } - - private void generate(XSSFWorkbook wb, SpreadsheetWriter sw, Map<String, XSSFCellStyle> styles, ReportData rd, String sql_whole, ReportRuntime rr, HttpServletRequest request, XSSFSheet sheet) throws Exception { + + XSSFCellStyle rowHeaderStyle = wb.createCellStyle(); + XSSFFont headerFont = wb.createFont(); + headerFont.setBold(true); + rowHeaderStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); + rowHeaderStyle.setFillPattern(fillPattern.SOLID_FOREGROUND); + rowHeaderStyle.setFont(headerFont); + rowHeaderStyle.setBorderTop(BorderStyle.THIN); + rowHeaderStyle.setBorderLeft(BorderStyle.THIN); + rowHeaderStyle.setBorderBottom(BorderStyle.THIN); + rowHeaderStyle.setBorderRight(BorderStyle.THIN); + hashMapStyles.put("header", rowHeaderStyle); + + XSSFCellStyle boldStyle = wb.createCellStyle(); + + boldStyle.setFont(headerFont); + boldStyle.setBorderTop(BorderStyle.THIN); + boldStyle.setBorderLeft(BorderStyle.THIN); + boldStyle.setBorderBottom(BorderStyle.THIN); + boldStyle.setBorderRight(BorderStyle.THIN); + boldStyle.setAlignment(HorizontalAlignment.CENTER); + hashMapStyles.put("title", boldStyle); + + XSSFCellStyle cellStyle = null; + if (semList == null || semList.getSemaphore() == null) { + hashMapStyles.put(DEFAULT, styleDefault); + } + loadedStyles.putAll(hashMapStyles); + return loadedStyles; + } + + private void generate(XSSFWorkbook wb, SpreadsheetWriter sw, Map<String, XSSFCellStyle> styles, ReportData rd, + String sql_whole, ReportRuntime rr, HttpServletRequest request, XSSFSheet sheet) throws Exception { HtmlStripper strip = new HtmlStripper(); XSSFCellStyle styleCell = null; XSSFCellStyle styleRowCell = null; XSSFCellStyle styleDefaultCell = null; - - styleDefaultCell = (XSSFCellStyle) styles.get("default"); - - + + styleDefaultCell = (XSSFCellStyle) styles.get(DEFAULT); + // to check performance - int mb = 1024*1024; - Runtime runtime = Runtime.getRuntime(); - + int mb = 1024 * 1024; + Runtime runtime = Runtime.getRuntime(); + int rowNum = 0; - /*short s1 = 0, s2 = (short) (col-1); - rowNum += 1; - sw.insertRow(rowNum); - int styleIndex = styles.get("header").getIndex(); - sw.createCell(rowNum, reportTitle, styleIndex); - - //header.setCenter(HSSFHeader.font("Tahoma", "")+ HSSFHeader.fontSize((short) 9)+reportTitle+"\n"+((Globals.getShowDescrAtRuntime() && nvl(reportDescr).length() > 0)?reportDescr:"")); - - // Report Description - if (Globals.getShowDescrAtRuntime() && nvl(reportDescr).length() > 0) { - sw.createCell(rowNum, reportDescr, styleIndex); - } - rowNum += 2; - sw.insertRow(rowNum);*/ - int cellNum = 0; - - + int cellNum = 0; + ColumnHeaderRow chr = null; java.util.HashMap dataTypeMap = new java.util.HashMap(); boolean firstPass = true; - int columnRows = rr.getVisibleColumnCount() ; - - HttpSession session = request.getSession(); - String drilldown_index = (String) session.getAttribute("drilldown_index"); - int index = 0; - try { - index = Integer.parseInt(drilldown_index); - } catch (NumberFormatException ex) { - index = 0; - } - String header = (String) session.getAttribute("TITLE_"+index); - String subtitle = (String) session.getAttribute("SUBTITLE_"+index); - if(nvl(header).length()>0) { - header = Utils.replaceInString(header, "<BR/>", " "); - header = Utils.replaceInString(header, "<br/>", " "); - header = Utils.replaceInString(header, "<br>", " "); - header = strip.stripHtml(nvl(header).trim()); - subtitle = Utils.replaceInString(subtitle, "<BR/>", " "); - subtitle = Utils.replaceInString(subtitle, "<br/>", " "); - subtitle = Utils.replaceInString(subtitle, "<br>", " "); - subtitle = strip.stripHtml(nvl(subtitle).trim()); - //XSSFRow row = sheet.createRow(rowNum); - sw.insertRow(rowNum); - cellNum = 0; - //XSSFCell cell = row.createCell(cellNum); - sw.createCell(cellNum, Utils.excelEncode(header)); - for (int i = 1; i <= columnRows; i++) { - sw.createCell(cellNum+i, ""); - } - sheet.addMergedRegion(new CellRangeAddress(rowNum+1, rowNum+1, cellNum+1, columnRows)); - sw.endRow(); -/* cell.setCellValue(Utils.excelEncode(header)); - cell.setCellStyle(styles.get("title")); -*/ //sw.createCell(cellNum,Utils.excelEncode(header), styles.get("title").getIndex()); -// sheet.addMergedRegion(new CellRangeAddress(rowNum+1, rowNum+1, cellNum+1, columnRows)); - rowNum += 1; -// row = sheet.createRow(rowNum); - sw.insertRow(rowNum); - cellNum = 0; -/* cell = row.createCell(cellNum); - cell.setCellValue(Utils.excelEncode(subtitle)); - cell.setCellStyle(styles.get("title")); -*/ //sw.createCell(cellNum,Utils.excelEncode(header), styles.get("title").getIndex()); - - sheet.addMergedRegion(new CellRangeAddress(rowNum+1, rowNum+1, cellNum+1, columnRows)); - sw.createCell(cellNum, Utils.excelEncode(subtitle)); - sw.endRow(); - //sheet.addMergedRegion(new CellRangeAddress(rowNum+1, rowNum+1, cellNum+1, columnRows)); -/* sw.insertRow(rowNum); - cellNum = 0; - sw.createCell(cellNum,Utils.excelEncode(subtitle), styles.get("title").getIndex()); - sheet.addMergedRegion(new CellRangeAddress(rowNum+1, rowNum+1, cellNum+1, columnRows)); - -*/ rowNum += 1; - } - cellNum = 0; - String title = ""; - for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { - sw.insertRow(rowNum); - cellNum = -1; - /*if(rd.reportTotalRowHeaderCols!=null) { - cellNum +=1; - sw.createCell(cellNum, "No.", styles.get("header").getIndex()); - - //row.getCell((short) cellNum).setCellStyle(styleDataHeader); - }*/ - chr = rd.reportColumnHeaderRows.getNext(); - - if(nvl(sql_whole).length() <= 0 || (!rr.getReportType().equals(AppConstants.RT_LINEAR))) { - - for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { - cellNum += 1; - RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); - title = rhc.getColumnTitle(); - title = Utils.replaceInString(title,"_nl_", " \n"); - - sw.createCell(cellNum,Utils.excelEncode(title), styles.get("header").getIndex()); - //sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum+columnRows, (short) cellNum, (short) (cellNum))); - - //System.out.println(" **************** Row Header Title " + rhc.getColumnTitle() + " " + cellNum + " " ); - //System.out.println(cellNum + " " + cellWidth.size()); - } // for - - } - - firstPass = false; - for (chr.resetNext(); chr.hasNext();) { - ColumnHeader ch = chr.getNext(); - if(ch.isVisible()) { - cellNum += 1; - int colSpan = ch.getColSpan()-1; - title = ch.getColumnTitle(); - title = Utils.replaceInString(title,"_nl_", " \n"); - sw.createCell(cellNum, Utils.excelEncode(title), styles.get("header").getIndex()); - if(colSpan > 0) { - for ( int k = 1; k <= colSpan; k++ ) { - sw.createCell(cellNum+k, "", styles.get("header").getIndex()); - } - //sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, (short) cellNum, (short) (cellNum+colSpan))); - } - if(colSpan > 0) - cellNum += colSpan; - } - } // for - rowNum += 1; - } // for - - sw.endRow(); - //All the possible combinations of date format + int columnRows = rr.getVisibleColumnCount(); + + HttpSession session = request.getSession(); + String drilldown_index = (String) session.getAttribute("drilldown_index"); + int index = 0; + try { + index = Integer.parseInt(drilldown_index); + } catch (NumberFormatException ex) { + index = 0; + } + String header = (String) session.getAttribute("TITLE_" + index); + String subtitle = (String) session.getAttribute("SUBTITLE_" + index); + if (nvl(header).length() > 0) { + header = Utils.replaceInString(header, "<BR/>", " "); + header = Utils.replaceInString(header, "<br/>", " "); + header = Utils.replaceInString(header, "<br>", " "); + header = strip.stripHtml(nvl(header).trim()); + subtitle = Utils.replaceInString(subtitle, "<BR/>", " "); + subtitle = Utils.replaceInString(subtitle, "<br/>", " "); + subtitle = Utils.replaceInString(subtitle, "<br>", " "); + subtitle = strip.stripHtml(nvl(subtitle).trim()); + sw.insertRow(rowNum); + cellNum = 0; + sw.createCell(cellNum, Utils.excelEncode(header)); + for (int i = 1; i <= columnRows; i++) { + sw.createCell(cellNum + i, ""); + } + sheet.addMergedRegion(new CellRangeAddress(rowNum + 1, rowNum + 1, cellNum + 1, columnRows)); + sw.endRow(); + rowNum += 1; + sw.insertRow(rowNum); + cellNum = 0; + + sheet.addMergedRegion(new CellRangeAddress(rowNum + 1, rowNum + 1, cellNum + 1, columnRows)); + sw.createCell(cellNum, Utils.excelEncode(subtitle)); + sw.endRow(); + rowNum += 1; + } + cellNum = 0; + String title = ""; + for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { + sw.insertRow(rowNum); + cellNum = -1; + + chr = rd.reportColumnHeaderRows.getNext(); + + if (nvl(sql_whole).length() <= 0 || (!rr.getReportType().equals(AppConstants.RT_LINEAR))) { + + for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { + cellNum += 1; + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + title = rhc.getColumnTitle(); + title = Utils.replaceInString(title, "_nl_", " \n"); + + sw.createCell(cellNum, Utils.excelEncode(title), styles.get("header").getIndex()); + } // for + + } + + firstPass = false; + for (chr.resetNext(); chr.hasNext();) { + ColumnHeader ch = chr.getNext(); + if (ch.isVisible()) { + cellNum += 1; + int colSpan = ch.getColSpan() - 1; + title = ch.getColumnTitle(); + title = Utils.replaceInString(title, "_nl_", " \n"); + sw.createCell(cellNum, Utils.excelEncode(title), styles.get("header").getIndex()); + if (colSpan > 0) { + for (int k = 1; k <= colSpan; k++) { + sw.createCell(cellNum + k, "", styles.get("header").getIndex()); + } + } + if (colSpan > 0) + cellNum += colSpan; + } + } // for + rowNum += 1; + } // for + + sw.endRow(); + // All the possible combinations of date format CreationHelper createHelper = wb.getCreationHelper(); HashMap<String, Short> dateFormatMap = new HashMap<>(); - SimpleDateFormat MMDDYYYYFormat = new SimpleDateFormat("MM/dd/yyyy"); - SimpleDateFormat YYYYMMDDFormat = new SimpleDateFormat("yyyy/MM/dd"); - SimpleDateFormat MONYYYYFormat = new SimpleDateFormat("MMM yyyy"); - SimpleDateFormat MMYYYYFormat = new SimpleDateFormat("MM/yyyy"); + SimpleDateFormat MMDDYYYYFormat = new SimpleDateFormat("MM/dd/yyyy"); + 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 YYYYMMDDDASHFormat = new SimpleDateFormat("yyyy-MM-dd"); - SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - SimpleDateFormat DDMONYYYYFormat = new SimpleDateFormat("dd-MMM-yyyy"); - SimpleDateFormat MONTHYYYYFormat = new SimpleDateFormat("MMMMM, yyyy"); - 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 DDMONYYHHMMFormat = new SimpleDateFormat("dd-MMM-yy 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 MMDDYYYYHHMMZFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm z"); - SimpleDateFormat MMMMMDDYYYYHHMMSS = new SimpleDateFormat("MMMMM-dd-yyyy HH:mm:ss"); - + SimpleDateFormat YYYYMMDDDASHFormat = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + SimpleDateFormat DDMONYYYYFormat = new SimpleDateFormat("dd-MMM-yyyy"); + SimpleDateFormat MONTHYYYYFormat = new SimpleDateFormat("MMMMM, yyyy"); + 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 DDMONYYHHMMFormat = new SimpleDateFormat("dd-MMM-yy 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 MMDDYYYYHHMMZFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm z"); + SimpleDateFormat MMMMMDDYYYYHHMMSS = new SimpleDateFormat("MMMMM-dd-yyyy HH:mm:ss"); + short dateFormat = createHelper.createDataFormat().getFormat("MM/dd/yyyy"); - dateFormatMap.put("MMDDYYYY", new Short(dateFormat)); + dateFormatMap.put("MMDDYYYY", new Short(dateFormat)); dateFormat = createHelper.createDataFormat().getFormat("yyyy/MM/dd"); dateFormatMap.put("YYYYMMDD", new Short(dateFormat)); dateFormat = createHelper.createDataFormat().getFormat("MMM yyyy"); @@ -4490,1813 +3839,1693 @@ public class ReportHandler extends org.onap.portalsdk.analytics.RaptorObject { dateFormatMap.put("MMDDYYYYHHMMZ", new Short(dateFormat)); dateFormat = createHelper.createDataFormat().getFormat("MMMMM-dd-yyyy HH:mm:ss"); dateFormatMap.put("MMMMMDDYYYYHHMMSS", new Short(dateFormat)); - + ResultSetMetaData rsmd = null; + if (nvl(sql_whole).length() > 0 && (rr.getReportType().equals(AppConstants.RT_LINEAR) + || rr.getReportType().equals(AppConstants.RT_HIVE))) { + try (Connection conn = ConnectionUtils.getConnection(rr.getDbInfo()); + Statement st = conn.createStatement(); + ResultSet rs = st.executeQuery(sql_whole)) { + + logger.debug(EELFLoggerDelegate.debugLogger, ("************* Map Whole SQL *************")); + logger.debug(EELFLoggerDelegate.debugLogger, (sql_whole)); + logger.debug(EELFLoggerDelegate.debugLogger, ("*****************************************")); + rsmd = rs.getMetaData(); + int numberOfColumns = rsmd.getColumnCount(); + HashMap colHash = new HashMap(); + DataRow dr = null; + int j = 0; + int rowCount = 0; + while (rs.next()) { + + rowCount++; + + if (rowCount % 10000 == 0) { + // to check performance + logger.debug(EELFLoggerDelegate.debugLogger, + ("Performance check for " + rowCount + " starting**************")); + logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####")); + logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:" + + (runtime.totalMemory() - runtime.freeMemory()) / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:" + + runtime.freeMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb)); + logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb)); + System.out.println(rowCount + "TH ROW****##### END #####"); + + // + } + sw.insertRow(rowNum); + cellNum = -1; + colHash = new HashMap(); + for (int i = 1; i <= numberOfColumns; i++) { + colHash.put(rsmd.getColumnLabel(i).toUpperCase(), strip.stripHtml(rs.getString(i))); + } + rd.reportDataRows.resetNext(); + dr = rd.reportDataRows.getNext(); + styleRowCell = null; + if (dr.isRowFormat() && styles != null) + styleRowCell = (XSSFCellStyle) styles.get(nvl(/* dr.getFormatId(), */"", DEFAULT)); + j = 0; + firstPass = false; + for (dr.resetNext(); dr.hasNext(); j++) { + styleCell = null; + DataValue dv = dr.getNext(); + HtmlFormatter htmlFormat = dv.getCellFormatter(); + + if (htmlFormat != null && dv.getFormatId() != null && styles != null) + styleCell = (XSSFCellStyle) styles.get(nvl(/* dv.getFormatId() */"", DEFAULT)); + String value = nvl((String) colHash.get(dv.getColId().toUpperCase())); + + boolean bold = false; + + if (dv.isVisible()) { + cellNum += 1; + String dataType = (String) (dataTypeMap.get(dv.getColId())); + if (dataType != null && dataType.equals("NUMBER")) { + int zInt = 0; + if (value.equals("null")) { + sw.createCell(cellNum, zInt, + styles.get(nvl(/* dv.getFormatId() */"", DEFAULT)).getIndex()); + } else { + + if ((value.indexOf(".")) != -1) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + + String tempDollar = dv.getDisplayValue().trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + if ((tempDollar.indexOf(",")) != -1) { + tempDollar = tempDollar.replaceAll(",", ""); + } + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if (styleRowCell != null) + sw.createCell(cellNum, tempDoubleDollar, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, tempDoubleDollar, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDoubleDollar, styles + .get(nvl(/* dv.getFormatId() */"", DEFAULT)).getIndex()); + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), + styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styles + .get(nvl(/* dv.getFormatId() */"", DEFAULT)).getIndex()); + } + } else { + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(value); + if (styleRowCell != null) + sw.createCell(cellNum, tempDouble, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, tempDouble, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDouble, styles + .get(nvl(/* dv.getFormatId() */"", DEFAULT)).getIndex()); + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, Utils.excelEncode(value), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, Utils.excelEncode(value), + styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(value), styles + .get(nvl(/* dv.getFormatId() */"", DEFAULT)).getIndex()); + } + + } + } else { + if (!(value.equals(""))) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + if ((tempInt.indexOf(",")) != -1) { + tempInt = tempInt.replaceAll(",", ""); + } + Long tempIntDollar = 0L; + try { + tempIntDollar = Long.parseLong(tempInt); + if (styleRowCell != null) + sw.createCell(cellNum, tempIntDollar, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, tempIntDollar, styleCell.getIndex()); + else + sw.createCell(cellNum, tempIntDollar, + styles.get(nvl(/* dv.getFormatId() */"", DEFAULT)) + .getIndex()); + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, tempInt, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, tempInt, styleCell.getIndex()); + else + sw.createCell(cellNum, tempInt, + styles.get(nvl(/* dv.getFormatId() */"", DEFAULT)) + .getIndex()); + } + } else { + // styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); + String tempStr = value.trim(); + if ((tempStr.indexOf(",")) != -1) { + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if (styleRowCell != null) + sw.createCell(cellNum, temp, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, temp, styleCell.getIndex()); + else + sw.createCell(cellNum, temp, + styles.get(nvl(/* dv.getFormatId() */"", DEFAULT)) + .getIndex()); + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), + styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempStr), + styles.get(nvl(/* dv.getFormatId() */"", DEFAULT)) + .getIndex()); + } + } + } + } + } + + } else if ((dataType != null && dataType.equals("DATE")) + || (dv.getDisplayName() != null + && dv.getDisplayName().toLowerCase().endsWith("date")) + || + (dv.getColId() != null && dv.getColId().toLowerCase().endsWith("date")) || + (dv.getColName() != null && dv.getColName().toLowerCase().endsWith("date"))) { + XSSFCellStyle cellStyle = null; + if (styleRowCell != null) { + cellStyle = styleRowCell; + } else if (styleCell != null) { + cellStyle = styleCell; + } else { + cellStyle = styles.get(nvl(/* dv.getFormatId() */"", "date")); + } + + Date date = null; + int flag = 0; + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMMSS")); + flag = 1; + } + if (date == null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMM")); + flag = 1; + } + if (date == null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYY")); + flag = 1; + } + if (date == null) + date = MMDDYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYYYHHMMSS")); + flag = 1; + } + if (date == null) + date = MMDDYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYYYHHMM")); + flag = 1; + } + if (date == null) + date = MMDDYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYYY")); + flag = 1; + } + if (date == null) + date = YYYYMMDDFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("YYYYMMDD")); + flag = 1; + } + if (date == null) + date = timestampFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("timestamp")); + flag = 1; + } + if (date == null) + date = MONYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MONYYYY")); + flag = 1; + } + if (date == null) + date = MMYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMYYYY")); + flag = 1; + } + if (date == null) + date = MMMMMDDYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMMMMDDYYYY")); + flag = 1; + } + if (date == null) + date = MONTHYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MONTHYYYY")); + flag = 1; + } + if (date == null) + date = YYYYMMDDHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("YYYYMMDDHHMMSS")); + flag = 1; + } + if (date == null) + date = YYYYMMDDDASHFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("YYYYMMDDDASH")); + flag = 1; + } + if (date == null) + date = YYYYMMDDHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("YYYYMMDDHHMM")); + flag = 1; + } + if (date == null) + date = DDMONYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("DDMONYYYYHHMMSS")); + flag = 1; + } + if (date == null) + date = DDMONYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("DDMONYYYYHHMM")); + flag = 1; + } + if (date == null) + date = DDMONYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("DDMONYYHHMM")); + flag = 1; + } + if (date == null) + date = DDMONYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("DDMONYYYY")); + flag = 1; + } + if (date == null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMMSS")); + flag = 1; + } + if (date == null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMM")); + flag = 1; + } + if (date == null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYY")); + flag = 1; + } + if (date == null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMM")); + flag = 1; + } + if (date == null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMMSS")); + flag = 1; + } + if (date == null) + date = MMDDYYYYHHMMZFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMDDYYYYHHMMZ")); + flag = 1; + } + if (date == null) + date = MMMMMDDYYYYHHMMSS.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + cellStyle.setDataFormat(dateFormatMap.get("MMMMMDDYYYYHHMMSS")); + flag = 1; + } + + if (date != null) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + sw.createCell(cellNum, cal, cellStyle.getIndex()); + } else { + sw.createCell(cellNum, Utils.excelEncode(value), cellStyle.getIndex()); + + } + + } else if ((dv.getDisplayTotal() != null && dv.getDisplayTotal().equals("SUM(")) + || (dv.getColName() != null && dv.getColName().indexOf("999") != -1)) { + int zInt = 0; + if (value.equals("null")) { + if (styleRowCell != null) + sw.createCell(cellNum, zInt, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, zInt, styleCell.getIndex()); + else + sw.createCell(cellNum, zInt, styleDefaultCell.getIndex()); + + } else { + + if ((value.indexOf(".")) != -1) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + + String tempDollar = value.trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + if ((tempDollar.indexOf(",")) != -1) { + tempDollar = tempDollar.replaceAll(",", ""); + } + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if (styleRowCell != null) + sw.createCell(cellNum, tempDoubleDollar, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, tempDoubleDollar, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDoubleDollar, styles + .get(nvl(/* dv.getFormatId() */"", DEFAULT)).getIndex()); + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), + styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styles + .get(nvl(/* dv.getFormatId() */"", DEFAULT)).getIndex()); + } + + } else { + String tempDoubleStr = value.trim(); + tempDoubleStr = tempDoubleStr.replaceAll(" ", "").substring(0); + if ((tempDoubleStr.indexOf(",")) != -1) { + tempDoubleStr = tempDoubleStr.replaceAll(",", ""); + } + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(tempDoubleStr); + if (styleRowCell != null) + sw.createCell(cellNum, tempDouble, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, tempDouble, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDouble, styles + .get(nvl(/* dv.getFormatId() */"", DEFAULT)).getIndex()); + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), + styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), styles + .get(nvl(/* dv.getFormatId() */"", DEFAULT)).getIndex()); + } + } + + } else { + if (!(value.equals(""))) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + if ((tempInt.indexOf(",")) != -1) { + tempInt = tempInt.replaceAll(",", ""); + } + + Long tempIntDollar = 0L; + + try { + tempIntDollar = Long.parseLong(tempInt); + if (styleRowCell != null) + sw.createCell(cellNum, tempIntDollar, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, tempIntDollar, styleCell.getIndex()); + else + sw.createCell(cellNum, tempIntDollar, + styles.get(nvl(/* dv.getFormatId() */"", DEFAULT)) + .getIndex()); + + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempInt), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempInt), + styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempInt), + styles.get(nvl(/* dv.getFormatId() */"", DEFAULT)) + .getIndex()); + } + } else { + String tempStr = value.trim(); + if ((tempStr.indexOf(",")) != -1) { + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if (styleRowCell != null) + sw.createCell(cellNum, temp, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, temp, styleCell.getIndex()); + else + sw.createCell(cellNum, temp, + styles.get(nvl(/* dv.getFormatId() */"", DEFAULT)) + .getIndex()); + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), + styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempStr), + styles.get(nvl(/* dv.getFormatId() */"", DEFAULT)) + .getIndex()); + + } + } + } else { + sw.createCell(cellNum, "", + styles.get(nvl(/* dv.getFormatId() */"", DEFAULT)).getIndex()); + } + } + } + + } else { + if (styleRowCell != null) + sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), + styleCell.getIndex()); + else { + if (nvl(value).startsWith(" ")) + sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), + styles.get(nvl(/* dv.getFormatId(), */"", "defaultLeft")).getIndex()); + else + sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), + styles.get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + + } - if(nvl(sql_whole).length() >0 && (rr.getReportType().equals(AppConstants.RT_LINEAR) || rr.getReportType().equals(AppConstants.RT_HIVE) )) { - try(Connection conn = ConnectionUtils.getConnection(rr.getDbInfo()); - Statement st = conn.createStatement(); - ResultSet rs = st.executeQuery(sql_whole)) { - - logger.debug(EELFLoggerDelegate.debugLogger, ("************* Map Whole SQL *************")); - logger.debug(EELFLoggerDelegate.debugLogger, (sql_whole)); - logger.debug(EELFLoggerDelegate.debugLogger, ("*****************************************")); - rsmd = rs.getMetaData(); - int numberOfColumns = rsmd.getColumnCount(); - HashMap colHash = new HashMap(); - DataRow dr = null; - int j = 0; - int rowCount = 0; - while(rs.next()) { - - rowCount++; - - if(rowCount%10000 == 0) { - // to check performance - logger.debug(EELFLoggerDelegate.debugLogger, ("Performance check for "+rowCount+" starting**************")); - logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####")); - logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:" - + (runtime.totalMemory() - runtime.freeMemory()) / mb)); - logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:" - + runtime.freeMemory() / mb)); - logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb)); - logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb)); - System.out.println(rowCount+"TH ROW****##### END #####"); - - // - } - sw.insertRow(rowNum); - cellNum = -1; - colHash = new HashMap(); - for (int i = 1; i <= numberOfColumns; i++) { - colHash.put(rsmd.getColumnLabel(i).toUpperCase(), strip.stripHtml(rs.getString(i))); - } - rd.reportDataRows.resetNext(); - dr = rd.reportDataRows.getNext(); - styleRowCell = null; - if (dr.isRowFormat() && styles != null) - styleRowCell = (XSSFCellStyle) styles.get(nvl(/*dr.getFormatId(),*/"","default")); - j = 0; - //if(rowCount%1000 == 0) wb.write(sos); - - /*if(rd.reportTotalRowHeaderCols!=null) { - //cellNum = -1; - //for (rd.reportRowHeaderCols.resetNext(); rd.reportRowHeaderCols.hasNext();) { - cellNum += 1; - //RowHeaderCol rhc = rd.reportRowHeaderCols.getRowHeaderCol(0); - //if (firstPass) - // rhc.resetNext(); - //RowHeader rh = rhc.getRowHeader(rowCount-1); - sw.createCell(cellNum, rowCount, styleDefaultCell.getIndex()); - - //} // for - }*/ - firstPass = false; - //cellNum = -1; - for (dr.resetNext(); dr.hasNext();j++) { - styleCell = null; - //for (chr.resetNext(); chr.hasNext();) { - //ColumnHeader ch = chr.getNext(); - DataValue dv = dr.getNext(); - HtmlFormatter htmlFormat = dv.getCellFormatter(); - - if (htmlFormat != null && dv.getFormatId() != null && styles != null) - styleCell = (XSSFCellStyle) styles.get(nvl(/*dv.getFormatId()*/"","default")); - String value = nvl((String)colHash.get(dv.getColId().toUpperCase())); - - boolean bold = false; - - if(dv.isVisible()) { - cellNum += 1; - //System.out.println("Stripping HTML 1"); - //cell.setCellValue(strip.stripHtml(dv.getDisplayValue())); - String dataType = (String) (dataTypeMap.get(dv.getColId())); - //System.out.println("Value " + value + " " + (( dataType !=null && dataType.equals("DATE")) || (dv.getColName()!=null && dv.getColName().toLowerCase().endsWith("date"))) ); - if (dataType!=null && dataType.equals("NUMBER")){ - //cellNumber = row.createCell((short) cellNum); - //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); - //cellNumber.setCellValue(dv.getDisplayValue()); - //cellCurrencyNumber = row.createCell((short) cellNum); - int zInt = 0; - if (value.equals("null")){ - sw.createCell(cellNum,zInt,styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - }else{ - - if ((value.indexOf("."))!= -1){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - - //if (dv.getDisplayValue().startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempDollar = dv.getDisplayValue().trim(); - tempDollar = tempDollar.replaceAll(" ", "").substring(0); - tempDollar = tempDollar.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempDollar); - //System.out.println("Before copy Value |" + tempDollar); - //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); - //System.out.println("After copy Value |" + tempDollar); - if ((tempDollar.indexOf(","))!= -1){ - tempDollar = tempDollar.replaceAll(",", ""); - } - //System.out.println("The final string 1 is "+tempDollar); - double tempDoubleDollar = 0.0; - try { - tempDoubleDollar = Double.parseDouble(tempDollar); - if(styleRowCell!=null) - sw.createCell(cellNum, tempDoubleDollar, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, tempDoubleDollar, styleCell.getIndex()); - else - sw.createCell(cellNum, tempDoubleDollar, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleCell.getIndex()); - else - sw.createCell(cellNum, Utils.excelEncode(tempDollar), styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - } - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - double tempDouble = 0.0; - try { - tempDouble = Double.parseDouble(value); - if(styleRowCell!=null) - sw.createCell(cellNum, tempDouble, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, tempDouble, styleCell.getIndex()); - else - sw.createCell(cellNum, tempDouble, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(value),styleRowCell.getIndex() ); - else if (styleCell!=null) - sw.createCell(cellNum, Utils.excelEncode(value), styleCell.getIndex()); - else - sw.createCell(cellNum, Utils.excelEncode(value), styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - } - - } - }else { - if (!(value.equals(""))){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - //if (dv.getDisplayValue().startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempInt = value.trim(); - tempInt = tempInt.replaceAll(" ", "").substring(0); - tempInt = tempInt.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempInt); - //System.out.println("Before copy Value |" + tempInt); - //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); - //System.out.println("After copy Value |" + tempInt); - if ((tempInt.indexOf(","))!= -1){ - tempInt = tempInt.replaceAll(",", ""); - } - //System.out.println("The final string INT is "+tempInt); - Long tempIntDollar = 0L; - try { - tempIntDollar = Long.parseLong(tempInt); - if(styleRowCell!=null) - sw.createCell(cellNum, tempIntDollar, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, tempIntDollar, styleCell.getIndex()); - else - sw.createCell(cellNum, tempIntDollar, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, tempInt, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, tempInt, styleCell.getIndex()); - else - sw.createCell(cellNum, tempInt, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - } - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - String tempStr = value.trim(); - if ((tempStr.indexOf(","))!= -1){ - tempStr = tempStr.replaceAll(",", ""); - } - Long temp = 0L; - - try { - temp = Long.parseLong(tempStr); - if(styleRowCell!=null) - sw.createCell(cellNum, temp, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, temp, styleCell.getIndex()); - else - sw.createCell(cellNum, temp, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempStr), styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempStr), styleCell.getIndex()); - else - sw.createCell(cellNum, Utils.excelEncode(tempStr), styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - } - } - } - } - } - - } else if ( ( dataType !=null && dataType.equals("DATE")) || (dv.getDisplayName()!=null && dv.getDisplayName().toLowerCase().endsWith("date")) || - (dv.getColId()!=null && dv.getColId().toLowerCase().endsWith("date")) || - (dv.getColName()!=null && dv.getColName().toLowerCase().endsWith("date")) ) { - XSSFCellStyle cellStyle = null; - if(styleRowCell!=null) { - cellStyle = styleRowCell; - } else if (styleCell!=null) { - cellStyle = styleCell; - } else { - cellStyle = styles.get(nvl(/*dv.getFormatId()*/"","date")); - } - - - Date date = null; - int flag = 0; - date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMMSS")); - flag = 1; - } - if(date==null) - date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMM")); - flag = 1; - } - if(date==null) - date = MMDDYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MMDDYY")); - flag = 1; - } - if(date==null) - date = MMDDYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MMDDYYYYHHMMSS")); - flag = 1; - } - if(date==null) - date = MMDDYYYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MMDDYYYYHHMM")); - flag = 1; - } - if(date==null) - date = MMDDYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MMDDYYYY")); - flag = 1; - } - if(date==null) - date = YYYYMMDDFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("YYYYMMDD")); - flag = 1; - } - if(date==null) - date = timestampFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("timestamp")); - flag = 1; - } - if(date==null) - date = MONYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MONYYYY")); - flag = 1; - } - if(date==null) - date = MMYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MMYYYY")); - flag = 1; - } - if(date==null) - date = MMMMMDDYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MMMMMDDYYYY")); - flag = 1; - } - if(date==null) - date = MONTHYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MONTHYYYY")); - flag = 1; - } - if(date==null) - date = YYYYMMDDHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("YYYYMMDDHHMMSS")); - flag = 1; - } - if(date==null) - date = YYYYMMDDDASHFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("YYYYMMDDDASH")); - flag = 1; - } - if(date==null) - date = YYYYMMDDHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("YYYYMMDDHHMM")); - flag = 1; - } - if(date==null) - date = DDMONYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("DDMONYYYYHHMMSS")); - flag = 1; - } - if(date==null) - date = DDMONYYYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("DDMONYYYYHHMM")); - flag = 1; - } - if(date==null) - date = DDMONYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("DDMONYYHHMM")); - flag = 1; - } - if(date==null) - date = DDMONYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("DDMONYYYY")); - flag = 1; - } - if(date==null) - date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMMSS")); - flag = 1; - } - if(date==null) - date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMM")); - flag = 1; - } - if(date==null) - date = MMDDYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MMDDYY")); - flag = 1; - } - if(date==null) - date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMM")); - flag = 1; - } - if(date==null) - date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MMDDYYHHMMSS")); - flag = 1; - } - if(date==null) - date = MMDDYYYYHHMMZFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MMDDYYYYHHMMZ")); - flag = 1; - } - if(date==null) - date = MMMMMDDYYYYHHMMSS.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - cellStyle.setDataFormat(dateFormatMap.get("MMMMMDDYYYYHHMMSS")); - flag = 1; - } - - if(date!=null) { - //System.out.println("ExcelDate " + HSSFDateUtil.getExcelDate(date)); - Calendar cal=Calendar.getInstance(); - cal.setTime(date); - //sw.createCell(cellNum, cal,styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - //if(styleRowCell!=null) - sw.createCell(cellNum, cal, cellStyle.getIndex()); - //else if (styleCell!=null) - //sw.createCell(cellNum, cal, cellStyle.getIndex()); - //else - //sw.createCell(cellNum, cal, cellStyle.getIndex()); - } else { - //cell.getCellStyle().setDataFormat((short)0); - //if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(value), cellStyle.getIndex()); - //else if (styleCell!=null) - //sw.createCell(cellNum, Utils.excelEncode(value), cellStyle.getIndex()); - //else - //sw.createCell(cellNum, Utils.excelEncode(value), cellStyle.getIndex()); - - } - //cellDate.setCellValue(date); - //cellDate.setCellValue(value); //cellDate.setCellValue(date); - //cellDate.setCellValue(dv.getDisplayValue()); - - } else if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ - //cellNumber = row.createCell((short) cellNum); - //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); - //cellNumber.setCellValue(dv.getDisplayValue()); - int zInt = 0; - if (value.equals("null")){ - if(styleRowCell!=null) - sw.createCell(cellNum, zInt, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, zInt, styleCell.getIndex()); - else - sw.createCell(cellNum, zInt, styleDefaultCell.getIndex()); - - } else { - - if ((value.indexOf("."))!= -1){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - - //if (value.startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempDollar = value.trim(); - tempDollar = tempDollar.replaceAll(" ", "").substring(0); - tempDollar = tempDollar.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempDollar); - //System.out.println("Before copy Value |" + tempDollar); - //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); - //System.out.println("After copy Value |" + tempDollar); - if ((tempDollar.indexOf(","))!= -1){ - tempDollar = tempDollar.replaceAll(",", ""); - } - //System.out.println("The final string 2IF is "+tempDollar); - double tempDoubleDollar = 0.0; - try { - tempDoubleDollar = Double.parseDouble(tempDollar); - if(styleRowCell!=null) - sw.createCell(cellNum, tempDoubleDollar,styleRowCell.getIndex() ); - else if (styleCell!=null) - sw.createCell(cellNum, tempDoubleDollar, styleCell.getIndex()); - else - sw.createCell(cellNum, tempDoubleDollar, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleCell.getIndex()); - else - sw.createCell(cellNum, Utils.excelEncode(tempDollar), styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - } - - - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - String tempDoubleStr = value.trim(); - tempDoubleStr = tempDoubleStr.replaceAll(" ", "").substring(0); - if ((tempDoubleStr.indexOf(","))!= -1){ - tempDoubleStr = tempDoubleStr.replaceAll(",", ""); - } - double tempDouble = 0.0; - try { - tempDouble = Double.parseDouble(tempDoubleStr); - if(styleRowCell!=null) - sw.createCell(cellNum, tempDouble, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, tempDouble, styleCell.getIndex()); - else - sw.createCell(cellNum, tempDouble, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), styleCell.getIndex()); - else - sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - } - } - - }else { - if (!(value.equals(""))){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - //if (value.startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempInt = value.trim(); - tempInt = tempInt.replaceAll(" ", "").substring(0); - tempInt = tempInt.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempInt); - //System.out.println("Before copy Value |" + tempInt); - //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); - //System.out.println("After copy Value |" + tempInt); - if ((tempInt.indexOf(","))!= -1){ - tempInt = tempInt.replaceAll(",", ""); - } - //System.out.println("The final string INT 2 is "+tempInt); - - Long tempIntDollar = 0L; - - try { - tempIntDollar = Long.parseLong(tempInt); - if(styleRowCell!=null) - sw.createCell(cellNum, tempIntDollar,styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, tempIntDollar,styleCell.getIndex()); - else - sw.createCell(cellNum, tempIntDollar,styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempInt), styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempInt),styleCell.getIndex()); - else - sw.createCell(cellNum, Utils.excelEncode(tempInt), styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - } - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - String tempStr = value.trim(); - if ((tempStr.indexOf(","))!= -1){ - tempStr = tempStr.replaceAll(",", ""); - } - Long temp = 0L; - - try { - temp = Long.parseLong(tempStr); - if(styleRowCell!=null) - sw.createCell(cellNum, temp, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, temp, styleCell.getIndex()); - else - sw.createCell(cellNum, temp, styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempStr), styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempStr), styleCell.getIndex()); - else - sw.createCell(cellNum, Utils.excelEncode(tempStr), styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - - } - } - } else { - sw.createCell(cellNum, "", styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - } - } - } - - - } - else { - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("General")); - if(styleRowCell!=null) - sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), styleCell.getIndex()); - else { - if(nvl(value).startsWith(" ")) - sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), styles.get(nvl(/*dv.getFormatId(),*/"","defaultLeft")).getIndex()); - else - sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - - } - - } - - if (dv.isBold()) { - if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ - if (value!=null && (value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - //cell.setCellStyle(styleCurrencyTotal); - } - else { - //cell.setCellStyle(styleTotal); - } - } else { - //cell.setCellStyle(styleDefaultTotal); - } - bold = true; - } - //System.out.println("2IF "+ (dr.isRowFormat()) + " " + (dv.isCellFormat()) + " " + (styles!=null)); - if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) { - //cell.setCellStyle((HSSFCellStyle) styles.get(nvl(dr.getFormatId(),"default"))); - continue; - } - //System.out.println("3IF "+ (htmlFormat != null) + " " + (dv.getFormatId() != null) + " " + (bold == false) + " "+ (styles != null)); - if (htmlFormat != null && dv.getFormatId() != null && bold == false - && styles != null) { - //cell.setCellStyle((HSSFCellStyle) styles.get(nvl(/*dv.getFormatId()*/"","default"))); - } //else if (bold == false) - //cell.setCellStyle(styleDefault); - } // dv.isVisible - - } - rowNum += 1; - sw.endRow(); - - } - if(rd.reportTotalRowHeaderCols!=null) { - rowCount++; - sw.insertRow(rowNum); - cellNum = -1; - rd.reportTotalRowHeaderCols.resetNext(); - cellNum += 1; - RowHeaderCol rhc = rd.reportTotalRowHeaderCols.getNext(); - RowHeader rh = rhc.getRowHeader(0); - if (dr.isRowFormat() && styles != null) - styleRowCell = (XSSFCellStyle) styles.get(nvl(/*dr.getFormatId(),*/"","default")); - - if(styleRowCell!=null) - sw.createCell(cellNum, strip.stripHtml(rh.getRowTitle()), styleRowCell.getIndex()); + } + + if (dv.isBold()) { + if ((dv.getDisplayTotal() != null && dv.getDisplayTotal().equals("SUM(")) + || (dv.getColName() != null && dv.getColName().indexOf("999") != -1)) { + if (value != null && (value.trim().startsWith("$")) + || (value.trim().startsWith("-$"))) { + } else { + } + } else { + } + bold = true; + } + if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) { + continue; + } + if (htmlFormat != null && dv.getFormatId() != null && bold == false + && styles != null) { + } + } + + } + rowNum += 1; + sw.endRow(); + + } + if (rd.reportTotalRowHeaderCols != null) { + rowCount++; + sw.insertRow(rowNum); + cellNum = -1; + rd.reportTotalRowHeaderCols.resetNext(); + cellNum += 1; + RowHeaderCol rhc = rd.reportTotalRowHeaderCols.getNext(); + RowHeader rh = rhc.getRowHeader(0); + if (dr.isRowFormat() && styles != null) + styleRowCell = (XSSFCellStyle) styles.get(nvl(/* dr.getFormatId(), */"", DEFAULT)); + + if (styleRowCell != null) + sw.createCell(cellNum, strip.stripHtml(rh.getRowTitle()), styleRowCell.getIndex()); else - sw.createCell(cellNum, strip.stripHtml(rh.getRowTitle()), styleDefaultCell.getIndex()); + sw.createCell(cellNum, strip.stripHtml(rh.getRowTitle()), styleDefaultCell.getIndex()); rd.reportDataTotalRow.resetNext(); - //rd.reportDataTotalRow.getNext(); - DataRow drTotal = rd.reportDataTotalRow.getNext(); - if(drTotal!=null) { - drTotal.resetNext(); drTotal.getNext(); - for (; drTotal.hasNext();) { - DataValue dv = drTotal.getNext(); - if(dv.isVisible()) { - cellNum += 1; - styleCell = null; - String value = dv.getDisplayValue(); - sw.createCell(cellNum,value,styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } - } - } - rowNum += 1; - sw.endRow(); - } - - - - - -/* // To Display Total Values for Linear report - if(rd.reportDataTotalRow!=null) { - row = sheet.createRow(rowNum); - cellNum = -1; - rd.reportTotalRowHeaderCols.resetNext(); - //for (rd.reportTotalRowHeaderCols.resetNext(); rd.reportTotalRowHeaderCols.hasNext();) { - cellNum += 1; - RowHeaderCol rhc = rd.reportTotalRowHeaderCols.getNext(); - RowHeader rh = rhc.getRowHeader(0); - row.createCell((short) cellNum).setCellValue(strip.stripHtml(rh.getRowTitle())); - row.getCell((short) cellNum).setCellStyle(styleDefaultTotal); - //} - - DataRow drTotal = rd.reportDataTotalRow.getNext(); - //cellNum = -1; - for (drTotal.resetNext(); drTotal.hasNext();j++) { - cellNum += 1; - cell = row.createCell((short) cellNum); - DataValue dv = drTotal.getNext(); - String value = dv.getDisplayValue(); - cell.setCellValue(value); - boolean bold = false; - if (dv.isBold()) { - if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ - if (value!=null && (value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - cell.setCellStyle(styleCurrencyTotal); - } else { - cell.setCellStyle(styleTotal); - } - } else { - cell.setCellStyle(styleDefaultTotal); - } - bold = true; - } - } - }*/ - - } catch (SQLException ex) { - throw new RaptorException(ex); - } catch (ReportSQLException ex) { - throw new RaptorException(ex); - } catch (Exception ex) { - if(!(ex.getCause() instanceof java.net.SocketException) ) - throw new RaptorException (ex); - } - - String footer = (String) session.getAttribute("FOOTER_"+index); - if(nvl(footer).length()>0) { - footer = Utils.replaceInString(footer, "<BR/>", " "); - footer = Utils.replaceInString(footer, "<br/>", " "); - footer = Utils.replaceInString(footer, "<br>", " "); - footer = strip.stripHtml(nvl(footer).trim()); - rowNum += 1; - sw.insertRow(rowNum); - cellNum = 0; - sw.createCell(cellNum, footer.replaceAll("&", "&"), styleDefaultCell.getIndex()); - sw.endRow(); - rowNum += 1; - } - - if(Globals.getShowDisclaimer()) { - rowNum += 1; - sw.insertRow(rowNum); - cellNum = 0; - - sw.createCell(cellNum, org.onap.portalsdk.analytics.system.Globals.getFooterFirstLine().replaceAll("&", "&"), styleDefaultCell.getIndex()); - sw.endRow(); - rowNum += 1; - sw.insertRow(rowNum); - cellNum = 0; - sw.createCell(cellNum, org.onap.portalsdk.analytics.system.Globals.getFooterSecondLine().replaceAll("&", "&"), styleDefaultCell.getIndex()); - sw.endRow(); - } - - } else { - //start data from rd - - int rowCount = 0; - DataRow dr = null; - for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) { - rowCount++; - - - dr = rd.reportDataRows.getNext(); - sw.insertRow(rowNum); - - cellNum = -1; - - if (rr.getReportType().equals(AppConstants.RT_LINEAR) && rd.reportTotalRowHeaderCols!=null) { - rd.reportRowHeaderCols.resetNext(0); - if(rd.reportTotalRowHeaderCols!=null) { - //cellNum = -1; - //for (rd.reportRowHeaderCols.resetNext(); rd.reportRowHeaderCols.hasNext();) { - //a commented to suppress rownum - //a cellNum += 1; - //RowHeaderCol rhc = rd.reportRowHeaderCols.getRowHeaderCol(0); - //if (firstPass) - // rhc.resetNext(); - //RowHeader rh = rhc.getRowHeader(rowCount-1); - //a sw.createCell(cellNum, rowCount, styleDefaultCell.getIndex()); - //} // for - } - - } - firstPass = false; - //cellNum = -1; - int j = 0; - - for (dr.resetNext(); dr.hasNext();j++) { - DataValue dv = dr.getNext(); - styleCell = null; - boolean bold = false; - String value = nvl(dv.getDisplayValue()); - value = strip.stripHtml(value); - HtmlFormatter htmlFormat = dv.getCellFormatter(); - if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) - styleCell = (XSSFCellStyle) styles.get(nvl(/*dr.getFormatId(),*/"","default")); - if (htmlFormat != null && dv.getFormatId() != null && styles != null) - styleCell = (XSSFCellStyle) styles.get(nvl(/*dv.getFormatId(),*/"","default")); - - if(dv.isVisible()) { - cellNum += 1; - //cell = row.createCell((short) cellNum); - //System.out.println("Stripping HTML 1"); - //cell.setCellValue(strip.stripHtml(value)); - String dataType = (String) (dataTypeMap.get(dv.getColId())); - //System.out.println(" The Display Value is ********"+value + " " + dv.getDisplayTotal() + " " + dv.getColName()); - - if (dataType!=null && dataType.equals("NUMBER")){ - //cellNumber = row.createCell((short) cellNum); - //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); - //cellNumber.setCellValue(value); - //cellCurrencyNumber = row.createCell((short) cellNum); - int zInt = 0; - if (value.equals("null")){ - sw.createCell(cellNum,zInt,styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - }else{ - - if ((value.indexOf("."))!= -1){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - - //if (value.startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempDollar = value.trim(); - tempDollar = tempDollar.replaceAll(" ", "").substring(0); - tempDollar = tempDollar.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempDollar); - //System.out.println("Before copy Value |" + tempDollar); - //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); - //System.out.println("After copy Value |" + tempDollar); - if ((tempDollar.indexOf(","))!= -1){ - tempDollar = tempDollar.replaceAll(",", ""); - } - //System.out.println("The final string 1 is "+tempDollar); - double tempDoubleDollar = 0.0; - try { - tempDoubleDollar = Double.parseDouble(tempDollar); - if(styleRowCell!=null) - sw.createCell(cellNum, tempDoubleDollar, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, tempDoubleDollar, styleCell.getIndex()); - else - sw.createCell(cellNum, tempDoubleDollar, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleCell.getIndex()); - else - sw.createCell(cellNum, Utils.excelEncode(tempDollar), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - double tempDouble = 0.0; - try { - tempDouble = Double.parseDouble(value); - if(styleRowCell!=null) - sw.createCell(cellNum, tempDouble, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, tempDouble, styleCell.getIndex()); - else - sw.createCell(cellNum, tempDouble, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(value),styleRowCell.getIndex() ); - else if (styleCell!=null) - sw.createCell(cellNum, Utils.excelEncode(value), styleCell.getIndex()); - else - sw.createCell(cellNum, Utils.excelEncode(value), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } - - } - }else { - if (!(value.equals(""))){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - //if (value.startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempInt = value.trim(); - tempInt = tempInt.replaceAll(" ", "").substring(0); - tempInt = tempInt.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempInt); - //System.out.println("Before copy Value |" + tempInt); - //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); - //System.out.println("After copy Value |" + tempInt); - if ((tempInt.indexOf(","))!= -1){ - tempInt = tempInt.replaceAll(",", ""); - } - //System.out.println("The final string INT is "+tempInt); - Long tempIntDollar = 0L; - try { - tempIntDollar = Long.parseLong(tempInt); - if(styleRowCell!=null) - sw.createCell(cellNum, tempIntDollar, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, tempIntDollar, styleCell.getIndex()); - else - sw.createCell(cellNum, tempIntDollar, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, tempInt, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, tempInt, styleCell.getIndex()); - else - sw.createCell(cellNum, tempInt, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - String tempStr = value.trim(); - if ((tempStr.indexOf(","))!= -1){ - tempStr = tempStr.replaceAll(",", ""); - } - Long temp = 0L; - - try { - temp = Long.parseLong(tempStr); - if(styleRowCell!=null) - sw.createCell(cellNum, temp, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, temp, styleCell.getIndex()); - else - sw.createCell(cellNum, temp, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempStr), styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempStr), styleCell.getIndex()); - else - sw.createCell(cellNum, Utils.excelEncode(tempStr), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } - - - } - //int temp = Integer.parseInt(value.trim()); - // cell.setCellValue(temp); - //}else{ - // cell.setCellValue(strip.stripHtml(value)); - //} - } - } - } - - }else if ( ( dataType !=null && dataType.equals("DATE")) || (dv.getDisplayName()!=null && dv.getDisplayName().toLowerCase().endsWith("date")) || - (dv.getColId()!=null && dv.getColId().toLowerCase().endsWith("date")) || - (dv.getColName()!=null && dv.getColName().toLowerCase().endsWith("date")) ) { - Date date = null; - int flag = 0; - date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MMDDYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MMDDYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MMDDYYYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MMDDYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = YYYYMMDDFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = timestampFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MONYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MMYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MMMMMDDYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MONTHYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = YYYYMMDDHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = YYYYMMDDDASHFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = YYYYMMDDHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = DDMONYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = DDMONYYYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = DDMONYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = DDMONYYYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MMDDYYFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MMDDYYYYHHMMZFormat.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - if(date==null) - date = MMMMMDDYYYYHHMMSS.parse(value, new ParsePosition(0)); - if(date != null && flag == 0) { - flag = 1; - } - - - if(date!=null) { - Calendar cal=Calendar.getInstance(); - cal.setTime(date); - //sw.createCell(cellNum, cal,styles.get(nvl(/*dv.getFormatId()*/"","default")).getIndex()); - if(styleRowCell!=null) - sw.createCell(cellNum, cal, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, cal, styleCell.getIndex()); - else - sw.createCell(cellNum, cal, styles.get(nvl(/*dv.getFormatId()*/"","date")).getIndex()); - - } else { - /*cell.getCellStyle().setDataFormat((short)0);*/ - if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(value), styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, Utils.excelEncode(value), styleCell.getIndex()); - else - sw.createCell(cellNum, Utils.excelEncode(value), styles.get(nvl(/*dv.getFormatId(),*/"","date")).getIndex()); - - } - //cellDate.setCellValue(date); - //cellDate.setCellValue(value); - - }else if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ - //cellNumber = row.createCell((short) cellNum); - //cellNumber.setCellType(HSSFCell.CELL_TYPE_NUMERIC); - //cellNumber.setCellValue(value); - int zInt = 0; - if (value.equals("null")){ - if(styleRowCell!=null) - sw.createCell(cellNum, zInt, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, zInt, styleCell.getIndex()); - else - sw.createCell(cellNum, zInt, styleDefaultCell.getIndex()); - } else { - - if ((value.indexOf("."))!= -1){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - - //if (value.startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempDollar = value.trim(); - tempDollar = tempDollar.replaceAll(" ", "").substring(0); - tempDollar = tempDollar.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempDollar); - //System.out.println("Before copy Value |" + tempDollar); - //tempDollar = String.copyValueOf(tempDollar.toCharArray(), 1, tempDollar.length()-1); - //System.out.println("After copy Value |" + tempDollar); - if ((tempDollar.indexOf(","))!= -1){ - tempDollar = tempDollar.replaceAll(",", ""); - } - //System.out.println("The final string 2IF is "+tempDollar); - double tempDoubleDollar = 0.0; - try { - tempDoubleDollar = Double.parseDouble(tempDollar); - if(styleRowCell!=null) - sw.createCell(cellNum, tempDoubleDollar,styleRowCell.getIndex() ); - else if (styleCell!=null) - sw.createCell(cellNum, tempDoubleDollar, styleCell.getIndex()); - else - sw.createCell(cellNum, tempDoubleDollar, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempDollar), styleCell.getIndex()); - else - sw.createCell(cellNum, Utils.excelEncode(tempDollar), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } - - - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - String tempDoubleStr = value.trim(); - tempDoubleStr = tempDoubleStr.replaceAll(" ", "").substring(0); - if ((tempDoubleStr.indexOf(","))!= -1){ - tempDoubleStr = tempDoubleStr.replaceAll(",", ""); - } - double tempDouble = 0.0; - try { - tempDouble = Double.parseDouble(tempDoubleStr); - if(styleRowCell!=null) - sw.createCell(cellNum, tempDouble, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, tempDouble, styleCell.getIndex()); - else - sw.createCell(cellNum, tempDouble, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), styleCell.getIndex()); - else - sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } - } - - }else { - if (!(value.equals(""))){ - if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - //if (value.startsWith("$")){ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0.00);($#,##0.00)")); - String tempInt = value.trim(); - tempInt = tempInt.replaceAll(" ", "").substring(0); - tempInt = tempInt.replaceAll("\\$", "").substring(0); - //System.out.println("SUBSTRING |" + tempInt); - //System.out.println("Before copy Value |" + tempInt); - //tempInt = String.copyValueOf(tempInt.toCharArray(), 1, tempInt.length()-1); - //System.out.println("After copy Value |" + tempInt); - if ((tempInt.indexOf(","))!= -1){ - tempInt = tempInt.replaceAll(",", ""); - } - //System.out.println("The final string INT 2 is "+tempInt); - - Long tempIntDollar = 0L; - - try { - tempIntDollar = Long.parseLong(tempInt); - if(styleRowCell!=null) - sw.createCell(cellNum, tempIntDollar,styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, tempIntDollar,styleCell.getIndex()); - else - sw.createCell(cellNum, tempIntDollar,styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempInt), styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempInt),styleCell.getIndex()); - else - sw.createCell(cellNum, Utils.excelEncode(tempInt), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } - }else{ - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00")); - String tempStr = value.trim(); - if ((tempStr.indexOf(","))!= -1){ - tempStr = tempStr.replaceAll(",", ""); - } - Long temp = 0L; - - try { - temp = Long.parseLong(tempStr); - if(styleRowCell!=null) - sw.createCell(cellNum, temp, styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, temp, styleCell.getIndex()); - else - sw.createCell(cellNum, temp, styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } catch (NumberFormatException ne) { - if(styleRowCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempStr), styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, Utils.excelEncode(tempStr), styleCell.getIndex()); - else - sw.createCell(cellNum, Utils.excelEncode(tempStr), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } - } - //int temp = Integer.parseInt(value.trim()); - // cell.setCellValue(temp); - //}else{ - // cell.setCellValue(strip.stripHtml(value)); - //} - } else { - sw.createCell(cellNum, "", styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } - } - } - - - } - else { - //styleDefault.setDataFormat(HSSFDataFormat.getBuiltinFormat("General")); - if(styleRowCell!=null) - sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), styleRowCell.getIndex()); - else if (styleCell!=null) - sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), styleCell.getIndex()); - else - sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } - - //if (!(value.equals(""))){ - //int temp = Integer.parseInt(value.trim()); - //cell.setCellValue(temp); - //}else{ - // cell.setCellValue(strip.stripHtml(value)); - //} - //HSSFCellStyle styleFormat = null; - //HSSFCellStyle numberStyle = null; - //HSSFFont formatFont = null; - //short fgcolor = 0; - //short fillpattern = 0; - //System.out.println("1IF "+ (dv.isBold()) + " "+ value + " " + dv.getDisplayTotal() + " " + dv.getColName() ); - if (dv.isBold()) { - if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ - if (value!=null && (value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { - //cell.setCellStyle(styleCurrencyTotal); - } - else { - //cell.setCellStyle(styleTotal); - } - } else { - //cell.setCellStyle(styleDefaultTotal); - } - bold = true; - } - //System.out.println("2IF "+ (dr.isRowFormat()) + " " + (dv.isCellFormat()) + " " + (styles!=null)); - if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) { - //cell.setCellStyle((HSSFCellStyle) styles.get(nvl(dr.getFormatId(),"default"))); - continue; - } - //System.out.println("3IF "+ (htmlFormat != null) + " " + (dv.getFormatId() != null) + " " + (bold == false) + " "+ (styles != null)); - if (htmlFormat != null && dv.getFormatId() != null && bold == false - && styles != null) { - // cell.setCellStyle((HSSFCellStyle) styles.get(nvl(/*dv.getFormatId()*/"","default"))); - } //else if (bold == false) - //cell.setCellStyle(styleDefault); - } // if (dv.isVisible) - } // for - - /*for (int tmp=0; tmp<dataTypeMap.size(); tmp++){ - String dataTypeStr = (String)(dataTypeMap.get(tmp)); - if(dataTypeStr.equals("NUMBER")){ - cell.setCellStyle(styleNumber); - }else if (dataTypeStr.equals("VARCHAR2")){ - cell.setCellStyle(styleDefault); - - }else if (dataTypeStr.equals("DATE")){ - cell.setCellStyle(styleDate); - }else{ - - } - - }*/ - rowNum += 1; + DataRow drTotal = rd.reportDataTotalRow.getNext(); + if (drTotal != null) { + drTotal.resetNext(); + drTotal.getNext(); + for (; drTotal.hasNext();) { + DataValue dv = drTotal.getNext(); + if (dv.isVisible()) { + cellNum += 1; + styleCell = null; + String value = dv.getDisplayValue(); + sw.createCell(cellNum, value, + styles.get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } + } + } + rowNum += 1; + sw.endRow(); + } + + /* + * // To Display Total Values for Linear report if(rd.reportDataTotalRow!=null) { row = + * sheet.createRow(rowNum); cellNum = -1; rd.reportTotalRowHeaderCols.resetNext(); //for + * (rd.reportTotalRowHeaderCols.resetNext(); rd.reportTotalRowHeaderCols.hasNext();) { cellNum += 1; + * RowHeaderCol rhc = rd.reportTotalRowHeaderCols.getNext(); RowHeader rh = rhc.getRowHeader(0); + * row.createCell((short) cellNum).setCellValue(strip.stripHtml(rh.getRowTitle())); + * row.getCell((short) cellNum).setCellStyle(styleDefaultTotal); //} + * + * DataRow drTotal = rd.reportDataTotalRow.getNext(); //cellNum = -1; for (drTotal.resetNext(); + * drTotal.hasNext();j++) { cellNum += 1; cell = row.createCell((short) cellNum); DataValue dv = + * drTotal.getNext(); String value = dv.getDisplayValue(); cell.setCellValue(value); boolean bold = + * false; if (dv.isBold()) { if((dv.getDisplayTotal()!=null && dv.getDisplayTotal().equals("SUM(")) + * || (dv.getColName()!=null && dv.getColName().indexOf("999")!=-1)){ if (value!=null && + * (value.trim().startsWith("$")) || (value.trim().startsWith("-$") )) { + * cell.setCellStyle(styleCurrencyTotal); } else { cell.setCellStyle(styleTotal); } } else { + * cell.setCellStyle(styleDefaultTotal); } bold = true; } } } + */ + + } catch (SQLException ex) { + throw new RaptorException(ex); + } catch (ReportSQLException ex) { + throw new RaptorException(ex); + } catch (Exception ex) { + if (!(ex.getCause() instanceof java.net.SocketException)) + throw new RaptorException(ex); + } + + String footer = (String) session.getAttribute("FOOTER_" + index); + if (nvl(footer).length() > 0) { + footer = Utils.replaceInString(footer, "<BR/>", " "); + footer = Utils.replaceInString(footer, "<br/>", " "); + footer = Utils.replaceInString(footer, "<br>", " "); + footer = strip.stripHtml(nvl(footer).trim()); + rowNum += 1; + sw.insertRow(rowNum); + cellNum = 0; + sw.createCell(cellNum, footer.replaceAll("&", "&"), styleDefaultCell.getIndex()); sw.endRow(); - } // for - - if (rr.getReportType().equals(AppConstants.RT_LINEAR) && rd.reportTotalRowHeaderCols!=null) { - - for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext();) { - rowCount++; - sw.insertRow(rowNum); - cellNum = -1; - cellNum += 1; - - RowHeaderCol rhc = rd.reportTotalRowHeaderCols.getNext(); - RowHeader rh = rhc.getRowHeader(0); - if (dr.isRowFormat() && styles != null) - styleRowCell = (XSSFCellStyle) styles.get(nvl(/*dr.getFormatId(),*/"","default")); - if(styleRowCell!=null) - sw.createCell(cellNum, strip.stripHtml(rh.getRowTitle()), styleRowCell.getIndex()); - else - sw.createCell(cellNum, strip.stripHtml(rh.getRowTitle()), styleDefaultCell.getIndex()); - - DataRow drTotal = rd.reportDataTotalRow.getNext(); - if(drTotal!=null) { - drTotal.resetNext(); drTotal.getNext(); - for (; drTotal.hasNext();) { - cellNum += 1; - styleCell = null; - DataValue dv = drTotal.getNext(); - String value = dv.getDisplayValue(); - sw.createCell(cellNum,value,styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex()); - } - } - - rowNum += 1; - sw.endRow(); - } - - - String footer = (String) session.getAttribute("FOOTER_"+index); - if(nvl(footer).length()>0) { - footer = Utils.replaceInString(footer, "<BR/>", " "); - footer = Utils.replaceInString(footer, "<br/>", " "); - footer = Utils.replaceInString(footer, "<br>", " "); - footer = strip.stripHtml(nvl(footer).trim()); - rowNum += 1; - sw.insertRow(rowNum); - cellNum = 0; - sw.createCell(cellNum, footer.replaceAll("&", "&"), styleDefaultCell.getIndex()); - sw.endRow(); - rowNum += 1; - } - - - if(Globals.getShowDisclaimer()) { - rowNum += 1; - sw.insertRow(rowNum); - cellNum = 0; - - sw.createCell(cellNum, org.onap.portalsdk.analytics.system.Globals.getFooterFirstLine().replaceAll("&", "&"), styleDefaultCell.getIndex()); - sw.endRow(); - rowNum += 1; - sw.insertRow(rowNum); - cellNum = 0; - sw.createCell(cellNum, org.onap.portalsdk.analytics.system.Globals.getFooterSecondLine().replaceAll("&", "&"), styleDefaultCell.getIndex()); - sw.endRow(); - } - - - } - // end data from rd - } + rowNum += 1; + } + + if (Globals.getShowDisclaimer()) { + rowNum += 1; + sw.insertRow(rowNum); + cellNum = 0; + + sw.createCell(cellNum, + org.onap.portalsdk.analytics.system.Globals.getFooterFirstLine().replaceAll("&", "&"), + styleDefaultCell.getIndex()); + sw.endRow(); + rowNum += 1; + sw.insertRow(rowNum); + cellNum = 0; + sw.createCell(cellNum, + org.onap.portalsdk.analytics.system.Globals.getFooterSecondLine().replaceAll("&", "&"), + styleDefaultCell.getIndex()); + sw.endRow(); + } + + } else { + + int rowCount = 0; + DataRow dr = null; + for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) { + rowCount++; + + dr = rd.reportDataRows.getNext(); + sw.insertRow(rowNum); + + cellNum = -1; + + if (rr.getReportType().equals(AppConstants.RT_LINEAR) && rd.reportTotalRowHeaderCols != null) { + rd.reportRowHeaderCols.resetNext(0); + if (rd.reportTotalRowHeaderCols != null) { + + } + + } + firstPass = false; + int j = 0; + + for (dr.resetNext(); dr.hasNext(); j++) { + DataValue dv = dr.getNext(); + styleCell = null; + boolean bold = false; + String value = nvl(dv.getDisplayValue()); + value = strip.stripHtml(value); + HtmlFormatter htmlFormat = dv.getCellFormatter(); + if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) + styleCell = (XSSFCellStyle) styles.get(nvl(/* dr.getFormatId(), */"", DEFAULT)); + if (htmlFormat != null && dv.getFormatId() != null && styles != null) + styleCell = (XSSFCellStyle) styles.get(nvl(/* dv.getFormatId(), */"", DEFAULT)); + + if (dv.isVisible()) { + cellNum += 1; + String dataType = (String) (dataTypeMap.get(dv.getColId())); + + if (dataType != null && dataType.equals("NUMBER")) { + int zInt = 0; + if (value.equals("null")) { + sw.createCell(cellNum, zInt, + styles.get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } else { + + if ((value.indexOf(".")) != -1) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + + String tempDollar = value.trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + if ((tempDollar.indexOf(",")) != -1) { + tempDollar = tempDollar.replaceAll(",", ""); + } + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if (styleRowCell != null) + sw.createCell(cellNum, tempDoubleDollar, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, tempDoubleDollar, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDoubleDollar, styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), + styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } + } else { + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(value); + if (styleRowCell != null) + sw.createCell(cellNum, tempDouble, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, tempDouble, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDouble, styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, Utils.excelEncode(value), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, Utils.excelEncode(value), styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(value), styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } + + } + } else { + if (!(value.equals(""))) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + if ((tempInt.indexOf(",")) != -1) { + tempInt = tempInt.replaceAll(",", ""); + } + Long tempIntDollar = 0L; + try { + tempIntDollar = Long.parseLong(tempInt); + if (styleRowCell != null) + sw.createCell(cellNum, tempIntDollar, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, tempIntDollar, styleCell.getIndex()); + else + sw.createCell(cellNum, tempIntDollar, styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, tempInt, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, tempInt, styleCell.getIndex()); + else + sw.createCell(cellNum, tempInt, styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } + } else { + String tempStr = value.trim(); + if ((tempStr.indexOf(",")) != -1) { + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if (styleRowCell != null) + sw.createCell(cellNum, temp, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, temp, styleCell.getIndex()); + else + sw.createCell(cellNum, temp, styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), + styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempStr), styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } + + } - // System.out.println(" Last Row " + wb.getSheetAt(0).getLastRowNum()); - } - - private void paintXSSFExcelParams(XSSFWorkbook wb,int rowNum,int col,ArrayList paramsList, String customizedParamInfo, XSSFSheet sheet, String reportTitle, String reportDescr) throws IOException { - //HSSFSheet sheet = wb.getSheet(getSheetName()); + } + } + } + + } else if ((dataType != null && dataType.equals("DATE")) + || (dv.getDisplayName() != null && dv.getDisplayName().toLowerCase().endsWith("date")) + || + (dv.getColId() != null && dv.getColId().toLowerCase().endsWith("date")) || + (dv.getColName() != null && dv.getColName().toLowerCase().endsWith("date"))) { + Date date = null; + int flag = 0; + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MMDDYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MMDDYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MMDDYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = YYYYMMDDFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = timestampFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MONYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MMYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MMMMMDDYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MONTHYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = YYYYMMDDHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = YYYYMMDDDASHFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = YYYYMMDDHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = DDMONYYYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = DDMONYYYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = DDMONYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = DDMONYYYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MMDDYYFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MMDDYYHHMMFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MMDDYYHHMMSSFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MMDDYYYYHHMMZFormat.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + if (date == null) + date = MMMMMDDYYYYHHMMSS.parse(value, new ParsePosition(0)); + if (date != null && flag == 0) { + flag = 1; + } + + if (date != null) { + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + if (styleRowCell != null) + sw.createCell(cellNum, cal, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, cal, styleCell.getIndex()); + else + sw.createCell(cellNum, cal, + styles.get(nvl(/* dv.getFormatId() */"", "date")).getIndex()); + + } else { + /* cell.getCellStyle().setDataFormat((short)0); */ + if (styleRowCell != null) + sw.createCell(cellNum, Utils.excelEncode(value), styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, Utils.excelEncode(value), styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(value), + styles.get(nvl(/* dv.getFormatId(), */"", "date")).getIndex()); + + } + + } else if ((dv.getDisplayTotal() != null && dv.getDisplayTotal().equals("SUM(")) + || (dv.getColName() != null && dv.getColName().indexOf("999") != -1)) { + int zInt = 0; + if (value.equals("null")) { + if (styleRowCell != null) + sw.createCell(cellNum, zInt, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, zInt, styleCell.getIndex()); + else + sw.createCell(cellNum, zInt, styleDefaultCell.getIndex()); + } else { + + if ((value.indexOf(".")) != -1) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + + String tempDollar = value.trim(); + tempDollar = tempDollar.replaceAll(" ", "").substring(0); + tempDollar = tempDollar.replaceAll("\\$", "").substring(0); + if ((tempDollar.indexOf(",")) != -1) { + tempDollar = tempDollar.replaceAll(",", ""); + } + double tempDoubleDollar = 0.0; + try { + tempDoubleDollar = Double.parseDouble(tempDollar); + if (styleRowCell != null) + sw.createCell(cellNum, tempDoubleDollar, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, tempDoubleDollar, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDoubleDollar, styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempDollar), + styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempDollar), styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } + + } else { + String tempDoubleStr = value.trim(); + tempDoubleStr = tempDoubleStr.replaceAll(" ", "").substring(0); + if ((tempDoubleStr.indexOf(",")) != -1) { + tempDoubleStr = tempDoubleStr.replaceAll(",", ""); + } + double tempDouble = 0.0; + try { + tempDouble = Double.parseDouble(tempDoubleStr); + if (styleRowCell != null) + sw.createCell(cellNum, tempDouble, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, tempDouble, styleCell.getIndex()); + else + sw.createCell(cellNum, tempDouble, styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), + styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempDoubleStr), styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } + } + + } else { + if (!(value.equals(""))) { + if ((value.trim().startsWith("$")) || (value.trim().startsWith("-$"))) { + String tempInt = value.trim(); + tempInt = tempInt.replaceAll(" ", "").substring(0); + tempInt = tempInt.replaceAll("\\$", "").substring(0); + if ((tempInt.indexOf(",")) != -1) { + tempInt = tempInt.replaceAll(",", ""); + } + + Long tempIntDollar = 0L; + + try { + tempIntDollar = Long.parseLong(tempInt); + if (styleRowCell != null) + sw.createCell(cellNum, tempIntDollar, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, tempIntDollar, styleCell.getIndex()); + else + sw.createCell(cellNum, tempIntDollar, styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempInt), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempInt), + styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempInt), styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } + } else { + String tempStr = value.trim(); + if ((tempStr.indexOf(",")) != -1) { + tempStr = tempStr.replaceAll(",", ""); + } + Long temp = 0L; + + try { + temp = Long.parseLong(tempStr); + if (styleRowCell != null) + sw.createCell(cellNum, temp, styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, temp, styleCell.getIndex()); + else + sw.createCell(cellNum, temp, styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } catch (NumberFormatException ne) { + if (styleRowCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, Utils.excelEncode(tempStr), + styleCell.getIndex()); + else + sw.createCell(cellNum, Utils.excelEncode(tempStr), styles + .get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } + } + + } else { + sw.createCell(cellNum, "", + styles.get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } + } + } + + } else { + if (styleRowCell != null) + sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), + styleRowCell.getIndex()); + else if (styleCell != null) + sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), styleCell.getIndex()); + else + sw.createCell(cellNum, strip.stripHtml(Utils.excelEncode(value)), + styles.get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } + + // if (!(value.equals(""))){ + // int temp = Integer.parseInt(value.trim()); + // cell.setCellValue(temp); + // }else{ + // cell.setCellValue(strip.stripHtml(value)); + // } + // HSSFCellStyle styleFormat = null; + // HSSFCellStyle numberStyle = null; + // HSSFFont formatFont = null; + // short fgcolor = 0; + // short fillpattern = 0; + // System.out.println("1IF "+ (dv.isBold()) + " "+ value + " " + dv.getDisplayTotal() + " " + + // dv.getColName() ); + if (dv.isBold()) { + if ((dv.getDisplayTotal() != null && dv.getDisplayTotal().equals("SUM(")) + || (dv.getColName() != null && dv.getColName().indexOf("999") != -1)) { + if (value != null && (value.trim().startsWith("$")) + || (value.trim().startsWith("-$"))) { + // cell.setCellStyle(styleCurrencyTotal); + } else { + // cell.setCellStyle(styleTotal); + } + } else { + // cell.setCellStyle(styleDefaultTotal); + } + bold = true; + } + + if ((dr.isRowFormat() && !dv.isCellFormat()) && styles != null) { + continue; + } + if (htmlFormat != null && dv.getFormatId() != null && bold == false + && styles != null) { + // cell.setCellStyle((HSSFCellStyle) styles.get(nvl(/*dv.getFormatId()*/"",DEFAULT))); + } // else if (bold == false) + // cell.setCellStyle(styleDefault); + } // if (dv.isVisible) + } // for + + /* + * for (int tmp=0; tmp<dataTypeMap.size(); tmp++){ String dataTypeStr = + * (String)(dataTypeMap.get(tmp)); if(dataTypeStr.equals("NUMBER")){ cell.setCellStyle(styleNumber); + * }else if (dataTypeStr.equals("VARCHAR2")){ cell.setCellStyle(styleDefault); + * + * }else if (dataTypeStr.equals("DATE")){ cell.setCellStyle(styleDate); }else{ + * + * } + * + * } + */ + rowNum += 1; + sw.endRow(); + } // for + + if (rr.getReportType().equals(AppConstants.RT_LINEAR) && rd.reportTotalRowHeaderCols != null) { + + for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext();) { + rowCount++; + sw.insertRow(rowNum); + cellNum = -1; + cellNum += 1; + + RowHeaderCol rhc = rd.reportTotalRowHeaderCols.getNext(); + RowHeader rh = rhc.getRowHeader(0); + if (dr.isRowFormat() && styles != null) + styleRowCell = (XSSFCellStyle) styles.get(nvl(/* dr.getFormatId(), */"", DEFAULT)); + if (styleRowCell != null) + sw.createCell(cellNum, strip.stripHtml(rh.getRowTitle()), styleRowCell.getIndex()); + else + sw.createCell(cellNum, strip.stripHtml(rh.getRowTitle()), styleDefaultCell.getIndex()); + + DataRow drTotal = rd.reportDataTotalRow.getNext(); + if (drTotal != null) { + drTotal.resetNext(); + drTotal.getNext(); + for (; drTotal.hasNext();) { + cellNum += 1; + styleCell = null; + DataValue dv = drTotal.getNext(); + String value = dv.getDisplayValue(); + sw.createCell(cellNum, value, + styles.get(nvl(/* dv.getFormatId(), */"", DEFAULT)).getIndex()); + } + } + + rowNum += 1; + sw.endRow(); + } + + String footer = (String) session.getAttribute("FOOTER_" + index); + if (nvl(footer).length() > 0) { + footer = Utils.replaceInString(footer, "<BR/>", " "); + footer = Utils.replaceInString(footer, "<br/>", " "); + footer = Utils.replaceInString(footer, "<br>", " "); + footer = strip.stripHtml(nvl(footer).trim()); + rowNum += 1; + sw.insertRow(rowNum); + cellNum = 0; + sw.createCell(cellNum, footer.replaceAll("&", "&"), styleDefaultCell.getIndex()); + sw.endRow(); + rowNum += 1; + } + + if (Globals.getShowDisclaimer()) { + rowNum += 1; + sw.insertRow(rowNum); + cellNum = 0; + + sw.createCell(cellNum, + org.onap.portalsdk.analytics.system.Globals.getFooterFirstLine().replaceAll("&", "&"), + styleDefaultCell.getIndex()); + sw.endRow(); + rowNum += 1; + sw.insertRow(rowNum); + cellNum = 0; + sw.createCell(cellNum, + org.onap.portalsdk.analytics.system.Globals.getFooterSecondLine().replaceAll("&", "&"), + styleDefaultCell.getIndex()); + sw.endRow(); + } + + } + // end data from rd + } + + } + + private void paintXSSFExcelParams(HSSFWorkbook wb, int rowNum, int col, ArrayList paramsList, + String customizedParamInfo, XSSFSheet sheet, String reportTitle, String reportDescr) throws IOException { int cellNum = 0; XSSFRow row = null; short s1 = 0, s2 = (short) 1; HtmlStripper strip = new HtmlStripper(); // Name Style - XSSFCellStyle styleName = wb.createCellStyle(); - //styleName.setFillBackgroundColor(HSSFColor.GREY_80_PERCENT.index); + HSSFCellStyle styleName = wb.createCellStyle(); styleName.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); - //styleName.setFillPattern(HSSFCellStyle.SPARSE_DOTS); styleName.setAlignment(HorizontalAlignment.CENTER); styleName.setBorderBottom(BorderStyle.THIN); styleName.setBorderTop(BorderStyle.THIN); styleName.setBorderRight(BorderStyle.THIN); styleName.setBorderLeft(BorderStyle.THIN); - styleName.setDataFormat((short)0); - XSSFFont font = wb.createFont(); - font.setFontHeight((short) (font_size / 0.05)); - font.setFontName("Tahoma"); + styleName.setDataFormat((short) 0); + HSSFFont font = wb.createFont(); + font.setFontHeight((short) (FONT_SIZE / 0.05)); + font.setFontName(FONT_TAHOMA); font.setColor(HSSFColor.BLACK.index); - font.setBold(true); + font.setBold(font.getBold()); styleName.setFont(font); - //Data Style - + // Data Style + // Create some fonts. - XSSFFont fontDefault = wb.createFont(); + HSSFFont fontDefault = wb.createFont(); + // Initialize the styles & fonts. // The default will be plain . fontDefault.setColor((short) HSSFFont.COLOR_NORMAL); - fontDefault.setFontHeight((short) (font_size / 0.05)); - fontDefault.setFontName("Tahoma"); + fontDefault.setFontHeight((short) (FONT_SIZE / 0.05)); + fontDefault.setFontName(FONT_TAHOMA); fontDefault.setItalic(true); // Style default will be normal with no background - XSSFCellStyle styleValue = wb.createCellStyle(); - styleValue.setDataFormat((short)0); + HSSFCellStyle styleValue = wb.createCellStyle(); + HSSFCellStyle styleCurrencyDecimalNumberTotal = wb.createCellStyle(); + styleValue.setDataFormat((short) 0); styleValue.setAlignment(HorizontalAlignment.CENTER); styleValue.setBorderBottom(BorderStyle.THIN); styleValue.setBorderTop(BorderStyle.THIN); styleValue.setBorderLeft(BorderStyle.THIN); styleValue.setBorderRight(BorderStyle.THIN); - // styleValue.setFillForegroundColor(HSSFColor.YELLOW.index); - styleValue.setFillPattern(FillPatternType.NO_FILL); + + styleValue.setFillPattern(fillPattern.NO_FILL); styleValue.setFont(fontDefault); XSSFCell cell = null; - XSSFCellStyle styleDescription = wb.createCellStyle(); + HSSFCellStyle styleDescription = wb.createCellStyle(); styleDescription.setAlignment(HorizontalAlignment.CENTER); -// styleDescription.setBorderBottom(BorderStyle.THIN); -// styleDescription.setBorderTop(BorderStyle.THIN); -// styleDescription.setBorderRight(BorderStyle.THIN); -// styleDescription.setBorderLeft(BorderStyle.THIN); - XSSFFont fontDescr = wb.createFont(); - fontDescr.setFontHeight((short) (font_header_descr_size / 0.05)); - fontDescr.setFontName("Tahoma"); + + HSSFFont fontDescr = wb.createFont(); + fontDescr.setFontHeight((short) (FONT_HEADER_DESCR_SIZE / 0.05)); + fontDescr.setFontName(FONT_TAHOMA); fontDescr.setColor(HSSFColor.BLACK.index); fontDescr.setBold(true); styleDescription.setFont(font); XSSFCell cellDescr = null; int paramSeq = 0; Header header = sheet.getHeader(); - StringBuffer strBuf = new StringBuffer(); - if(!Globals.customizeFormFieldInfo() || customizedParamInfo.length()<=0) { - for (Iterator iter = paramsList.iterator(); iter.hasNext();) { - IdNameValue value = (IdNameValue) iter.next(); - //System.out.println("\"" + value.getId() + " = " + value.getName() + "\""); - if(nvl(value.getId()).trim().length()>0 && (!nvl(value.getId()).trim().equals("BLANK"))) { - paramSeq += 1; - if(paramSeq <= 1) { - row = sheet.createRow(++rowNum); - cell = row.createCell((short) 0); - sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); - cellDescr = row.createCell((short) 0); - cellDescr.setCellValue("Run-time Parameters"); - cellDescr.setCellStyle(styleDescription); - - - strBuf.append(reportTitle+"\n"); - //strBuf.append("Run-time Parameters\n"); - } - row = sheet.createRow(++rowNum); - cellNum = 0; - //System.out.println("RowNum " + rowNum + " " + value.getId() + " " +value.getName()); - cell = row.createCell((short) cellNum); - cell.setCellValue(value.getId()); - cell.setCellStyle(styleName); - cellNum += 1; - cell = row.createCell((short) cellNum); - cell.setCellValue(value.getName().replaceAll("~",",")); - cell.setCellStyle(styleValue); - - //strBuf.append(value.getId()+": "+ value.getName()+"\n"); - } - } //for + StringBuffer strBuf = new StringBuffer(); + if (!Globals.customizeFormFieldInfo() || customizedParamInfo.length() <= 0) { + for (Iterator iter = paramsList.iterator(); iter.hasNext();) { + IdNameValue value = (IdNameValue) iter.next(); + // System.out.println("\"" + value.getId() + " = " + value.getName() + "\""); + if (nvl(value.getId()).trim().length() > 0 && (!nvl(value.getId()).trim().equals("BLANK"))) { + paramSeq += 1; + if (paramSeq <= 1) { + row = sheet.createRow(++rowNum); + cell = row.createCell((short) 0); + sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); + cellDescr = row.createCell((short) 0); + cellDescr.setCellValue(RUNTIME_PARAMETERS); + cellDescr.setCellStyle(styleDescription); + + strBuf.append(reportTitle + "\n"); + } + row = sheet.createRow(++rowNum); + cellNum = 0; + cell = row.createCell((short) cellNum); + cell.setCellValue(value.getId()); + cell.setCellStyle(styleName); + cellNum += 1; + cell = row.createCell((short) cellNum); + cell.setCellValue(value.getName().replaceAll("~", ",")); + cell.setCellStyle(styleValue); + + } + } // for } else { - strBuf.append(reportTitle+"\n"); - Document document = new Document(); - document.open(); + strBuf.append(reportTitle + "\n"); + Document document = new Document(); + document.open(); HTMLWorker worker = new HTMLWorker(document); - StyleSheet style = new StyleSheet(); - style.loadTagStyle("body", "leading", "16,0"); - ArrayList p = HTMLWorker.parseToList(new StringReader(customizedParamInfo), style); - String name = ""; - String token = ""; - String value = ""; - String s = ""; - PdfPTable pdfTable = null; - for (int k = 0; k < p.size(); ++k){ - if(p.get(k) instanceof Paragraph) - s = ((Paragraph)p.get(k)).toString(); - else { /*if ((p.get(k) instanceof PdfPTable))*/ - pdfTable = ((PdfPTable)p.get(k)); - } - //todo: Logic for parsing pdfTable should be added after upgrading to iText 5.0.0 - //s = Utils.replaceInString(s, ",", "|"); - s = s.replaceAll(",", "|"); - s = s.replaceAll("~", ","); - if(s.indexOf(":")!= -1) { - //System.out.println("|"+s+"|"); - row = sheet.createRow(++rowNum); + StyleSheet style = new StyleSheet(); + style.loadTagStyle("body", "leading", "16,0"); + ArrayList p = HTMLWorker.parseToList(new StringReader(customizedParamInfo), style); + String name = ""; + String token = ""; + String value = ""; + String s = ""; + PdfPTable pdfTable = null; + for (int k = 0; k < p.size(); ++k) { + if (p.get(k) instanceof Paragraph) + s = ((Paragraph) p.get(k)).toString(); + else { /* if ((p.get(k) instanceof PdfPTable)) */ + pdfTable = ((PdfPTable) p.get(k)); + } + // todo: Logic for parsing pdfTable should be added after upgrading to iText 5.0.0 + s = s.replaceAll(",", "|"); + s = s.replaceAll("~", ","); + if (s.indexOf(":") != -1) { + // System.out.println("|"+s+"|"); + row = sheet.createRow(++rowNum); cell = row.createCell((short) 0); sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); cellDescr = row.createCell((short) 0); - cellDescr.setCellValue("Run-time Parameters"); - cellDescr.setCellStyle(styleDescription); - - //strBuf.append("Run-time Parameters\n"); - StringTokenizer st = new StringTokenizer(s.trim(), "|"); - while(st.hasMoreTokens()) { - token = st.nextToken(); - token = token.trim(); - if (!(token.trim().equals("|") || token.trim().equals("]]") || token.trim().equals("]") || token.trim().equals("[") )) { - if(token.endsWith(":")) { - name = token; - name = name.substring(0, name.length()-1); - if(name.startsWith("[")) - name = name.substring(1); - value = st.nextToken(); - if(nvl(value).endsWith("]"))value = nvl(value).substring(0, nvl(value).length()-1); - } /*else if(name != null && name.length() > 0) { - value = st.nextToken(); - if(value.endsWith("]]"))value = value.substring(0, value.length()-1); - }*/ - if(name!=null && name.trim().length()>0) { - row = sheet.createRow((short) ++rowNum); - cellNum = 0; - cell = row.createCell((short) cellNum); - cell.setCellValue(name.trim()); - cell.setCellStyle(styleName); - cellNum += 1; - cell = row.createCell((short) cellNum); - cell.setCellValue(value.trim()); - cell.setCellStyle(styleValue); - //strBuf.append(name.trim()+": "+ value.trim()+"\n"); - } -/* if(token.endsWith(":") && (value!=null && value.trim().length()<=0) && (name!=null && name.trim().length()>0 && name.endsWith(":"))) { - name = name.substring(0, name.indexOf(":")+1); - //value = token.substring(token.indexOf(":")+1); - row = sheet.createRow((short) ++rowNum); - cellNum = 0; - cell = row.createCell((short) cellNum); - cell.setCellValue(name.trim()); - cell.setCellStyle(styleName); - cellNum += 1; - cell = row.createCell((short) cellNum); - cell.setCellValue(value.trim()); - cell.setCellStyle(styleValue); - - //strBuf.append(name.trim()+": "+ value.trim()+"\n"); - value = ""; - name = ""; - } -*/ } - int cw = 0; - cw = name.trim().length() + 12; - // if(i!=cellWidth.size()-1) - if(sheet.getColumnWidth((short)0)< (short) name.trim().length()) - sheet.setColumnWidth((short)0, (short) name.trim().length()); - if(sheet.getColumnWidth((short)1)< (short) value.trim().length()) - sheet.setColumnWidth((short)1, (short) value.trim().length()); - name = ""; - value = ""; - - } - - try { - SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss"); - Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime()); - SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern()); - - row = sheet.createRow((short) ++rowNum); - cellNum = 0; - cell = row.createCell((short) cellNum); - cell.setCellValue("Report Date/Time"); - cell.setCellStyle(styleName); - cellNum += 1; - cell = row.createCell((short) cellNum); - - cell.setCellValue(dtimestamp.format(sysdate)+" "+Globals.getTimeZone()); - cell.setCellStyle(styleValue); - - } catch(Exception ex) { - //ex.printStackTrace(); - } - - - } - } - - -/* Iterator iter1 = paramsList.iterator(); - s1 = 0; s2 = (short)10; - if(iter1.hasNext()) { - row = sheet.createRow((short) ++rowNum); - cellNum = 0; - cell = row.createCell((short) cellNum); - sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); - cell.setCellValue(strip.stripHtml(customizedParamInfo)); - } -*/ -/* rowNum += 2; - row = sheet.createRow(rowNum);*/ - } // if + cellDescr.setCellValue(RUNTIME_PARAMETERS); + cellDescr.setCellStyle(styleDescription); + + StringTokenizer st = new StringTokenizer(s.trim(), "|"); + while (st.hasMoreTokens()) { + token = st.nextToken(); + token = token.trim(); + if (!(token.trim().equals("|") || token.trim().equals("]]") || token.trim().equals("]") + || token.trim().equals("["))) { + if (token.endsWith(":")) { + name = token; + name = name.substring(0, name.length() - 1); + if (name.startsWith("[")) + name = name.substring(1); + value = st.nextToken(); + if (nvl(value).endsWith("]")) + value = nvl(value).substring(0, nvl(value).length() - 1); + } /* + * else if(name != null && name.length() > 0) { value = st.nextToken(); + * if(value.endsWith("]]"))value = value.substring(0, value.length()-1); } + */ + if (name != null && name.trim().length() > 0) { + row = sheet.createRow((short) ++rowNum); + cellNum = 0; + cell = row.createCell((short) cellNum); + cell.setCellValue(name.trim()); + cell.setCellStyle(styleName); + cellNum += 1; + cell = row.createCell((short) cellNum); + cell.setCellValue(value.trim()); + cell.setCellStyle(styleValue); + // strBuf.append(name.trim()+": "+ value.trim()+"\n"); + } + /* + * if(token.endsWith(":") && (value!=null && value.trim().length()<=0) && (name!=null && + * name.trim().length()>0 && name.endsWith(":"))) { name = name.substring(0, + * name.indexOf(":")+1); //value = token.substring(token.indexOf(":")+1); row = + * sheet.createRow((short) ++rowNum); cellNum = 0; cell = row.createCell((short) cellNum); + * cell.setCellValue(name.trim()); cell.setCellStyle(styleName); cellNum += 1; cell = + * row.createCell((short) cellNum); cell.setCellValue(value.trim()); + * cell.setCellStyle(styleValue); + * + * //strBuf.append(name.trim()+": "+ value.trim()+"\n"); value = ""; name = ""; } + */ } + int cw = 0; + cw = name.trim().length() + 12; + // if(i!=cellWidth.size()-1) + if (sheet.getColumnWidth((short) 0) < (short) name.trim().length()) + sheet.setColumnWidth((short) 0, (short) name.trim().length()); + if (sheet.getColumnWidth((short) 1) < (short) value.trim().length()) + sheet.setColumnWidth((short) 1, (short) value.trim().length()); + name = ""; + value = ""; + + } + + try { + SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss"); + Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime()); + SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern()); + + row = sheet.createRow((short) ++rowNum); + cellNum = 0; + cell = row.createCell((short) cellNum); + cell.setCellValue("Report Date/Time"); + cell.setCellStyle(styleName); + cellNum += 1; + cell = row.createCell((short) cellNum); + + cell.setCellValue(dtimestamp.format(sysdate) + " " + Globals.getTimeZone()); + cell.setCellStyle(styleValue); + + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "Excetion occured", ex); + } + + } + } + + /* + * Iterator iter1 = paramsList.iterator(); s1 = 0; s2 = (short)10; if(iter1.hasNext()) { row = + * sheet.createRow((short) ++rowNum); cellNum = 0; cell = row.createCell((short) cellNum); + * sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, s1, s2)); + * cell.setCellValue(strip.stripHtml(customizedParamInfo)); } + */ + + } // if Iterator iterCheck = paramsList.iterator(); - if(iterCheck.hasNext()) { + if (iterCheck.hasNext()) { rowNum += 2; row = sheet.createRow(rowNum); } - header.setCenter(HSSFHeader.font("Tahoma", "")+ HSSFHeader.fontSize((short) font_header_title_size)+strBuf.toString()); + header.setCenter(HSSFHeader.font(FONT_TAHOMA, "") + HSSFHeader.fontSize((short) FONT_HEADER_TITLE_SIZE) + + strBuf.toString()); } - - // Trying different --> - public void createHTMLFileContent(Writer out, ReportData rd, - ReportRuntime rr, String sql_whole, HttpServletRequest request, HttpServletResponse response) - throws RaptorException, IOException { - //response.setContentType("application/vnd.ms-excel"); - //response.setHeader("Content-disposition", - // "attachment; filename=" + - // "Example.xls" ); - PrintWriter csvOut = response.getWriter(); - HtmlStripper strip = new HtmlStripper(); - ResultSet rs = null; + + // Trying different --> + public void createHTMLFileContent(Writer out, ReportData rd, + ReportRuntime rr, String sql_whole, HttpServletRequest request, HttpServletResponse response) + throws RaptorException, IOException { + + PrintWriter csvOut = response.getWriter(); + HtmlStripper strip = new HtmlStripper(); + ResultSet rs = null; Connection conn = null; Statement st = null; ResultSetMetaData rsmd = null; ColumnHeaderRow chr = null; - int mb = 1024*1024; - Runtime runtime = Runtime.getRuntime(); - csvOut.println("<HTML>\n" + + int mb = 1024 * 1024; + Runtime runtime = Runtime.getRuntime(); + csvOut.println("<HTML>\n" + "<HEAD><TITLE>" + rr.getReportName() + "</TITLE></HEAD>\n" + - "<BODY>\n" ); - System.out.println("HTML-Excel Generation Triggered: " + new java.util.Date()); - csvOut.print("<TABLE>"); + "<BODY>\n"); + System.out.println("HTML-Excel Generation Triggered: " + new java.util.Date()); + csvOut.print("<TABLE>"); if (Globals.getPrintParamsInCSVDownload()) { - ArrayList paramsList = rr.getParamNameValuePairsforPDFExcel(request, 1); + ArrayList paramsList = rr.getParamNameValuePairsforPDFExcel(request, 1); int paramSeq = 0; - for (Iterator iter = paramsList.iterator(); iter.hasNext();) { - IdNameValue value = (IdNameValue) iter.next(); - //System.out.println("\"" + value.getId() + " = " + value.getName() + "\""); - if(nvl(value.getId()).trim().length()>0 && (!nvl(value.getId()).trim().equals("BLANK"))) { - paramSeq += 1; - if(paramSeq <= 1) { - csvOut.println("<TR><TD COLSPAN=\"2\">" + "Run-time Parameters" + "</TD></TR>"); - //strBuf.append("Run-time Parameters\n"); - } - csvOut.println("<TR><TD>" + value.getId() +"</TD>"); - csvOut.println("<TD>" + value.getName().replaceAll("~",",")+ "</TD>"); - csvOut.println("</TR>"); - - //strBuf.append(value.getId()+": "+ value.getName()+"\n"); - } - } //for - csvOut.println("<TR><TD COLSPAN=\"2\"> </TD></TR>"); - csvOut.println("<TR><TD COLSPAN=\"2\"> </TD></TR>"); - System.out.println("HTML-Excel: Header Rendering complete " + new java.util.Date()); + for (Iterator iter = paramsList.iterator(); iter.hasNext();) { + IdNameValue value = (IdNameValue) iter.next(); + if (nvl(value.getId()).trim().length() > 0 && (!nvl(value.getId()).trim().equals("BLANK"))) { + paramSeq += 1; + if (paramSeq <= 1) { + csvOut.println("<TR><TD COLSPAN=\"2\">" + RUNTIME_PARAMETERS + "</TD></TR>"); + } + csvOut.println("<TR><TD>" + value.getId() + "</TD>"); + csvOut.println("<TD>" + value.getName().replaceAll("~", ",") + "</TD>"); + csvOut.println("</TR>"); + + } + } // for + csvOut.println("<TR><TD COLSPAN=\"2\"> </TD></TR>"); + csvOut.println("<TR><TD COLSPAN=\"2\"> </TD></TR>"); + System.out.println("HTML-Excel: Header Rendering complete " + new java.util.Date()); } int rowCount = 0; - if(nvl(sql_whole).length()>0) { - try { - conn = ConnectionUtils.getConnection(rr.getDbInfo()); - st = conn.createStatement(); - Log.write("[SQL] " + sql_whole, 4); - int downloadLimit = Globals.getDownloadLimit(); - Callable<ResultSet> callable = new ExecuteQuery(st, sql_whole, downloadLimit); - ExecutorService executor = new ScheduledThreadPoolExecutor(5); - System.out.println("Time Started" + new java.util.Date()); - Future<ResultSet> future = executor.submit(callable); - try { - rs = future.get(900, TimeUnit.SECONDS); - } catch (TimeoutException ex) { - System.out.println("Cancelling Query"); - st.cancel(); - System.out.println("Query Cancelled"); - throw new Exception("user requested"); - } - rsmd = rs.getMetaData(); - int numberOfColumns = rsmd.getColumnCount(); - HashMap colHash = new HashMap(); - - if(rd!=null) { - for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { - chr = rd.reportColumnHeaderRows.getNext(); - csvOut.println("<TR>"); - if(chr!=null){ - for (chr.resetNext(); chr.hasNext();) { - ColumnHeader ch = chr.getNext(); - if(ch.isVisible()) { - csvOut.print("<TD bgColor=\"8F9381\">" + ch.getColumnTitle() + "</TD>"); - //for (int i = 1; i < ch.getColSpan(); i++) - // csvOut.print(","); - - } - } // for - } - csvOut.println("</TR>"); - } // for - - - while(rs.next()) { - csvOut.println("<TR>"); -/* if(runtime.freeMemory()/mb <= ((runtime.maxMemory()/mb)*Globals.getMemoryThreshold()/100) ) { - csvOut.print(Globals.getUserDefinedMessageForMemoryLimitReached() + " " + rowCount +"records out of " + rr.getReportDataSize() + " were downloaded to CSV."); - break; - } -*/ rowCount++; - colHash = new HashMap(); - for (int i = 1; i <= numberOfColumns; i++) { - colHash.put(rsmd.getColumnName(i), rs.getString(i)); - } - for (chr.resetNext(); chr.hasNext();) { - ColumnHeader ch = chr.getNext(); - if(ch.isVisible()) { - csvOut.println("<TD>" + strip.stripCSVHtml(nvl((String)colHash.get(ch.getLinkColId().toUpperCase()))) + "</TD>"); - } - - } - csvOut.println("</TR>"); - } - System.out.println("Downloaded Rows in HTML-Excel " + rowCount + " : "+ new java.util.Date()); - if(rowCount == 0) { - csvOut.print("<TR><TD COLSPAN=\""+ numberOfColumns + "\">No Data Found</TD></TR>"); - } else { - } - } else { - csvOut.println("<TR><TD COLSPAN=\""+ numberOfColumns + "\">No Data Found</TD></TR>"); - } - csvOut.println("</TABLE></BODY>\n</HTML>"); - - } catch (SQLException ex) { - throw new RaptorException(ex); - } catch (ReportSQLException ex) { - throw new RaptorException(ex); - } catch (Exception ex) { - throw new RaptorException (ex); - } finally { - try { - if(conn!=null) - conn.close(); - if(st!=null) - st.close(); - if(rs!=null) - rs.close(); - } catch (SQLException ex) { - throw new RaptorException(ex); - } - } - //csvOut.flush(); - } else { - boolean firstPass = true; - int numberOfColumns = 0; - if(rd!=null) { - for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { - chr = rd.reportColumnHeaderRows.getNext(); - csvOut.println("<TR>"); - for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { - RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); - - if (firstPass) { - numberOfColumns++; - csvOut.print("<TD bgColor=\"8F9381\">" + rhc.getColumnTitle() + "</TD>"); - } - //csvOut.print(","); - } // for - - - for (chr.resetNext(); chr.hasNext();) { - ColumnHeader ch = chr.getNext(); - if(ch.isVisible()) { - if(firstPass) numberOfColumns++; - csvOut.print("<TD bgColor=\"8F9381\">" + ch.getColumnTitle() + "</TD>"); - //for (int i = 1; i < ch.getColSpan(); i++) - //csvOut.print(","); - } - } // for - firstPass = false; - csvOut.println("</TR>"); - } // for - - firstPass = true; - for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) { - DataRow dr = rd.reportDataRows.getNext(); - csvOut.println("<TR>"); - for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { - RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); - if (firstPass) - rhc.resetNext(); - RowHeader rh = rhc.getNext(); - - csvOut.print("<TD bgColor=\"8F9381\">" + strip.stripCSVHtml(rh.getRowTitle()) + "</TD>"); - } // for - firstPass = false; - - for (dr.resetNext(); dr.hasNext();) { - DataValue dv = dr.getNext(); - if(dv.isVisible()) - csvOut.print("<TD bgColor=\"8F9381\">" + strip.stripCSVHtml(dv.getDisplayValue()) + "</TD>"); - } // for - - csvOut.println("</TR>"); - - } // for - //csvOut.flush(); + if (nvl(sql_whole).length() > 0) { + try { + conn = ConnectionUtils.getConnection(rr.getDbInfo()); + st = conn.createStatement(); + Log.write("[SQL] " + sql_whole, 4); + int downloadLimit = Globals.getDownloadLimit(); + Callable<ResultSet> callable = new ExecuteQuery(st, sql_whole, downloadLimit); + ExecutorService executor = new ScheduledThreadPoolExecutor(5); + System.out.println("Time Started" + new java.util.Date()); + Future<ResultSet> future = executor.submit(callable); + try { + rs = future.get(900, TimeUnit.SECONDS); + } catch (TimeoutException ex) { + logger.error(EELFLoggerDelegate.errorLogger, "TimeoutException occured", ex); + logger.debug(EELFLoggerDelegate.debugLogger, "Cancelling Query"); + st.cancel(); + logger.debug(EELFLoggerDelegate.debugLogger, "Query Cancelled"); + throw new Exception("user requested"); + } + rsmd = rs.getMetaData(); + int numberOfColumns = rsmd.getColumnCount(); + HashMap colHash = new HashMap(); + + if (rd != null) { + for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { + chr = rd.reportColumnHeaderRows.getNext(); + csvOut.println("<TR>"); + if (chr != null) { + for (chr.resetNext(); chr.hasNext();) { + ColumnHeader ch = chr.getNext(); + if (ch.isVisible()) { + csvOut.print("<TD bgColor=\"8F9381\">" + ch.getColumnTitle() + "</TD>"); + + } + } // for + } + csvOut.println("</TR>"); + } // for + + while (rs.next()) { + csvOut.println("<TR>"); + /* + * if(runtime.freeMemory()/mb <= ((runtime.maxMemory()/mb)*Globals.getMemoryThreshold()/100) ) { + * csvOut.print(Globals.getUserDefinedMessageForMemoryLimitReached() + " " + rowCount + * +"records out of " + rr.getReportDataSize() + " were downloaded to CSV."); break; } + */ rowCount++; + colHash = new HashMap(); + for (int i = 1; i <= numberOfColumns; i++) { + colHash.put(rsmd.getColumnName(i), rs.getString(i)); + } + if (chr != null) { + for (chr.resetNext(); chr.hasNext();) { + ColumnHeader ch = chr.getNext(); + if (ch.isVisible()) { + csvOut.println("<TD>" + + strip.stripCSVHtml( + nvl((String) colHash.get(ch.getLinkColId().toUpperCase()))) + + "</TD>"); + } + + } + } + csvOut.println("</TR>"); + } + System.out.println("Downloaded Rows in HTML-Excel " + rowCount + " : " + new java.util.Date()); + if (rowCount == 0) { + csvOut.print("<TR><TD COLSPAN=\"" + numberOfColumns + "\">No Data Found</TD></TR>"); + } else { + } + } else { + csvOut.println("<TR><TD COLSPAN=\"" + numberOfColumns + "\">No Data Found</TD></TR>"); + } + csvOut.println("</TABLE></BODY>\n</HTML>"); + + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occured", ex); + throw new RaptorException(ex); + } finally { + try { + if (conn != null) + conn.close(); + if (st != null) + st.close(); + if (rs != null) + rs.close(); + } catch (SQLException ex) { + logger.error(EELFLoggerDelegate.errorLogger, "SQLException occured", ex); + } + } + // csvOut.flush(); } else { - csvOut.println("<TR><TD COLSPAN=\""+ numberOfColumns + "\">No Data Found</TD></TR>"); + boolean firstPass = true; + int numberOfColumns = 0; + if (rd != null) { + for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) { + chr = rd.reportColumnHeaderRows.getNext(); + csvOut.println("<TR>"); + for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + + if (firstPass) { + numberOfColumns++; + csvOut.print("<TD bgColor=\"8F9381\">" + rhc.getColumnTitle() + "</TD>"); + } + // csvOut.print(","); + } // for + + for (chr.resetNext(); chr.hasNext();) { + ColumnHeader ch = chr.getNext(); + if (ch.isVisible()) { + if (firstPass) + numberOfColumns++; + csvOut.print("<TD bgColor=\"8F9381\">" + ch.getColumnTitle() + "</TD>"); + // for (int i = 1; i < ch.getColSpan(); i++) + // csvOut.print(","); + } + } // for + firstPass = false; + csvOut.println("</TR>"); + } // for + + firstPass = true; + for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) { + DataRow dr = rd.reportDataRows.getNext(); + csvOut.println("<TR>"); + for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) { + RowHeaderCol rhc = rd.reportRowHeaderCols.getNext(); + if (firstPass) + rhc.resetNext(); + RowHeader rh = rhc.getNext(); + + csvOut.print("<TD bgColor=\"8F9381\">" + strip.stripCSVHtml(rh.getRowTitle()) + "</TD>"); + } // for + firstPass = false; + + for (dr.resetNext(); dr.hasNext();) { + DataValue dv = dr.getNext(); + if (dv.isVisible()) + csvOut.print( + "<TD bgColor=\"8F9381\">" + strip.stripCSVHtml(dv.getDisplayValue()) + "</TD>"); + } // for + + csvOut.println("</TR>"); + + } // for + // csvOut.flush(); + } else { + csvOut.println("<TR><TD COLSPAN=\"" + numberOfColumns + "\">No Data Found</TD></TR>"); + } } - } - csvOut.println("</TABLE></BODY>\n</HTML>"); - System.out.println("HTML-Excel Generation: Data Rendering complete " + new java.util.Date()); - System.out.println("##### Heap utilization statistics [MB] #####"); - System.out.println("Used Memory:" - + (runtime.maxMemory() - runtime.freeMemory()) / mb); - System.out.println("Free Memory:" - + runtime.freeMemory() / mb); - System.out.println("Total Memory:" + runtime.totalMemory() / mb); - System.out.println("Max Memory:" + runtime.maxMemory() / mb); - - } // createCSVFileContent - - /** - * Checking if every row and cell in merging region exists, and create those which are not - * @param sheet in which check is performed - * @param region to check - * @param cellStyle cell style to apply for whole region - */ - private void cleanBeforeMergeOnValidCells(XSSFSheet sheet,CellRangeAddress region, XSSFCellStyle cellStyle ) - { - for(int rowNum =region.getFirstRow();rowNum<=region.getLastRow();rowNum++){ - XSSFRow row= sheet.getRow(rowNum); - if(row==null){ - sheet.createRow(rowNum); - } - if(row!=null){ - for(int colNum=region.getFirstColumn();colNum<=region.getLastColumn();colNum++){ - XSSFCell currentCell = row.getCell(colNum); - if(currentCell==null){ - currentCell = row.createCell(colNum); - } - - currentCell.setCellStyle(cellStyle); - - } - } - - } + csvOut.println("</TABLE></BODY>\n</HTML>"); + System.out.println("HTML-Excel Generation: Data Rendering complete " + new java.util.Date()); + System.out.println("##### Heap utilization statistics [MB] #####"); + System.out.println("Used Memory:" + + (runtime.maxMemory() - runtime.freeMemory()) / mb); + System.out.println("Free Memory:" + + runtime.freeMemory() / mb); + System.out.println("Total Memory:" + runtime.totalMemory() / mb); + System.out.println("Max Memory:" + runtime.maxMemory() / mb); + } // createCSVFileContent - } + /** + * Checking if every row and cell in merging region exists, and create those which are not + * + * @param sheet in which check is performed + * @param region to check + * @param cellStyle cell style to apply for whole region + */ + private void cleanBeforeMergeOnValidCells(XSSFSheet sheet, CellRangeAddress region, XSSFCellStyle cellStyle) { + for (int rowNum = region.getFirstRow(); rowNum <= region.getLastRow(); rowNum++) { + XSSFRow row = sheet.getRow(rowNum); + if (row == null) { + sheet.createRow(rowNum); + } + if (row != null) { + for (int colNum = region.getFirstColumn(); colNum <= region.getLastColumn(); colNum++) { + XSSFCell currentCell = row.getCell(colNum); + if (currentCell == null) { + currentCell = row.createCell(colNum); + } + currentCell.setCellStyle(cellStyle); + } + } + } + } } // ReportHandler diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/base/IdNameList.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/base/IdNameList.java index 8f44e37b..154c94b4 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/base/IdNameList.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/base/IdNameList.java @@ -176,20 +176,6 @@ public class IdNameList extends Vector { public void loadData(String pageNo, String searchString, String dbInfo) throws RaptorException {} private void loadData(int pageNo, String searchString, String dbInfo) throws RaptorException {} -/* - public void loadData(int pageNo, String dbInfo) throws RaptorException { - } - - public void loadUserData(int pageNo, String dbInfo, String userId) throws RaptorException { - } - - - - - public void loadData(String pageNo, String searchString) throws RaptorException { - } - -*/ protected static String nvl(String s) { return (s == null) ? "" : s; } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/base/IdNameLookup.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/base/IdNameLookup.java index f2a15f43..590fd1aa 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/base/IdNameLookup.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/base/IdNameLookup.java @@ -60,29 +60,6 @@ public class IdNameLookup extends IdNameSql { this(dbTableName, dbIdField, dbNameField, null, "", false); } // IdNameLookup -/* public IdNameLookup(String dbTableName, String dbIdField, String dbNameField, - String dbSortByField) { - super(); - - setDbTableName(dbTableName); - setDbIdField(dbIdField); - setDbNameField(dbNameField); - setDbSortByField(dbSortByField); - updateParentSQL(); - } // IdNameLookup - - public IdNameLookup(String dbTableName, String dbIdField, String dbNameField, - String dbSortByField, String defaultSQL) { - super(); - - setDbTableName(dbTableName); - setDbIdField(dbIdField); - setDbNameField(dbNameField); - setDbSortByField(dbSortByField); - setDefaultSQL(defaultSQL); - updateParentSQL(); - } // IdNameLookup -*/ public IdNameLookup(String dbTableName, String dbIdField, String dbNameField, String dbSortByField, boolean textField) { super(); @@ -153,10 +130,6 @@ public class IdNameLookup extends IdNameSql { dbSortByField.indexOf(' ')) : dbSortByField) + " sort"; setSqlNoOrderBy(sql_start + sql_middle + sql_end); -// System.out.println("SQL Start " + sql_start); -// System.out.println("SQL Middle " + sql_middle); -// System.out.println("SQL End " + sql_end); -// System.out.println("DbSortByField " + dbSortByField); setSql(sql_start + sql_middle + sql_end + " ORDER BY " + nvl(dbSortByField, "2")); } // updateParentSQL @@ -173,16 +146,6 @@ public class IdNameLookup extends IdNameSql { return "SELECT " + dbIdField + " FROM " + dbTableName; } // getBaseSQL - /* - public void loadData(int pageNo) throws RaptorException { - loadData(pageNo, ""); - } // loadData - - public void loadData(String pageNo) throws RaptorException { - loadData(pageNo, ""); - } // loadData -*/ - public void loadData(String pageNo, String searchString, String dbInfo) throws RaptorException { int iPageNo = 0; diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/pdf/PdfReportHandler.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/pdf/PdfReportHandler.java index d77e6bc7..1ff21200 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/pdf/PdfReportHandler.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/pdf/PdfReportHandler.java @@ -200,7 +200,6 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ reportDisplayTypeMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP); if(reportRuntimeMap!=null) { - //ServletOutputStream sos = response.getOutputStream(); Set setReportRuntime = reportRuntimeMap.entrySet(); Set setReportDataMap = reportDataMap.entrySet(); Set setReportDisplayTypeMap = reportDisplayTypeMap.entrySet(); @@ -213,7 +212,6 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ Map.Entry entryData = (Entry) iter2.next(); Map.Entry entry = (Entry) iter.next(); Map.Entry entryCheckChart = (Entry) iter3.next(); - //String rep_id = (String) entry.getKey(); ReportRuntime rrDashRep = (ReportRuntime) entry.getValue(); if(count == 1) { @@ -224,7 +222,6 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ } ReportData rdDashRep = (ReportData) entryData.getValue(); int col = 0; - //pb.setDisplayChart(nvl(rr.getChartType()).trim().length()>0 && rr.getDisplayChart()); if( ((rrDashRep.getChartType()).trim().length()>0 && rrDashRep.getDisplayChart()) && entryCheckChart.getValue().toString().equals("c")) { document.newPage(); pb.setTitle(nvl(rrDashRep.getReportTitle()).length()>0?rrDashRep.getReportTitle():rrDashRep.getReportName()); @@ -244,9 +241,6 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ logger.error(EELFLoggerDelegate.errorLogger, "RaptorException in createPdfFileContent", rex); } } else { - - //ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); - //ReportData rd = (ReportData) request.getSession().getAttribute(AppConstants.RI_REPORT_DATA); rr = null; ReportData rd = null; String parent = ""; @@ -267,7 +261,6 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ pb = preparePdfBean(request,rr); FONT_FAMILY = rr.getPDFFont(); FONT_SIZE = rr.getPDFFontSize(); - //System.out.println(pb); formattedReportName = new HtmlStripper().stripSpecialCharacters(rr.getReportName()); @@ -290,18 +283,14 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ writer.setPageEvent(new PageEvent(pb));//header,footer,bookmark document.open(); - //System.out.println("Document 1 " + document); if(pb.isCoverPageIncluded()) { document = paintCoverPage(document, rr, request); } - - //boolean isImageRotate = false; - //System.out.println("Document 2 " + document); + if(pb.isDisplayChart()) { paintPdfImage(request, document,AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+".png", rr); } - //System.out.println("Document 4" + document); document.newPage(); if(type == 3 && rr.getSemaphoreList()==null && !(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) ) { //type = 3 is whole @@ -310,7 +299,6 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ } else if(type == 2) { returnValue = paintPdfData(request, document, rd, rr, ""); } else { - //String sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE); int downloadLimit = (rr.getMaxRowsInExcelDownload()>0)?rr.getMaxRowsInExcelDownload():Globals.getDownloadLimit(); String action = request.getParameter(AppConstants.RI_ACTION); @@ -326,9 +314,6 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ } - - //paintPdfData(document,rd,rr); - } catch (DocumentException de) { logger.error(EELFLoggerDelegate.errorLogger, "DocumentException in createPdfFileContent", de); @@ -350,7 +335,6 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ private Document paintCoverPage(Document doc, ReportRuntime rr, HttpServletRequest request) throws IOException, DocumentException { - //System.out.println("PDFREPORTHANDLER STARTED ... " ); if(nvl(rr.getPdfImg()).length()>0) { Image image1 = Image.getInstance(AppUtils.getExcelTemplatePath()+"../../"+AppUtils.getImgFolderURL()+rr.getPdfImg()); image1.scalePercent(20f, 20f); @@ -411,7 +395,6 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ Iterator it = al.iterator(); addEmptyRows(table,1); - //if(!Globals.customizeFormFieldInfo()) { if(rr.getFormFieldComments(request).length()<=0) { while(it.hasNext()) { @@ -422,9 +405,7 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ IdNameValue value = (IdNameValue)it.next(); if(!value.getId().trim().equals("BLANK")) - //System.out.println("PDFREPORTHANDLER " + value.getId()+" : "+value.getName()); add2Cells(table, value.getId()+" : ",value.getName().replaceAll("~",",")); - //add2Cells(table, rr.getFormFieldComments(request), " "); } addEmptyRows(table,1); doc.add(table); @@ -432,10 +413,8 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ } else { it = al.iterator(); if(it.hasNext()) { - //add2Cells(table, "Run-time Criteria : ", " "); addEmptyRows(table,1); doc.add(table); - //com.lowagie.text.html.HtmlParser.parse(doc, new StringReader(rr.getFormFieldComments(request))); ArrayList p = HTMLWorker.parseToList(new StringReader(rr.getFormFieldComments(request).replaceAll("~",",")), style); for (int k = 0; k < p.size(); ++k){ @@ -450,7 +429,6 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ private Document paintDashboardCoverPage(Document doc, ReportRuntime rrDashRep, ReportRuntime firstReportRuntimeObj, HttpServletRequest request) throws IOException, DocumentException { - //System.out.println("PDFREPORTHANDLER STARTED ... " ); float firstColumnSize = Globals.getCoverPageFirstColumnSize(); float[] relativeWidths = {firstColumnSize,1f-firstColumnSize}; PdfPTable table = new PdfPTable(relativeWidths); @@ -481,7 +459,6 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ ArrayList al = firstReportRuntimeObj.getParamNameValuePairsforPDFExcel(request, 2); Iterator it = al.iterator(); addEmptyRows(table,1); - //if(!Globals.customizeFormFieldInfo()) { if(firstReportRuntimeObj.getFormFieldComments(request).length()<=0) { while(it.hasNext()) { @@ -492,9 +469,7 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ IdNameValue value = (IdNameValue)it.next(); if(!value.getId().trim().equals("BLANK")) - //System.out.println("PDFREPORTHANDLER " + value.getId()+" : "+value.getName()); add2Cells(table, value.getId()+" : ",value.getName()); - //add2Cells(table, rr.getFormFieldComments(request), " "); } addEmptyRows(table,1); doc.add(table); @@ -502,10 +477,8 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ } else { it = al.iterator(); if(it.hasNext()) { - //add2Cells(table, "Run-time Criteria : ", " "); addEmptyRows(table,1); doc.add(table); - //com.lowagie.text.html.HtmlParser.parse(doc, new StringReader(rr.getFormFieldComments(request))); HTMLWorker worker = new HTMLWorker(doc); StyleSheet style = new StyleSheet(); style.loadTagStyle("body", "leading", "16,0"); @@ -547,7 +520,6 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ { ArrayList images = getImage(request, fileName,pb.isAttachmentOfEmail()?true:false, rr); - //Image image = getImage(request, fileName,pb.isAttachmentOfEmail()?true:false); PdfPTable table = null; PdfPCell cellValue = null; if(images!=null) { @@ -558,16 +530,12 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ cellValue.setHorizontalAlignment(Rectangle.ALIGN_CENTER); Image image = (Image) images.get(i); image.setAlignment(Image.ALIGN_CENTER); - //System.out.println("Document 3 " + document + " i-" + i); if(i%2 ==0) document.newPage(); - //System.out.println("Document 31 " + document); cellValue.setImage(image); //table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER); table.addCell(cellValue); - //System.out.println("Document 32 " + document + "table " + table); document.add(table); - //System.out.println("Document 33 " + document); } } } @@ -599,7 +567,6 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ if(isGenerateNewImage && retryCreateNewImageCount<RetryCreateNewImage){ retryCreateNewImageCount++; return generateNewImage(request, rr); - //return getImage(request,fileName, false); } return null; @@ -692,31 +659,7 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():""; chartTitle = rr.getFormFieldFilled(chartTitle); downloadFileName = AppUtils.getTempFolderPath()+"cr_"+pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png"; - filename = null;/*(String) ChartGen.generateChart( chartType, - request.getSession(), - ds, - legendColumnName, - chartLeftAxisLabel, - chartRightAxisLabel, - rr.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i, i+1), - rr.getChartColumnColorsList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i, i+1), - rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i, i+1), - "", - chartTitle, - null, - rr.getChartWidthAsInt(), - rr.getChartHeightAsInt(), - rr.getChartValueColumnsList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i,i+1), - rr.hasSeriesColumn(), - //rr.isChartMultiSeries(), - rr.isMultiSeries(), - rr.getAllColumns(), - downloadFileName, - totalOnChart, - AppConstants.WEB_VERSION deviceType, - additionalChartOptionsMap, - true - );*/ + filename = null; try { Image image = Image.getInstance(downloadFileName); images.add(image); @@ -740,60 +683,25 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ for (int i=0; i<lGroups.size();i++) { String chartGroupOrg = (String) lGroups.get(i); String chartYAxis = (String) mapYAxis.get(chartGroupOrg); - //System.out.println("chartGroupOrg " + chartGroupOrg); if(nvl(chartGroupOrg).length()>0) tempChartGroupCurrent = chartGroupOrg.substring(0,chartGroupOrg.lastIndexOf("|")); if(i>0) tempChartGroupPrev = ((String) lGroups.get(i-1)).substring(0,((String) lGroups.get(i-1)).lastIndexOf("|")); - //System.out.println("TEMPCHARTGROUP " + tempChartGroupCurrent + " " + tempChartGroupPrev); if(tempChartGroupCurrent.equals(tempChartGroupPrev)) continue; - //System.out.println("CHARTGROUPORG " + chartGroupOrg + " " + lGroups) ; - //String chartGroup = chartGroupOrg.substring(0,chartGroupOrg.lastIndexOf("|")); String chartGroup = chartGroupOrg; - //System.out.println("$$$$CHARTGROUP in JSP " +chartGroup+ " "+ chartGroupOrg ); - //System.out.println(" rr.getChartGroupDisplayNamesList(chartGroup) " + rr.getChartGroupDisplayNamesList(chartGroup)); - //System.out.println(" rr.getChartGroupColumnColorsList(chartGroup) " + rr.getChartGroupColumnColorsList(chartGroup)); - //System.out.println(" rr.getChartGroupColumnAxisList(chartGroup) " + rr.getChartGroupColumnAxisList(chartGroup)); - //System.out.println(" rr.getChartGroupValueColumnAxisList(chartGroupOrg) " + rr.getChartGroupValueColumnAxisList(chartGroupOrg)); - downloadFileName = AppUtils.getTempFolderPath()+"cr_"+pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png"; String chartTitle = (Globals.getDisplayChartTitle()? (chartGroup!=null && chartGroup.indexOf("|") > 0 ?chartGroup.substring(0,chartGroup.lastIndexOf("|")):rr.getReportName()):""); chartTitle = rr.getFormFieldFilled(chartTitle); String leftAxisLabel = ""; - //if(!rr.isChartMultiSeries()) { if(!rr.isMultiSeries()) { leftAxisLabel = ((chartYAxis!=null && chartYAxis.indexOf("|") > 0) ? chartYAxis.substring(0,chartYAxis.lastIndexOf("|")): chartLeftAxisLabel ); } else { leftAxisLabel = chartLeftAxisLabel; } - filename = null;/*(String) ChartGen.generateChart( chartType, - request.getSession(), - ds, - legendColumnName, - leftAxisLabel, - chartRightAxisLabel, - ((chartType.indexOf("Stacked")>0 || chartType.equals(AppConstants.GT_PIE_MULTIPLE) || chartType.equals(AppConstants.GT_BAR_3D))?rr.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartGroupDisplayNamesList(chartGroup, formValues)), - ((chartType.indexOf("Stacked")>0 || chartType.equals(AppConstants.GT_PIE_MULTIPLE) || chartType.equals(AppConstants.GT_BAR_3D))?rr.getChartColumnColorsList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartGroupColumnColorsList(chartGroup, formValues)), - ((chartType.indexOf("Stacked")>0 || chartType.equals(AppConstants.GT_PIE_MULTIPLE) || chartType.equals(AppConstants.GT_BAR_3D))?rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartGroupValueColumnAxisList(chartGroupOrg, formValues)), - "", - chartTitle, - null, - rr.getChartWidthAsInt(), - rr.getChartHeightAsInt(), - ((chartType.indexOf("Stacked")>0 || chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues):rr.getChartGroupValueColumnAxisList(chartGroupOrg, formValues)), - rr.hasSeriesColumn(), - //rr.isChartMultiSeries(), - rr.isMultiSeries(), - rr.getAllColumns(), - downloadFileName, - totalOnChart, - AppConstants.WEB_VERSION deviceType, - additionalChartOptionsMap, - true - );*/ + filename = null; try { Image image = Image.getInstance(downloadFileName); images.add(image); @@ -813,9 +721,6 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ if(!chartType.equals(AppConstants.GT_PIE_MULTIPLE)) { for (int i=0; i<rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).size();i++) { - //System.out.println(" rr.getChartDisplayNamesList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1) " + rr.getChartDisplayNamesList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1)); - //System.out.println(" rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1) " + rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1)); - //System.out.println(" rr.getChartValueColumnsList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i,i+1) " + rr.getChartValueColumnsList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i,i+1)); downloadFileName = AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png"; String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():""; @@ -924,37 +829,11 @@ public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{ } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "Exception in generateNewImage", e); } -// System.out.println("Total Images " + images.size()); return images.size()>0?images:null; } -/* - private boolean isImageRotate(Document doc, Image image) { - - System.out.println("image size="+image.getWidthPercentage()+ " "+ image.scaledWidth()+ - " "+image.scaledHeight()+" "+image.getXYRatio()); - System.out.println("page size = "+ doc.getPageSize().width() + " " +doc.getPageSize().height() +" "+ - doc.topMargin() + " " +doc.bottomMargin() + " " + doc.leftMargin() + " " + - doc.rightMargin()); - System.out.println(image.scaledWidth()/image.scaledHeight()); - System.out.println((PageEvent.getPageWidth(doc)/PageEvent.getPageHeight(doc))); -// System.out.println(doc.getPageSize().getRotation()); - - float image_w = image.scaledWidth(); - float image_h = image.scaledHeight(); - float image_ratio = image_w/image_h; - - float page_w = PageEvent.getPageWidth(doc); - float page_h = PageEvent.getPageHeight(doc); - float page_ratio = page_w/page_h; - - return (image_w > page_w && image_ratio > page_ratio) || - (image_h > page_h && image_ratio < page_ratio); - } - -*/ private final int DEFAULT_PDF_DISPLAY_WIDTH = 10; private int paintPdfData(final HttpServletRequest request, final Document document, final ReportData rd, diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartD3Helper.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartD3Helper.java index ff8094fd..dd063554 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartD3Helper.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartD3Helper.java @@ -278,13 +278,11 @@ public class ChartD3Helper { } } - //Object uniqueElements [] = ts.toArray(); - //SortedSet s = Collections.synchronizedSortedSet(ts); uniqueElements = ts.toArray(); } else { DataColumnType dct = null; List yTextSeries = reportRuntime.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues); - //if(columnValuesList.size() == 1) { + for (Iterator iter = l.iterator(); iter.hasNext();) { dct = (DataColumnType) iter.next(); @@ -307,19 +305,10 @@ public class ChartD3Helper { chartLeftAxisLabel = (chartLeftAxisLabel.indexOf("|")!=-1)?chartLeftAxisLabel.substring(0,chartLeftAxisLabel.indexOf("|")):""; } columnMap.put(dct.getDisplayName(), dct.getColId()); - /* - 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()); - */ } } } - //SortedSet s = Collections.synchronizedSortedSet(ts); uniqueElements = ts.toArray(); } @@ -373,13 +362,10 @@ public class ChartD3Helper { wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/tooltip.js\"></script> \n"); wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/utils.js\"></script> \n"); wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/axis.min.js\"></script> \n"); - //wholeScript.append("<script src=\""+ AppUtils.getBaseFolderURL() +"d3/js/models/discreteBar.js\"></script> \n"); - //wholeScript.append("<script src=\""+ AppUtils.getBaseFolderURL() +"d3/js/models/discreteBarChart.js\"></script> \n"); wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/multiChart.js\"></script> \n"); //json wholeScript.append("<script> \n"); wholeScript.append("historicalBarChart = [ \n"); - //wholeScript.append("{ \n"); // data ArrayList dataSeries = new ArrayList(); @@ -453,7 +439,6 @@ public class ChartD3Helper { //continue; flagNoDate = 1; int pos = 0; - //if(!((String)uniqueElementsList.get(i)).equals(dateStr)) { for (int f=0 ; f< uniqueXAxisElements.length; f++) { if(uniqueXAxisElements[f].equals(dateStr)){ pos = f ; @@ -462,10 +447,9 @@ public class ChartD3Helper { } dateStrList.add("'"+dateStr+"'"); - //uniqueElement = (String)uniqueElements[j]; try { YAXISNUM = Integer.parseInt(ds.getString(i, columnMap.get((hasCustomizedChartColor?(uniqueElement.indexOf("|")!=-1?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement):uniqueElement)))); - //if(MAXNUM < YAXISNUM) MAXNUM = YAXISNUM; + if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM; } catch (NumberFormatException ex) { @@ -571,7 +555,6 @@ public class ChartD3Helper { //continue; flagNoDate = 1; int pos = 0; - //if(!((String)uniqueElementsList.get(i)).equals(dateStr)) { for (int f=0 ; f< uniqueXAxisElements.length; f++) { if(uniqueXAxisElements[f].equals(dateStr)){ pos = f ; @@ -622,7 +605,6 @@ public class ChartD3Helper { } dataSeriesOverAllMap.put(uniqueElements[j], dataSeriesStrMap); } else { - //date = MMDDYYYYFormat.parse(ds.getString(i, 1), new ParsePosition(0)); if(!barRealTimeAxis) { // true - non-time if(!dateStrList.contains(new Long(date.getTime()).toString())) { dateStrList.add(new Long(date.getTime()).toString()); @@ -652,8 +634,6 @@ public class ChartD3Helper { //flagNull = 1; } - //if(ds.getString(i, 2).equals(uniqueElements[j])) { - // dateStrList.add("'"+dateStr+"'"); HashMap<String, String> dataMap = dataSeriesMap.get((String) uniqueElements[j]); if(logScale) { 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")); @@ -662,9 +642,7 @@ public class ChartD3Helper { dataMap.remove(date.getTime()); } dataMap.put(date.getTime()+"", (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(YAXISDOUBLENUM).toString():new Integer(YAXISNUM).toString()): "null")); - //System.out - // .println(dataMap + " " + dataSeriesMap); - //} + } } else if (AppUtils.nvl(ds.getString(i, 2)).length()<=0) { @@ -681,7 +659,6 @@ public class ChartD3Helper { } } } - // dataSeriesOverAllMap.put(uniqueElements[j], dataSeriesMap); } } @@ -719,19 +696,13 @@ public class ChartD3Helper { Long endDate = Long.parseLong((String) dateElements[dateElements.length-1]); java.util.Date date1 = null; //first value - date1 = new java.util.Date(initialDate.longValue()); - /* DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss Z"); - System.out.println(formatter.format(new java.util.Date(initialDate.longValue()))); - */ //initialDate = initialDate + HOUR; - + date1 = new java.util.Date(initialDate.longValue()); dateStrBuf.append(initialDate+","); sortSet.add(""+initialDate); // DateUtils. while ( initialDate <= endDate) { - //System.out.println("********** " + df.format(initialDate)); - //date1 = new java.util.Date(initialDate.longValue() * 1000); date1 = new java.util.Date(initialDate.longValue()); if(formatFlag==HOURFLAG) date1 = DateUtils.addHours(date1, 1); @@ -749,13 +720,7 @@ public class ChartD3Helper { dateStrBuf.append(initialDate+","); sortSet.add(""+initialDate); } - //DateUtils.addHours(date1, 1); - } - //DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); - //df.setTimeZone(TimeZone.getTimeZone("UTC")); - //java.util.Date date1 = new java.util.Date(initialDate.longValue() * 1000); - //java.util.Date d = df. - //for () + } } } dateStrBuf.deleteCharAt(dateStrBuf.length()-1); @@ -1230,16 +1195,7 @@ public class ChartD3Helper { } } - /*StringBuffer dataSeries1 = new StringBuffer(""); - dataSeries1.append(" { key: \"Series1\",values: ["); - StringBuffer dataSeries2 = new StringBuffer(""); - dataSeries2.append(" { key: \"Series2\", values: ["); - StringBuffer dataSeries3 = new StringBuffer(""); - dataSeries3.append(" { key: \"Series3\", values: ["); - */ - - //long minTime = 1000000000000000L; int MAXNUM = 0; double MAXDOUBLENUM = 0.0; int YAXISNUM = 0; @@ -1449,17 +1405,9 @@ public class ChartD3Helper { } } - // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + minTime + " , \"y\":" + 0 +"}, "); } -/* if(ds.getString(i, 2).equals("Series1")) { - dataSeries1.append("[ " + date.getTime() + " , " + ds.getString(i, 3) +"], "); - } else if (ds.getString(i, 2).equals("Series2")) { - dataSeries2.append("[ " + date.getTime() + " , " + ds.getString(i, 3) +"], "); - } else if (ds.getString(i, 2).equals("Series3")) { - dataSeries3.append("[ " + date.getTime() + " , " + ds.getString(i, 3) +"], "); - } -*/ } + } for (int i = 0; i < uniqueRevElements.length; i++) { StringBuffer strBuf = ((StringBuffer) dataSeries.get(i)); @@ -1475,10 +1423,8 @@ public class ChartD3Helper { for (int i = 0; i < uniqueRevElements.length; i++) { wholeScript.append((StringBuffer)dataSeries.get(i)); } -/* wholeScript.append(dataSeries1); - wholeScript.append(dataSeries2); - wholeScript.append(dataSeries3); -*/ wholeScript.append("];\n"); + + wholeScript.append("];\n"); /* Sorting is commented out.*/ StringBuffer dateStrBuf = new StringBuffer(""); @@ -1911,12 +1857,7 @@ public class ChartD3Helper { columnValues.add(AppUtils.nvls(ds.getString(i, columnIndex), "null")); } } -/* actual = ds.getString(i, "actual"); - //forecast = ds.getString(i, "forecast"); - upperBound = ds.getString(i, "upperBound"); - lowerBound = ds.getString(i, "lowerBound"); - -*/ if(!timeCharts) + if(!timeCharts) anomalyText = ds.getString(i, "anomaly_text"); //dataStrBuf.append(" [new Date(moment(\""+dateStr+"\")),"+ actual /*+","+ forecast*/+","+ lowerBound +","+ upperBound +"],\n"); dataStrBuf.append(" [new Date(moment(\""+dateStr+"\"))"); @@ -1952,9 +1893,7 @@ public class ChartD3Helper { } } - - //if(!timeCharts) - //anomalyRec = anomalyRec - 1; + 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()); @@ -1965,7 +1904,6 @@ public class ChartD3Helper { wholeScript.append("<!DOCTYPE html>\n"); wholeScript.append("<html>\n"); wholeScript.append(" <head>\n"); - //wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7; IE=EmulateIE9\">\n"); wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n"); wholeScript.append("<script type=\"text/javascript\" src=\""+ chartScriptsPath +"dy3/js/dygraph-combined.js\"></script>\n"); wholeScript.append("<script type=\"text/javascript\" src=\""+ chartScriptsPath +"dy3/js/moment.min.js\"></script>\n"); @@ -2185,8 +2123,6 @@ public class ChartD3Helper { if(!timeCharts) { wholeScript.append(" function nameAnnotation(ann) { \n"); wholeScript.append(" return ann.shortText; \n"); - //wholeScript.append(" var m = moment(ann.x);\n"); - //wholeScript.append(" return \"(\" + ann.series + \", \" + m.format(\"YYYY-MM-DD HH\"); + \")\"; \n"); wholeScript.append(" }\n"); wholeScript.append(" anns = [];\n"); } @@ -2195,9 +2131,6 @@ public class ChartD3Helper { wholeScript.append(" g = new Dygraph(\n"); wholeScript.append(" document.getElementById(\"div_g"+reportRuntime.getReportID()+"\"),\n"); //data here - /*wholeScript.append(" [\n"); - wholeScript.append(dataStrBuf.toString()); - wholeScript.append(" ],\n");*/ wholeScript.append(" data , \n"); wholeScript.append(" {\n"); @@ -2242,16 +2175,8 @@ public class ChartD3Helper { wholeScript.append(" var minutes = d.getMinutes();\n"); wholeScript.append(" var seconds = d.getSeconds();\n"); wholeScript.append(" var wholeString = Dygraph.zeropad(month)+'/'+Dygraph.zeropad(day);\n"); - // wholeScript.append(" if(hour >= 0 && minutes > 0 && seconds > 0) {\n"); - //wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes)+':'+Dygraph.zeropad(seconds);\n"); - //wholeScript.append(" } else if (hour >= 0 && minutes > 0 && seconds == 0) {\n"); if(AppUtils.nvl(reportRuntime.getTimeAxisType()).length()==0 || AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes);\n"); - //wholeScript.append(" } else if (hour >= 0 && (minutes >= 0 && seconds > 0)) {\n"); - //wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes)+':'+Dygraph.zeropad(seconds);\n"); - //wholeScript.append(" } else if (hour >= 0) { \n"); - //wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour); \n"); - //wholeScript.append(" } \n"); wholeScript.append(" return wholeString; \n"); wholeScript.append(" },\n"); wholeScript.append(" ticker: function (a, b, pixels, opts, dygraph, vals) { \n "); @@ -2280,15 +2205,6 @@ public class ChartD3Helper { wholeScript.append(" touchstart : newDygraphTouchstart,\n"); wholeScript.append(" touchend : Dygraph.defaultInteractionModel.touchend,\n"); wholeScript.append(" touchmove : Dygraph.defaultInteractionModel.touchmove\n"); - //wholeScript.append(" 'dblclick' : dblClickV3,\n"); - //wholeScript.append(" 'mousewheel' : scrollV3\n"); - - /*wholeScript.append(" 'mousedown' : downV3,\n"); - wholeScript.append(" 'mousemove' : moveV3,\n"); - wholeScript.append(" 'mouseup' : upV3,\n"); - wholeScript.append(" 'click' : clickV3,\n"); - wholeScript.append(" 'dblclick' : dblClickV3,\n"); - wholeScript.append(" 'mousewheel' : scrollV3\n");*/ wholeScript.append("},\n"); /*wholeScript.append(" zoomCallback: function(minDate, maxDate, yRanges) { \n"); if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) { diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartJSON.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartJSON.java index cbb06c77..f3066f96 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartJSON.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartJSON.java @@ -33,7 +33,6 @@ * * ============LICENSE_END============================================ * - * */ package org.onap.portalsdk.analytics.model.runtime; @@ -43,15 +42,7 @@ class Row { private String displayValue; private String dataType; private String colId; - //private boolean visible; - - /*public boolean isVisible() { - return visible; - } - public void setVisible(boolean visible) { - this.visible = visible; - }*/ public String getDisplayValue() { return displayValue; } @@ -153,24 +144,6 @@ public class ChartJSON { private String secondaryAxisLabel; private String minRange; private String maxRange; - //private int topMargin; - //private int bottomMargin; - //private int leftMargin; - //private int rightMargin; - - /*private boolean showMaxMin; - private boolean showLegend; - private boolean showControls; - private String topMargin; - private String bottomMargin; - private String leftMargin; - private String rightMargin; - private String subType; - private boolean stacked; - private boolean horizontalBar; - private boolean barRealTimeAxis; - private boolean barReduceXAxisLabels; - private boolean timeAxis;*/ public String getReportID() { return reportID; @@ -268,85 +241,7 @@ public class ChartJSON { public void setShowTitle(boolean showTitle) { this.showTitle = showTitle; } - /*public boolean isShowMaxMin() { - return showMaxMin; - } - public void setShowMaxMin(boolean showMaxMin) { - this.showMaxMin = showMaxMin; - } - public boolean isShowLegend() { - return showLegend; - } - public void setShowLegend(boolean showLegend) { - this.showLegend = showLegend; - } - public boolean isShowControls() { - return showControls; - } - public void setShowControls(boolean showControls) { - this.showControls = showControls; - } - public String getTopMargin() { - return topMargin; - } - public void setTopMargin(String topMargin) { - this.topMargin = topMargin; - } - public String getBottomMargin() { - return bottomMargin; - } - public void setBottomMargin(String bottomMargin) { - this.bottomMargin = bottomMargin; - } - public String getLeftMargin() { - return leftMargin; - } - public void setLeftMargin(String leftMargin) { - this.leftMargin = leftMargin; - } - public String getRightMargin() { - return rightMargin; - } - public void setRightMargin(String rightMargin) { - this.rightMargin = rightMargin; - } - - public String getSubType() { - return subType; - } - public void setSubType(String subType) { - this.subType = subType; - } - public boolean isStacked() { - return stacked; - } - public void setStacked(boolean stacked) { - this.stacked = stacked; - } - public boolean isHorizontalBar() { - return horizontalBar; - } - public void setHorizontalBar(boolean horizontalBar) { - this.horizontalBar = horizontalBar; - } - public boolean isBarRealTimeAxis() { - return barRealTimeAxis; - } - public void setBarRealTimeAxis(boolean barRealTimeAxis) { - this.barRealTimeAxis = barRealTimeAxis; - } - public boolean isBarReduceXAxisLabels() { - return barReduceXAxisLabels; - } - public void setBarReduceXAxisLabels(boolean barReduceXAxisLabels) { - this.barReduceXAxisLabels = barReduceXAxisLabels; - } - public boolean isTimeAxis() { - return timeAxis; - } - public void setTimeAxis(boolean timeAxis) { - this.timeAxis = timeAxis; - }*/ + public ChartTypeJSON getChartTypeJSON() { return chartTypeJSON; } @@ -398,12 +293,6 @@ public class ChartJSON { public void setMaxRange(String maxRange) { this.maxRange = maxRange; } - /*public ArrayList<Row> getRowList() { - return rowList; - } - public void setRowList(ArrayList<Row> rowList) { - this.rowList = rowList; - }*/ public ArrayList<ArrayList<Row>> getWholeList() { return wholeList; @@ -411,8 +300,7 @@ public class ChartJSON { public void setWholeList(ArrayList<ArrayList<Row>> wholeList) { this.wholeList = wholeList; } - //private ArrayList<ColumnHeader> reportDataColumns; - //private ArrayList<Map<String,Object>> reportDataRows; + public ArrayList<ChartColumnJSON> getChartColumnJSONList() { return chartColumnJSONList; } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartJSONHelper.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartJSONHelper.java index 0caca218..268b20cc 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartJSONHelper.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartJSONHelper.java @@ -302,7 +302,6 @@ public class ChartJSONHelper { public String generateJSON(ReportRuntime reportRuntime,Map<String, String> chartOptionsMap, HttpServletRequest request, boolean showData) throws RaptorException { - //String width, String height, boolean animation, String rotateLabels, boolean staggerLabels, boolean showMaxMin, boolean showLegend, boolean showControls, String topMargin, String bottomMargin, boolean showTitle, String subType String userId = AppUtils.getUserID(request); String width = chartOptionsMap.get("width"); String height = chartOptionsMap.get("height"); @@ -343,7 +342,6 @@ public class ChartJSONHelper { List l = reportRuntime.getAllColumns(); List lGroups = reportRuntime.getAllChartGroups(); HashMap mapYAxis = reportRuntime.getAllChartYAxis(reportRuntime.getReportParamValues()); - //ReportParamValues reportParamValues = reportRuntime.getReportParamValues(); String chartLeftAxisLabel = reportRuntime.getFormFieldFilled(nvl(reportRuntime.getChartLeftAxisLabel())); String chartRightAxisLabel = reportRuntime.getFormFieldFilled(nvl(reportRuntime.getChartRightAxisLabel())); @@ -391,7 +389,6 @@ public class ChartJSONHelper { ds = ConnectionUtils.getDataSet(reportSQL, dbInfo); } } catch (RaptorException ex) { - //throw new RaptorException("Error while loading chart data", ex); logger.error(EELFLoggerDelegate.debugLogger, ("********************************************************************************")); logger.error(EELFLoggerDelegate.debugLogger, (chartType.toUpperCase()+" - " + "Report ID : " + reportRuntime.getReportID() + " ERROR THROWN FOR GIVEN QUERY ")); logger.error(EELFLoggerDelegate.debugLogger, ("QUERY - " + reportRuntime.getWholeSQL())); @@ -400,7 +397,6 @@ public class ChartJSONHelper { } if(ds==null) { - //displayChart = false; if(chartType.equals(AppConstants.GT_ANNOTATION_CHART)) ds = new DataSet(); else @@ -468,19 +464,11 @@ public class ChartJSONHelper { categoryAxisJSON.setValue(dct.getColId()); chartJSON.setCategoryAxisJSON(categoryAxisJSON); } - //allColumns - //.add(new Item(dct.getColId(), dct.getDisplayName())); } - //chartJSON.setCategoryAxis(categoryAxis); - //chartJSON.set List<DataColumnType> chartValueCols = reportRuntime.getChartValueColumnsList(AppConstants.CHART_ALL_COLUMNS, null); DataColumnType dct_RangeAxis = null; - //int noChart = 0; - //if(chartValueCols.size()<=0) { - //chartValueCols.addAll(reportCols); - //noChart = 1; - //} + if(chartValueCols.size() <= 0) { chartValueCols = reportCols; } @@ -617,8 +605,6 @@ public class ChartJSONHelper { chartTypeJSON.setValue(chartType); chartJSON.setChartTypeJSON(chartTypeJSON); } - //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY); - //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE)); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String jsonInString = ""; @@ -681,14 +667,10 @@ public class ChartJSONHelper { //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 "); @@ -724,13 +706,9 @@ public class ChartJSONHelper { 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( @@ -739,7 +717,6 @@ public class ChartJSONHelper { } logger.debug(EELFLoggerDelegate.debugLogger, ("SQL " + reportSQL)); String legendCol = "1 a"; - // String valueCol = "1"; StringBuffer groupCol = new StringBuffer(); StringBuffer seriesCol = new StringBuffer(); StringBuffer valueCols = new StringBuffer(); @@ -749,8 +726,6 @@ public class ChartJSONHelper { 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(", "); @@ -760,18 +735,9 @@ public class ChartJSONHelper { 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(); @@ -794,7 +760,6 @@ public class ChartJSONHelper { 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 @@ -803,7 +768,6 @@ public class ChartJSONHelper { 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)) @@ -816,45 +780,14 @@ public class ChartJSONHelper { 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; @@ -863,11 +796,10 @@ public class ChartJSONHelper { 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); + pos_first_select = reportSQL.indexOf("SELECT"); 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) { @@ -891,9 +823,6 @@ public class ChartJSONHelper { } // 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()) { diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartWebRuntime.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartWebRuntime.java index d10cd1c4..63aef767 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartWebRuntime.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ChartWebRuntime.java @@ -115,12 +115,8 @@ public class ChartWebRuntime implements Serializable { logger.error(EELFLoggerDelegate.errorLogger, "RaptorException occurred in generateChart",ex); } List roleList = getRolesCommaSeperated(request); - // final Map<String, Object> params = new HashMap<String, Object>(); params.put("user_id", user_id); params.put("role_list", roleList); - // params.put("public_yn", "Y"); - - // String action = request.getParameter(AppConstants.RI_ACTION); String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID); ReportHandler rh = new ReportHandler(); @@ -131,9 +127,6 @@ public class ChartWebRuntime implements Serializable { if (rr.getReportType().equals(AppConstants.RT_HIVE)) { String sql = rr.getReportSQL(); rr.setWholeSQL(sql); - // if(genReportData) - // reportData = rr.loadHiveLinearReportData(rr.getWholeSQL(),user_id.toString(), - // 10000,request); } else { if (genReportData) reportData = rr.loadReportData(0, user_id.toString(), 10000, request, @@ -247,16 +240,6 @@ public class ChartWebRuntime implements Serializable { ? AppUtils.getRequestNvlValue(request, "precision") : "2"; - /* - * boolean animation = AppUtils.getRequestFlag(request, "animation"); boolean staggerLabels - * = AppUtils.getRequestFlag(request, "staggerLabels"); boolean showMaxMin = - * (showMaxMinStr.length()<=0)?false:Boolean.parseBoolean(showMaxMinStr); boolean - * showControls = (showControlsStr.length()<=0)?true:Boolean.parseBoolean(showControlsStr); - * boolean showLegend = - * (showLegendStr.length()<=0)?true:Boolean.parseBoolean(showLegendStr); boolean showTitle = - * (showTitleStr.length()<=0)?true:Boolean.parseBoolean(showTitleStr); boolean stacked = - * (stackedStr.length()<=0)?true:Boolean.parseBoolean(stackedStr); - */ // Add all options to Map chartOptionsMap.put("width", width); chartOptionsMap.put("height", height); @@ -293,17 +276,12 @@ public class ChartWebRuntime implements Serializable { reportRuntime.getChartType(); return drawD3Charts(chartOptionsMap, request); - // drawD3Charts(); - } else /* if (action.equals("chart.json")) */ { + } else{ reportRuntime.getChartType(); return returnChartJSON(chartOptionsMap, request, showData); - } /* - * else { - * - * return ("Internal Error Occurred."); } - */ + } } @@ -441,14 +419,6 @@ public class ChartWebRuntime implements Serializable { } - - /* - * public void drawD3Charts(HashMap<String,String> chartOptionsMap) { - * drawD3Charts(chartOptionsMap); - * - * } - */ - public String drawD3Charts(Map<String, String> chartOptionsMap, HttpServletRequest request) { ChartD3Helper chartHelper = new ChartD3Helper(reportRuntime); diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/FormField.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/FormField.java index f3633a67..49ed35b3 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/FormField.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/FormField.java @@ -142,9 +142,6 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme public static final String FFT_TEXTAREA = "TEXT"; -// Changed to "TEXT" -// public static final String FFT_TEXTAREA = "TEXTAREA"; - public static final String FFT_COMBO_BOX = "COMBO_BOX"; public static final String FFT_LIST_BOX = "LIST_BOX"; @@ -186,7 +183,6 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme boolean required, String defaultValue, String helpText, boolean visible, String dependsOn, Calendar rangeStartDate, Calendar rangeEndDate, String rangeStartDateSQL, String rangeEndDateSQL, String multiSelectListSize) { - // super(); this(fieldName, fieldDisplayName, fieldType, validationType, required, defaultValue, helpText, dependsOn, rangeStartDate, rangeEndDate, rangeStartDateSQL, rangeEndDateSQL, multiSelectListSize); setVisible(visible); @@ -251,7 +247,6 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme String rangeStartDateSQL, String rangeEndDateSQL, String multiSelectListSize) { this(fieldName, fieldDisplayName, fieldType, validationType, required, defaultValue, helpText, dependsOn, rangeStartDate, rangeEndDate, rangeStartDateSQL, rangeEndDateSQL, multiSelectListSize); - // if(dependsOn !=null){ this.dependsOn = dependsOn; }else { this.dependsOn = "" if (defaultValue != null && defaultValue.length() > 10 && defaultValue.substring(0, 10).trim().toLowerCase().startsWith("select")) { setFieldDefaultSQL(defaultValue); @@ -388,14 +383,7 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme } public String getHelpLink(String fieldName) { - // return "<a href=\"#\" onclick=\"javascript:ShowContent('" + fieldName + - // "_div')\"><img src=\""+AppUtils.getBaseFolderURL()+"images/quickhelp_dk.gif\" - // width=\"12\" height=\"12\" alt=\"\" border=\"0\" class=\"qh-element\" - // /></a>"; return ((getHelpText() != null && getHelpText().length() > 0) ? "tooltipText=\"" + getHelpText() + "\">" : ">"); - // return ((getHelpText()!=null && getHelpText().length()>0)? "<img - // src=\"static/fusion/raptor/images/quickhelp_lt.gif\" tooltipText=\""+ - // getHelpText() + "\"/>": ""); } public String getCallableAfterChainingJavascript(String fieldName, ReportRuntime rr) { @@ -459,7 +447,6 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme } if (fieldType.equals(FFT_COMBO_BOX)) { StringBuffer sb = new StringBuffer(); - // System.out.println("COMBO BOX " + fieldName); String oldSQL = ""; if (!required) sb.append("obj.options[obj.options.length] = new Option('-->select value<--','');"); @@ -467,18 +454,10 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme IdNameList lookup = getLookupList(); try { if (!hasPredefinedList) { - // if(dependsOn != null && dependsOn != "") { - // if(dependsOn != null && dependsOn != "" ) { IdNameSql lu = (IdNameSql) lookup; String SQL = ""; SQL = lu.getSql(); - /* - * if(nvl(fieldValue,"").length()<=0) SQL = lu.getSql(); else SQL = - * lu.getBaseSQLForPDFExcel(false); - */ - // System.out.println("FORMFIELD 6666667 First" + ((IdNameSql)lookup).getSql()); oldSQL = lu.getSql(); - // SQL = Utils.replaceInString(SQL, "[VALUE]", fieldValue); if (formValues != null) { Set set = formValues.entrySet(); String value = ""; @@ -502,10 +481,7 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme } lookup = new IdNameSql(-1, SQL, lu.getDefaultSQL()); } - // } lookupList = lookup; - - // } try { lookup.loadUserData(0, "", getDbInfo(), getUserId()); } catch (Exception e) { @@ -519,12 +495,6 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme for (lookup.resetNext(); lookup.hasNext();) { IdNameValue value = lookup.getNext(); if (value != null && value.getId() != null && value.getName() != null) { - /* - * if (count == 0 && required) { selectedValue = value.getId(); count++; } else - * if (nvl(fieldValue).length()>0){ if (fieldValue != null && - * fieldValue.equals(value.getId())){ selectedValue = value.getId(); } count++; - * } else { count++; } - */ if (count == 0) { if (required) { selectedValue = value.getId(); @@ -550,14 +520,12 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme } formValues.put(fieldDisplayName, selectedValue); } catch (Exception e) { - // throw new RaptorRuntimeException(e); } if (!hasPredefinedList) { if (oldSQL != null && !oldSQL.equals("")) { ((IdNameSql) lookup).setSQL(oldSQL); } } - // System.out.println("FORMFIELD 6666667 " + ((IdNameSql)lookup).getSql()); if (isVisible()) return sb.toString(); else @@ -570,16 +538,9 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme IdNameList lookup = getLookupList(); try { if (!hasPredefinedList) { - // if(dependsOn != null && dependsOn != "") { - // if(dependsOn != null && dependsOn != "" ) { IdNameSql lu = (IdNameSql) lookup; String SQL = ""; SQL = lu.getSql(); - /* - * if(nvl(fieldValue,"").length()<=0) SQL = lu.getSql(); else SQL = - * lu.getBaseSQLForPDFExcel(false); SQL = Utils.replaceInString(SQL, "[VALUE]", - * fieldValue); - */ oldSQL = lu.getSql(); if (formValues != null) { Set set = formValues.entrySet(); @@ -633,7 +594,6 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme else return ""; } else if (fieldType.equals(FFT_TEXT_W_POPUP)) { - // System.out.println("TEXT POPUP " + fieldName); String oldSQL = ""; IdNameValue idNamevalue = null; String fieldDefValue = ""; @@ -661,7 +621,6 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme } } SQL = Utils.replaceInString(SQL, "[" + entry.getKey() + "]", value); - // if(SQL.indexOf("'"+"["+entry.getKey()+"]"+"'")!=-1) { if (SQL.indexOf("'" + "[" + entry.getKey() + "]" + "'") != -1 || SQL.indexOf("'" + "[" + entry.getKey()) != -1 || SQL.indexOf(entry.getKey() + "]" + "'") != -1 @@ -698,7 +657,6 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme lookup = new IdNameSql(-1, SQL, null); } } - // lookupList = lookup; if (getFieldDefaultSQL() != null && (fieldValue == null || fieldValue.trim().equalsIgnoreCase("null") || fieldValue.trim().length() <= 0)) { @@ -739,7 +697,6 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme } } catch (Exception e) { - // throw new RaptorRuntimeException(e); } // ----- END ---// @@ -757,16 +714,9 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme } } - } catch (Exception e) { // throw new RaptorRuntimeException(e); + } catch (Exception e) { } if (isVisible()) { - /* - * return "<input type=text class=\"text\" size=30 maxlength=50 id=\"" + - * fieldName +"\" name=\"" + fieldName + "\" value=\"" + nvl(fieldDefValue) + - * "\">\n" + "<a href=\"javascript:showArgPopupNew('" + fieldName + - * "', 'document.formd." + fieldName + "')\"><img border=0 src=\"" + - * AppUtils.getImgFolderURL() + "shareicon.gif\" " + getHelpLink(fieldName); - */ return "obj.value=\"" + Utils.singleQuoteEncode(nvl(fieldDefValue)) + "\";"; } else @@ -776,11 +726,8 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme String oldSQL = ""; try { IdNameList lookup = getLookupList(); - // if(dependsOn != null && dependsOn != "") { - // if(dependsOn != null && dependsOn != "" ) { IdNameSql lu = (IdNameSql) lookup; String SQL = lu.getSql(); - // System.out.println("SQL HIDDEN 1 " + SQL); oldSQL = lu.getSql(); if (formValues != null) { Set set = formValues.entrySet(); @@ -798,14 +745,11 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme } } - // System.out.println("HIDDEN " + "["+entry.getKey()+"]" + "-" + value); SQL = Utils.replaceInString(SQL, "[" + entry.getKey() + "]", value); } lookup = new IdNameSql(-1, SQL, lu.getDefaultSQL()); } - // System.out.println("SQL HIDDEN 2 " + SQL); - // } lookupList = lookup; // } if (nvl(fieldValue).length() > 0 && (dependsOn == null || dependsOn.length() <= 0)) { @@ -815,7 +759,6 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme int iCnt = 0; for (lookup.resetNext(); lookup.hasNext(); iCnt++) { IdNameValue value = lookup.getNext(); - // System.out.println("HIDDEN " + value.getId() + " " + value.getName()); sb.append((value != null) ? "obj.value=\"" + nvl(value.getId()) + "\";" : ""); if (value.isReadOnly()) sb.append("obj.disabled=true;"); @@ -834,15 +777,12 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme if (oldSQL != null && !oldSQL.equals("")) { ((IdNameSql) lookup).setSQL(oldSQL); } - // lookup.clearData(); } catch (Exception e) { - // throw new RaptorRuntimeException(e); } // if(isVisible()) return sb.toString(); } else if (fieldType.equals(FFT_LIST_BOX)) { StringBuffer sb = new StringBuffer(); - // System.out.println("COMBO BOX " + fieldName); String oldSQL = ""; if (!required) sb.append("obj.options[obj.options.length] = new Option('-->select value<--','');"); @@ -850,18 +790,10 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme IdNameList lookup = getLookupList(); try { if (!hasPredefinedList) { - // if(dependsOn != null && dependsOn != "") { - // if(dependsOn != null && dependsOn != "" ) { IdNameSql lu = (IdNameSql) lookup; String SQL = ""; SQL = lu.getSql(); - /* - * if(nvl(fieldValue,"").length()<=0) SQL = lu.getSql(); else SQL = - * lu.getBaseSQLForPDFExcel(false); - */ - // System.out.println("FORMFIELD 6666667 First" + ((IdNameSql)lookup).getSql()); oldSQL = lu.getSql(); - // SQL = Utils.replaceInString(SQL, "[VALUE]", fieldValue); if (formValues != null) { Set set = formValues.entrySet(); String value = ""; @@ -903,12 +835,6 @@ public class FormField extends org.onap.portalsdk.analytics.RaptorObject impleme for (lookup.resetNext(); lookup.hasNext();) { IdNameValue value = lookup.getNext(); if (value != null && value.getId() != null && value.getName() != null) { - /* - * if (count == 0 && required) { selectedValue = value.getId(); count++; } else - * if (nvl(fieldValue).length()>0){ if (fieldValue != null && - * fieldValue.equals(value.getId())){ selectedValue = value.getId(); } count++; - * } else { count++; } - */ if (count == 0) { if (required) { selectedValue = value.getId(); diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/FormatProcessor.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/FormatProcessor.java index 0805b22c..62bf4335 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/FormatProcessor.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/FormatProcessor.java @@ -134,9 +134,6 @@ public class FormatProcessor extends RaptorObject { + origValue.substring(3, 5); try { - // DataSet ds = DbUtils.executeQuery("SELECT TO_CHAR(TO_DATE('" + origValue + "', '" - // + dateFormat + "'), 'YYYY-MM-DD') val FROM DUAL"); - String sql = Globals.getGenerateSqlVisualDual(); DataSet ds = DbUtils.executeQuery("SELECT TO_CHAR(TO_DATE('" + origValue + "', '" + dateFormat + "'), 'YYYY-MM-DD') val"+sql); @@ -166,8 +163,6 @@ public class FormatProcessor extends RaptorObject { beforeDecimalPoint = false; else if (c == '-' && integerValue.length() == 0) isNegative = true; - // else - // if(c=='0'||c=='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9') else if (Character.isDigit(c)) if (beforeDecimalPoint) integerValue.append(c); @@ -276,8 +271,6 @@ public class FormatProcessor extends RaptorObject { if( anyFormatter == null ) anyFormatter = formatter; - // String sValue = convertValue(dv.getDisplayValue()); - //if (sValue.length() > 0) { for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter .hasNext();) { FormatType fmt = (FormatType) iter.next(); @@ -311,42 +304,16 @@ public class FormatProcessor extends RaptorObject { valueMatched = isEqual(sValue, formatterValue) || isLessThan(sValue, formatterValue); } - //s_logger.debug("SYSOUT " + " " +sValue +" " +fmt.getBgColor() + " " + fmt.getLessThanValue()+ " " +valueMatched); if (fmt.getLessThanValue().length() > 0 && valueMatched) { formatter = (HtmlFormatter) formatters.get(fmt.getFormatId()); formatter.setFormatId(fmt.getFormatId()); formatModified = true; - //dv.setFormatId(fmt.getFormatId()); - //dr.setFormatId(fmt.getFormatId()); - //break; - } else { // if + } else { if(!formatModified) formatter = anyFormatter; - //if(!((formatter!=null && formatter!=anyFormatter) || (defaultFormatter!=null && formatter!=defaultFormatter))) - // formatter = anyFormatter; - //formatter.setFormatId(anyFormatter.getFormatId()); } - /*else if ((fmt.getLessThanValue().length() <= 0) - && (fmt.getFormatId().length() > 0)) { - formatter = (HtmlFormatter) formatters.get(fmt.getFormatId()); - System.out.println("---------------lesser "+ fmt.getFormatId()+ " " + fmt.getBgColor()); - dv.setFormatId(fmt.getFormatId()); - dr.setFormatId(fmt.getFormatId()); - // break; - } // else if*/ - } // for - /*} else { - for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter - .hasNext();) { - FormatType fmt = (FormatType) iter.next(); - if(fmt.getLessThanValue().length()<=0 && fmt.getExpression().length()<=0 && !fmt.isBold() && !fmt.isItalic() && !fmt.isUnderline() && fmt.getFontSize().equals("11")) { - formatter = defaultFormatter; - } else - formatter = anyFormatter; } - - //formatter.setFormatId(anyFormatter.getFormatId()); - } */ + if(formatter != null) { if (semaphore.getSemaphoreType().equals(AppConstants.ST_ROW)) { @@ -356,17 +323,14 @@ public class FormatProcessor extends RaptorObject { dr.setRowFormatter(formatter); dr.setFormatId(formatter.getFormatId()); // This is added for excel download - //if (!formatter.equals(defaultFormatter)) { dr.setRowFormat(true); - //} } } else { if(nvl(targetColId).length()>0) { if(targetDataValue!=null) { targetDataValue.setCellFormatter(formatter); - targetDataValue.setFormatId(formatter.getFormatId()); - //if (!formatter.equals(defaultFormatter)) { + targetDataValue.setFormatId(formatter.getFormatId()); targetDataValue.setCellFormat(true); int count = 0; for (dr.resetNext(); dr.hasNext();) { @@ -383,12 +347,10 @@ public class FormatProcessor extends RaptorObject { } else { dv.setCellFormatter(formatter); - dv.setFormatId(formatter.getFormatId()); - //if (!formatter.equals(defaultFormatter)) { + dv.setFormatId(formatter.getFormatId()); dv.setCellFormat(true); - //} } - }// else + } } } // setHtmlFormatters diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ReportFormFields.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ReportFormFields.java index 7bacd229..e50d465e 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ReportFormFields.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ReportFormFields.java @@ -86,15 +86,12 @@ public class ReportFormFields extends Vector { String visible = nvl(fft.getVisible(),"Y"); String dependsOn = nvl(fft.getDependsOn(), ""); Calendar rangeStartDate = (fft.getRangeStartDate()==null)?null:fft.getRangeStartDate().toGregorianCalendar(); - Calendar rangeEndDate = (fft.getRangeEndDate()==null)?null:fft.getRangeEndDate().toGregorianCalendar(); - //Calendar rangeEndDate = fft.getRangeEndDate().toGregorianCalendar(); + Calendar rangeEndDate = (fft.getRangeEndDate()==null)?null:fft.getRangeEndDate().toGregorianCalendar(); String rangeStartDateSQL = fft.getRangeStartDateSQL(); String rangeEndDateSQL = fft.getRangeEndDateSQL(); String userId = AppUtils.getUserID(request); String multiSelectListSize = fft.getMultiSelectListSize(); - - //s_logger.debug("ranges are : " + fft.getRangeStartDate() + fft.getRangeEndDate()); - //s_logger.debug("fieldSQL B4" + fieldSQL); + if(fieldSQL!=null) { for (int i = 0; i < reqParameters.length; i++) { if(!reqParameters[i].startsWith("ff") && (request.getParameter(reqParameters[i].toUpperCase())!=null && request.getParameter(reqParameters[i].toUpperCase()).length() > 0)) @@ -104,7 +101,6 @@ public class ReportFormFields extends Vector { } for (int i = 0; i < scheduleSessionParameters.length; i++) { - //s_logger.debug(" Session " + " scheduleSessionParameters[i] " + scheduleSessionParameters[i].toUpperCase() + " " + request.getParameter(scheduleSessionParameters[i])); if(request.getParameter(scheduleSessionParameters[i])!=null && request.getParameter(scheduleSessionParameters[i]).trim().length()>0 ) fieldSQL = Utils.replaceInString(fieldSQL, "[" + scheduleSessionParameters[i].toUpperCase()+"]", ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(), request.getParameter(scheduleSessionParameters[i]) )); if(request.getAttribute(scheduleSessionParameters[i])!=null && ((String)request.getAttribute(scheduleSessionParameters[i])).trim().length()>0 ) @@ -113,14 +109,9 @@ public class ReportFormFields extends Vector { } for (int i = 0; i < sessionParameters.length; i++) { - //if(!sessionParameters[i].startsWith("ff")) - //fieldSQL = Utils.replaceInString(fieldSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i].toUpperCase()) ); - //else { if (session.getAttribute(sessionParameters[i])!=null && ((String)session.getAttribute(sessionParameters[i])).length() > 0) { - //s_logger.debug(" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i])); fieldSQL = Utils.replaceInString(fieldSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) ); } - // } } fieldSQL = Utils.replaceInString(fieldSQL, "[USERID]", userId); fieldSQL = Utils.replaceInString(fieldSQL, "[USER_ID]", userId); @@ -136,7 +127,6 @@ public class ReportFormFields extends Vector { fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + reqParameters[i].toUpperCase()+"]", ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(), request.getParameter(reqParameters[i]) )); } for (int i = 0; i < scheduleSessionParameters.length; i++) { - //s_logger.debug(" Session " + " scheduleSessionParameters[i] " + scheduleSessionParameters[i].toUpperCase() + " " + request.getParameter(scheduleSessionParameters[i])); if(request.getParameter(scheduleSessionParameters[i])!=null && request.getParameter(scheduleSessionParameters[i]).trim().length()>0 ) fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + scheduleSessionParameters[i].toUpperCase()+"]", ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(), request.getParameter(scheduleSessionParameters[i]) )); if(request.getAttribute(scheduleSessionParameters[i])!=null && ((String)request.getAttribute(scheduleSessionParameters[i])).trim().length()>0 ) @@ -145,9 +135,6 @@ public class ReportFormFields extends Vector { } for (int i = 0; i < sessionParameters.length; i++) { - //if(!sessionParameters[i].startsWith("ff")) - //fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i].toUpperCase()) ); - //else if (session.getAttribute(sessionParameters[i])!=null && ((String)session.getAttribute(sessionParameters[i])).length() > 0) fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) ); } @@ -156,7 +143,6 @@ public class ReportFormFields extends Vector { fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[USER_ID]", userId); fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[LOGGED_USERID]", userId); } - //s_logger.debug("fieldSQL After" + fieldSQL); if(rangeStartDateSQL!=null) { for (int i = 0; i < reqParameters.length; i++) { if(!reqParameters[i].startsWith("ff") && (request.getParameter(reqParameters[i].toUpperCase())!=null && request.getParameter(reqParameters[i].toUpperCase()).length() > 0)) @@ -217,9 +203,8 @@ public class ReportFormFields extends Vector { String lColFormat = null; if (rw.getReportDefType().equals(AppConstants.RD_SQL_BASED)) { String colId = nvl(fft.getColId()); - lTableName = ReportWrapper.getSQLBasedFFTColTableName(colId); // colId.substring(0, - // colId.indexOf('.')); - lColumnName = ReportWrapper.getSQLBasedFFTColColumnName(colId); // colId.substring(colId.lastIndexOf('.')+1); + lTableName = ReportWrapper.getSQLBasedFFTColTableName(colId); + lColumnName = ReportWrapper.getSQLBasedFFTColColumnName(colId); lColumnType = AppConstants.CT_CHAR; try { lColumnType = nvl(DataCache.getReportTableDbColumnType(lTableName, @@ -249,8 +234,6 @@ public class ReportFormFields extends Vector { if (lColumnType.equals(AppConstants.CT_DATE)) selectVal = "TO_CHAR(" + selectVal + ", '" + AppConstants.DEFAULT_DATE_FORMAT + "')"; - // DataSet ds = DbUtils.executeQuery("SELECT - // "+selectVal+" FROM "+lTableName); DataSet ds = ConnectionUtils.getDataSet("SELECT " + selectVal + " FROM " + lTableName, rw.getDBInfo()); if (ds.getRowCount() > 0) diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ReportJSONRuntime.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ReportJSONRuntime.java index d3d44ac3..de5c892b 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ReportJSONRuntime.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ReportJSONRuntime.java @@ -406,48 +406,12 @@ import org.onap.portalsdk.analytics.view.ColumnHeader; }*/ -/*class Row { - private String displayValue; - private String dataType; - private String colId; - private boolean visible; - - - public boolean isVisible() { - return visible; - } - public void setVisible(boolean visible) { - this.visible = visible; - } - public String getDisplayValue() { - return displayValue; - } - public void setDisplayValue(String displayValue) { - this.displayValue = displayValue; - } - public String getDataType() { - return dataType; - } - public void setDataType(String dataType) { - this.dataType = dataType; - } - public String getColId() { - return colId; - } - public void setColId(String colId) { - this.colId = colId; - } - - -}*/ class FormFieldJSON { private String fieldId; private String fieldDisplayName; private String fieldType; private String validationType; private boolean required; - //private String defaultValue; - private Calendar rangeStartDate; private Calendar rangeEndDate; private String multiSelectListSize; diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ReportRuntime.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ReportRuntime.java index b6f944a7..d10826af 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ReportRuntime.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/model/runtime/ReportRuntime.java @@ -55,7 +55,8 @@ import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; - +import org.apache.commons.lang.StringUtils; +import org.apache.jcs.engine.CacheUtils; import org.onap.portalsdk.analytics.error.RaptorException; import org.onap.portalsdk.analytics.model.DataCache; import org.onap.portalsdk.analytics.model.ReportHandler; @@ -70,7 +71,9 @@ import org.onap.portalsdk.analytics.system.ConnectionUtils; import org.onap.portalsdk.analytics.system.DbUtils; import org.onap.portalsdk.analytics.system.Globals; import org.onap.portalsdk.analytics.util.AppConstants; +import org.onap.portalsdk.analytics.util.CachingUtils; import org.onap.portalsdk.analytics.util.DataSet; +import org.onap.portalsdk.analytics.util.RemDbInfo; import org.onap.portalsdk.analytics.util.Utils; import org.onap.portalsdk.analytics.view.ColumnHeader; import org.onap.portalsdk.analytics.view.ColumnHeaderRow; @@ -85,9 +88,11 @@ import org.onap.portalsdk.analytics.xmlobj.DataColumnType; import org.onap.portalsdk.analytics.xmlobj.FormFieldType; import org.onap.portalsdk.analytics.xmlobj.ObjectFactory; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.objectcache.jcs.JCSCacheManager; import org.onap.portalsdk.core.util.SecurityCodecUtil; import org.owasp.esapi.ESAPI; - +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; @@ -108,11 +113,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; * */ +@Component public class ReportRuntime extends ReportWrapper implements Cloneable, Serializable { private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportRuntime.class); - //TODO DELETE IF PARSE SQL is not working private int curSQLParsePos = 0; private String xmlFileURL = null; @@ -131,10 +136,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa private boolean displayContent = true; - private boolean reportRunLogged = false; // Used to avoid multiple - // entries in the report log - // when executing with different - // params or going to next page + private boolean reportRunLogged = false; private DataSet chartDataCache = null; @@ -142,11 +144,13 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa private int cachedPageNo = -1; - private String cachedSQL = null; // For display purposes only + private String cachedSQL = null; - private String wholeSQL = null; // For display purposes only + private String wholeSQL = null; - private String totalSql = null; // For display purposes only + private String totalSql = null; + + private boolean isSinglePageDownload = false; private ReportParamValues reportParamValues = null; @@ -184,53 +188,51 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa private int DATE_OPTION = -1; + public boolean isSinglePageDownload() { + return isSinglePageDownload; + } + + public void setSinglePageDownload(boolean isSinglePageDownload) { + this.isSinglePageDownload = isSinglePageDownload; + } + public void setReportFormFields(ReportFormFields reportFormFields) { this.reportFormFields = reportFormFields; } + public ReportRuntime() { + super(); + } - /* - * private ReportRuntime(CustomReport cr, String reportID, - * HttpServletRequest request) { super(cr, reportID); - * - * reportParamValues = new ReportParamValues(this); reportFormFields = new - * ReportFormFields(this); - * - * if(request!=null) setParamValues(request); } // ReportRuntime - */ private ReportRuntime(CustomReportType crType, String reportID, HttpServletRequest request, String ownerID, String createID, String createDate, String updateID, String updateDate, String menuID, boolean menuApproved) throws RaptorException { super(crType, reportID, ownerID, createID, createDate, updateID, updateDate, menuID, menuApproved); initializeReportRuntime(request); - } // ReportRuntime + } public ReportRuntime(ReportWrapper rw) throws RaptorException { this(rw, null); - } // ReportRuntime + } public ReportRuntime(ReportWrapper rw, HttpServletRequest request)throws RaptorException { super(rw); initializeReportRuntime(request); - } // ReportRuntime + } private void initializeReportRuntime(HttpServletRequest request) throws RaptorException { reportFormFields = new ReportFormFields(this, request); setParamValues(request, true, true); visualManager = new VisualManager(); - } // initializeReportRuntime + } -// public void setReportFormFields(HttpServletRequest request) { -// reportFormFields = new ReportFormFields(this, request); -// setParamValues(request, true, true); -// } public static ReportRuntime unmarshal(String reportXML, String reportID) throws RaptorException { return unmarshal(reportXML, reportID, null); - } // unmarshal + } public static ReportRuntime unmarshal(String reportXML, String reportID, HttpServletRequest request) throws RaptorException { @@ -242,7 +244,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa return new ReportRuntime(crType, reportID, request, null, null, null, null, null, null, false); - } // unmarshal + } public String getXmlFileURL() { return xmlFileURL; @@ -339,8 +341,8 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa setDisplayForm(false); else setDisplayForm(true); - } // else - } // setDisplayFlags + } + } public void logReportRun(String userID, String executionTime, String formFields) throws RaptorException { if (reportRunLogged) @@ -348,7 +350,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa ReportLoader.createReportLogEntry(null, reportID, userID, AppConstants.RLA_RUN,executionTime,formFields ); reportRunLogged = true; - } // logReportRun + } public void logReportExecutionTime(String userId, String executionTime, String action, String formFields) throws RaptorException { ReportLoader.createReportLogEntryForExecutionTime(null, reportID, userId,executionTime , action, formFields); @@ -367,7 +369,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa if (pageDataCache != null) pageDataCache.resetVisualSettings(); - } // resetVisualSettings + } /** ************** ReportParamValues processing *************** */ @@ -385,7 +387,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } else if (request != null) { paramsUpdated = reportParamValues.setParamValues(request,refresh); } - // This is called even in the wizard page. Hence this condition. + if((ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null) { if(reportParamValuesFPE!=null) reportParamValuesFPE.setParamValues(request,refresh); else { @@ -394,15 +396,12 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } } else { reportFormFields = new ReportFormFields(this, request); - //added below two lines for dashboard default value reportParamValues = new ReportParamValues(reportFormFields, getReportDefType()); reportParamValues.setParamValues(request,refresh); - //End reportParamValuesFPE = new ReportParamValuesForPDFExcel(reportFormFields, getReportDefType()); reportParamValuesFPE.setParamValues(request,refresh); } -// } if (paramsUpdated) { setReportDataSize(-1); chartDataCache = null; @@ -417,35 +416,32 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa grandTotalCrosstab = null; if(!refresh) resetVisualSettings(); - } // if + } displayChart = (request.getParameter(AppConstants.RI_DISPLAY_CHART) == null) ? !isDisplayOptionHideChart() : request.getParameter("display_chart") .equals("Y"); return paramsUpdated; - } // setParamValues + } public String getParamValue(String key) { - //reportParamValues.printValues(); return reportParamValues.getParamValue(key); - } // getParamValue + } - public String getParamDisplayValue(String key) { - //reportParamValues.printValues(); + public String getParamDisplayValue(String key) {; return reportParamValues.getParamDisplayValue(key); - } // getParamValue - + } public Enumeration getParamKeys() { return reportParamValues.keys(); - } // getParamKeys + } public Enumeration getParamKeysForPDFExcel() { return reportParamValuesFPE.keys(); - } // getParamKeys + } public String getParamValueForPDFExcel(String key) { return reportParamValuesFPE.getParamValue(key); - } // getParamValue + } public ArrayList getParamNameValuePairs() { ArrayList paramList = new ArrayList(getReportFormFields().size()); @@ -453,9 +449,9 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa FormField ff = (FormField) iter.next(); paramList.add(new IdNameValue(ff.getFieldDisplayName(), reportParamValues .getParamDisplayValue(ff.getFieldName()))); - } // for + } return paramList; - } // getParamNameValuePairs + } public ArrayList getParamNameValuePairsforPDFExcel(HttpServletRequest request, int type /*excel =1; pdf=2*/) { javax.servlet.http.HttpSession session = request.getSession(); @@ -465,7 +461,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa if(paramList!=null && paramList.size()>0) return paramList; } - //System.out.println(" getParamNamePairs type " + type + " " + Globals.customizeFormFieldInfo()); if ( reportParamValuesFPE == null) { reportParamValuesFPE = new ReportParamValuesForPDFExcel(reportFormFields, getReportDefType()); reportParamValuesFPE.setParamValues(request,true); @@ -474,7 +469,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa String valueString = ""; for (Iterator iter = getReportFormFields().iterator(); iter.hasNext();) { FormField ff = (FormField) iter.next(); - if(ff.isVisible() && /*!ff.getFieldType().equals(FormField.FFT_HIDDEN) &&*/ type == 1){ + if(ff.isVisible() && type == 1){ valueString = reportParamValuesFPE.getParamDisplayValue(ff.getFieldName()); } else if(ff.isVisible() && type != 1) { valueString = reportParamValuesFPE.getParamDisplayValue(ff.getFieldName()); @@ -482,8 +477,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa if(valueString.equalsIgnoreCase("NULL")) valueString=""; paramList.add(new IdNameValue(ff.getFieldDisplayName(), valueString)); -// } - } // for + } String pdfAttachmentKey = AppUtils.getRequestValue(request, "pdfAttachmentKey"); boolean isSchedule = false; @@ -501,10 +495,8 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } if(isSchedule) { - //debugLogger.debug("Globals " + Globals.getSessionParamsForScheduling()); String[] scheduleSessionParam = Globals.getSessionParamsForScheduling().split(","); for (int i = 0; i < scheduleSessionParam.length; i++) { - //debugLogger.debug(" scheduleSessionParam[i] " + scheduleSessionParam[i] + " " + request.getParameter(scheduleSessionParam[i]) ); if(request.getParameter(scheduleSessionParam[i])!=null) paramList.add(new IdNameValue(ESAPI.encoder().canonicalize(scheduleSessionParam[i].toUpperCase()), ESAPI.encoder().canonicalize(request.getParameter(scheduleSessionParam[i])))); } @@ -518,7 +510,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } catch(Exception ex) {} } else { - //System.out.println(" In Else getParamNamePairs type " + type); String[] sessionDisplayParameters = Globals.getDisplaySessionParamInPDFEXCEL().split(","); if(session != null && !isSchedule ) { session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request)); @@ -526,7 +517,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa String sessionDispParam = sessionDisplayParameters[i]; if(nvl(sessionDispParam).length()>0) { String sessionDispParamArr[] = sessionDispParam.split(";"); - //System.out.println("Session " + sessionDispParamArr[1] + " " + (String)session.getAttribute(sessionDispParamArr[0])); paramList.add(new IdNameValue(sessionDispParamArr[1], nvl((String)session.getAttribute(sessionDispParamArr[0]),""))); } } @@ -555,9 +545,8 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa String name = value.getName().replaceAll(",","~"); value.setName(name); } - //request.getSession().setAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO, paramList); return paramList; - } // getParamNameValuePairs + } /** ************** ReportFormFields processing *************** */ @@ -570,7 +559,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa if(comment.length()>0) { al = getParamNameValuePairsforPDFExcel(request, 2); if(al!=null) { - //st = new StringBuffer(comment); for (int i=0; i < al.size(); i++) { IdNameValue idNameValue = (IdNameValue)al.get(i); if(nvl(idNameValue.getId()).equals("DATE")) @@ -591,15 +579,15 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa public boolean needFormInput() { return reportFormFields.getFieldCount() > 0; - } // needFormInput + } public FormField getFormField(String fieldName) { return reportFormFields.getFormField(fieldName); - } // getFormField + } public ReportFormFields getReportFormFields() { return reportFormFields; - } // getReportFormFields + } public void setChartDataCache(DataSet chartDataCache) { this.chartDataCache = chartDataCache; @@ -621,10 +609,10 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa ds = ConnectionUtils.getDataSet(sql, dbInfo); if (Globals.getCacheChartData()) chartDataCache = ds; - } // if + } return ds; - } // loadChartData + } public String getReportDataSQL(String userId, int downloadLimit, HttpServletRequest request) throws RaptorException { String reportSQL = ""; @@ -643,11 +631,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa rd = pageDataCache; if(isGoBackAction && rd!=null) return rd; - if (rd == null) { // Commented So that Data is refreshed from DB again - if (getReportDataSize() < 0) - if (pageNo > 0) - pageNo = 0; - + if (rd == null) { if (getReportType().equals(AppConstants.RT_CROSSTAB)) rd = loadCrossTabReportData(pageNo, userId, downloadLimit, request, download); else if (getReportType().equals(AppConstants.RT_LINEAR)) @@ -661,10 +645,10 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa pageDataCache = rd; cachedPageNo = pageNo; } - } // if // Commented So that Data is refreshed from DB again + } return rd; - } // loadReportData + } private ReportData loadCrossTabReportData(int pageNo, String userId, int downloadLimit, HttpServletRequest request, boolean download) throws RaptorException { String reportSQL = generateSQL(reportParamValues, userId, request); @@ -672,13 +656,11 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa cachedSQL = reportSQL; wholeSQL = reportSQL; List reportCols = getAllColumns(); - // replace the request parameter specified in the drill down DataColumnType dataColumnRequest = getCrossTabValueColumn(); reportSQL = parseReportSQLForDrillDownParams(reportSQL, dataColumnRequest, request); DataSet ds = null; - // try { String dbInfo = getDBInfo(); StringBuffer colNames = new StringBuffer(); StringBuffer colExtraIdNames = new StringBuffer(); @@ -687,24 +669,18 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa for (Iterator iter = reportCols.iterator(); iter.hasNext();) { DataColumnType dc = (DataColumnType) iter.next(); - //TODO: commented if (dc.isVisible()) { if (colNames.length() > 0) colNames.append(", "); colNames.append(dc.getColId()); - //TODO uncomment if it's not working} // if - - // Checking for extra fields necessary for drill-down if (nvl(dc.getDrillDownURL()).length() > 0) { System.out.println("Drilldown URL " + dc.getDrillDownURL()); } - } // for + } if (reportSQL.toUpperCase().indexOf("GROUP BY ") < 0) colNames.append(colExtraIdNames.toString()); colNames.append(colExtraDateNames.toString()); - //reportSQL = " SELECT ROWNUM rnum, " - // + colNames.toString() + " FROM (" + reportSQL + ") "; String rSQL = Globals.getLoadCrosstabReportData(); rSQL = rSQL.replace("[colNames.toString()]", colNames.toString()); @@ -769,8 +745,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_ROW)) { RowHeaderCol rhc = new RowHeaderCol(); rhc.setColumnTitle(dct.getDisplayName()); - // rhc.setColumnWidth("10%"); - //rhc.setColumnWidth(dct.getDisplayWidth() + "%"); if(nvl(dct.getDisplayWidthInPxls()).length()<=0) { dct.setDisplayWidthInPxls("100px"); } @@ -805,29 +779,12 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa rd.reportRowHeaderCols.addRowHeaderCol(rhc); } } - } // for - - //int dataColumnIdx = getCrossTabValueColumnIndex(); + } FormatProcessor formatProcessor = new FormatProcessor(getSemaphoreById(dataColumn .getSemaphoreId()), getReportDefType().equals(AppConstants.RD_SQL_BASED) ? AppConstants.CT_NUMBER : dataColumn.getColType(), dataColumn.getColFormat(), false); List dataList = new ArrayList(); - /* //fillup all rows based on rowheaders - Vector rowHeaders = crossTabOrderManager.getRowHeaderValues(); - CrossTabColumnValues crossTabRowValues; - int size = 0; - for (int i = 0; i < rowHeaders.size(); i++) { - if((i+1)==rowHeaders.size()) { - crossTabRowValues = (CrossTabColumnValues) rowHeaders.get(i); - size = crossTabRowValues.getValuesCount(); - } - } - - for (int i = 0; i < size; i++) { - dataList.add(new DataRow()); - }*/ - for (int i = 0; i < ds.getRowCount(); i++) { Vector rValues = new Vector(); Vector cValues = new Vector(); @@ -865,41 +822,19 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa dv.setDisplayName(dataColumn.getDisplayName()); dv.setColId(dataColumn.getColId()); dv.setNowrap(nvl(dataColumn.getNowrap(),"null").equals("false")?"null":nvl(dataColumn.getNowrap(),"null")); - /*StringBuffer indentation = new StringBuffer(""); - if(dataColumn.getIndentation()!=null && dataColumn.getIndentation().intValue()>0) { - for (int indent=0; indent < dataColumn.getIndentation(); indent++) { - indentation.append("\t"); - } - dv.setNowrap("true"); - } - dv.setIndentation(indentation.toString());*/ - if (nvl(dataColumn.getDrillDownURL()).length() > 0) { if(dv.getDisplayValue().length() > 0) { dv.setDrillDownURL(parseDrillDownURL(i, /* dataColumnIdx, */ds, dataColumn,request, childReportFormFields)); dv.setDrillDowninPoPUp(dataColumn.isDrillinPoPUp()!=null?dataColumn.isDrillinPoPUp():false); } if (dv.getDisplayValue().length() == 0) { - //dv.setDisplayValue("[NULL]"); dv.setDisplayValue(""); } - } // if + } rd.setDataValue(rValues, cValues, cValuesSort.size()==0?null:cValuesSort, dv, formatProcessor, crossTabOrderManager, dataList); - } // for + } rd.setReportDataList(dataList); - /*if (getReportDataSize() < 0) - setReportDataSize(rd.getDataRowCount());*/ - - /*if (pageNo >= 0) - rd.truncateData(pageNo * getPageSize(), (pageNo + 1) * getPageSize() - 1); - else { - if( downloadLimit != -1) - rd.truncateData(0, downloadLimit - 1); - else - rd.truncateData(0, -1); - }*/ - if (colDataTotalsCrosstab == null) colDataTotalsCrosstab = generateDataTotalsCrossTab(AppConstants.CV_COLUMN, userId,request); if (displayColTotals && colDataTotalsCrosstab != null) @@ -926,13 +861,9 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa rd.setGrandTotalCrossTab(Utils.truncateTotalDecimals(grandTotalCrosstab), dataColumn.getDisplayAlignment(), getCrossTabDisplayTotal(AppConstants.CV_COLUMN), dataList); - } // if + } rd.consolidateColumnHeaders(visualManager); - //if (Globals.getMergeCrosstabRowHeadings()) - // rd.consolidateRowHeaders(); - //rd.addRowNumbers(pageNo, dataList); - if (displayColTotals && colDataTotalsCrosstab != null) { String totalLabel = "Total"; String colDisplayTotal = getCrossTabDisplayTotal(AppConstants.CV_COLUMN); @@ -942,11 +873,8 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa if (getReportDataSize() > getPageSize()) totalLabel += "_nl_(for all pages)"; - //rd.setCrossTabColumnTotalLabel(totalLabel); - } // if - //rd.applyVisibility(); - //Collections.sort((List)dataList, new DataRowComparable()); + } DataRow drInFor1 = null; Vector<DataValue> v1= null, v2 = null; ArrayList<String> temp = new ArrayList<>(); @@ -957,9 +885,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa v1 = drInFor1.getRowValues(); if(i<dataList.size()-1) { v2 = ((DataRow)dataList.get(i+1)).getRowValues(); - } /*else { - v2 = ((DataRow)dataList.get(i-1)).getRowValues(); - }*/ + } for (int j = 0; j < v1.size(); j++) { if(j==0) { if(v1.get(j).getDisplayValue().length()>0) { // another ArrayList @@ -975,13 +901,11 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } rd.setReportDataList(dataList); if (getReportDataSize() < 0) { - //setReportDataSize(rd.getDataRowCount()); setReportDataSize(rd.getReportDataList().size()); } return rd; - } // loadCrossTabReportData - + } public DataValue addDataValue(DataColumnType dataColumn, String columnValue) { DataValue dv = new DataValue(); @@ -998,7 +922,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } - /*private*/ public boolean doesReportContainsGroupFormField() { + public boolean doesReportContainsGroupFormField() { int flag = 0; if(getFormFieldList()!=null) { for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) { @@ -1013,10 +937,12 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } private ReportData loadLinearReportData(int pageNo, String userId, int downloadLimit, HttpServletRequest request, boolean download) throws RaptorException { + long startTime = System.currentTimeMillis(); + logger.info("Session ID: " + request.getSession().getId()); + boolean isSameSession = false; + String action = nvl(request.getParameter(AppConstants.RI_ACTION), request.getParameter("action"));; - String reportSQL = ""; - if(action.endsWith("session")) { reportSQL = getWholeSQL(); wholeSQL = reportSQL; @@ -1028,11 +954,24 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } DataSet ds = null; String dbInfo = getDBInfo(); - ds = ConnectionUtils.getDataSet(wholeSQL, dbInfo); - setReportDataSize(ds.getRowCount()); - //wholeSQL = reportSQL; + long runWHoleSqlStart = System.currentTimeMillis(); + String SQLForCount = "SELECT count(*) FROM (" + reportSQL + ")"+ (Globals.isPostgreSQL() || Globals.isMySQL()?" AS ":"") +" x "; + boolean isPageDowload = Boolean.valueOf(request.getParameter(AppConstants.PAGE_DOWNLOAD)); + if(download) { + if(isPageDowload) { + ds = ConnectionUtils.getDataSet(cachedSQL, dbInfo); + } + else { + String downloadAll = generateSubsetSQL(0, downloadLimit, userId, request, true, null); + ds = ConnectionUtils.getDataSet(downloadAll, dbInfo); + } + } + long runWHoleSqlEnd = System.currentTimeMillis(); + logger.info("Run whole sql to set reportDataSize took:"+ (runWHoleSqlEnd - runWHoleSqlStart)/1000F + "Seconds"); + long hibernateSessionTimeStart = System.currentTimeMillis(); HttpSession session = request.getSession(); - //debugLogger.debug(" ******** Download Limit ********* " + downloadLimit + " %%%%%%%%%%PAGE " + pageNo ); + long hibernateSessionTimeEnd = System.currentTimeMillis(); + logger.info("Hibernate session time : " + (hibernateSessionTimeEnd - hibernateSessionTimeStart)/1000F + " Seconds"); List reportCols = null; StringBuffer colNames = new StringBuffer(); @@ -1049,12 +988,18 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } else { - String pagedSQL = null; // reportSQL; + String pagedSQL = null; + long genaratePageSqlStart = System.currentTimeMillis(); + boolean getColumnNamesFromReportSQL = false; + if(Globals.getDBType().equals(AppConstants.ORACLE)) { + getColumnNamesFromReportSQL = true; + } if (pageNo >= 0) - pagedSQL = generatePagedSQL(pageNo, userId, request, false, null); + pagedSQL = generatePagedSQL(pageNo, userId, request, getColumnNamesFromReportSQL, null); else - pagedSQL = generateSubsetSQL(0, downloadLimit, userId, request, false, null); - // replace the request parameter specified in the drill down + pagedSQL = generateSubsetSQL(0, downloadLimit, userId, request, getColumnNamesFromReportSQL, null); + long genaratePageSqlend = System.currentTimeMillis(); + logger.info("generate paged sql took : " + (genaratePageSqlend - genaratePageSqlStart)/1000F + " Seconds"); reportCols = getAllColumns(); colNames = new StringBuffer(); for (Iterator iter = reportCols.iterator(); iter.hasNext();) { @@ -1072,18 +1017,30 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa cachedSQL = pagedSQL; - // try { + if(doesReportContainsGroupFormField()) { if (pageNo >= 0) - pagedSQL = generatePagedSQL(pageNo, userId, request, true, reportParamValues); + pagedSQL = generatePagedSQL(pageNo, userId, request, getColumnNamesFromReportSQL, reportParamValues); else - pagedSQL = generateSubsetSQL(0, downloadLimit, userId, request, true, reportParamValues); + pagedSQL = generateSubsetSQL(0, downloadLimit, userId, request, getColumnNamesFromReportSQL, reportParamValues); } - //check for Group formfield - //if groupformfield get columns from sql - + long start = System.currentTimeMillis(); ds = ConnectionUtils.getDataSet(pagedSQL, dbInfo); - + long end = System.currentTimeMillis(); + float sec = (end - start) / 1000F; + logger.info("Get page data : "+sec + " seconds"); + if (ds.getRowCount() < getPageSize() && pageNo == 0) { + setReportDataSize(ds.getRowCount()); + } else { + if (CachingUtils.isTotalCountAvailable(request.getSession().getId() + wholeSQL) && !download) { + setReportDataSize(CachingUtils.getTotalRowsCount(request.getSession().getId() + wholeSQL)); + } else { + DataSet countData = null; + countData = ConnectionUtils.getDataSet(SQLForCount, dbInfo); + setReportDataSize(countData.getInt(0, 0)); + CachingUtils.cacheTotalRowCount(request.getSession().getId() + wholeSQL, countData.getInt(0, 0)); + } + } if(doesReportContainsGroupFormField()) { List reportCols1 = getAllColumns(); reportCols = new Vector(); @@ -1120,20 +1077,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } } - - // if ( (remDbInfo!=null) && (!remDbInfo.equals(AppConstants.DB_LOCAL))) - // { - // Globals.getRDbUtils().setDBPrefix(remDbInfo); - // ds = RemDbUtils.executeQuery(pagedSQL); - // } - // else - // ds = DbUtils.executeQuery(pagedSQL); - /* - * } catch(SQLException e) { throw new - * ReportSQLException("[ReportRuntime.loadLinearReportData] - * "+e.getMessage(), pagedSQL); } - */ - if (getReportDataSize() < 0) if (pageNo < 0) setReportDataSize(ds.getRowCount()); @@ -1141,30 +1084,11 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa setReportDataSize(ds.getRowCount()); else { - /*Pattern re1 = Pattern.compile("[Oo][Rr][Dd][Ee][Rr](.*?[^\r\n]*)[Bb][Yy]", Pattern.DOTALL); - Pattern re2 = Pattern.compile("[Oo][Rr][Dd][Ee][Rr](.*?[^\r\n]*)[Bb][Yy]((.*?[^\r\n]*)|[\\s]|[^0-9a-zA-Z])\\)", Pattern.DOTALL); - Matcher matcher = re1.matcher(reportSQL); - Matcher matcher2 = null; - int startPoint = reportSQL.length()-30; - String startReportSQL = ""; - String endReportSQL = ""; - while(reportSQL.indexOf("xid", startPoint)!=-1)startPoint++; - if (matcher.find(startPoint)) { - startReportSQL = reportSQL.substring(0, reportSQL.indexOf(matcher.group())); - endReportSQL = reportSQL.substring(reportSQL.indexOf(matcher.group())); - matcher2 = re2.matcher(endReportSQL); - if(matcher2.find()) - endReportSQL = endReportSQL.substring(matcher.group().length()-1); - else - endReportSQL = ""; - reportSQL = startReportSQL + endReportSQL; - }*/ String countSQL = "SELECT count(*) FROM (" + reportSQL + ")"+ (Globals.isPostgreSQL() || Globals.isMySQL()?" AS ":"") +" x "; String dbType = ""; if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) { try { - org.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.portalsdk.analytics.util.RemDbInfo(); dbType = remDbInfo.getDBType(dbInfo); if (dbType.equals("DAYTONA") && reportSQL.trim().toUpperCase().startsWith("SELECT")) { Pattern re1 = Pattern.compile("order(.*?[^\r\n]*)by", Pattern.DOTALL); @@ -1185,9 +1109,11 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } DataSet ds2 = null; - // try { if(reportSQL.trim().toUpperCase().startsWith("SELECT")) { + long start1 = System.currentTimeMillis(); ds2 = ConnectionUtils.getDataSet(countSQL, dbInfo); + long end1 = System.currentTimeMillis(); + float sec1 = (end1 - start1) / 1000F; System.out.println("Get count data : "+sec1 + " seconds"); if (ds2.getRowCount() > 0) setReportDataSize(ds2.getInt(0, 0)); else @@ -1195,26 +1121,11 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa "[ReportRuntime.loadLinearReportData] Unable to load report data size"); } else setReportDataSize(50); - // if ( (remDbInfo!=null) && - // (!remDbInfo.equals(AppConstants.DB_LOCAL))){ - // Globals.getRDbUtils().setDBPrefix(remDbInfo); - // ds2 = RemDbUtils.executeQuery(countSQL); - // } - // else - // ds2 = DbUtils.executeQuery(countSQL); - /* - * } catch(SQLException e) { throw new - * ReportSQLException("[ReportRuntime.loadLinearReportData size] - * "+e.getMessage(), countSQL); } - */ - - - } // else + + + } } ReportData rd = new ReportData(pageNo, true); - - // Already defined changed for modifying request parameters - //List reportCols = getAllColumns(); Vector visibleCols = new Vector(reportCols.size()); Vector formatProcessors = new Vector(reportCols.size()); @@ -1222,8 +1133,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa // rd.reportColumnHeaderRows.addColumnHeaderRow(chr); // chr.setRowHeight("30"); int count =0 ; - - /* ADDED */ ReportFormFields rff = getReportFormFields(); ReportFormFields childReportFormFields = null; String fieldDisplayName = ""; @@ -1236,7 +1145,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa for(int i = 0 ; i < rff.size(); i++) { fieldDisplayName = "["+((FormField)rff.getFormField(i)).getFieldDisplayName()+"]"; fieldValue = ""; - //if(dct.getOriginalDisplayName()==null) dct.setOriginalDisplayName(dct.getDisplayName()); if (dct.getDependsOnFormField().equals(fieldDisplayName)) { fieldValue = nvl(request.getParameter(((FormField)rff.getFormField(i)).getFieldName())); @@ -1253,8 +1161,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } } } - - /* ADDED */ String displayName = ""; for (Iterator iter = reportCols.iterator(); iter.hasNext();) { @@ -1266,11 +1172,14 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa AppConstants.RD_SQL_BASED))); if (nvl(dc.getDrillDownURL()).length() > 0) { + if(!dc.getDrillDownURL().contains("c_master")) { childReportFormFields = getChildReportFormFields(request,AppUtils.getDrillActionURL()+""+dc.getDrillDownURL()); + }else { + childReportFormFields = getChildReportFormFields(request,dc.getDrillDownURL()); + } } if (dc.isVisible()) { visibleCols.add(count,dc); - //if(dc.getColId().startsWith("group")) { for (int d = 0; d < reportCols.size(); d++) { if(reportCols.get(d)!=null) { DataColumnType dct1 = (DataColumnType) reportCols.get(d); @@ -1295,43 +1204,19 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa visualManager.isColumnVisible(dc.getColId()), visualManager .getSortByColId().equals(dc.getColId()) ? visualManager .getSortByAscDesc() : null, isRuntimeColSortDisabled(), dc.getLevel()!=null?dc.getLevel():0, dc.getStart()!=null?dc.getStart():0, dc.getColspan()!=null?dc.getColspan():0, dc.isIsSortable()!=null?dc.isIsSortable():false); - // chr.addColumnHeader(new ColumnHeader(dc.getDisplayName(), - // (dc.getDisplayWidth()>100)?"10%":(""+dc.getDisplayWidth()+"%"))); - } // if + } else { visibleCols.add(count,null); rd.createColumn(dc.getColId(), AppConstants.HIDDEN, dc.getDisplayWidthInPxls(), dc.getDisplayHeaderAlignment(), true, null,false, dc.getLevel()!=null?dc.getLevel():0, dc.getStart()!=null?dc.getStart():0, dc.getColspan()!=null?dc.getColspan():0, dc.isIsSortable()!=null?dc.isIsSortable():false); -// formatProcessors.add(count,null); } count++; - } // for + } if(getReportDefType().equals(AppConstants.RD_SQL_BASED_DATAMIN) && pageNo ==0) { - /*Vector v = null; - try { - v = addForecastData(reportSQL); - } catch (Exception ex) { - ex.printStackTrace(); - throw new RaptorException (ex); - } - session.setAttribute("FORECASTED_DATA", v); - DataSet dsWhole = ConnectionUtils.getDataSet(wholeSQL, dbInfo); - dsWhole.addAll(v); - session.setAttribute(AppConstants.RI_CHART_FORECAST_DATA, dsWhole); - } - if(getReportDefType().equals(AppConstants.RD_SQL_BASED_DATAMIN) && session.getAttribute("FORECASTED_DATA")!=null) { - Vector vForecastedData = (Vector)session.getAttribute("FORECASTED_DATA"); - if(vForecastedData.size() > 0) - ds.addAll(vForecastedData);*/ } - - // Utils._assert(chr.size()==ds.getColumnCount(), - // "[ReportRuntime.loadLinearReportData] The number of visible columns - // does not match the number of data columns"); - //TODO: This should be optimized to accept -1 for flat file download for (int r = 0; r < Math.min(ds.getRowCount(), ((pageNo < 0) ? (downloadLimit == -1?Globals.getFlatFileUpperLimit():Globals.getDownloadLimit() ) : getPageSize())); r++) { DataRow dr = new DataRow(); rd.reportDataRows.addDataRow(dr); @@ -1341,6 +1226,11 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa DataColumnType dct = (DataColumnType) reportCols.get(c); DataValue dv = new DataValue(); dr.addDataValue(dv); + String reverseDispalyValue = reverseDisplayValue(ds.getString(r, ds.getColumnIndex(dct.getColId()))); + reverseDispalyValue = StringUtils.substringBefore(reverseDispalyValue, ","); + if(download) + dv.setDisplayValue(reverseDispalyValue); + else dv.setDisplayValue(ds.getString(r, ds.getColumnIndex(dct.getColId()))); dv.setColName(dct.getColName()); dv.setColId(dct.getColId()); @@ -1368,7 +1258,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } if (dv.getDisplayValue().length() == 0) { - //dv.setDisplayValue("[NULL]"); dv.setDisplayValue(""); } } // if @@ -1377,20 +1266,14 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa dv.setVisible(false); dv.setHidden(true); } - //System.out.println("in Linear report b4" + dr.getFormatId() + dr.getBgColorHtml() + dv.getDisplayValue()); - if(dr.getFormatId()!=null) ((FormatProcessor) formatProcessors.get(c)).setHtmlFormatters(dv, dr, true); else ((FormatProcessor) formatProcessors.get(c)).setHtmlFormatters(dv, dr, false); + } + } + } - //System.out.println("in Linear report After" + dr.getFormatId() + dr.getBgColorHtml() + dv.getDisplayValue()); - } // if reportCols - } // for - } // for - - //Only if rownumber options is needed - //rd.addRowNumbers(pageNo, getPageSize()); if (colDataTotalsLinear == null) { if(!download && !action.endsWith("session")) @@ -1406,12 +1289,13 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa totalLabel += "<br><font size=1>(for all pages)</font>"; rd.setColumnDataTotalsLinear(colDataTotalsLinear, totalLabel); - } // if - // Please note the below function doesn't set the visibility for dv since this is set in this function. - Sundar + } rd.applyVisibility(); - + long endTime = System.currentTimeMillis(); + float totalTime = (endTime - startTime)/1000F; + logger.info("Linearreportdata took: " + totalTime +"Seconds"); return rd; - } // loadLinearReportData + } @@ -1427,16 +1311,13 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa if (nvl(dct.getDisplayTotal()).length() > 0) { displayColTotals = true; break; - } // if - } // if checking dct - } // for + } + } + } DataSet ds = null; if (displayColTotals) { dr = new DataRow(); - // ds = - // DbUtils.executeQuery(generateTotalSQLLinear(reportParamValues, - // userId)); ds = ConnectionUtils.getDataSet(reportSQL, dbInfo); @@ -1473,12 +1354,12 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa dv.setVisible(dct.isVisible()); if(dv.isVisible()) dr.addDataValue(dv); - } // dct check - } // for + } + } } return dr; - } // generateColumnDataTotalsLinear + } public ReportData loadHiveLinearReportData(String reportSQL, String userId, int downloadLimit, HttpServletRequest request) throws RaptorException { @@ -1492,7 +1373,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa HttpSession session = request.getSession(); DataSet ds = null; - // try { String dbInfo = getDBInfo(); List reportCols = getAllColumns(); @@ -1508,18 +1388,11 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa ds = ConnectionUtils.getDataSet(wholeSQL, dbInfo); ReportData rd = new ReportData(0, true); - - // Already defined changed for modifying request parameters - //List reportCols = getAllColumns(); Vector visibleCols = new Vector(reportCols.size()); Vector formatProcessors = new Vector(reportCols.size()); - - // ColumnHeaderRow chr = new ColumnHeaderRow(); - // rd.reportColumnHeaderRows.addColumnHeaderRow(chr); - // chr.setRowHeight("30"); int count =0 ; + - /* ADDED */ ReportFormFields rff = getReportFormFields(); ReportFormFields childReportFormFields = null; String fieldDisplayName = ""; @@ -1532,7 +1405,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa for(int i = 0 ; i < rff.size(); i++) { fieldDisplayName = "["+((FormField)rff.getFormField(i)).getFieldDisplayName()+"]"; fieldValue = ""; - //if(dct.getOriginalDisplayName()==null) dct.setOriginalDisplayName(dct.getDisplayName()); if (dct.getDependsOnFormField().equals(fieldDisplayName)) { fieldValue = nvl(request.getParameter(((FormField)rff.getFormField(i)).getFieldName())); @@ -1550,7 +1422,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } } - /* ADDED */ String displayName = ""; for (Iterator iter = reportCols.iterator(); iter.hasNext();) { @@ -1566,7 +1437,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } if (dc.isVisible()) { visibleCols.add(count,dc); - //if(dc.getColId().startsWith("group")) { for (int d = 0; d < reportCols.size(); d++) { if(reportCols.get(d)!=null) { DataColumnType dct1 = (DataColumnType) reportCols.get(d); @@ -1591,17 +1461,15 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa visualManager.isColumnVisible(dc.getColId()), visualManager .getSortByColId().equals(dc.getColId()) ? visualManager .getSortByAscDesc() : null, isRuntimeColSortDisabled(), dc.getLevel()!=null?dc.getLevel():0, dc.getStart()!=null?dc.getStart():0, dc.getColspan()!=null?dc.getColspan():0, dc.isIsSortable()!=null?dc.isIsSortable():false); - // chr.addColumnHeader(new ColumnHeader(dc.getDisplayName(), - // (dc.getDisplayWidth()>100)?"10%":(""+dc.getDisplayWidth()+"%"))); - } // if + + } else { visibleCols.add(count,null); rd.createColumn(dc.getColId(), "", dc.getDisplayWidthInPxls(), dc.getDisplayHeaderAlignment(), true, null,false, dc.getLevel()!=null?dc.getLevel():0, dc.getStart()!=null?dc.getStart():0, dc.getColspan()!=null?dc.getColspan():0, dc.isIsSortable()!=null?dc.isIsSortable():false); -// formatProcessors.add(count,null); } count++; - } // for + } ArrayList reportDataList = new ArrayList(); for (int r = 0; r < ds.getRowCount(); r++) { @@ -1640,30 +1508,24 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } if (dv.getDisplayValue().length() == 0) { - //dv.setDisplayValue("[NULL]"); dv.setDisplayValue(""); } - } // if + } } else { dv.setVisible(false); dv.setHidden(true); } - //System.out.println("in Linear report b4" + dr.getFormatId() + dr.getBgColorHtml() + dv.getDisplayValue()); if(dr.getFormatId()!=null) ((FormatProcessor) formatProcessors.get(c)).setHtmlFormatters(dv, dr, true); else ((FormatProcessor) formatProcessors.get(c)).setHtmlFormatters(dv, dr, false); - - //System.out.println("in Linear report After" + dr.getFormatId() + dr.getBgColorHtml() + dv.getDisplayValue()); - } // if reportCols - } // for + } + } reportDataList.add(dr); - } // for + } rd.setReportDataList(reportDataList); - //Only if rownumber options is needed - //rd.addRowNumbers(pageNo, getPageSize()); if (colDataTotalsLinear == null) colDataTotalsLinear = generateColumnDataTotalsLinear(new ArrayList(reportCols), userId, @@ -1674,21 +1536,19 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa totalLabel += "<br><font size=1>(for all pages)</font>"; rd.setColumnDataTotalsLinear(colDataTotalsLinear, totalLabel); - } // if - // Please note the below function doesn't set the visibility for dv since this is set in this function. - Sundar + } + rd.applyVisibility(); return rd; - } // loadHiveLinearReportData + } + - //For Hive reports public int getHiveReportCount(String sql) throws RaptorException { - //select t from (select count(*) t from (select * from program)x)x1; int count = 0; String countSql = "select t from (select count(*) t from ("+ sql + ")" + (Globals.isPostgreSQL() || Globals.isMySQL() ?" AS ":"") + " x) AS x1"; DataSet ds = null; - // try { String dbInfo = getDBInfo(); System.out.println("SQL getReportCount()- " + countSql); try { @@ -1697,7 +1557,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa String dbType = ""; if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) { try { - org.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.portalsdk.analytics.util.RemDbInfo(); dbType = remDbInfo.getDBType(dbInfo); } catch (Exception ex) { throw new RaptorException(ex); @@ -1709,10 +1568,10 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } catch (NumberFormatException ex) {} return count; - } // getReportCount + } - /*private*/ public ReportFormFields getChildReportFormFields( HttpServletRequest request, String URL ) throws RaptorException { + public ReportFormFields getChildReportFormFields( HttpServletRequest request, String URL ) throws RaptorException { String childReportID = getReportID(URL); ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, childReportID, @@ -1733,20 +1592,12 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa return reportID; } - /*private*/ public String parseDrillDownURL(int rowIdx, /* int colIdx, */DataSet ds, DataColumnType dct, HttpServletRequest request, ReportFormFields ddReportFormFields) +public String parseDrillDownURL(int rowIdx, /* int colIdx, */DataSet ds, DataColumnType dct, HttpServletRequest request, ReportFormFields ddReportFormFields) throws RaptorException { Vector viewActions = DataCache.getDataViewActions(); javax.servlet.http.HttpSession session = request.getSession(); StringBuffer dUrl = new StringBuffer(); - - //String childReportID = getReportID(dct.getDrillDownURL()); - - //ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, childReportID, - // false, 1); - - //ReportFormFields ddReportFormFields = ddRr.getReportFormFields(); - boolean isViewAction = false; int flag = 0; String requestParam =""; @@ -1755,18 +1606,14 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa AppUtils.getBaseActionURL() + ((String) viewActions.get(k)))) isViewAction = true; if (isViewAction) { - // Drill-down to record details - String param = nvl(dct.getDrillDownParams()); // i.e. - // "c_master=[bo1.RECID$]" + String param = nvl(dct.getDrillDownParams()); param = param.substring(AppUtils.getBaseActionParam().length() + 1, - param.length() - 1); // i.e. "bo1.RECID$" - param = param.replace('.', '_'); // i.e. "bo1.RECID$" + param.length() - 1); + param = param.replace('.', '_'); dUrl.append(AppUtils.getBaseActionParam()); dUrl.append(java.net.URLEncoder.encode(ds.getString(rowIdx, param.toLowerCase()))); } else { - // Drill-down to another report - // Replacing col ids with values String param = nvl(dct.getDrillDownParams()); while (param.indexOf('[') >= 0) { int startIdx = param.indexOf('['); @@ -1782,13 +1629,10 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa sb.append(param.substring(0, startIdx)); if (param.charAt(startIdx + 1) == '!') { - // Parameter is a form field value String fieldId = param.substring(startIdx + 2, endIdx); String fieldValue = (String) reportParamValues.get(fieldId); sb.append(java.net.URLEncoder.encode(nvl(fieldValue))); - //TODO Add a else if condition to check whether the param is from request Param - //TODO make a unique symbol like # }else if (param.charAt(startIdx + 1) == '#') { flag = 1; String fieldId = param.substring(startIdx + 2, endIdx); @@ -1796,14 +1640,12 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa sb.append(java.net.URLEncoder.encode(nvl(fieldValue))); }else { - // Parameter is a column value String fieldValue = ""; String colValue = null; String colId = null; if (param.indexOf('!') < 0 || param.indexOf('!') > endIdx) colId = param.substring(startIdx + 1, endIdx); else { - // Need to use NVL(column, form field) colId = param.substring(startIdx + 1, param.indexOf('!')); String fieldId = param.substring(param.indexOf('!') + 1, endIdx); @@ -1812,7 +1654,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa fieldValue = reportParamValues.getParamValueforTextAreaDrilldown(fieldId); } else fieldValue = (String) reportParamValues.get(fieldId); - } // else + } DataColumnType column = getColumnById(colId); String columnName = ""; @@ -1835,39 +1677,29 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa if(nvl(dependsOn).length()>0) System.out.println("DependsOn " + dependsOn); if (column != null) { - // if (column.getColType().equals(AppConstants.CT_DATE)) - //if (!nvl(column.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT) - // .equals(AppConstants.DEFAULT_DATE_FORMAT)) - // Use extra column instead - //commented out below line usually for Visual - //colId += AppConstants.DD_COL_EXTENSION; colValue = ds.getString(rowIdx, colId.toLowerCase()); - // if SQL-Based and drill-down param is a date, decode - // it to the expected Oracle format **/ if (getReportDefType().equals(AppConstants.RD_SQL_BASED)) if (!getColumnNoParseDateFlag(column)) if (ReportParamDateValueParser.isDateParam(colValue)) colValue = ReportParamDateValueParser .formatDateParamValue(colValue); - } // if + } String suppressValues = "|" + nvl(dct.getDrillDownType()) + "|"; if (suppressValues.length() > 2 && suppressValues.indexOf("|" + colValue + "|") >= 0) - // Parameter value is suppressed and not passed to the - // drill-down report colValue = null; sb.append(java.net.URLEncoder.encode(nvl(colValue, fieldValue))); } else { sb.delete(sb.lastIndexOf("&")+1, sb.length()); } - } // else + } if (endIdx < param.length() - 1) sb.append(param.substring(endIdx + 1)); param = sb.toString(); - } // while + } if(Globals.getPassRequestParamInDrilldown()) { if(param.indexOf('#') < 0) { String[] reqParameters = Globals.getRequestParams().split(","); @@ -1920,28 +1752,16 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } dUrl.append(AppConstants.DRILLDOWN_INDEX); int index = Integer.parseInt(nvl(AppUtils.getRequestValue(request, AppConstants.DRILLDOWN_INDEX), "0")); - /* - int form_index = Integer.parseInt(nvl(AppUtils.getRequestValue(request, AppConstants.FORM_DRILLDOWN_INDEX), "0")); - index = index>0 ? --index : 0; - form_index = form_index>0 ? --form_index : 0;*/ request.setAttribute(AppConstants.DRILLDOWN_INDEX, Integer.toString(index)); - /*session.setAttribute(AppConstants.DRILLDOWN_INDEX, Integer.toString(index)); - request.setAttribute(AppConstants.FORM_DRILLDOWN_INDEX, Integer.toString(form_index)); - session.setAttribute(AppConstants.FORM_DRILLDOWN_INDEX, Integer.toString(form_index));*/ - dUrl.append("=" + AppUtils.getRequestNvlValue(request, AppConstants.DRILLDOWN_INDEX)); - - //TODO Add a if condition to check whether the param is request Param - } // if + } if (dUrl.length() > 0) dUrl.insert(0, ((dct.getDrillDownURL()).indexOf('&') > 0) ? '&' : '&'); dUrl.insert(0, AppUtils.getDrillActionURL()+dct.getDrillDownURL()); - //debugLogger.debug(" [[[[[[[[[[[[[[[[ " + dUrl); - return dUrl.toString(); - } // parseDrillDownURL + } /** *********************************************************************************** */ @@ -1957,16 +1777,13 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa if (nvl(dct.getDisplayTotal()).length() > 0) { displayColTotals = true; break; - } // if - } // if checking dct - } // for + } + } + } DataSet ds = null; if (displayColTotals) { dr = new DataRow(); - // ds = - // DbUtils.executeQuery(generateTotalSQLLinear(reportParamValues, - // userId)); ds = ConnectionUtils.getDataSet(generateTotalSQLLinear(reportParamValues, userId,request), dbInfo); @@ -1985,6 +1802,9 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa totalValue = nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(dct .getDisplayTotal())) + ": " + totalValue; + if( nvl(dct.getDisplayTotal()).length() > 0 && dct.getDisplayTotal().equals(AppConstants.TOTAL_SUM_ID)){ + totalValue = "Total: "+ totalValue; + } dv.setDisplayValue(Utils.truncateTotalDecimals(totalValue)); dv.setAlignment(dct.getDisplayAlignment()); @@ -2002,12 +1822,12 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa dv.setIndentation(indentation.toString()); dv.setDisplayTotal(dct.getDisplayTotal()); dv.setBold(true); - } // dct check - } // for + } + } } return dr; - } // generateColumnDataTotalsLinear + } private Vector generateDataTotalsCrossTab(String rowColPos, String userId, HttpServletRequest request) throws RaptorException { @@ -2022,9 +1842,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa displayRowTotals = displayTotals; if (displayTotals) { - // DataSet ds = - // DbUtils.executeQuery(generateTotalSQLCrossTab(reportParamValues, - // rowColPos, userId)); String executeSql = generateTotalSQLCrossTab( sql, rowColPos, userId, request, reportParamValues); DataSet ds = ConnectionUtils.getDataSet(executeSql, getDbInfo()); @@ -2044,34 +1861,31 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa dataValue.setAlignment("center"); dataValue.setDisplayValue(ds.getString(i, cPos++)); headerValues.add(dataValue); - - //headerValues.add(ds.getString(i, cPos++)); } else if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_VALUE)) totalValue = ds.getString(i, cPos++); - } // for + } dataTotals.add(new CrossTabTotalValue(headerValues, Utils .truncateTotalDecimals(totalValue))); - } // for - } // if + } + } return dataTotals; - } // generateDataTotalsCrossTab - + } /** *********************************************************************************** */ public void hideColVisual(String colId) { visualManager.hideColumn(colId); if (pageDataCache != null) pageDataCache.columnVisualShowHide(colId, false); - } // hideColVisual + } public void showColVisual(String colId) { visualManager.showColumn(colId); if (pageDataCache != null) pageDataCache.columnVisualShowHide(colId, true); - } // showColVisual + } public void sortColVisual(String colId) { visualManager.setSortByColumn(colId); @@ -2079,13 +1893,13 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa pageDataCache = null; cachedPageNo = -1; - } // sortColVisual + } /** *********************************************************************************** */ public String generateDistinctValuesSQL(DataColumnType dct, String userId, HttpServletRequest request) throws RaptorException { return super.generateDistinctValuesSQL(reportParamValues, dct, userId, request); - } // generateDistinctValuesSQL + } public String getDbInfo() { return this.cr.getDbInfo(); @@ -2102,18 +1916,12 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa logger.debug(EELFLoggerDelegate.debugLogger, ("Flat File parseReportSQL ******* SQL " + sql)); sql = sql.replaceAll("([\\s]*\\() (?!FROM)", "("); sql = sql.replaceAll("[\\s]*\\)", ")"); - //sql = sql.replaceAll("[dD][eE][cC][oO][dD][eE] ", "decode"); - //sql = sql.replaceAll("[\\s]*\\(", "("); - //sql = replaceNewLine(sql, "decode ", "decode"); - //sql = replaceNewLine(sql, "DECODE ", "decode"); - //sql = replaceNewLine(sql, "Decode ", "decode"); String nextToken = getNextSQLParseToken(sql, true); String dbInfo = getDbInfo(); boolean isCYMBALScript = false; if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) { try { - org.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.portalsdk.analytics.util.RemDbInfo(); String dbType = remDbInfo.getDBType(dbInfo); if (dbType.equals("DAYTONA") && !(nextToken.toUpperCase().equals("SELECT"))) { isCYMBALScript = true; @@ -2124,9 +1932,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } if ( isCYMBALScript == false ) { while (nextToken.length() > 0) { - //System.out.println("LastToken " + lastToken + " NextToken " + nextToken); - - if (parsedSQL.length() == 0) { if (nextToken.toUpperCase().equals("SELECT")) parsedSQL.append("SELECT "); @@ -2155,9 +1960,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa parsedSQL.append(sql.substring(lastParsePos)); break; } else { - //System.out.println("Next Token " + nextToken); if (nextToken.charAt(nextToken.length() - 1) == ',') { - // The token ends with , nextToken = nextToken.substring(0, nextToken.length() - 1); if (nextToken.length() == 0) { @@ -2165,9 +1968,8 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa updatedReportCols.add(getParseSQLDataColumn(lastToken, null, parsedSQL, updatedReportCols, false)); lastToken = null; - } // else just comma => ignore it + } } else { - //System.out.println("Next Token " + nextToken + " is Here" + " Last Token " + lastToken); if (lastToken != null) { updatedReportCols.add(getParseSQLDataColumn(lastToken, nextToken, parsedSQL, updatedReportCols, false)); @@ -2177,28 +1979,25 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa parsedSQL, updatedReportCols, false)); } } else { - // The token doesn't end with , if (lastToken == null) lastToken = nextToken; else { String token = getNextSQLParseToken(sql, false); - //System.out.println(" ********** " + token + " " + lastToken); if (!token.toUpperCase().equals("FROM")) throw new org.onap.portalsdk.analytics.error.ValidationException( "|FROM keyword or a comma expected after [" + nextToken + "]."); - //System.out.println("Next Token " + nextToken); updatedReportCols.add(getParseSQLDataColumn(lastToken, nextToken, parsedSQL, updatedReportCols, false)); lastToken = null; - } // else - } // else - } // else + } + } + } lastParsePos = curSQLParsePos; nextToken = getNextSQLParseToken(sql, true); - } // while - } else { // if CYMBAL Script + } + } else { nextToken = getNextCYMBALSQLParseToken(sql, true); Pattern re = null; Matcher matcher = null; @@ -2207,7 +2006,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa if (lastToken == null) lastToken = nextToken; if( lastToken.toUpperCase().equals("DO DISPLAY")) { - re = Pattern.compile("each(.*)\\[.(.*?)\\]"); //\\[(.*?)\\] + re = Pattern.compile("each(.*)\\[.(.*?)\\]"); matcher = re.matcher(nextToken); if (matcher.find()) { extracted = matcher.group(); @@ -2238,7 +2037,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa return parsedSQL.toString(); - } // parseReportSQL + } private String getNextCYMBALSQLParseToken(String sql, boolean updateParsePos) { int braketCount = 0; @@ -2250,11 +2049,10 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa if (ch!='\n') nextToken.append(ch); else break; - } // for + } return nextToken.toString(); - } // getNextSQLParseToken - + } private String getNextSQLParseToken(String sql, boolean updateParsePos) { int braketCount = 0; boolean isInsideQuote = false; @@ -2283,12 +2081,11 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa braketCount--; else if (ch == '\''/* ||ch=='\"' */) isInsideQuote = (!isInsideQuote); - } // else - } // for + } + } return nextToken.toString(); - } // getNextSQLParseToken - + } private DataColumnType getParseSQLDataColumn(String sqlExpression, String colId, StringBuffer parsedSQL, Vector updatedReportCols, boolean isCYMBALScript) throws RaptorException { DataColumnType dct = null; @@ -2302,7 +2099,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa dct = getColumnById(colId); } else { - // Getting unique column id + colId = ""; int colIdN = 0; for (int i = 0; (i < sqlExpression.length()) && (colIdN < 2); i++) @@ -2328,10 +2125,10 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa idAlreadyUsed = true; break; } - } // for + } colId += (colIdN - 1); - } // else + } if (dct == null) { dct = (new ObjectFactory()).createDataColumnType(); @@ -2339,7 +2136,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa dct.setDisplayWidth(10); dct.setDisplayAlignment("Left"); dct.setVisible(true); - dct.setGroupBreak(false); // ??? + dct.setGroupBreak(false); boolean isValidIdentifier = Character.isLetterOrDigit(sqlExpression.charAt(0)); for (int i = 0; i < sqlExpression.length(); i++) @@ -2353,8 +2150,8 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa dct.setDisplayName(sqlExpression); } else { dct.setDisplayName(colId); - } // else - } // if + } + } if(!isCYMBALScript) sqlExpression = sqlExpression.replaceAll(", '", ",'"); dct.setDbColName(sqlExpression); @@ -2362,7 +2159,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa dct.setCalculated(true); dct.setColType(AppConstants.CT_CHAR); dct.setDbColType(AppConstants.CT_CHAR); - adjustColumnType(dct); // ??? + adjustColumnType(dct); if(!isCYMBALScript) { if (parsedSQL.toString().equals("SELECT ") @@ -2376,8 +2173,7 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa } return dct; - } // getParseSQLDataColumn - + } private boolean isParseSQLColID(String token) { if (nvl(token).length() == 0) return false; @@ -2390,12 +2186,12 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa if (!(Character.isLetterOrDigit(ch) || ch == '_')) return false; - } // for + } return true; - } // isParseSQLColID + } - /*private*/ public String parseReportSQLForDrillDownParams(String reportSQL, DataColumnType dataColumnRequest, HttpServletRequest request){ + public String parseReportSQLForDrillDownParams(String reportSQL, DataColumnType dataColumnRequest, HttpServletRequest request){ String param = nvl(dataColumnRequest.getDrillDownParams()); String sql = reportSQL; int pos = 0; @@ -2409,7 +2205,6 @@ public class ReportRuntime extends ReportWrapper implements Cloneable, Serializa else break; if (param.charAt(startIdx + 1) == '#') { - // Parameter is a form field value String fieldId = param.substring(startIdx + 2, endIdx); String fieldValue = ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(), request.getParameter(fieldId)); sql = Utils.replaceInString(sql, "[" + fieldId.toUpperCase()+"]", fieldValue ); @@ -2479,7 +2274,6 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep try { return super.clone(); } catch (CloneNotSupportedException e) { - // this shouldn't happen, since we are Cloneable throw new InternalError("Cloning throws error."); } } @@ -2491,7 +2285,6 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep public String getReportSQLWithRowNum(String _orderBy, boolean asc) { String sql = getWholeSQL(); int closeBracketPos = 0; - // Added reportSQLOnlyFirstPart which has Column information with Rownum return nvl(getReportSQLOnlyFirstPart()) + " " + sql + ") x "; } @@ -2540,11 +2333,11 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep visibleColExist = true; break; } - } // for - } // if + } + } return visibleColExist; - } // canPersistLinearReport + } public void persistLinearReport(HttpServletRequest request) throws RaptorException { @@ -2557,8 +2350,6 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep String reportXML = marshal(); logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Report " + reportID + " XML marshalled succesfully")); - - // Update report verifySQLBasedReportAccess(request); reportSecurity.reportUpdate(request); connection = DbUtils.startTransaction(); @@ -2575,7 +2366,7 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep } finally { DbUtils.clearConnection(connection); } - } // persistLinearReport + } public void persistDashboardReport(HttpServletRequest request) throws RaptorException { @@ -2586,8 +2377,6 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep String reportXML = marshal(); logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Report " + reportID + " XML marshalled succesfully")); - - // Update report verifySQLBasedReportAccess(request); reportSecurity.reportUpdate(request); connection = DbUtils.startTransaction(); @@ -2604,7 +2393,7 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep } finally { DbUtils.clearConnection(connection); } - } // persistDashboardReport + } public String getTotalSql() { return totalSql; } @@ -2663,7 +2452,6 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep ObjectMapper mapper = new ObjectMapper(); ReportJSONRuntime reportJSONRuntime = new ReportJSONRuntime(); reportJSONRuntime.setReportTitle(getReportTitle()); - //reportJSONRuntime.setReportSubTitle(getReportSubTitle()); reportJSONRuntime.setReportID(getReportID()); reportJSONRuntime.setReportDescr(getReportDescr()); reportJSONRuntime.setReportName(getReportName()); @@ -2672,7 +2460,6 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep reportJSONRuntime.setAllowEdit(isAllowEdit(request)); reportJSONRuntime.setColIdxTobeFreezed(getFrozenColumnId()); reportJSONRuntime.setNumFormCols(getNumFormColsAsInt()); - //back button url reportJSONRuntime.setBackBtnURL(""); String chartType = getChartType(); boolean displayChart = (nvl(chartType).length()>0)&&getDisplayChart(); @@ -2699,7 +2486,6 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep ffJSON.setHelpText(ff.getHelpText()); ffJSON.setValidationType(ff.getValidationType()); ffJSON.setVisible(ff.isVisible()); - //ffJSON.setTriggerOtherFormFields(ff.getDependsOn()); IdNameList lookup = null; lookup = ff.getLookupList(); String selectedValue = ""; @@ -2723,7 +2509,7 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep lookupList = lookup; try { lookup.loadUserData(0, "", ff.getDbInfo(), ff.getUserId()); - } catch (Exception e ){ e.printStackTrace(); //throw new RaptorRuntimeException(e); + } catch (Exception e ){ e.printStackTrace(); } } lookup.trimToSize(); @@ -2735,7 +2521,6 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep IdNameValue value = lookup.getNext(); readOnly = value.isReadOnly(); if(requestValue != null && Arrays.asList(requestValue).contains(value.getId())) { - //if(value.getId().equals(requestValue)) value.setDefaultValue(true); } else if (AppUtils.nvl(ff.getDefaultValue()).length()>0) { if(ff.getDefaultValue().equals(value.getId())) { @@ -2749,7 +2534,7 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep || ff.getFieldType().equals(FormField.FFT_LIST_MULTI)) { formFieldValues.add(value); } - //break; + } } else { if(requestValue!=null && requestValue.length>0) { @@ -2783,7 +2568,6 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep } // for } reportJSONRuntime.setFormFieldList(formFieldJSONList); - //reportJSONRuntime.setReportDataColumns(get); int count = 0; Map<String,Object> dvJSON = null; if(rd!=null) { @@ -2791,6 +2575,7 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep reportJSONRuntime.setTotalRows(getReportDataSize()); ArrayList<ColumnHeader> colList = new ArrayList<>(); ArrayList<Map<String,Object>> reportDataRows = new ArrayList<>(); + ArrayList<Map<String,Object>> reportTotalDataRows = new ArrayList<Map<String,Object>>(); for(rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext(); ) { count++; ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext(); @@ -2815,10 +2600,26 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep reportDataRows.add(dvJSON); } } + if(rd.reportDataTotalRow != null) { + for(rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext(); count++) { + dvJSON = new HashMap<String,Object>(); + DataRow dr = rd.reportDataTotalRow.getNext(); + for(dr.resetNext(); dr.hasNext(); ) { + DataValue dv = dr.getNext(); + try { + dvJSON.put(dv.getColId(), dv); + } catch (Exception ex) { + ex.printStackTrace(); + + } + } + reportTotalDataRows.add(dvJSON); + } + } reportJSONRuntime.setReportDataColumns(colList); reportJSONRuntime.setReportDataRows(reportDataRows); - //reportJSONRuntime.setSqlWhole(getWholeSQL()); reportJSONRuntime.setPageSize(getPageSize()); + reportJSONRuntime.setReportTotalDataRows(reportTotalDataRows); } @@ -2880,16 +2681,14 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep setTriggerThisFormFieldCheck(getReportFormFields(), ff); SQL = parseAndFillReq_Session_UserValues(request, SQL, userId); SQL = parseAndFillOtherFormfieldValues(request, SQL, userId, formFieldJSONList); - //SQL = parseAndFillWithCurrentValues(formGrid,SQL, ff); String defaultSQL = lu.getDefaultSQL(); defaultSQL = parseAndFillReq_Session_UserValues(request, defaultSQL, userId); - //defaultSQL = parseAndFillWithCurrentValues(formGrid,defaultSQL, ff); lookup = new IdNameSql(-1,SQL,defaultSQL); lookupList = lookup; try { lookup.loadUserData(0, "", ff.getDbInfo(), ff.getUserId()); - } catch (Exception e ){ e.printStackTrace(); //throw new RaptorRuntimeException(e); + }catch (Exception e) { } } lookup.trimToSize(); @@ -2898,10 +2697,6 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep ArrayList<String> requestValueList = new ArrayList<>(); requestValueList.add(requestValue); - /*if(ff.isTriggerThisFormfield()) { - refreshFormFieldsWithLatestValue(request, userId, ff, formFieldJSONList); - }*/ - for (lookup.resetNext(); lookup.hasNext();) { IdNameValue value = lookup.getNext(); @@ -2911,7 +2706,7 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep value.setDefaultValue(true); } formFieldValues.add(value); - //break; + } } else { @@ -2931,21 +2726,17 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep ((IdNameSql)lookup).setSQL(oldSQL); } } - - - //if(!ff.isTriggerThisFormfield()) { ffJSON.setFormFieldValues(formFieldValues); - //} + break; - } //if - } //for - }//for - }//if + } + } + } + } reportJSONRuntime.setFormFieldList(formFieldJSONList); - //reportJSONRuntime.setReportDataColumns(get); return reportJSONRuntime; @@ -2993,16 +2784,12 @@ public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.Rep boolean multiple = false; if(type.equals("LIST_MULTI_SELECT")) multiple = true; - //multiple = (selectedItems.size()>1); for(Iterator iter = selectedItems.iterator(); iter.hasNext(); ) { count++; String entry = (String) iter.next(); if(count == 1 && multiple) value.append("("); - //if(type.equals(FormField.FFT_CHECK_BOX)) - /*if(type.equals(FormField.FFT_CHECK_BOX)) - value.append("'"+Utils.oracleSafe(entry)+"'"); - else*/ if (type.equals(FormField.FFT_LIST_MULTI)) + else if (type.equals(FormField.FFT_LIST_MULTI)) value.append("'"+Utils.oracleSafe(entry)+"'"); else if(type.equals(FormField.FFT_LIST_BOX)) value.append(Utils.oracleSafe(entry)); @@ -3029,14 +2816,10 @@ public String parseAndFillWithCurrentValues(HttpServletRequest request, String s String fieldDisplay = getFormFieldDisplayName(fft); String formfield_value = ""; List<String> selectedItems = new ArrayList<>(); - //Added so that Combo Box in old RAPTOR definition is translated to List box if(fft.getFieldType().equals(FormField.FFT_COMBO_BOX)) { fft.setFieldType(FormField.FFT_LIST_BOX); } if(!fft.getFieldType().equals(FormField.FFT_BLANK)) { - //if(source_Formfield==null || (source_Formfield!=null && !fft.getFieldId().equals(source_Formfield.getFieldName()))) { - // Add oracle safe - // Add param base sql if(fft.getFieldType().equals(FormField.FFT_LIST_MULTI) || fft.getFieldType().equals(FormField.FFT_CHECK_BOX)) { if(request.getParameterValues(fieldId)!=null && request.getParameterValues(fieldId).length > 0) { @@ -3067,73 +2850,10 @@ public String parseAndFillWithCurrentValues(HttpServletRequest request, String s } } else if (fft.getValidationType().equals(FormField.VT_DATE) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)|| fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) { - /*if(formGrid.hasFellow(fieldId, true)) { - Datebox tb = (Datebox) formGrid.getFellowIfAny(fieldId, true); - try { - formfield_value = tb.getText(); - } catch (WrongValueException ex) { - formfield_value = ""; - } - if(AppUtils.nvl(formfield_value).length() > 0) { - if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)) { - if(formGrid.hasFellow(fieldId+"_Hr", true)) { - Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true); - formfield_value = formfield_value + " " + hiddenLbHr.getValue(); - } - } else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)) { - if(formGrid.hasFellow(fieldId+"_Min", true)) { - Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true); - //formfield_value = formfield_value + " " + hiddenLbHr.getValue(); - Label hiddenLbMin = (Label) formGrid.getFellowIfAny(fieldId+"_Min", true); - formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue(); - - } - } else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) { - if(formGrid.hasFellow(fieldId+"_Sec", true)) { - Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true); - //formfield_value = formfield_value + " " + hiddenLbHr.getValue(); - Label hiddenLbMin = (Label) formGrid.getFellowIfAny(fieldId+"_Min", true); - //formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue(); - Label hiddenLbSec = (Label) formGrid.getFellowIfAny(fieldId+"_Sec", true); - formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue()+ ":" +hiddenLbSec.getValue(); - - } - } - } - } else { - formfield_value = ""; - }*/ } else if ((fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)|| fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC))) { - /*if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)|| - fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) { - if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)) { - if(formGrid.hasFellow(fieldId+"_Hr", true)) { - Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true); - formfield_value = formfield_value + " " + hiddenLbHr.getValue(); - } - } else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)) { - if(formGrid.hasFellow(fieldId+"_Min", true)) { - Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true); - //formfield_value = formfield_value + " " + hiddenLbHr.getValue(); - Label hiddenLbMin = (Label) formGrid.getFellowIfAny(fieldId+"_Min", true); - formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue(); - - } - } else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) { - if(formGrid.hasFellow(fieldId+"_Sec", true)) { - Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true); - //formfield_value = formfield_value + " " + hiddenLbHr.getValue(); - Label hiddenLbMin = (Label) formGrid.getFellowIfAny(fieldId+"_Min", true); - //formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue(); - Label hiddenLbSec = (Label) formGrid.getFellowIfAny(fieldId+"_Sec", true); - formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue()+ ":" +hiddenLbSec.getValue(); - } - } - - } */ } else if (fft.getFieldType().equals(FormField.FFT_TEXT_W_POPUP)) { if(request.getParameter(fieldId)!=null) { formfield_value = request.getParameter(fieldId); @@ -3146,16 +2866,15 @@ public String parseAndFillWithCurrentValues(HttpServletRequest request, String s } else { formfield_value = ""; } - //} + } if(nvl(formfield_value).length()>0) { sql = Utils.replaceInString(sql, fieldDisplay, formfield_value); } else { sql = Utils.replaceInString(sql, "'"+fieldDisplay+"'", "null"); sql = Utils.replaceInString(sql, fieldDisplay, "null"); - //sql = Utils.replaceInString(sql, fieldDisplay, "''"); } - } // for + } } } return sql; @@ -3177,7 +2896,6 @@ public String parseAndFillWithCurrentValues(HttpServletRequest request, String s } for (int i = 0; i < scheduleSessionParameters.length; i++) { - //debugLogger.debug(" Session " + " scheduleSessionParameters[i] " + scheduleSessionParameters[i].toUpperCase() + " " + request.getParameter(scheduleSessionParameters[i])); if(request.getParameter(scheduleSessionParameters[i])!=null && request.getParameter(scheduleSessionParameters[i]).trim().length()>0 ) sql = Utils.replaceInString(sql, "[" + scheduleSessionParameters[i].toUpperCase()+"]", request.getParameter(scheduleSessionParameters[i]) ); if(request.getAttribute(scheduleSessionParameters[i])!=null && ((String)request.getAttribute(scheduleSessionParameters[i])).trim().length()>0 ) @@ -3186,14 +2904,10 @@ public String parseAndFillWithCurrentValues(HttpServletRequest request, String s } for (int i = 0; i < sessionParameters.length; i++) { - //if(!sessionParameters[i].startsWith("ff")) - //fieldSQL = Utils.replaceInString(fieldSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i].toUpperCase()) ); - //else { if (session.getAttribute(sessionParameters[i])!=null && ((String)session.getAttribute(sessionParameters[i])).length() > 0) { - //debugLogger.debug(" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i])); sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) ); } - // } + } sql = Utils.replaceInString(sql, "[USERID]", user_id); sql = Utils.replaceInString(sql, "[USER_ID]", user_id); @@ -3203,4 +2917,24 @@ public String parseAndFillWithCurrentValues(HttpServletRequest request, String s return sql; } -} // ReportRuntime + private static String reverseDisplayValue(String value) { + int i = value.length() - 1; + int start, end = i + 1; + String result = ""; + while (i >= 0) { + if (value.charAt(i) == ',') { + start = i + 1; + while (start != end) + result += value.charAt(start++); + result += ','; + end = i; + } + i--; + } + start = 0; + while (start != end) + result += value.charAt(start++); + return result; + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/scheduler/SendEmail.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/scheduler/SendEmail.java index 1e0f574b..191334f6 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/scheduler/SendEmail.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/scheduler/SendEmail.java @@ -36,9 +36,9 @@ * */ package org.onap.portalsdk.analytics.scheduler; - import java.io.File; import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -51,75 +51,59 @@ import java.sql.Types; import java.util.ArrayList; import java.util.Calendar; import java.util.List; - +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; import org.onap.portalsdk.analytics.error.ReportSQLException; import org.onap.portalsdk.analytics.scheduler.SchedulerUtil.Executor; import org.onap.portalsdk.analytics.system.Globals; - - - - +import org.onap.portalsdk.analytics.util.EmailUtils; +import org.onap.portalsdk.analytics.util.MailAttachment; public class SendEmail { - -SchedulerUtil schedulerUtil; - + SchedulerUtil schedulerUtil; + EmailUtils emailUtils; public SendEmail() { - } - - - public void sendEmail( String p_mail_server, String p_sender, String p_subject, String p_mail_text, String p_url, int p_file_type, int p_schedule_id, int p_time_interval, boolean p_send_attachment, int connectionTimeout) throws SQLException, ReportSQLException{ - + public void sendEmail(String p_mail_server, String p_sender, String p_subject, String p_mail_text, String p_url, + int p_file_type, int p_schedule_id, int p_time_interval, boolean p_send_attachment, int connectionTimeout) + throws Exception { String allEmailAddr = ""; final List<String> emailArr = new ArrayList<>(); - //int count1 = 0; String schedular_email; - - - schedular_email = (String) schedulerUtil.getSingleResult("select email from fn_user au, cr_report_schedule crs where CRS.SCHED_USER_ID = AU.USER_ID and CRS.SCHEDULE_ID = "+ p_schedule_id, "email"); - - - String sql=Globals.getSchedulerUserEmails().replace("[p_schedule_id]", p_schedule_id+""); + schedular_email = (String) schedulerUtil.getSingleResult( + "select email from fn_user au, cr_report_schedule crs where CRS.SCHED_USER_ID = AU.USER_ID and CRS.SCHEDULE_ID = " + + p_schedule_id, + "email"); + String sql = Globals.getSchedulerUserEmails().replace("[p_schedule_id]", p_schedule_id + ""); schedulerUtil.getAndExecute(sql, new Executor() { - @Override public void execute(ResultSet rs) throws SQLException { - - emailArr.add(rs.getString("email")); - // count1 = count1 + 1 + emailArr.add(rs.getString("email")); } - }); - if (!p_send_attachment) { http_to_blob(p_url, p_file_type, p_schedule_id, connectionTimeout); } - int i = 0; for (String email : emailArr) { - /* If the email address is invalid ignore that email address */ if (email.contains("@")) { - if (i == 0) allEmailAddr = email; else allEmailAddr += ',' + email; - i++; } } - - /*List<MailAttachment> mailAttachments = null; - + List<MailAttachment> mailAttachments = null; + p_send_attachment=true; if (p_file_type > 1 && p_send_attachment) { mailAttachments = add_attachment(p_url, p_file_type, p_schedule_id, connectionTimeout); } - AppUtils.notifyWithAttachments(p_mail_text, emailArr.toArray(new String[emailArr.size()]), p_sender, p_subject, new String[] { schedular_email }, null, mailAttachments, true); - */ + emailUtils.notifyWithAttachments(p_mail_text, emailArr.toArray(new String[emailArr.size()]), p_sender, + p_subject, new String[] { schedular_email }, null, mailAttachments, true); } - class HistRec { - String file_blob; BigDecimal rep_id; BigDecimal hist_id; @@ -133,160 +117,134 @@ SchedulerUtil schedulerUtil; int user_id; String deleted_yn; } - - - private HistRec http_to_blob(String p_url, int v_file_type, int p_schedule_id, int connectionTimeout) throws SQLException , ReportSQLException{ - - + private HistRec http_to_blob(String p_url, int v_file_type, int p_schedule_id, int connectionTimeout) + throws SQLException, ReportSQLException { final HistRec v_hist_rec = initializeVHistoryRecord(p_url, v_file_type, p_schedule_id); HttpURLConnection con = null; - try { + try { URL url = new URL(p_url); con = (HttpURLConnection) url.openConnection(); - con.setConnectTimeout(connectionTimeout*1000); + con.setConnectTimeout(connectionTimeout * 1000); con.setRequestMethod("GET"); - schedulerUtil.insertOrUpdate("INSERT INTO cr_filehist_log (SCHEDULE_ID, url, notes, run_time) VALUES ("+ p_schedule_id +",'" + p_url+ "','http_to_blob: Initiated HTTP request', " + Globals.getCurrentDateString() + " )"); + schedulerUtil.insertOrUpdate("INSERT INTO cr_filehist_log (SCHEDULE_ID, url, notes, run_time) VALUES (" + + p_schedule_id + ",'" + p_url + "','http_to_blob: Initiated HTTP request', " + + Globals.getCurrentDateString() + " )"); int responseCode = con.getResponseCode(); String outputFolder = Globals.getProjectFolder() + java.io.File.separator + Globals.getOutputFolder(); String fileName = v_hist_rec.file_name; createFile(con, outputFolder, fileName); - File readFile = new File(outputFolder + java.io.File.separator + fileName); - // need to revist this conversion; may not be safe for large file sizes - v_hist_rec.file_size = (int)readFile.length(); - - schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url +"', 'http_to_blob: http response recieved. Code " + responseCode + "', " + Globals.getCurrentDateString() + " )"); - - //v_hist_rec.file_blob = response.toString(); - //v_hist_rec.file_size = v_hist_rec.file_blob.length(); - + v_hist_rec.file_size = (int) readFile.length(); + schedulerUtil + .insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + + p_schedule_id + ",'" + p_url + "', 'http_to_blob: http response recieved. Code " + + responseCode + "', " + Globals.getCurrentDateString() + " )"); List<Object> params = new ArrayList<>(); List<Integer> types = new ArrayList<>(); prepareHisRecUpdate(v_hist_rec, params, types); - - schedulerUtil - .insertOrUpdateWithPrepared("INSERT INTO cr_report_file_history(HIST_ID, SCHED_USER_ID, SCHEDULE_ID, USER_ID, REP_ID, RUN_DATE, RECURRENCE, FILE_TYPE_ID, FILE_NAME, FILE_SIZE, RAPTOR_URL, ERROR_YN, ERROR_CODE, DELETED_YN, DELETED_BY)" + schedulerUtil.insertOrUpdateWithPrepared( + "INSERT INTO cr_report_file_history(HIST_ID, SCHED_USER_ID, SCHEDULE_ID, USER_ID, REP_ID, RUN_DATE, RECURRENCE, FILE_TYPE_ID, FILE_NAME, FILE_SIZE, RAPTOR_URL, ERROR_YN, ERROR_CODE, DELETED_YN, DELETED_BY)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", - params, types - ); - - try(FileInputStream fileStream = new FileInputStream(readFile)) { - schedulerUtil.updateBinaryStream("update cr_report_file_history set file_blob = ? where hist_id = ?", v_hist_rec.hist_id, fileStream, v_hist_rec.file_size); - }catch (Exception e){ - //throw the exception to outer block for handling it + params, types); + try (FileInputStream fileStream = new FileInputStream(readFile)) { + schedulerUtil.updateBinaryStream("update cr_report_file_history set file_blob = ? where hist_id = ?", + v_hist_rec.hist_id, fileStream, v_hist_rec.file_size); + } catch (Exception e) { throw e; } - - String userAddRecSql = - Globals.getSchedulerUserEmails().replace("[p_schedule_id]", p_schedule_id+""); - + String userAddRecSql = Globals.getSchedulerUserEmails().replace("[p_schedule_id]", p_schedule_id + ""); schedulerUtil.getAndExecute(userAddRecSql, new Executor() { - @Override public void execute(ResultSet rs) throws SQLException { - try { - schedulerUtil.insertOrUpdate("INSERT INTO CR_HIST_USER_MAP (HIST_ID, USER_ID) values ( " + v_hist_rec.hist_id + "," + rs.getInt("user_id") + ")"); + schedulerUtil.insertOrUpdate("INSERT INTO CR_HIST_USER_MAP (HIST_ID, USER_ID) values ( " + + v_hist_rec.hist_id + "," + rs.getInt("user_id") + ")"); } catch (ReportSQLException e) { throw new SQLException(e.getMessage()); } } - }); - - schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url + "','Success: http_to_blob', " + Globals.getCurrentDateString() + " )"); - - + schedulerUtil.insertOrUpdate( + "insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + + ",'" + p_url + "','Success: http_to_blob', " + Globals.getCurrentDateString() + " )"); } catch (Exception e) { - schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url + "', 'Failure: http_to_blob : Exception" + e.getMessage() +"', " + Globals.getCurrentDateString() + " )"); + schedulerUtil + .insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + + p_schedule_id + ",'" + p_url + "', 'Failure: http_to_blob : Exception" + e.getMessage() + + "', " + Globals.getCurrentDateString() + " )"); e.printStackTrace(); } finally { - if(con != null) + if (con != null) con.disconnect(); } return v_hist_rec; - } - - - protected void prepareHisRecUpdate(final HistRec v_hist_rec, List<Object> params, - List<Integer> types) { - params.add( v_hist_rec.hist_id); + protected void prepareHisRecUpdate(final HistRec v_hist_rec, List<Object> params, List<Integer> types) { + params.add(v_hist_rec.hist_id); types.add(Types.BIGINT); - params.add( v_hist_rec.sched_user_id); + params.add(v_hist_rec.sched_user_id); types.add(Types.INTEGER); - params.add( v_hist_rec.schedule_id); + params.add(v_hist_rec.schedule_id); types.add(Types.INTEGER); - params.add( v_hist_rec.user_id); + params.add(v_hist_rec.user_id); types.add(Types.INTEGER); - params.add( v_hist_rec.rep_id); + params.add(v_hist_rec.rep_id); types.add(Types.BIGINT); - params.add( new java.sql.Date(Calendar.getInstance().getTime().getTime())); + params.add(new java.sql.Date(Calendar.getInstance().getTime().getTime())); types.add(Types.DATE); - params.add( v_hist_rec.recurrence); + params.add(v_hist_rec.recurrence); types.add(Types.VARCHAR); - params.add( v_hist_rec.file_type_id); + params.add(v_hist_rec.file_type_id); types.add(Types.INTEGER); - params.add( v_hist_rec.file_name); + params.add(v_hist_rec.file_name); types.add(Types.VARCHAR); - params.add( v_hist_rec.file_size); + params.add(v_hist_rec.file_size); types.add(Types.INTEGER); - params.add( v_hist_rec.raptor_url); + params.add(v_hist_rec.raptor_url); types.add(Types.VARCHAR); - params.add( "N"); + params.add("N"); types.add(Types.VARCHAR); - params.add( "NULL"); + params.add("NULL"); types.add(Types.INTEGER); - params.add( v_hist_rec.deleted_yn); + params.add(v_hist_rec.deleted_yn); types.add(Types.VARCHAR); - params.add(v_hist_rec.sched_user_id ); + params.add(v_hist_rec.sched_user_id); types.add(Types.INTEGER); } - - - protected HistRec initializeVHistoryRecord(String p_url, int v_file_type, - int p_schedule_id) throws SQLException, - ReportSQLException { - + protected HistRec initializeVHistoryRecord(String p_url, int v_file_type, int p_schedule_id) + throws SQLException, ReportSQLException { final HistRec v_hist_rec = new HistRec(); - - v_hist_rec.rep_id = (BigDecimal) schedulerUtil.getSingleResult("SELECT rep_id FROM cr_report_schedule WHERE schedule_id =" + p_schedule_id, "rep_id"); - - Object sequenceId = schedulerUtil.getSingleResult(Globals.getSequenceNextVal().replace("[sequenceName]", "seq_cr_report_file_history"),"ID"); - - if(sequenceId instanceof Long) - v_hist_rec.hist_id = new BigDecimal((Long)sequenceId); - else if(sequenceId instanceof BigDecimal) - v_hist_rec.hist_id = (BigDecimal)sequenceId; - - v_hist_rec.file_name = (String) schedulerUtil.getSingleResult("select translate(title||to_char( "+ Globals.getCurrentDateString() + ",'MM-dd-yyyyHH24:mm:ss'), " - + "'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'||'():;.-`~^\\|'||chr(34)||chr(39)||chr(9)||' ', " - + "'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')|| "+ v_hist_rec.hist_id +" as title FROM cr_report WHERE rep_id = "+v_hist_rec.rep_id, "title"); - - + v_hist_rec.rep_id = (BigDecimal) schedulerUtil + .getSingleResult("SELECT rep_id FROM cr_report_schedule WHERE schedule_id =" + p_schedule_id, "rep_id"); + Object sequenceId = schedulerUtil.getSingleResult( + Globals.getSequenceNextVal().replace("[sequenceName]", "seq_cr_report_file_history"), "ID"); + if (sequenceId instanceof Long) + v_hist_rec.hist_id = new BigDecimal((Long) sequenceId); + else if (sequenceId instanceof BigDecimal) + v_hist_rec.hist_id = (BigDecimal) sequenceId; + v_hist_rec.file_name = (String) schedulerUtil.getSingleResult("select translate(title||to_char( " + + Globals.getCurrentDateString() + ",'MM-dd-yyyyHH24:mm:ss'), " + + "'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'||'():;.-`~^\\|'||chr(34)||chr(39)||chr(9)||' ', " + + "'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')|| " + v_hist_rec.hist_id + + " as title FROM cr_report WHERE rep_id = " + v_hist_rec.rep_id, "title"); class File { - String file_name; String file_ext; } final File file = new File(); - schedulerUtil.getAndExecute("select template_file from cr_report_template_map where report_id = " + v_hist_rec.rep_id, new Executor() { - - @Override - public void execute(ResultSet rs) throws SQLException { - - file.file_name = rs.getString("template_file"); - file.file_ext = file.file_name.substring(file.file_name.indexOf('.')); - - } - }); - + schedulerUtil.getAndExecute( + "select template_file from cr_report_template_map where report_id = " + v_hist_rec.rep_id, + new Executor() { + @Override + public void execute(ResultSet rs) throws SQLException { + file.file_name = rs.getString("template_file"); + file.file_ext = file.file_name.substring(file.file_name.indexOf('.')); + } + }); if (v_file_type == 2) { v_hist_rec.file_name = v_hist_rec.file_name + ".pdf"; - } else if (v_file_type == 4) { v_hist_rec.file_name = v_hist_rec.file_name + ".xls"; - } else if (v_file_type == 5) { if (file.file_name != null && file.file_ext.length() > 0) { v_hist_rec.file_name = v_hist_rec.file_name + file.file_ext; @@ -295,140 +253,87 @@ SchedulerUtil schedulerUtil; } } else if (v_file_type == 3) { v_hist_rec.file_name = v_hist_rec.file_name + ".csv"; - } - - - schedulerUtil.getAndExecute("select sched_user_id, rep_id, recurrence from cr_report_schedule where schedule_id="+p_schedule_id, new Executor() { - - @Override - public void execute(ResultSet rs) throws SQLException { - v_hist_rec.sched_user_id = rs.getInt("sched_user_id"); - v_hist_rec.rep_id = rs.getBigDecimal("rep_id"); - v_hist_rec.recurrence = rs.getString("recurrence"); - } - }); - - + schedulerUtil.getAndExecute( + "select sched_user_id, rep_id, recurrence from cr_report_schedule where schedule_id=" + p_schedule_id, + new Executor() { + @Override + public void execute(ResultSet rs) throws SQLException { + v_hist_rec.sched_user_id = rs.getInt("sched_user_id"); + v_hist_rec.rep_id = rs.getBigDecimal("rep_id"); + v_hist_rec.recurrence = rs.getString("recurrence"); + } + }); v_hist_rec.file_size = 0; v_hist_rec.raptor_url = p_url; v_hist_rec.schedule_id = p_schedule_id; v_hist_rec.file_type_id = v_file_type; v_hist_rec.user_id = v_hist_rec.sched_user_id; v_hist_rec.deleted_yn = "N"; - return v_hist_rec; } - - - - /*private List<MailAttachment> add_attachment(String p_url, int v_file_type, int p_schedule_id, int connectionTimeout) throws SQLException,ReportSQLException{ - - + private List<MailAttachment> add_attachment(String p_url, int v_file_type, int p_schedule_id, int connectionTimeout) + throws SQLException, ReportSQLException,Exception { List<MailAttachment> mailAttachmentList = new ArrayList<MailAttachment>(); - final HistRec vHistRec = initializeVHistoryRecord(p_url, v_file_type, p_schedule_id); - - /* - refer to http_to_blob for more details - - String v_content_type; - String v_content_disposition; - int transfer_timeout_limit = 1800; - String v_title; - - if (v_file_type == 2) { - v_content_type = "application/pdf"; - v_content_disposition ="inline; filename=\""+v_title+".pdf\""; - - }else if(v_file_type == 4){ - v_content_type = "application/excel"; - v_content_disposition ="inline; filename=\""+v_title+".xls\""; - - }else if(v_file_type == 5){ - v_content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; - - if (file.file_ext != null && file.file_ext.length() > 0) { - v_content_disposition ="inline; filename=\""+v_title+ file.file_ext+"\""; - if (".xlsm".equals(file.file_ext)) { - v_content_type = "application/vnd.ms-excel.sheet.macroEnabled.12"; - } - } else { - v_content_disposition ="inline; filename=\""+v_title+".xlsx\""; - }; - }else if(v_file_type == 3){ - v_content_type = "application/csv"; - v_content_disposition ="inline; filename=\""+v_title+".csv\""; - - } - * ... / + final HistRec vHistRec = initializeVHistoryRecord(p_url, v_file_type, p_schedule_id); HttpURLConnection con = null; try { URL url = new URL(p_url); con = (HttpURLConnection) url.openConnection(); - con.setConnectTimeout(connectionTimeout*1000); + con.setConnectTimeout(connectionTimeout * 1000); con.setRequestMethod("GET"); - schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'"+ p_url +"', 'Success: http request began.', " + Globals.getCurrentDateString() + " )"); + schedulerUtil + .insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + + p_schedule_id + ",'" + p_url + "', 'Success: http request began.', " + + Globals.getCurrentDateString() + " )"); int responseCode = con.getResponseCode(); - String outputFolder = Globals.getProjectFolder() + java.io.File.separator + Globals.getOutputFolder(); String fileName = vHistRec.file_name; createFile(con, outputFolder, fileName); - MailAttachment mailAttachment = new MailAttachment(); mailAttachment.setAttachmentType(MailAttachment.FILE_ATTACHMENT); mailAttachment.setFilePathName(outputFolder); mailAttachment.setFileName(fileName); mailAttachmentList.add(mailAttachment); - - schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url +"', 'Success: http response recieved. Code " + responseCode + "', " + Globals.getCurrentDateString() + " )"); - - schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url + "','Success: added attachment', " + Globals.getCurrentDateString() + " )"); - + schedulerUtil + .insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + + p_schedule_id + ",'" + p_url + "', 'Success: http response recieved. Code " + responseCode + + "', " + Globals.getCurrentDateString() + " )"); + schedulerUtil.insertOrUpdate( + "insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + + ",'" + p_url + "','Success: added attachment', " + Globals.getCurrentDateString() + " )"); } catch (Exception e) { - schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url + "', 'Failure: adding attachment : Exception" + e.getMessage() +"', " + Globals.getCurrentDateString() + " )"); + schedulerUtil + .insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + + p_schedule_id + ",'" + p_url + "', 'Failure: adding attachment : Exception" + + e.getMessage() + "', " + Globals.getCurrentDateString() + " )"); e.printStackTrace(); } finally { - if(con != null) + if (con != null) con.disconnect(); } - - return mailAttachmentList; - }*/ - - - void createFile(HttpURLConnection con, String outputFolder, String fileName) - throws IOException { - //BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); - InputStream in = con.getInputStream(); - + } + public void createFile(HttpURLConnection con, String outputFolder, String fileName) throws IOException { + InputStream in = con.getInputStream(); try { - - try (FileOutputStream out = new FileOutputStream(outputFolder + java.io.File.separator + fileName )) { + try (FileOutputStream out = new FileOutputStream(outputFolder + java.io.File.separator + fileName)) { int inputLine; - while ((inputLine = in.read()) != -1) { out.write(inputLine); } out.flush(); - } catch(Exception e){ + } catch (Exception e) { throw e; } - - } - finally { + } finally { in.close(); } } - - public SchedulerUtil getSchedulerUtil() { return schedulerUtil; } - - public void setSchedulerUtil(SchedulerUtil schedulerUtil) { this.schedulerUtil = schedulerUtil; } - } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/util/AppConstants.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/util/AppConstants.java index dc90de77..1806db77 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/util/AppConstants.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/util/AppConstants.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the "License"); + * 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 * diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/util/Utils.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/util/Utils.java index 416fbab7..16d6a899 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/util/Utils.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/util/Utils.java @@ -246,7 +246,7 @@ public class Utils extends org.onap.portalsdk.analytics.RaptorObject { Vector allUsers = AppUtils.getAllUsers(query,param, isAdmin); Vector result = new Vector(allUsers.size()); - List<Item> resultLatest = new ArrayList<Item>(); + List<Item> resultLatest = new ArrayList<>(); for (Iterator iter = allUsers.iterator(); iter.hasNext();) { IdNameValue value = (IdNameValue) iter.next(); @@ -282,7 +282,7 @@ public class Utils extends org.onap.portalsdk.analytics.RaptorObject { Vector allRoles = AppUtils.getAllRoles(query, param, isAdmin); Vector result = new Vector(allRoles.size()); - List<Item> resultLatest = new ArrayList<Item>(); + List<Item> resultLatest = new ArrayList<>(); for (Iterator iter = allRoles.iterator(); iter.hasNext();) { IdNameValue value = (IdNameValue) iter.next(); @@ -357,11 +357,14 @@ public class Utils extends org.onap.portalsdk.analytics.RaptorObject { int numberOfTimesLooped = 0; boolean isSorted = false; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); - Date date1 = null, date2 = null; + Date date1 = null; + Date date2 = null; Date currDate = new Date(); Object[] matchingfileNamesArr = matchingFiles.toArray(); //System.out.println("SIZE " + matchingFiles.size()); - String fileName1 = "", fileName2 =""; + String fileName1 = ""; + String fileName2 =""; + do { isSorted = true; for (int j = 1; j < matchingfileNamesArr.length - numberOfTimesLooped++; j++) { diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/view/ReportData.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/view/ReportData.java index fd87f4cb..a0c35e0c 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/view/ReportData.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/view/ReportData.java @@ -157,11 +157,6 @@ public class ReportData extends org.onap.portalsdk.analytics.RaptorObject implem r++; } // for -/* for (reportDataRows.resetNext(); reportDataRows.hasNext();) { - DataRow dr = reportDataRows.getNext(); - dr.addDataValue(colIdx, new DataValue()); - } // for - */ for(int j = 0; j < dataList.size(); j++) { DataRow dr = (DataRow) dataList.get(j); dr.addDataValue(colIdx, new DataValue()); @@ -183,11 +178,9 @@ public class ReportData extends org.onap.portalsdk.analytics.RaptorObject implem try { boolean nameFound = false; - // String prevColName = null; Vector prevColNames = new Vector(); int columnSort = -1; for (int r = 0; r < colNameValues.size(); r++) { - //String colName = (String) colNameValues.get(r); String colName = ((DataValue) colNameValues.get(r)).getDisplayValue(); Integer colSortName = null; if(colNameSortValues!=null) @@ -266,9 +259,6 @@ public class ReportData extends org.onap.portalsdk.analytics.RaptorObject implem for (c = 0; c < getDataColumnCount(); c++) { dr.addDataValue(new DataValue()); } - - //reportDataRows.addDataRow(rowIdx, dr); - //dr.setRowNum(dataList.size()==0?1:dataList.size()); dataList.add(rowIdx, dr); } // insertRow @@ -288,7 +278,6 @@ public class ReportData extends org.onap.portalsdk.analytics.RaptorObject implem boolean nameFound = false; Vector prevRowNames = new Vector(); for (int c = 0; c < rowNameValues.size(); c++) { - //String rowName = (String) rowNameValues.get(c); String rowName = ((DataValue) rowNameValues.get(c)).getDisplayValue(); RowHeaderCol rhc = reportRowHeaderCols.getRowHeaderCol(c); @@ -341,7 +330,6 @@ public class ReportData extends org.onap.portalsdk.analytics.RaptorObject implem int colIdx = findColumnIdx(colNameValues, colNameSortValues, crossTabOrderManager, true, dataList); if ((rowIdx >= 0) && (colIdx >= 0)) { - //DataRow dr = reportDataRows.getDataRow(rowIdx); DataRow dr = (DataRow)dataList.get(rowIdx); dr.setRowValues(rowNameValues); dr.setDataValue(colIdx, value); @@ -435,11 +423,9 @@ public class ReportData extends org.onap.portalsdk.analytics.RaptorObject implem public void addRowNumbers(int pageNo, List dataList) { pageNo = 0; - //int startRowNum = ((pageNo < 0) ? 0 : pageNo) * pageSize + 1; int startRowNum = 0; RowHeaderCol rhc = new RowHeaderCol(); reportRowHeaderCols.addRowHeaderCol(0, rhc); - //rhc.setColumnWidth("5%"); for (int r = 0; r < dataList.size(); r++) { rhc.add(new RowHeader(startRowNum + r+"")); ((DataRow)dataList.get(r)).setRowNum(r); @@ -477,17 +463,13 @@ public class ReportData extends org.onap.portalsdk.analytics.RaptorObject implem reportColumnHeaderRows.addColumnHeaderRow(chr); chr.setRowHeight("30"); } // if - /*ColumnHeader ch = new ColumnHeader(displayName, (displayWidth > 100) ? "10%" : ("" - + displayWidth + "%"), alignment, 1, isRuntimeColSortDisabled ? null : colId); - */ + ColumnHeader ch = new ColumnHeader(displayName, displayWidthInPxls, alignment, 1, isRuntimeColSortDisabled ? null : colId); ch.setGroupLevel(level); ch.setStartGroup(start); ch.setColSpanGroup(colspan); ch.setColId(colId); ch.setSortable(sortable); - //chr.addColumnHeader(new ColumnHeader(displayName, (displayWidth > 100) ? "10%" : ("" - // + displayWidth + "%"), 1, isRuntimeColSortDisabled ? null : colId)); if (displayName != "Hidden") { @@ -529,7 +511,6 @@ public class ReportData extends org.onap.portalsdk.analytics.RaptorObject implem } // for int row = 0; for (reportDataRows.resetNext(); reportDataRows.hasNext();) { - //reportDataRows.getNext().getDataValue(colIdx).setVisible(newVisible); DataRow dr = reportDataRows.getNext(); if(colIdx < dr.getDataValueList().size()) { DataValue dv = dr.getDataValue(colIdx); @@ -718,25 +699,16 @@ public class ReportData extends org.onap.portalsdk.analytics.RaptorObject implem DataValue dataValue = new DataValue(); String totalValue = tVal.getTotalValue(); - // if(colDisplayTotal.length()>0&&(! - // colDisplayTotal.equals(AppConstants.TOTAL_SUM_ID))) - // totalValue = - // nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(colDisplayTotal))+": - // "+totalValue; dataValue.setDisplayValue(totalValue); //added below statement for displaying in excel as number dataValue.setDisplayTotal("SUM("); dataValue.setAlignment(totalsAlignment); dataValue.setBold(true); totalsDataRow.setDataValue(colIdx, dataValue); - - //totalsDataRow.addDataValue(dataValue); } // if } // for - //reportDataRows.addDataRow(totalsDataRow); - //dr.setRowValues(rowNameValues); Vector rowNameValues = new Vector(); for (int i=0; i < reportRowHeaderCols.size(); i++) { if(i==0) { @@ -745,9 +717,7 @@ public class ReportData extends org.onap.portalsdk.analytics.RaptorObject implem dataValue.setAlignment("center"); dataValue.setDisplayValue("Total"); rowNameValues.add(dataValue); - //rowNameValues.add("Total"); } else { - //rowNameValues.add(""); DataValue dataValue = new DataValue(); dataValue.setDisplayValue(""); rowNameValues.add(dataValue); @@ -757,7 +727,6 @@ public class ReportData extends org.onap.portalsdk.analytics.RaptorObject implem totalsDataRow.setRowValues(rowNameValues); totalsDataRow.setRowNum(dataList.size()); dataList.add(totalsDataRow); - //reportRowHeaderCols.getNext().addRowHeader(new RowHeader("", "30", 1, 0)); } // setColumnDataTotalsCrossTab public void setRowDataTotalsCrossTab(Vector rowDataTotals, String totalsAlignment, @@ -792,11 +761,6 @@ public class ReportData extends org.onap.portalsdk.analytics.RaptorObject implem DataValue dataValue = new DataValue(); String totalValue = tVal.getTotalValue(); - // if(rowDisplayTotal.length()>0&&(! - // rowDisplayTotal.equals(AppConstants.TOTAL_SUM_ID))) - // totalValue = - // nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(rowDisplayTotal))+": - // "+totalValue; dataValue.setDisplayValue(totalValue); //added below statement for displaying in excel as number dataValue.setDisplayTotal("SUM("); @@ -813,20 +777,13 @@ public class ReportData extends org.onap.portalsdk.analytics.RaptorObject implem String displayTotal, List dataList) { DataValue dataValue = new DataValue(); - // if(displayTotal.length()>0&&(! - // displayTotal.equals(AppConstants.TOTAL_SUM_ID))) - // totalValue = - // nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(displayTotal))+": - // "+totalValue; dataValue.setDisplayValue(totalValue); //added below statement for displaying in excel as number dataValue.setDisplayTotal("SUM("); dataValue.setAlignment(totalAlignment); dataValue.setBold(true); - //int colIdx = getDataColumnCount() - 1; int rowIdx = getDataRowCount() - 1; - //reportDataRows.getDataRow(rowIdx).getDataValueList().add(colIdx, dataValue); DataRow dr = (DataRow)dataList.get(rowIdx); dr.addDataValue(dr.getDataValueList().size(), dataValue); } // setGrandTotalCrossTab diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ChartDrillOptions.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ChartDrillOptions.java index de8593a8..dfe91132 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ChartDrillOptions.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ChartDrillOptions.java @@ -217,7 +217,7 @@ public class ChartDrillOptions { */ public List<ChartDrillFormfield> getTargetFormfield() { if (targetFormfield == null) { - targetFormfield = new ArrayList<ChartDrillFormfield>(); + targetFormfield = new ArrayList<>(); } return this.targetFormfield; } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ColFilterList.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ColFilterList.java index 6a56d590..18cb0075 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ColFilterList.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ColFilterList.java @@ -104,7 +104,7 @@ public class ColFilterList { */ public List<ColFilterType> getColFilter() { if (colFilter == null) { - colFilter = new ArrayList<ColFilterType>(); + colFilter = new ArrayList<>(); } return this.colFilter; } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DashboardEditorList.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DashboardEditorList.java index b2b105f5..577b896c 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DashboardEditorList.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DashboardEditorList.java @@ -104,7 +104,7 @@ public class DashboardEditorList { */ public List<DashboardEditorReport> getEditorList() { if (editorList == null) { - editorList = new ArrayList<DashboardEditorReport>(); + editorList = new ArrayList<>(); } return this.editorList; } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DashboardReports.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DashboardReports.java index b4ef7389..8f1f1d2f 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DashboardReports.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DashboardReports.java @@ -104,7 +104,7 @@ public class DashboardReports { */ public List<Reports> getReportsList() { if (reportsList == null) { - reportsList = new ArrayList<Reports>(); + reportsList = new ArrayList<>(); } return this.reportsList; } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DashboardReportsNew.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DashboardReportsNew.java index 3eadf6f5..849aa651 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DashboardReportsNew.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DashboardReportsNew.java @@ -110,7 +110,7 @@ public class DashboardReportsNew { */ public List<Reports> getReportsList() { if (reportsList == null) { - reportsList = new ArrayList<Reports>(); + reportsList = new ArrayList<>(); } return this.reportsList; } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DataColumnList.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DataColumnList.java index dffce0e9..4d9ba5d9 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DataColumnList.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DataColumnList.java @@ -106,7 +106,7 @@ public class DataColumnList { */ public List<DataColumnType> getDataColumn() { if (dataColumn == null) { - dataColumn = new ArrayList<DataColumnType>(); + dataColumn = new ArrayList<>(); } return this.dataColumn; } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DataSourceList.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DataSourceList.java index 86f2d9cc..ac69dbd2 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DataSourceList.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/DataSourceList.java @@ -40,7 +40,6 @@ // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.06.07 at 02:07:29 PM EDT -// package org.onap.portalsdk.analytics.xmlobj; @@ -104,7 +103,7 @@ public class DataSourceList { */ public List<DataSourceType> getDataSource() { if (dataSource == null) { - dataSource = new ArrayList<DataSourceType>(); + dataSource = new ArrayList<>(); } return this.dataSource; } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/FormFieldList.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/FormFieldList.java index 9ddba794..817075d3 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/FormFieldList.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/FormFieldList.java @@ -107,7 +107,7 @@ public class FormFieldList { */ public List<FormFieldType> getFormField() { if (formField == null) { - formField = new ArrayList<FormFieldType>(); + formField = new ArrayList<>(); } return this.formField; } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/FormatList.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/FormatList.java index 129f500a..d403798d 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/FormatList.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/FormatList.java @@ -106,7 +106,7 @@ public class FormatList { */ public List<FormatType> getFormat() { if (format == null) { - format = new ArrayList<FormatType>(); + format = new ArrayList<>(); } return this.format; } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/JavascriptList.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/JavascriptList.java index d2c04119..18d06675 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/JavascriptList.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/JavascriptList.java @@ -110,7 +110,7 @@ public class JavascriptList { */ public List<JavascriptItemType> getJavascriptItem() { if (javascriptItem == null) { - javascriptItem = new ArrayList<JavascriptItemType>(); + javascriptItem = new ArrayList<>(); } return this.javascriptItem; } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ObjectFactory.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ObjectFactory.java index 189b44b3..647afdb2 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ObjectFactory.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ObjectFactory.java @@ -308,7 +308,7 @@ public class ObjectFactory { */ @XmlElementDecl(namespace = "", name = "customReport") public JAXBElement<CustomReportType> createCustomReport(CustomReportType value) { - return new JAXBElement<CustomReportType>(_CustomReport_QNAME, CustomReportType.class, null, value); + return new JAXBElement<>(_CustomReport_QNAME, CustomReportType.class, null, value); } /** @@ -317,7 +317,7 @@ public class ObjectFactory { */ @XmlElementDecl(namespace = "", name = "comment") public JAXBElement<String> createComment(String value) { - return new JAXBElement<String>(_Comment_QNAME, String.class, null, value); + return new JAXBElement<>(_Comment_QNAME, String.class, null, value); } } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/PredefinedValueList.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/PredefinedValueList.java index 29baaf68..0752cab8 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/PredefinedValueList.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/PredefinedValueList.java @@ -104,7 +104,7 @@ public class PredefinedValueList { */ public List<String> getPredefinedValue() { if (predefinedValue == null) { - predefinedValue = new ArrayList<String>(); + predefinedValue = new ArrayList<>(); } return this.predefinedValue; } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ReportMap.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ReportMap.java index d0ce8781..e4d42437 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ReportMap.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/ReportMap.java @@ -455,7 +455,7 @@ public class ReportMap { */ public List<Marker> getMarkers() { if (markers == null) { - markers = new ArrayList<Marker>(); + markers = new ArrayList<>(); } return this.markers; } diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/SemaphoreList.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/SemaphoreList.java index 41930939..dc1d6b8a 100644 --- a/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/SemaphoreList.java +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/onap/portalsdk/analytics/xmlobj/SemaphoreList.java @@ -104,7 +104,7 @@ public class SemaphoreList { */ public List<SemaphoreType> getSemaphore() { if (semaphore == null) { - semaphore = new ArrayList<SemaphoreType>(); + semaphore = new ArrayList<>(); } return this.semaphore; } diff --git a/ecomp-sdk/epsdk-analytics/src/test/java/org/onap/portalsdk/analytics/xmlobj/ReportRuntimeTest.java b/ecomp-sdk/epsdk-analytics/src/test/java/org/onap/portalsdk/analytics/xmlobj/ReportRuntimeTest.java index 08b992e7..116c1bfa 100644 --- a/ecomp-sdk/epsdk-analytics/src/test/java/org/onap/portalsdk/analytics/xmlobj/ReportRuntimeTest.java +++ b/ecomp-sdk/epsdk-analytics/src/test/java/org/onap/portalsdk/analytics/xmlobj/ReportRuntimeTest.java @@ -592,10 +592,10 @@ public class ReportRuntimeTest { Mockito.when(rw.getDBInfo()).thenReturn(""); -// ReportRuntime reportRuntime = new ReportRuntime(); -// ReportRuntime spy = PowerMockito.spy(reportRuntime); -// PowerMockito.doReturn(rd).when(spy, "loadLinearReportData",1,"",1,mockedRequest,false); -// Mockito.when(reportRuntime.generateSubsetSQL(0, 1, "", mockedRequest, true, null)).thenReturn("subsetSql"); + ReportRuntime reportRuntime = new ReportRuntime(); + ReportRuntime spy = PowerMockito.spy(reportRuntime); + PowerMockito.doReturn(rd).when(spy, "loadLinearReportData",1,"",1,mockedRequest,false); + Mockito.when(reportRuntime.generateSubsetSQL(0, 1, "", mockedRequest, true, null)).thenReturn("subsetSql"); rr.loadReportData(1, "userId", 1, mockedRequest, true); |