/*
* ============LICENSE_START==========================================
* ONAP Portal SDK
* ===================================================================
* Copyright © 2017 AT&T Intellectual Property. All rights reserved.
* ===================================================================
*
* Unless otherwise specified, all software contained herein is licensed
* under the Apache License, Version 2.0 (the "License");
* you may not use this software except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Unless otherwise specified, all documentation contained herein is licensed
* under the Creative Commons License, Attribution 4.0 Intl. (the "License");
* you may not use this documentation except in compliance with the License.
* You may obtain a copy of the License at
*
* https://creativecommons.org/licenses/by/4.0/
*
* Unless required by applicable law or agreed to in writing, documentation
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ============LICENSE_END============================================
*
*
*/
/* ===========================================================================================
* This class is part of RAPTOR (Rapid Application Programming Tool for OLAP Reporting)
* Raptor : This tool is used to generate different kinds of reports with lot of utilities
* ===========================================================================================
*
* -------------------------------------------------------------------------------------------
* ActionHandler.java - This class is used to call actions related to reports.
* -------------------------------------------------------------------------------------------
*
*
*
* Changes
* -------
* 31-Aug-2009 : Version 8.5.1 (Sundar);
- reportFormFieldPopup iterates form field collections.
* 18-Aug-2009 : Version 8.5.1 (Sundar);- request Object is passed to prevent caching user/roles - Datamining/Hosting.
* 13-Aug-2009 : Version 8.5 (Sundar);- reportFormFieldPopup is changed to have effect on textfield with popup.
* 06-Aug-2009 : Version 9.0 (Sundar);- reportFormFieldPopupB is changed.
* 29-Jul-2009 : Version 8.4 (Sundar);- Previously report data for dashboard stored only page level data. This has been changed to show all the data up to the maximum specified.
* 27-Jul-2009 : Version 8.4 (Sundar);- Bug due to not showing back button after child report in drilldown is navigated more than
* one page is resolved.
* 14-Jul-2009 : Version 8.4 (Sundar); - Dashboard reports can now be generated excel as separate sheets or group together in PDF.
* They can also be scheduled.
*
*/
package org.onap.portalsdk.analytics.controller;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FilenameUtils;
import org.onap.portalsdk.analytics.error.RaptorException;
import org.onap.portalsdk.analytics.error.RaptorRuntimeException;
import org.onap.portalsdk.analytics.error.RaptorSchedularException;
import org.onap.portalsdk.analytics.error.ReportSQLException;
import org.onap.portalsdk.analytics.error.UserDefinedException;
import org.onap.portalsdk.analytics.error.ValidationException;
import org.onap.portalsdk.analytics.model.DashboardChildReport;
import org.onap.portalsdk.analytics.model.DataCache;
import org.onap.portalsdk.analytics.model.ReportHandler;
import org.onap.portalsdk.analytics.model.ReportLoader;
import org.onap.portalsdk.analytics.model.SearchHandler;
import org.onap.portalsdk.analytics.model.base.IdNameColLookup;
import org.onap.portalsdk.analytics.model.base.IdNameList;
import org.onap.portalsdk.analytics.model.base.IdNameSql;
import org.onap.portalsdk.analytics.model.base.ReportSecurity;
import org.onap.portalsdk.analytics.model.definition.ReportDefinition;
import org.onap.portalsdk.analytics.model.definition.ReportSchedule;
import org.onap.portalsdk.analytics.model.runtime.ChartWebRuntime;
import org.onap.portalsdk.analytics.model.runtime.ErrorJSONRuntime;
import org.onap.portalsdk.analytics.model.runtime.FormField;
import org.onap.portalsdk.analytics.model.runtime.FormatProcessor;
import org.onap.portalsdk.analytics.model.runtime.ReportFormFields;
import org.onap.portalsdk.analytics.model.runtime.ReportJSONRuntime;
import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
import org.onap.portalsdk.analytics.model.runtime.VisualManager;
import org.onap.portalsdk.analytics.model.search.ReportSearchResultJSON;
import org.onap.portalsdk.analytics.system.AppUtils;
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.system.fusion.domain.QuickLink;
import org.onap.portalsdk.analytics.util.AppConstants;
import org.onap.portalsdk.analytics.util.DataSet;
import org.onap.portalsdk.analytics.util.Utils;
import org.onap.portalsdk.analytics.view.DataRow;
import org.onap.portalsdk.analytics.view.DataValue;
import org.onap.portalsdk.analytics.view.ReportData;
import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
import org.onap.portalsdk.analytics.xmlobj.FormFieldType;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.util.SecurityCodecUtil;
import org.owasp.esapi.ESAPI;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class ActionHandler extends org.onap.portalsdk.analytics.RaptorObject {
private static final String PARENT = "parent_";
private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ActionHandler.class);
private static final String REPORT_DOWNLOAD_PDF = "report.download.pdf";
private static final String REPORT_TEXT_DOWNLOAD = "report.text.download";
private static final String REPORT_CSV_DOWNLOAD = "report.csv.download";
private static final String REPORT_DOWNLOAD_EXCEL2007 = "report.download.excel2007";
private static final String REPORT_DOWNLOAD = "report.download";
private static final String REPORT_DOWNLOAD_PAGE = ";report.download.page";
private static final String FALSE = "false";
private static final String COLNAME = "[colName]";
private static final String FORM_FIELDS = "formFields";
private static final String USER_ID = "user_id";
private static final String MESSAGE = "message";
private void preserveReportRuntimeAsBackup(HttpServletRequest request) {
HttpSession session = request.getSession();
ArrayList repAl = null;
if(session.getAttribute(AppConstants.DRILLDOWN_REPORTS_LIST)!=null)
repAl = ((ArrayList)session.getAttribute(AppConstants.DRILLDOWN_REPORTS_LIST));
int index = Integer.parseInt(nvl((String) session.getAttribute(AppConstants.DRILLDOWN_INDEX), "0"));
int formIndex = Integer.parseInt(nvl((String) session.getAttribute(AppConstants.FORM_DRILLDOWN_INDEX), "0"));
if(repAl ==null || repAl.isEmpty()) {
repAl = new ArrayList();
repAl.add((ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME));
} else {
if(Globals.getMaxDrillDownLevel() < repAl.size()) {
repAl.remove(0);
if(index > 0)
{
index--;
}
} else if(index < repAl.size())
repAl.remove(index);
repAl.add(index, (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME));
}
index = index + 1;
// needed to differentiate form and report index to store form parameters for ZK
formIndex = formIndex + 1;
session.setAttribute(AppConstants.FORM_DRILLDOWN_INDEX, Integer.toString(formIndex));
session.setAttribute(AppConstants.DRILLDOWN_INDEX, Integer.toString(index));
request.getSession().setAttribute(AppConstants.DRILLDOWN_REPORTS_LIST, repAl);
} // preserveReportRuntimeAsBackup
private boolean isDashboardInDrillDownList(HttpServletRequest request) {
ArrayList aL = (ArrayList) request.getSession().getAttribute(
AppConstants.DRILLDOWN_REPORTS_LIST);
ReportRuntime rr = null;
if(aL ==null || aL.isEmpty()) {
return false;
} else {
for (int i =0; i0)?rr.getMaxRowsInExcelDownload():Globals.getDownloadLimit();
if(REPORT_CSV_DOWNLOAD.equals(actionKey))
downloadLimit = Globals.getCSVDownloadLimit();
if(rr!=null && rr.getReportType().equals(AppConstants.RT_LINEAR)) {
String sqlWhole = rr.getReportDataSQL(userId, downloadLimit, request);
request.setAttribute(AppConstants.RI_REPORT_SQL_WHOLE, sqlWhole);
} else if(rr!=null && rr.getReportType().equals(AppConstants.RT_CROSSTAB)) {
rd = rr.loadReportData(-1, userId, downloadLimit,request, false); /* TODO: should be changed to true */
request.getSession().setAttribute(AppConstants.RI_REPORT_DATA, rd);
}
if(!isFromReportLog) {
if(pdfAttachmentKey!=null && pdfAttachmentKey.length()>0) {
if(REPORT_DOWNLOAD.equals(actionKey)) {
rr.logReportExecutionTime(userId, "",AppConstants.RLA_SCHEDULED_DOWNLOAD_EXCEL, formFields);
} else if (REPORT_DOWNLOAD_PDF.equals(actionKey)) {
rr.logReportExecutionTime(userId, "",AppConstants.RLA_SCHEDULED_DOWNLOAD_PDF, formFields);
} else if (REPORT_DOWNLOAD_EXCEL2007.equals(actionKey)) {
rr.logReportExecutionTime(userId, "",AppConstants.RLA_SCHEDULED_DOWNLOAD_EXCELX, formFields);
}
} else {
if(REPORT_DOWNLOAD.equals(actionKey) ) {
rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_EXCEL, formFields);
} else if (REPORT_DOWNLOAD_PDF.equals(actionKey)) {
rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_PDF, formFields);
} else if (REPORT_CSV_DOWNLOAD.equals(actionKey)) {
rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_CSV, formFields);
} else if (REPORT_TEXT_DOWNLOAD.equals(actionKey)) {
rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_TEXT, formFields);
} else if (REPORT_DOWNLOAD_PAGE.equals(actionKey)) {
rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_PAGE_EXCEL, formFields);
} else if (REPORT_DOWNLOAD_EXCEL2007.equals(actionKey)) {
rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_EXCELX, formFields);
}
}
}
return nextPage;
}
}// pdfAttachmentKey
String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); //changing session to request
String reportIDFromSession = (rr!=null)?rr.getReportID():"";
logger.debug(EELFLoggerDelegate.debugLogger, ("in Action Handler ********** " + reportID + " " + reportIDFromSession + " "+ actionKey));
logger.debug(EELFLoggerDelegate.debugLogger, ("^^^^^^^^^^^^^^report ID from session " + ((rr!=null)?rr.getReportID():"no report id in session")));
ReportHandler rh1 = new ReportHandler();
ReportRuntime rr1 = null;
boolean isGoBackAction = AppUtils.getRequestFlag(request, AppConstants.RI_GO_BACK);
if (AppUtils.getRequestFlag(request, AppConstants.RI_SHOW_BACK_BTN) && !isGoBackAction) {
if(!reportID.equals(reportIDFromSession))
preserveReportRuntimeAsBackup(request);
}
if(reportID !=null)
rr1 = rh1.loadReportRuntime(request, reportID, true, 1);
if(rr1!=null && rr1.getReportType().equals(AppConstants.RT_DASHBOARD)) {
int dash=7;
int requestFlag = dash;
ReportHandler rh = new ReportHandler();
// Added below statement to add parent dashboard report id in session.
request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REP_ID, reportID);
String strHTML = rr1.getDashboardLayoutHTML();
String strJson = rr1.getDashboardLayoutJSON();
TreeMap treeMap = getListOfReportsFromDashBoardJson(strJson);
TreeMap treeMapHtml = getListOfReportsFromDashBoardHTML(strHTML);
Set set = treeMap.entrySet();
HashMap reportsRuntimeMap = new HashMap();
HashMap reportDataMap = new HashMap();
HashMap reportChartDataMap = new HashMap();
// displayTypeMap differentiates whether report need to be displayed as data or chart
HashMap reportDisplayTypeMap = new HashMap();
userId = null;
userId = AppUtils.getUserID(request);
int pageNo = -1;
int downloadLimit = 0;
ReportRuntime rrDashboardReports = null;
Integer intObj = null;
ReportRuntime similiarReportRuntime = null;
rd = null;
DataSet ds = null;
String reportIDFromMap = null;
int record = 0;
boolean buildReportdata = true;
for(Iterator iter = set.iterator(); iter.hasNext(); ) {
record++;
Map.Entry entry = (Entry) iter.next();
reportIDFromMap = entry.getValue().toString().substring(1);
// The below line is used to optimize, so that if there is
// already same report id it wouldn't go through the whole
// process
similiarReportRuntime = getSimiliarReportRuntime(reportsRuntimeMap, reportIDFromMap);
if(similiarReportRuntime != null ) {
rrDashboardReports = (ReportRuntime) getSimiliarReportRuntime(reportsRuntimeMap,
reportIDFromMap).clone();
intObj = getKey(reportsRuntimeMap,reportIDFromMap);
} else {
rrDashboardReports = rh.loadReportRuntime(request, reportIDFromMap, true, requestFlag);
}
if(entry.getValue().toString().toLowerCase().startsWith("c")) {
rrDashboardReports.setDisplayMode(ReportRuntime.DISPLAY_CHART_ONLY);
} else {
rrDashboardReports.setDisplayMode(ReportRuntime.DISPLAY_DATA_ONLY);
}
downloadLimit = (rrDashboardReports.getMaxRowsInExcelDownload() > 0)
? rrDashboardReports.getMaxRowsInExcelDownload() : Globals.getDownloadLimit();
if(record == 1) {
if (rrDashboardReports.getReportFormFields() != null
&& rrDashboardReports.getReportFormFields().size() > 0) {
buildReportdata = false;
if(rDisplayContent)
buildReportdata = true;
}
}
if(buildReportdata) {
if(similiarReportRuntime != null ) {
rd = (ReportData) reportDataMap.get(intObj);
ds = (DataSet) reportChartDataMap.get(intObj);
} else {
if (!rrDashboardReports.getReportType().equals(AppConstants.RT_HIVE))
rd = rrDashboardReports.loadReportData(pageNo, userId, downloadLimit, request,
false /* download */);
else
rd = rrDashboardReports.loadHiveLinearReportData(rrDashboardReports.getReportSQL(),
userId, 2, request);
ds = rrDashboardReports.loadChartData(userId,request);
}
}
long totalTime = System.currentTimeMillis() - currentTime;
formFields = AppUtils.getRequestNvlValue(request, FORM_FIELDS);
if(buildReportdata) {
/*
* rrDashboardReports.logReportRun(userId, String.valueOf(totalTime),
* formFields); rrDashboardReports.logReportExecutionTime(userId,
* String.valueOf(totalTime), AppConstants.RLA_EXECUTION_TIME, formFields);
*/
}
if(!entry.getValue().toString().toLowerCase().startsWith("c")) {
reportsRuntimeMap.put(
new Integer(entry.getKey().toString()) + "_" + rrDashboardReports.getReportID(),
rrDashboardReports);
reportDisplayTypeMap.put(
new Integer(entry.getKey().toString()) + "_" + rrDashboardReports.getReportID(),
entry.getValue().toString().substring(0, 1));
if(buildReportdata) {
reportDataMap.put(
new Integer(entry.getKey().toString()) + "_" + rrDashboardReports.getReportID(), rd);
reportChartDataMap.put(
new Integer(entry.getKey().toString()) + "_" + rrDashboardReports.getReportID(), ds);
}
}
}
request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP, new TreeMap(reportsRuntimeMap));
request.getSession().setAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP, new TreeMap(reportDisplayTypeMap));
if(buildReportdata) {
request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP, new TreeMap(reportDataMap));
request.getSession().setAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP, new TreeMap(reportChartDataMap));
}
request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr1); //changing session to request
if((String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!= null || rr1.getReportType().equals(AppConstants.RT_DASHBOARD)) {
request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME, rr1);
}
return "{\"return\" : \"raptor/report_dashboard_run_container.jsp\"}";
} else {
fromDashboard = AppUtils.getRequestFlag(request,"fromDashboard");
if(isDashboardInDrillDownList(request))
fromDashboard= true;
if(!fromDashboard) {
request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP);
request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP);
request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP);
request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP);
request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_REP_ID);
request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME);
request.getSession().removeAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP);
request.getSession().removeAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP);
}
String reportEmailSentLogId = ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(),AppUtils.getRequestValue(request, "log_id"));
logger.debug(EELFLoggerDelegate.debugLogger, ("Email PDF" + pdfAttachmentKey+" "+ reportEmailSentLogId));
//email pdf attachment specific
if(nvl(pdfAttachmentKey).length()>0 && reportEmailSentLogId !=null)
isEmailAttachment = true;
if(isEmailAttachment) {
String query = Globals.getDownloadAllEmailSent();
query = query.replace("[pdfAttachmentKey.trim()]", pdfAttachmentKey.trim());
query = query.replace("[report_email_sent_log_id.trim()]", reportEmailSentLogId.trim());
DataSet ds = DbUtils.executeQuery(query, 1);
if(!ds.isEmpty()) {
userId = ds.getString(0,USER_ID);
reportID = ds.getString(0, "rep_id");
request.setAttribute("schedule_email_userId", userId);
} else {
request.setAttribute(MESSAGE, "This link has expired, please login and regenerate the report");
return "raptor/message.jsp";
}
} else
userId = AppUtils.getUserID(request);
// Scheduling Dashoard report
if(reportID !=null && nvl(pdfAttachmentKey).length()>0)
rr = rh1.loadReportRuntime(request, reportID, true, 1);
if(rr!=null && rr.getReportType().equals(AppConstants.RT_DASHBOARD) && nvl(pdfAttachmentKey).length()>0) {
int DASH=7;
int requestFlag = DASH;
ReportHandler rh = new ReportHandler();
request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REP_ID, reportID);
// get dashboard HTML from report runtime. getListOfReportsFromDashBoardHTML
String strHTML = rr.getDashboardLayoutHTML();
// call getListOfReportsFromDashBoardHTML returns HashMap
TreeMap treeMap = getListOfReportsFromDashBoardHTML(strHTML);
Set set = treeMap.entrySet();
String value = "";
HashMap reportsRuntimeMap = new HashMap();
HashMap reportDataMap = new HashMap();
HashMap reportChartDataMap = new HashMap();
HashMap reportDisplayTypeMap = new HashMap();
userId = null;
userId = AppUtils.getUserID(request);
int pageNo = -1;
int downloadLimit = 0;
int rep_idx = 0;
int widthFlag = 0;
int heightFlag = 0;
ReportRuntime rrDashboardReports = null;
Integer intObj = null;
ReportRuntime similiarReportRuntime = null;
rd = null;
DataSet ds = null;
String reportIDFromMap = null;
int record = 0;
boolean buildReportdata = true;
for(Iterator iter = set.iterator(); iter.hasNext(); ) {
record++;
Map.Entry entry = (Entry) iter.next();
reportIDFromMap = entry.getValue().toString().substring(1);
similiarReportRuntime = getSimiliarReportRuntime(reportsRuntimeMap, reportIDFromMap);
if(similiarReportRuntime != null ) {
rrDashboardReports = getSimiliarReportRuntime(reportsRuntimeMap, reportIDFromMap);
intObj = getKey(reportsRuntimeMap,reportIDFromMap);
} else {
rrDashboardReports = rh.loadReportRuntime(request, reportIDFromMap, true, requestFlag);
}
downloadLimit = (rrDashboardReports.getMaxRowsInExcelDownload()>0)?rrDashboardReports.getMaxRowsInExcelDownload():Globals.getDownloadLimit();
if (new Integer(nvl(rrDashboardReports.getDataContainerWidth(),"100")).intValue() >100) widthFlag = 1;
if (new Integer(nvl(rrDashboardReports.getDataContainerHeight(),"100")).intValue() >100) heightFlag = 1;
if(record == 1) {
if(rrDashboardReports.getReportFormFields()!=null && rrDashboardReports.getReportFormFields().size()>0) {
buildReportdata = false;
if(rDisplayContent) buildReportdata = true;
}
}
if(buildReportdata) {
if(similiarReportRuntime != null ) {
rd = (ReportData) reportDataMap.get(intObj);
ds = (DataSet) reportChartDataMap.get(intObj);
} else {
if (!rrDashboardReports.getReportType().equals(AppConstants.RT_HIVE))
rd = rrDashboardReports.loadReportData(pageNo, userId, downloadLimit,request, false /*download*/);
else
rd = rrDashboardReports.loadHiveLinearReportData(rrDashboardReports.getReportSQL(), userId, 2,request);
ds = rrDashboardReports.loadChartData(userId,request);
}
}
long totalTime = System.currentTimeMillis() - currentTime;
formFields = AppUtils.getRequestNvlValue(request, FORM_FIELDS);
rrDashboardReports.logReportRun(userId, String.valueOf(totalTime),formFields);
rrDashboardReports.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_EXECUTION_TIME, formFields);
reportsRuntimeMap.put(new Integer(entry.getKey().toString()), rrDashboardReports);
reportDisplayTypeMap.put(new Integer(entry.getKey().toString()), entry.getValue().toString().substring(0,1));
if(buildReportdata) {
reportDataMap.put(new Integer(entry.getKey().toString()), rd);
reportChartDataMap.put(new Integer(entry.getKey().toString()), ds);
}
}
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));
}
} else {
// Ends
ReportHandler rh = new ReportHandler();
//rr = null; // COMMENT THIS LINE
boolean resetParams = AppUtils.getRequestFlag(request,
AppConstants.RI_RESET_PARAMS);
boolean resetAction = AppUtils.getRequestFlag(request,
AppConstants.RI_RESET_ACTION);
boolean refresh = false;
if (resetAction) {
rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
resetParams=true;
refresh = true;
if(rr!=null) {
rr.setParamValues(request, resetParams,refresh);
request.getSession().removeAttribute(AppConstants.RI_REPORT_DATA);
rr.resetVisualSettings();
}
return nextPage;
}
logger.debug(EELFLoggerDelegate.debugLogger, ("Ocurring during Schedule "));
//TODO differentiate Schedule with other actions
rr = rh.loadReportRuntime(request, reportID);
//setParamValues called for Drilldown to display formfield
//} // else
ArrayList aL = (ArrayList)request.getSession().getAttribute(AppConstants.DRILLDOWN_REPORTS_LIST);
ReportRuntime aLR = null;
if(aL != null) {
aLR = (ReportRuntime) aL.get(0);
if (aLR!=null && !aLR.getReportID().equals(reportID)) {
request.setAttribute(AppConstants.RI_SHOW_BACK_BTN, "Y");
}
}
if(rDisplayContent)
rr.setDisplayFlags(true, true);
if (rr.getDisplayContent()) {
int pageNo = 0;
if (isGoBackAction)
pageNo = rr.getCachedPageNo();
else {
try {
pageNo = Integer.parseInt(AppUtils.getRequestNvlValue(request, AppConstants.RI_NEXT_PAGE));
} catch (Exception e) {
}
String vAction = AppUtils.getRequestNvlValue(request,
AppConstants.RI_VISUAL_ACTION);
String vCoId = AppUtils.getRequestNvlValue(request,
AppConstants.RI_DETAIL_ID);
if (vAction.equals(AppConstants.VA_HIDE))
rr.hideColVisual(vCoId);
else if (vAction.equals(AppConstants.VA_SHOW))
rr.showColVisual(vCoId);
else if (vAction.equals(AppConstants.VA_SORT)) {
rr.sortColVisual(vCoId);
pageNo = 0;
} // else
} // else
int downloadLimit = (rr.getMaxRowsInExcelDownload()>0)?rr.getMaxRowsInExcelDownload():Globals.getDownloadLimit();
if(isEmailAttachment) {
String limit = nvl(request.getParameter("download_limit"),"1000");
downloadLimit = Integer.parseInt(limit);
}
long reportTime = System.currentTimeMillis();
if (!rr.getReportType().equals(AppConstants.RT_HIVE))
rd = rr.loadReportData(pageNo, userId, downloadLimit,request,false /*download*/);
else
rd = rr.loadHiveLinearReportData(rr.getReportSQL(), userId, 2,request);
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");
request.getSession().setAttribute(AppConstants.RI_REPORT_DATA, rd);
if(rr!=null && rr.getReportType().equals(AppConstants.RT_LINEAR)) {
String sqlWhole = rr.getReportDataSQL(userId, downloadLimit, request);
request.setAttribute(AppConstants.RI_REPORT_SQL_WHOLE, sqlWhole);
} else if(rr.getReportType().equals(AppConstants.RT_HIVE)) {
String sqlWhole = rr.getReportSQL();
request.setAttribute(AppConstants.RI_REPORT_SQL_WHOLE, sqlWhole);
}
if (!rr.getReportType().equals(AppConstants.RT_HIVE)) {
long currentChartTime = System.currentTimeMillis();
DataSet chartDS = rr.loadChartData(userId,request);
if(chartDS != null)
request.getSession().setAttribute(AppConstants.RI_CHART_DATA, rr.loadChartData(userId,request));
else
request.getSession().removeAttribute(AppConstants.RI_CHART_DATA);
logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] ------->Time Taken for the loading chart data --- " + (System.currentTimeMillis() - currentChartTime)));
}
}
request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); //changing session to request
request.getSession().setAttribute(AppConstants.RI_REPORT_DATA, rd);
} // else
long totalTime = System.currentTimeMillis() - currentTime;
formFields = AppUtils.getRequestNvlValue(request, FORM_FIELDS);
request.setAttribute(AppConstants.RLA_EXECUTION_TIME, "" + totalTime);
boolean isFromReportLog = AppUtils.getRequestFlag(request, "fromReportLog");
if(!isFromReportLog) {
if(pdfAttachmentKey!=null && pdfAttachmentKey.length()>0) {
if(actionKey.equals(REPORT_DOWNLOAD)) {
rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_SCHEDULED_DOWNLOAD_EXCEL, formFields);
} else if (actionKey.equals(REPORT_DOWNLOAD_PDF)) {
rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_SCHEDULED_DOWNLOAD_PDF, formFields);
}
} else {
if(actionKey.equals(REPORT_DOWNLOAD) ) {
rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_DOWNLOAD_EXCEL, formFields);
} else if (actionKey.equals(REPORT_DOWNLOAD_PDF)) {
rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_DOWNLOAD_PDF, formFields);
} else if (actionKey.equals(REPORT_CSV_DOWNLOAD)) {
rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_DOWNLOAD_CSV, formFields);
} else if (actionKey.equals(REPORT_TEXT_DOWNLOAD)) {
rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_DOWNLOAD_TEXT, formFields);
} else {
if(rd!=null && !action.equals("report.run.container"))
rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_EXECUTION_TIME, formFields);
}
}
} else {
rr.logReportExecutionTimeFromLogList(userId, String.valueOf(totalTime),formFields);
}
if(rr.isDrillDownURLInPopupPresent()) {
request.getSession().setAttribute(PARENT+rr.getReportID()+"_rr", rr);
request.getSession().setAttribute(PARENT+rr.getReportID()+"_rd", rd);
}
if(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) {
return "raptor/report_crosstab_run_container.jsp";
} else if (rr.getReportType().equals(AppConstants.RT_HIVE) && !isEmailAttachment) {
return "raptor/report_hive_run_container.jsp";
}
} // else
boolean isEmbedded = false;
Object temp = request.getSession().getAttribute("isEmbedded");
if(temp!=null){
isEmbedded = (boolean)temp;
}
if(isEmbedded && !action.equals("chart.run")){
HashMap embeddedReportsRuntimeMap = null;
HashMap embeddedReportsDataMap = null;
if(request.getSession().getAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP)!= null){
embeddedReportsRuntimeMap = (HashMap)request.getSession().getAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP);
} else {
embeddedReportsRuntimeMap = new HashMap();
}
if(request.getSession().getAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP)!= null){
embeddedReportsDataMap = (HashMap)request.getSession().getAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP);
} else {
embeddedReportsDataMap = new HashMap();
}
embeddedReportsRuntimeMap.put(rr.getReportID(), rr);
embeddedReportsDataMap.put(rr.getReportID(), rd);
request.getSession().setAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP, embeddedReportsRuntimeMap);
request.getSession().setAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP, embeddedReportsDataMap);
}
ReportJSONRuntime reportJSONRuntime = rr.createReportJSONRuntime(request, rd);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String jsonInString = "";
try {
jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(reportJSONRuntime);
} catch (Exception ex) {
logger.error(EELFLoggerDelegate.errorLogger,"reportRun", ex);
}
return jsonInString;
} catch (RaptorException e) {
try {
logger.error(EELFLoggerDelegate.errorLogger,"reportRun", e);
if(rr!=null) { // when user tries report they don't have access this should not throw exception that's why this if is added.
if(isEmailAttachment)
rr.logReportExecutionTime(userId, "", "Scheduled: " + AppConstants.RLA_ERROR, formFields);
else
rr.logReportExecutionTime(userId, "", "On Demand: " + AppConstants.RLA_ERROR, formFields);
}
ReportJSONRuntime reportJSONRuntime = new ReportJSONRuntime();
if (rr != null) {
reportJSONRuntime = rr.createReportJSONRuntime(request, rd);
}
ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
errorJSONRuntime.setAllowEdit(reportJSONRuntime.isAllowEdit());
errorJSONRuntime.setErrormessage(e.getMessage());
errorJSONRuntime.setStacktrace(getStackTrace(e));
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String jsonInString = "";
try {
jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
} catch (Exception ex) {
logger.error(EELFLoggerDelegate.errorLogger,"reportRun", ex);
}
return jsonInString;
} catch (RaptorException ex) {
nextPage = (new ErrorHandler()).processFatalError(request, ex);
ReportJSONRuntime reportJSONRuntime = new ReportJSONRuntime();
if (rr != null) {
reportJSONRuntime = rr.createReportJSONRuntime(request, rd);
}
ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
errorJSONRuntime.setAllowEdit(reportJSONRuntime.isAllowEdit());
errorJSONRuntime.setErrormessage(ex.getMessage());
errorJSONRuntime.setStacktrace(getStackTrace(ex));
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String jsonInString = "";
try {
jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
} catch (Exception ex1) {
logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex);
}
return jsonInString;
}
} catch (Exception t) {
logger.error(EELFLoggerDelegate.errorLogger,t.getMessage(), t);
ReportJSONRuntime reportJSONRuntime = new ReportJSONRuntime();
if (rr != null) {
reportJSONRuntime = rr.createReportJSONRuntime(request, rd);
}
ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
errorJSONRuntime.setAllowEdit(reportJSONRuntime.isAllowEdit());
errorJSONRuntime.setErrormessage(t.toString());
errorJSONRuntime.setStacktrace(getStackTrace(t));
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String jsonInString = "";
try {
jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
} catch (Exception ex) {
logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex);
}
return jsonInString;
}
} // reportRun
public static String getStackTrace(Throwable aThrowable) {
Writer result = new StringWriter();
PrintWriter printWriter = new PrintWriter(result);
aThrowable.printStackTrace(printWriter);
return result.toString();
}
/**
* The below method is used to optimize, so that if there is already same report id in hashMap it wouldn't go through the whole process again.
**/
private ReportRuntime getSimiliarReportRuntime(HashMap reportsRuntimeMap, String reportID) {
Set set = reportsRuntimeMap.entrySet();
for(Iterator iter = set.iterator(); iter.hasNext(); ) {
Map.Entry entry = (Entry) iter.next();
if (((ReportRuntime) entry.getValue()).getReportID().equals(reportID)) {
return (ReportRuntime) entry.getValue();
}
}
return null;
}
private Integer getKey(HashMap reportsRuntimeMap, String reportID) {
Set set = reportsRuntimeMap.entrySet();
for(Iterator iter = set.iterator(); iter.hasNext(); ) {
Map.Entry entry = (Entry) iter.next();
if (((ReportRuntime) entry.getValue()).getReportID().equals(reportID)) {
return new Integer(((String) entry.getKey()).substring(((String) entry.getKey()).indexOf("_")+1));
}
}
return null;
}
public String reportSearch(HttpServletRequest request, String nextPage) {
return reportSearchExecute(request, nextPage);
} // reportSearch
public String reportSearchUser(HttpServletRequest request, String nextPage) {
removeVariablesFromSession(request);
request.setAttribute(AppConstants.RI_USER_REPORTS, "Y");
return reportSearchExecute(request, nextPage);
} // reportSearchUser
public String reportSearchPublic(HttpServletRequest request, String nextPage) {
removeVariablesFromSession(request);
request.setAttribute(AppConstants.RI_PUBLIC_REPORTS, "Y");
return reportSearchExecute(request, nextPage);
} // reportSearchPublic
public String reportSearchFavorites(HttpServletRequest request, String nextPage) {
removeVariablesFromSession(request);
request.setAttribute(AppConstants.RI_FAVORITE_REPORTS, "Y");
return reportSearchExecute(request, nextPage);
} // reportSearchFavorites
public String reportSearchExecute(HttpServletRequest request, String nextPage) {
removeVariablesFromSession(request);
try {
SearchHandler sh = new SearchHandler();
ReportSearchResultJSON sr = sh.loadReportSearchResult(request);
return sr.getJSONString();
} catch (RaptorException e) {
nextPage = (new ErrorHandler()).processFatalError(request, e);
}
return nextPage;
} // reportSearchExecute
public String reportChartRun(HttpServletRequest request, String nextPage) {
ChartWebRuntime cwr = new ChartWebRuntime();
return cwr.generateChart(request, false); //no data
} // reportSearchExecute
public String reportChartDataRun(HttpServletRequest request, String nextPage) {
ChartWebRuntime cwr = new ChartWebRuntime();
return cwr.generateChart(request); //data
} // reportSearchExecute
public String getQuickLinksJSON(HttpServletRequest request, String nextPage) {
String jsonInString = null;
try {
ArrayList quickLinks = ReportLoader.getQuickLinksJSON(request, ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(),request.getParameter("quick_links_menu_id")),true);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(quickLinks);
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), e);
}
return jsonInString;
}
public String processScheduleReportList(HttpServletRequest request, String nextPage) {
String reportID = "";
reportID = AppUtils.getRequestNvlValue(request, "schedule_reports");
if (nvl(reportID).length()<=0)
reportID = AppUtils.getRequestNvlValue(request, AppConstants.RI_REPORT_ID);
// Added for form field chaining in schedule tab so that setParamValues() is called
request.setAttribute(AppConstants.SCHEDULE_ACTION, "Y");
try {
boolean isAdmin = AppUtils.isAdminUser(request);
boolean check = ReportLoader.doesUserCanScheduleReport(request, null);
logger.debug(EELFLoggerDelegate.debugLogger, ("^^^^^^^^^^^^^Check " + check + " Admin "+ isAdmin));
if(!(check || isAdmin)) {
String message = "You have reached the scheduled report limit for your Login ID. Please remove any old schedule requests in the \"My Scheduled Reports\" screen before attempting to schedule any additional reports.";
nextPage = (new ErrorHandler()).processFatalError(request, new RaptorSchedularException(message));
return nextPage;
}
if(!reportID.isEmpty()) {
ReportHandler rh = new ReportHandler();
ReportDefinition rdef = rh.loadReportDefinition(request, reportID);
request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
ReportSchedule reportSchedule = null;
if(rdef!=null) {
reportSchedule = new ReportSchedule(reportID, AppUtils.getUserID(request), false, request);
}
request.getSession().setAttribute(AppConstants.SI_REPORT_SCHEDULE, reportSchedule);
}
} catch(Exception ex) { logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex);}
return nextPage;
}
public String processSchedule(HttpServletRequest request, String nextPage) {
// Added for form field chaining in schedule tab so that setParamValues() is called
request.setAttribute(AppConstants.SCHEDULE_ACTION, "Y");
if(request.getSession().getAttribute(AppConstants.SI_REPORT_SCHEDULE)!=null && (!AppUtils.getRequestNvlValue(request, AppConstants.RI_ACTION).equals("report.schedule_only_from_search"))) {
String action = nvl(request.getParameter(AppConstants.RI_WIZARD_ACTION),
AppConstants.WA_BACK);
String scheduleID = "";
scheduleID = AppUtils.getRequestValue(request, AppConstants.RI_SCHEDULE_ID);
ReportSchedule reportSchedule = null;
if( nvl(scheduleID).length() <= 0) {
reportSchedule = (ReportSchedule) request.getSession().getAttribute(AppConstants.SI_REPORT_SCHEDULE);
scheduleID = reportSchedule.getScheduleID();
}
String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
try {
boolean isAdmin = AppUtils.isAdminUser(request);
boolean check = ReportLoader.doesUserCanScheduleReport(request, scheduleID);
if(!isAdmin && !check) {
String message = "You have reached the scheduled report limit for your Login ID. Please remove any old schedule requests in the My Scheduled Reports screen before attempting to schedule any additional reports.";
nextPage = (new ErrorHandler()).processFatalError(request, new RaptorSchedularException(message));
return nextPage;
}
} catch (Exception ex) { logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex);}
if(reportSchedule == null)
reportSchedule = new ReportSchedule(reportID, scheduleID, AppUtils.getUserID(request), request);
String formFields = "";
formFields = reportSchedule.getFormFields();
formFields = (formFields.length()>1)?formFields.substring(1):formFields;
String[] formFieldsArr = formFields.split("&");
String[] sessionParams = Globals.getSessionParamsForScheduling().split(",");
for (int i=0; i1)?formFields.substring(1):formFields;
String[] formFieldsArr = formFields.split("&");
String[] sessionParams = Globals.getSessionParamsForScheduling().split(",");
for (int i=0; i 0)
ws.performGoToStep(goToStep);
else
ws.performAction(action, rdef);
} catch (ValidationException ve) {
(new ErrorHandler()).processError(request, ve);
} catch (RaptorException e) {
nextPage = (new ErrorHandler()).processFatalError(request, e);
} catch (Exception t) {
logger.error(EELFLoggerDelegate.errorLogger,t.getMessage(), t);
}
return nextPage;
} // reportWizard
public String refreshCache ( HttpServletRequest request, String nextPage ) {
removeVariablesFromSession(request);
DataCache.refreshAll();
Globals.getAppUtils().resetUserCache();
request.setAttribute(MESSAGE, "Cache Refreshed");
return nextPage;
}
public String reportCreate(HttpServletRequest request, String nextPage) {
try {
removeVariablesFromSession(request);
ReportDefinition rdef = ReportDefinition.createBlank(request);
request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
DataCache.refreshReportTableSources();
request.getSession().removeAttribute("remoteDB");
} catch (RaptorException e) {
nextPage = (new ErrorHandler()).processFatalError(request, e);
}
return nextPage;
} // reportCreate
public String reportImportSave(HttpServletRequest request, String nextPage) {
try {
String reportXML = nvl(AppUtils.getRequestValue(request, "reportXML")).trim();
ReportHandler rh = new ReportHandler();
ReportDefinition rdef = rh.createReportDefinition(request, "-1", reportXML);
rdef.updateReportDefType();
rdef.generateWizardSequence(request);
rdef.setReportName("Import: " + rdef.getReportName());
rdef.clearAllDrillDowns();
request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
} catch (RaptorException e) {
request.setAttribute("error_extra_msg", "Unable to parse XML. Nested error: ");
nextPage = (new ErrorHandler()).processFatalError(request, e);
}
return nextPage;
} // reportImportSave
private String reportLoad(HttpServletRequest request, String nextPage, boolean asCopy) {
try {
String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
ReportHandler rh = new ReportHandler();
ReportDefinition rdef = rh.loadReportDefinition(request, reportID);
if (asCopy)
rdef.setAsCopy(request);
else
rdef.checkUserWriteAccess(request);
rdef.getWizardSequence().performGoToStep(AppConstants.WS_DEFINITION);
request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
} catch (RaptorException e) {
nextPage = (new ErrorHandler()).processFatalError(request, e);
}
return nextPage;
} // reportLoad
public String reportCopy(HttpServletRequest request, String nextPage) {
return reportLoad(request, nextPage, true);
} // reportCopy
public String reportEdit(HttpServletRequest request, String nextPage) {
return reportLoad(request, nextPage, false);
} // reportEdit
public String reportDelete(HttpServletRequest request, String nextPage) {
try {
String reportID = ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(),AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID));
try {
int i = Integer.parseInt(reportID);
} catch(NumberFormatException ex) {
throw new UserDefinedException("Not a valid report id");
}
String userID = AppUtils.getUserID(request);
(new ReportSecurity(reportID)).checkUserDeleteAccess(request);
ReportLoader.deleteReportRecord(reportID);
return "{\"deleted\":true}";
} catch (RaptorException e) {
nextPage = (new ErrorHandler()).processFatalError(request, e);
}
return "{\"deleted\":false}";
} // reportDelete
private String generateSearchString(HttpServletRequest request) {
String searchString = AppUtils.getRequestNvlValue(request, AppConstants.RI_SEARCH_STRING);
boolean containFlag = AppUtils.getRequestFlag(request, AppConstants.RI_CONTAIN_FLAG);
return (searchString.length() > 0) ? ((containFlag ? "%" : "") + searchString + "%"):"";
} // generateSearchString
public String reportFormFieldPopup(HttpServletRequest request, String nextPage) {
try {
ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(
AppConstants.SI_REPORT_RUNTIME);
FormField ff = rr.getFormField(request.getParameter(AppConstants.RI_FIELD_NAME));
ReportFormFields rff = rr.getReportFormFields();
FormField ff1 = null;
Map fieldNameMap = new HashMap();
int countOfFields = 0 ;
String userId = AppUtils.getUserID(request);
IdNameList lookup = ff.getLookupList();
String oldSQL = lookup.getOldSql();
if(AppUtils.getRequestFlag(request, AppConstants.RI_TEXTFIELD_POP)) {
for(rff.resetNext(); rff.hasNext(); ) {
ff1 = rff.getNext();
fieldNameMap.put(ff1.getFieldName(), ff1.getFieldDisplayName());
countOfFields++;
}
String formField = "";
HashMap valuesMap = new HashMap();
for(int i = 0 ; i < rff.size(); i++) {
formField = (rff.getFormField(i)).getFieldName();
if(request.getParameterValues(formField) != null && request.getParameterValues(formField).length > 1 ) {
String[] vals = request.getParameterValues(formField);
String value = "";
StringBuilder valueBuf = new StringBuilder();
for(int ii = 0 ; ii < vals.length; ii++) {
if(ii == 0)
valueBuf.append("(");
valueBuf.append(vals[ii]);
if(ii == vals.length-1)
valueBuf.append(")");
else valueBuf.append(",");
}
value = valueBuf.toString();
valuesMap.put(fieldNameMap.get(formField), value);
} else if(request.getParameter(formField) != null) {
valuesMap.put(fieldNameMap.get(formField), request.getParameter(formField));
}
}
if(countOfFields != 0) {
IdNameSql lu = (IdNameSql) lookup;
String SQL = (oldSQL==null)?lu.getSql():oldSQL;
oldSQL = SQL;
Set set = valuesMap.entrySet();
String value = "";
StringBuilder valueBuf = new StringBuilder();
for(Iterator iter = set.iterator(); iter.hasNext(); ) {
Map.Entry entry = (Entry) iter.next();
if(entry.getValue() instanceof String[]) {
String[] vals = (String[]) entry.getValue();
for(int i = 0 ; i < vals.length; i++) {
if(i == 0)
valueBuf.append("(");
valueBuf.append(vals[i]);
if(i == vals.length-1)
valueBuf.append(")");
else valueBuf.append(",");
}
value = valueBuf.toString();
} else {
value = (String) entry.getValue();
}
// added so empty string would be treated as null value if not given in single quotes.
if(value==null || value.trim().length()<=0) value="NULL";
SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", Utils.oracleSafe(value));
}
if(request.getParameter(ff.getFieldName())!=null) {
lookup = new IdNameSql(-1,SQL,null);
lookup.setOldSql(oldSQL);
}
else {
lookup = new IdNameSql(-1,SQL,lu.getDefaultSQL());
lookup.setOldSql(oldSQL);
}
}
if(lookup instanceof IdNameSql) ((IdNameSql)lookup).setDataSizeUsedinPopup(-3); // -3 indicates to run the count sql for pagination.
}
if(lookup instanceof IdNameSql) {
((IdNameSql)lookup).loadUserData(request.getParameter(AppConstants.RI_NEXT_PAGE),
nvl(generateSearchString(request),"%"), rr.getDBInfo(),userId);
}
int dataSizeForPopUp = 0;
if(lookup instanceof IdNameSql) {
dataSizeForPopUp = ((IdNameSql)lookup).getDataSizeUsedinPopup();
} else
dataSizeForPopUp = lookup.getDataSize();
ff.setLookupList(lookup);
request.setAttribute("lookupList", lookup);
if(dataSizeForPopUp >= 0)
request.getSession().setAttribute(AppConstants.SI_DATA_SIZE_FOR_TEXTFIELD_POPUP, ""+dataSizeForPopUp);
} catch (RaptorException e) {
logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), e);
nextPage = (new ErrorHandler()).processFatalError(request, e);
}
return nextPage;
} // reportFormFieldPopup
public String reportValuesMapDefPopup(HttpServletRequest request, String nextPage) {
try {
ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(
AppConstants.SI_REPORT_DEFINITION);
String colName = AppUtils.getRequestNvlValue(request, "colName");
String colType = nvl(AppUtils.getRequestValue(request, "colType"),
AppConstants.CT_CHAR);
String displayName = AppUtils.getRequestNvlValue(request, "displayName");
String displayFormat = AppUtils.getRequestNvlValue(request, "displayFormat");
String tableId = AppUtils.getRequestNvlValue(request, "tableId");
String dbInfo = rdef.getDBInfo();
if (Utils.isNull(dbInfo)) {
dbInfo = (String) request.getSession().getAttribute("remoteDB");
}
String q1 = Globals.getReportValuesMapDefA();
String q2 = Globals.getReportValuesMapDefB();
q2 = q2.replace(COLNAME, colName);
q2 = q2.replace("[nvl(displayFormat, AppConstants.DEFAULT_DATE_FORMAT)]", nvl(displayFormat, AppConstants.DEFAULT_DATE_FORMAT));
String q3 = Globals.getReportValuesMapDefC();
q3 = q3.replace(COLNAME, colName);
String q4 = Globals.getReportValuesMapDefD();
q4 = q4.replace("[rdef.getTableById(tableId).getTableName()]", rdef.getTableById(tableId).getTableName());
q4 = q4.replace(COLNAME, colName);
q4 = q4.replace("[Globals.getDefaultPageSize()]", String.valueOf(Globals.getDefaultPageSize()));
String query = q1 + (colType.equals(AppConstants.CT_DATE) ? q2 : q3) + q4;
DataSet ds = ConnectionUtils.getDataSet(query, dbInfo);
request.setAttribute(AppConstants.RI_DATA_SET, ds);
} catch (RaptorException e) {
nextPage = (new ErrorHandler()).processFatalError(request, e);
}
return nextPage;
} // reportValuesMapDefPopup
public String reportDrillDownToReportDefPopup(HttpServletRequest request, String nextPage) {
try {
String ddReportID = AppUtils
.getRequestNvlValue(request, AppConstants.RI_REPORT_ID);
ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, ddReportID,
false);
if (ddRr != null)
request.setAttribute(AppConstants.RI_FORM_FIELDS, ddRr.getReportFormFields());
} catch (RaptorException e) {
nextPage = (new ErrorHandler()).processFatalError(request, e);
}
return nextPage;
} // reportDrillDownToReportDefPopup
public String reportFilterDataPopup(HttpServletRequest request, String nextPage) {
try {
ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(
AppConstants.SI_REPORT_DEFINITION);
String colId = AppUtils.getRequestNvlValue(request, AppConstants.RI_COLUMN_ID);
IdNameColLookup lookup = null;
String dbInfo = rdef.getDBInfo();
if (Utils.isNull(dbInfo)) {
dbInfo = (String) request.getSession().getAttribute("remoteDB");
}
if (!AppUtils.getRequestFlag(request, AppConstants.RI_RESET_PARAMS))
lookup = (IdNameColLookup) request.getSession().getAttribute(
AppConstants.SI_COLUMN_LOOKUP);
if (lookup == null || (!colId.equals(lookup.getColId()))) {
DataColumnType dct = rdef.getColumnById(colId);
lookup = new IdNameColLookup(colId, rdef.getTableById(dct.getTableId())
.getTableName(), dct.getColName(), rdef.getSelectExpr(dct), dct
.getColName()
+ (dct.getColType().equals(AppConstants.CT_DATE) ? " DESC" : ""));
request.getSession().setAttribute(AppConstants.SI_COLUMN_LOOKUP, lookup);
} // if
lookup.loadData(nvl(request.getParameter(AppConstants.RI_NEXT_PAGE), "0"),
generateSearchString(request), dbInfo);
} catch (RaptorException e) {
nextPage = (new ErrorHandler()).processFatalError(request, e);
}
return nextPage;
} // reportFilterDataPopup
public String reportShowSQLPopup(HttpServletRequest request, String nextPage) {
try {
ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(
AppConstants.SI_REPORT_DEFINITION);
String reportSQL = rdef.generateSQL(AppUtils.getUserID(request),request);
String[] sqlClause = { "SELECT ", "FROM ", "WHERE ", "GROUP BY ", "HAVING ",
"ORDER BY " };
int idxNext = 0;
StringBuffer sb = new StringBuffer();
while (idxNext < sqlClause.length) {
sb.append("");
if (idxNext > 0)
sb.append(" ");
sb.append(sqlClause[idxNext]);
sb.append("
\n");
int clauseStartPos = reportSQL.indexOf(sqlClause[idxNext])
+ sqlClause[idxNext].length();
do
idxNext++;
while ((idxNext < sqlClause.length)
&& (reportSQL.indexOf(sqlClause[idxNext]) < 0));
String clauseContent = null;
if (idxNext < sqlClause.length)
clauseContent = reportSQL.substring(clauseStartPos, reportSQL
.indexOf(sqlClause[idxNext]) - 1);
else
clauseContent = reportSQL.substring(clauseStartPos);
while (clauseContent.length() > 0) {
int braketCount = 0;
StringBuffer nextToken = new StringBuffer();
for (int i = 0; i < clauseContent.length(); i++) {
char ch = clauseContent.charAt(i);
nextToken.append(ch);
if (ch == '(')
braketCount++;
else if (ch == ')')
braketCount--;
else if (ch == ',')
if (braketCount == 0)
break;
} // for %>
sb.append(" ");
sb.append(nextToken.toString());
sb.append("
\n");
if (nextToken.length() < clauseContent.length())
clauseContent = clauseContent.substring(nextToken.length() + 1);
else
clauseContent = "";
} // while
} // while
request.setAttribute(AppConstants.RI_FORMATTED_SQL, sb.toString());
request.setAttribute(AppConstants.RI_PAGE_TITLE, "Generated SQL");
request.setAttribute(AppConstants.RI_PAGE_SUBTITLE, "Generated SQL for report "
+ rdef.getReportName());
} catch (RaptorException e) {
nextPage = (new ErrorHandler()).processFatalError(request, e);
}
return nextPage;
} // reportShowSQLPopup
public String testSchedCondPopup(HttpServletRequest request, String nextPage) {
try {
ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(
AppConstants.SI_REPORT_DEFINITION);
String sql = AppUtils.getRequestNvlValue(request, AppConstants.RI_FORMATTED_SQL);
request.setAttribute("msg_align", " align=center");
request.setAttribute(AppConstants.RI_PAGE_TITLE, "Test Scheduler Condition");
String query = Globals.getTestSchedCondPopup();
query = query.replace("[sql]", sql);
DataSet ds = null;
String remoteDb = request.getParameter("remoteDbPrefix");
String remoteDbPrefix = (remoteDb != null && !remoteDb.equalsIgnoreCase("null")) ? remoteDb
: rdef.getDBInfo();
ds = ConnectionUtils.getDataSet(sql, remoteDbPrefix);
if (ds.getRowCount() == 0)
request
.setAttribute(AppConstants.RI_FORMATTED_SQL,
"
Condition NOT satisfied - email notification will NOT be send.
");
else
request
.setAttribute(AppConstants.RI_FORMATTED_SQL,
"
Condition satisfied - email notification will be send.
");
} catch (Exception e) {
request.setAttribute(AppConstants.RI_FORMATTED_SQL, "
SQL ERROR "
+ e.getMessage() + "
Email notification will NOT be send.
");
}
return nextPage;
} // testSchedCondPopup
public String testRunSQLPopup(HttpServletRequest request, String nextPage) {
String sql = AppUtils.getRequestNvlValue(request, AppConstants.RI_FORMATTED_SQL);
if(nvl(sql).length()<=0) {
sql = AppUtils.getRequestNvlValue(request, "reportSQL");
}
boolean chkFormFieldSQL = AppUtils.getRequestNvlValue(request,
AppConstants.RI_CHK_FIELD_SQL).equals("Y");
try {
if (!sql.trim().toUpperCase().startsWith("SELECT"))
throw new UserDefinedException(
"Invalid statement - the SQL must start with the keyword SELECT");
ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(
AppConstants.SI_REPORT_DEFINITION);
if (!chkFormFieldSQL) {
if (rdef.getFormFieldList() != null)
for (Iterator iter = rdef.getFormFieldList().getFormField().iterator(); iter
.hasNext();) {
FormFieldType fft = (FormFieldType) iter.next();
String fieldId = fft.getFieldId();
String fieldDisplay = rdef.getFormFieldDisplayName(fft);
sql = Utils.replaceInString(sql, fieldDisplay, "NULL");
} // for
} // if
DataSet ds = null;
String remoteDb = request.getParameter("remoteDbPrefix");
String remoteDbPrefix = (remoteDb != null && !remoteDb.equalsIgnoreCase("null")) ? remoteDb
: rdef.getDBInfo();
String userId = AppUtils.getUserID(request);
sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId);
String[] reqParameters = Globals.getRequestParams().split(",");
String[] sessionParameters = Globals.getSessionParams().split(",");
javax.servlet.http.HttpSession session = request.getSession();
logger.debug(EELFLoggerDelegate.debugLogger, ("B4 testRunSQL " + sql));
if(request != null ) {
for (int i = 0; i < reqParameters.length; i++) {
if(!reqParameters[i].startsWith("ff"))
sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(),request.getParameter(reqParameters[i].toUpperCase()) ));
else
sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(),request.getParameter(reqParameters[i]) ));
}
}
if(session != null ) {
for (int i = 0; i < sessionParameters.length; i++) {
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 (chkFormFieldSQL && ds.getRowCount() > 0) {
String id = ds.getString(0, "id");
String name = ds.getString(0, "name");
} // if
request.setAttribute(AppConstants.RI_DATA_SET, ds);
} catch (RaptorException e) {
request.setAttribute(AppConstants.RI_EXCEPTION, e);
}
return nextPage;
} // testRunSQLPopup
public String importSemaphorePopup(HttpServletRequest request, String nextPage) {
try {
(new WizardProcessor()).processImportSemaphorePopup(request);
} catch (RaptorException e) {
nextPage = (new ErrorHandler()).processFatalError(request, e);
}
return nextPage;
} // importSemaphorePopup
public String saveSemaphorePopup(HttpServletRequest request, String nextPage) {
try {
(new WizardProcessor()).processSemaphorePopup(request);
} catch (RaptorException e) {
nextPage = (new ErrorHandler()).processFatalError(request, e);
}
return nextPage;
} // saveSemaphorePopup
public String gotoJsp(HttpServletRequest request, String nextPage) {
return nextPage;
} // gotoJsp
public String downloadAll(HttpServletRequest request, String nextPage) throws InterruptedException, IOException, Exception {
String emailId = null;
String pdfAttachmentKey = AppUtils.getRequestValue(request, "pdfAttachmentKey");
boolean isFromSchedule = nvl(pdfAttachmentKey).length()>0;
if(!isFromSchedule)
emailId = AppUtils.getUserEmail(request);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
java.util.Date currDate = new java.util.Date();
String timestamp = sdf.format(currDate);
String dateStr = sdf1.format(currDate);
String userId = null;
if(!isFromSchedule)
userId = AppUtils.getUserID(request);
else
userId = AppUtils.getRequestValue(request, USER_ID);
Runtime runtime = Runtime.getRuntime();
ReportRuntime rr = null;
if(!isFromSchedule) {
rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
if(rr!=null) AppUtils.getUserEmail(request);
}
String scheduleId = "";
if(isFromSchedule) {
String reportID = null;
String report_email_sent_log_id = AppUtils.getRequestValue(request, "log_id");
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());
DataSet ds = DbUtils.executeQuery(query, 1);
if(!ds.isEmpty()) {
userId = ds.getString(0,USER_ID);
reportID = ds.getString(0, "rep_id");
request.setAttribute("schedule_email_userId", userId);
} else {
request.setAttribute(MESSAGE, "This link has expired, please login and regenerate the report");
return "raptor/message.jsp";
}
ReportHandler rh1 = new ReportHandler();
if(reportID !=null && nvl(pdfAttachmentKey).length()>0) {
rr = rh1.loadReportRuntime(request, reportID, true, 1);
rr.loadReportData(-1, userId, 1000 ,request, false /*download*/);
}
String d_sql = Globals.getDownloadAllGenKey();
d_sql = d_sql.replace("[pdfAttachmentKey]", pdfAttachmentKey);
ds = DbUtils.executeQuery(d_sql);
for (int i = 0; i < ds.getRowCount(); i++) {
scheduleId = ds.getString(i,0);
}
}
logger.debug(EELFLoggerDelegate.debugLogger, ("SQL2:\n"+ rr.getCachedSQL()));
String fileName = FilenameUtils.normalize(rr.getReportID()+"_"+userId+"_"+timestamp);
boolean flag = false;
logger.debug(EELFLoggerDelegate.debugLogger, (""+Utils.isDownloadFileExists(rr.getReportID()+"_"+userId+"_"+dateStr)));
if(flag){
String strFileName = Utils.getLatestDownloadableFile(rr.getReportID()+"_"+userId+"_"+dateStr);
StringBuffer messageBuffer = new StringBuffer("");
messageBuffer.append("Download data file using the following link
");
messageBuffer.append("click here.");
request.setAttribute(MESSAGE, messageBuffer.toString());
}
else if(!flag) {
String whole_fileName = FilenameUtils.normalize (Globals.getShellScriptDir() +AppConstants.SHELL_QUERY_DIR+ fileName+AppConstants.FT_SQL);
String whole_columnsfileName = FilenameUtils.normalize (Globals.getShellScriptDir() +AppConstants.SHELL_QUERY_DIR+ fileName+AppConstants.FT_COLUMNS);
logger.debug(EELFLoggerDelegate.debugLogger, ("FILENAME "+whole_fileName));
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("|");
}
try {
PrintWriter xmlOut = new PrintWriter(new BufferedWriter(new FileWriter(new File(whole_columnsfileName))));
xmlOut.println(allColumnsBuffer.toString());
xmlOut.flush();
xmlOut.close();
} catch (IOException e) {logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), e);}
try {
PrintWriter xmlOut = new PrintWriter(new BufferedWriter(new FileWriter(new File(whole_fileName))));
logger.debug(EELFLoggerDelegate.debugLogger, ("**************************"));
logger.debug(EELFLoggerDelegate.debugLogger, (rr.getWholeSQL()));
logger.debug(EELFLoggerDelegate.debugLogger, ("************************"));
logger.debug(EELFLoggerDelegate.debugLogger, ("************************"));
logger.debug(EELFLoggerDelegate.debugLogger, (rr.parseReportSQL(rr.getWholeSQL())));
xmlOut.println(rr.parseReportSQL(rr.getWholeSQL()));
xmlOut.flush();
xmlOut.close();
} catch (IOException e) {logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), e);}
StringBuffer command = new StringBuffer(Globals.getShellScriptDir() + AppConstants.SHELL_SCRIPTS_DIR);
if(nvl(emailId).length()>0) {
command.append(AppConstants.SHELL_SCRIPT_NAME + " " + (fileName+AppConstants.FT_SQL));
command.append(" "+emailId);
}
else if (nvl(scheduleId).length()>0) {
command.append(AppConstants.SCHEDULE_SHELL_SCRIPT_NAME + " " + (fileName+AppConstants.FT_SQL));
command.append(" " + scheduleId);
}
logger.debug(EELFLoggerDelegate.debugLogger, ("Command " + command));
Process downloadProcess = runtime.exec(command.toString());
logger.debug(EELFLoggerDelegate.debugLogger, ("Command Executed "));
Enumeration enum1 = rr.getParamKeys();
String value = "";
String paramStr = "";
StringBuffer paramBuffer = new StringBuffer();
if(enum1!=null) {
for (; enum1.hasMoreElements();) {
String key = (String) enum1.nextElement();
value = rr.getParamValue(key);
paramBuffer.append(key+":"+value+" ");
}
paramStr = paramBuffer.toString();
}
StringBuffer retrieveUserEmailQry = null;
ArrayList userEmailList = new ArrayList();
if(nvl(scheduleId).length()>0) {
String r_sql = Globals.getDownloadAllRetrieve();
r_sql = r_sql.replace("[scheduleId]", scheduleId);
DataSet ds = DbUtils.executeQuery(r_sql);
for (int i = 0; i < ds.getRowCount(); i++) {
userEmailList.add(ds.getString(i, 0));
}
}
String insertQry = Globals.getDownloadAllInsert();
try(Connection connection = DbUtils.getConnection();
PreparedStatement pst = connection.prepareStatement(insertQry)){
if(nvl(emailId).length()>0){
pst.setInt(1, Integer.parseInt(userId));
pst.setInt(2, Integer.parseInt(rr.getReportID()));
pst.setString(3, fileName+AppConstants.FT_ZIP);
pst.setTimestamp(4,new java.sql.Timestamp(currDate.getTime()));
pst.setString(5,paramStr);
pst.execute();
connection.commit();
} else {
for (int i = 0; i < userEmailList.size(); i++) {
pst.setInt(1, Integer.parseInt((String)userEmailList.get(i)));
pst.setInt(2, Integer.parseInt(rr.getReportID()));
pst.setString(3, fileName+AppConstants.FT_ZIP);
pst.setTimestamp(4,new java.sql.Timestamp(currDate.getTime()));
pst.setString(5,paramStr);
pst.execute();
connection.commit();
}
}
logger.debug(EELFLoggerDelegate.debugLogger, ("Data inserted"));
} catch (SQLException ex) {
throw new RaptorException(ex);
} catch (ReportSQLException ex) {
throw new RaptorException(ex);
} catch (Exception ex) {
throw new RaptorException (ex);
}
}
return nextPage;
}
public String getChildDropDown(HttpServletRequest request, String nextPage) throws RaptorRuntimeException {
if(request.getParameter("firstTime") != null) { return nextPage; }
return nextPage;
}
private void removeVariablesFromSession(HttpServletRequest request) {
HttpSession session = request.getSession();
session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST);
session.removeAttribute(AppConstants.DRILLDOWN_INDEX);
session.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX);
session.removeAttribute(AppConstants.SI_BACKUP_FOR_REP_ID);
session.removeAttribute(AppConstants.SI_COLUMN_LOOKUP);
session.removeAttribute(AppConstants.SI_DASHBOARD_REP_ID);
session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP);
session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME);
session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP);
session.removeAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP);
session.removeAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP);
session.removeAttribute(AppConstants.SI_DATA_SIZE_FOR_TEXTFIELD_POPUP);
session.removeAttribute(AppConstants.SI_MAP);
session.removeAttribute(AppConstants.SI_MAP_OBJECT);
session.removeAttribute(AppConstants.SI_REPORT_DEFINITION);
session.removeAttribute(AppConstants.SI_REPORT_RUNTIME);
session.removeAttribute(AppConstants.SI_REPORT_RUN_BACKUP);
session.removeAttribute(AppConstants.SI_REPORT_SCHEDULE);
session.removeAttribute(AppConstants.RI_REPORT_DATA);
session.removeAttribute(AppConstants.RI_CHART_DATA);
session.removeAttribute(AppConstants.SI_FORMFIELD_INFO);
session.removeAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO);
session.removeAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP);
session.removeAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP);
Enumeration enum1 = session.getAttributeNames();
String attributeName = "";
while(enum1.hasMoreElements()) {
attributeName = enum1.nextElement();
if(attributeName.startsWith(PARENT)) {
session.removeAttribute(attributeName);
}
}
}
private TreeMap getListOfReportsFromDashBoardJson(String jsonString) throws Exception {
HashMap hashReports = new HashMap();
ObjectMapper mapper = new ObjectMapper();
TypeReference> mapType = new TypeReference>() {
};
List reportList = mapper.readValue(jsonString, mapType);
int index = 1;
for (DashboardChildReport childRep : reportList) {
String str = childRep.getHasContent().get("id");
hashReports.put(index, (str.substring(0).toLowerCase().startsWith("chart") ? "c" : "d")
+ str.substring(str.indexOf("#") + 1, str.length()));
index++;
}
return new TreeMap(hashReports);
}
private TreeMap getListOfReportsFromDashBoardHTML(String htmlString) {
String sourcestring = htmlString;
Pattern re = Pattern.compile("\\[(.*?)\\]"); //\\[(.*?)\\]
Matcher m = re.matcher(sourcestring);
HashMap hashReports = new HashMap();
int mIdx = 0;
while (m.find()){
for( int groupIdx = 0; groupIdx < m.groupCount(); groupIdx++ ){
String str = m.group(groupIdx);
hashReports.put(new String(Integer.toString(mIdx+1)), (str.substring(1).toLowerCase().startsWith("chart")?"c":"d") + str.substring(str.indexOf("#")+1, str.length()-1));
}
mIdx++;
}
return new TreeMap(hashReports);
}
public ReportData getReportData(ReportRuntime reportRuntime, HttpServletRequest request, String sql, int maxRows) throws RaptorException {
// replace the request parameter specified in the drill down
List reportCols = reportRuntime.getAllColumns();
StringBuffer colNames = new StringBuffer();
for (Iterator> iter = reportCols.iterator(); iter.hasNext();) {
DataColumnType dc = (DataColumnType) iter.next();
if (colNames.length() > 0)
colNames.append(", ");
colNames.append(dc.getColId());
if (dc.isVisible()) {
//TODO: Drilldown URL
}
}
DataSet ds = null;
String dbInfo = reportRuntime.getDBInfo();
if(maxRows == 1)
sql += " limit "+ maxRows;
System.out.println("SQL getReportData()- " + sql);
ds = ConnectionUtils.getDataSet(sql, dbInfo);
int totalRows = 0;
String dbType = "";
if (dbInfo!=null && (!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);
}
}
totalRows = ds.getRowCount();
ReportData rd = new ReportData(0, true);
if(totalRows > 0) {
// Already defined changed for modifying request parameters
Vector visibleCols = new Vector(reportCols.size());
Vector formatProcessors = new Vector(reportCols.size());
int count =0 ;
/* ADDED */
ReportFormFields rff = reportRuntime.getReportFormFields();
ReportFormFields childReportFormFields = null;
String fieldDisplayName = "";
String fieldValue = "";
for (int c = 0; c < reportCols.size(); c++) {
if(reportCols.get(c)!=null) {
DataColumnType dct = (DataColumnType) reportCols.get(c);
if(nvl(dct.getDependsOnFormField()).length()>0 && nvl(dct.getDependsOnFormField()).indexOf("[")!=-1) {
for(int i = 0 ; i < rff.size(); i++) {
fieldDisplayName = "["+((FormField)rff.getFormField(i)).getFieldDisplayName()+"]";
fieldValue = "";
if (dct.getDependsOnFormField().equals(fieldDisplayName)) {
fieldValue = nvl(request.getParameter(((FormField)rff.getFormField(i)).getFieldName()));
if (fieldValue.length()>0) {
if(!fieldValue.toUpperCase().equals("Y"))
dct.setDisplayName(fieldValue);
if(!dct.isVisible())
dct.setVisible(true);
} else {
dct.setVisible(false);
}
}
}
}
}
}
/* ADDED */
String displayName = "";
for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
DataColumnType dc = (DataColumnType) iter.next();
formatProcessors.add(count,new FormatProcessor(
reportRuntime.getSemaphoreById(dc.getSemaphoreId()), dc.getColType(), dc
.getColFormat(), reportRuntime.getReportDefType().equals(
AppConstants.RD_SQL_BASED)));
/* TODO: Add Drilldown URL */
if (nvl(dc.getDrillDownURL()).length() > 0) {
childReportFormFields = reportRuntime.getChildReportFormFields(request,dc.getDrillDownURL());
}
if (dc.isVisible()) {
visibleCols.add(count,dc);
for (int d = 0; d < reportCols.size(); d++) {
if(reportCols.get(d)!=null) {
DataColumnType dct1 = (DataColumnType) reportCols.get(d);
if(dct1.getColId().equals(dc.getColId()+"_name") && ds.getRowCount()>0) {
displayName = ds.getString(0,dct1.getColId());
dc.setDisplayName(displayName);
}
}
}
VisualManager visualManager = reportRuntime.getVisualManager();
rd.createColumn(dc.getColId(), dc.getDisplayName(), dc.getDisplayWidthInPxls(),dc.getDisplayHeaderAlignment(),
visualManager.isColumnVisible(dc.getColId()), visualManager
.getSortByColId().equals(dc.getColId()) ? visualManager
.getSortByAscDesc() : null, true, dc.getLevel()!=null?dc.getLevel():0, dc.getStart()!=null?dc.getStart():0, dc.getColspan()!=null?dc.getColspan():0, dc.isIsSortable()!=null?dc.isIsSortable():false);
} // if
else {
visibleCols.add(count,null);
rd.createColumn(dc.getColId(), AppConstants.HIDDEN, dc.getDisplayWidthInPxls(), dc.getDisplayHeaderAlignment(),
false, 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);
}
count++;
} // for
// 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
if(maxRows > totalRows) maxRows = totalRows;
ArrayList reportDataList = new ArrayList();
for (int r = 0; r < maxRows; r++) {
DataRow dr = new DataRow();
rd.reportDataRows.addDataRow(dr);
for (int c = 0; c < reportCols.size(); c++) {
if(reportCols.get(c)!=null) {
DataColumnType dct = (DataColumnType) reportCols.get(c);
//Modified since ds is null.
DataValue dv = new DataValue();
if(ds.getRowCount()>0){
if(ds.getColumnIndex(dct.getColId())!= -1) {
dr.addDataValue(dv);
dv.setDisplayValue(ds.getString(r, dct.getColId()));
} else {
continue;
}
} else {
dv.setDisplayValue("");
}
dv.setColName(dct.getColName());
dv.setColId(dct.getColId());
dv.setNowrap(nvl(dct.getNowrap(),"null").equals(FALSE)?"null":nvl(dct.getNowrap(),"null"));
//Add Drilldown URL to dv
if (nvl(dct.getDrillDownURL()).length() > 0) {
if(dv.getDisplayValue().length() > 0) {
dv.setDrillDownURL(reportRuntime.parseDrillDownURL(r, /* c, */ds, dct, request, childReportFormFields));
dv.setDrillDowninPoPUp(dct.isDrillinPoPUp()!=null?dct.isDrillinPoPUp():false);
}
if (dv.getDisplayValue().length() == 0) {
dv.setDisplayValue("");
}
} // if
StringBuffer indentation = new StringBuffer("");
if(dct.getIndentation()!=null && dct.getIndentation()>0) {
for (int indent=0; indent< dct.getIndentation(); indent++) {
indentation.append("\t");
}
dv.setNowrap("true");
}
dv.setIndentation(indentation.toString());
if(dct.isVisible()) {
dv.setVisible(true);
dv.setAlignment(dct.getDisplayAlignment());
dv.setDisplayTotal(dct.getDisplayTotal());
dv.setDisplayName(dct.getDisplayName());
} else {
dv.setVisible(false);
dv.setHidden(true);
}
if(dr.getFormatId()!=null)
((FormatProcessor) formatProcessors.get(c)).setHtmlFormatters(dv, dr, true);
else
((FormatProcessor) formatProcessors.get(c)).setHtmlFormatters(dv, dr, false);
} // if reportCols
} // for
reportDataList.add(dr);
} // for
rd.setReportDataList(reportDataList);
//Only if rownumber options is needed
DataRow colDataTotalsLinear = null;
if (colDataTotalsLinear == null)
colDataTotalsLinear = reportRuntime.generateColumnDataTotalsLinear(new ArrayList(reportCols), AppUtils.getUserID(request),
reportRuntime.getDbInfo(),request);
if(colDataTotalsLinear!=null)
rd.setColumnDataTotalsLinear(colDataTotalsLinear, "Total");
// Please note the below function doesn't set the visibility for dv since this is set in this function. - Sundar
rd.applyVisibility();
}
return rd;
} // loadLinearReportData
public String formFieldRun(HttpServletRequest request, String nextPage) {
ReportRuntime rr = null;
rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
if(rr!=null) {
ReportJSONRuntime reportJSONRuntime = rr.createFormFieldJSONRuntime(request);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String jsonInString = "";
try {
jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(reportJSONRuntime);
} catch (Exception ex) {
logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), ex);
}
return jsonInString;
}
return "";
}
} // ActionHandler