reportwizardcontroller.java

来自「Java的框架」· Java 代码 · 共 1,066 行 · 第 1/3 页

JAVA
1,066
字号
package mcaps.core.reporting.webapp.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.design.JasperDesign;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContextException;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.RequestUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import mcap.core.base.webapp.controller.BaseWizardFormController;
import mcap.core.logging.Log;
import mcap.core.reporting.model.Report;
import mcap.core.reporting.model.SubReport;
import mcap.core.reporting.service.ReportException;
import mcap.core.reporting.service.ReportManager;
import mcap.core.reporting.util.JasperReportDesignUtil;
import mcap.core.reporting.util.NameConstants;
import mcap.core.user.service.RoleManager;
import mcap.core.util.FileUtil;

/**
 * Implementation of BaseWizardFormController that interacts with the 
 * ReportManager to handle request pertaining to report template management.
 * This wizard works with two different repository: database and filesystem.
 * Database is used for storage of information pertaining to the report template
 * while file system is used to store all the report templates and their 
 * corresponding sub report templates. This wizard also facilitate role based 
 * access rights control that together with the report template information and the
 * physical file saved, to facilitate the generation of user report.
 * 
 * @author jov
 * @date May 25, 2006
 * @version 2.0.1.0
 */
public class ReportWizardController extends BaseWizardFormController implements
InitializingBean {
	
	private ReportManager reportManager;
	private RoleManager roleManager;
	private String baseDir;
	private String fullBaseDir;
	
	/**
	 * Returns the baseDir.
	 * @return String
	 */
	public String getBaseDir () {
		return baseDir;
	}
	
	/**
	 * Sets the baseDir.
	 * @param baseDir The baseDir to set.
	 */
	public void setBaseDir (String baseDir) {
		this.baseDir = baseDir;
	}
	
	
	/**
	 * Returns the reportManager.
	 * @return ReportManager
	 */
	public ReportManager getReportManager () {
		return reportManager;
	}
	
	/**
	 * Sets the reportManager.
	 * @param reportManager The reportManager to set.
	 */
	public void setReportManager (ReportManager reportManager) {
		this.reportManager = reportManager;
	}
	
	/**
	 * Returns the roleManager.
	 * @return RoleManager
	 */
	public RoleManager getRoleManager () {
		return roleManager;
	}
	
	/**
	 * Sets the roleManager.
	 * @param roleManager The roleManager to set.
	 */
	public void setRoleManager (RoleManager roleManager) {
		this.roleManager = roleManager;
	}
	
	// ===========================================================================================================
	// INITIALIZING BEAN IMPLEMENTATION
	// ===========================================================================================================
	
	/*
	 * (non-Javadoc)
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 *      Invoked by a BeanFactory after it has set all bean properties
	 *      supplied. This allows the bean instance to perform initialization only
	 *      possible when all bean properties have been set and to throw an
	 *      exception in the event of misconfiguration.
	 */
	public void afterPropertiesSet () throws Exception {
		if (reportManager == null){
			Log.warn("Must set reportManager bean property on " + getClass());
			throw new ApplicationContextException(
					"Must set reportManager bean property on " + getClass());
		}
		if (roleManager == null){
			Log.warn("Must set roleManager bean property on " + getClass());
			throw new ApplicationContextException(
					"Must set roleManager bean property on " + getClass());
		}
		System.setProperty(
				"jasper.reports.compile.class.path",
				this.getServletContext().getRealPath("/WEB-INF/lib/jasperreports-1.0.3.jar")
				+ System.getProperty("path.separator")
				+ this.getServletContext().getRealPath("/WEB-INF/classes/"));
		
		Log.info("Set jasper.reports.compile.class.path : " + System.getProperty("jasper.reports.compile.class.path"));
		
		fullBaseDir = getServletContext().getRealPath(baseDir);
		Log.info("Report full base dir : " + fullBaseDir);
		File file = new File(fullBaseDir);
		if (!file.exists()){
			file.mkdir();
		}	
		
		File tempDir = new File(fullBaseDir + "/temp");
		Log.info("Report temp dir : " + tempDir);
		if (!tempDir.exists()){
			tempDir.mkdir();
		}
	}
	
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
	 * Retrieve a backing object for the current form from the given request.
	 */
	protected Object formBackingObject (HttpServletRequest request)
	throws Exception {
		
		Log.debug("formBackingObject");
		Report report = null;
		if (StringUtils.equals (request.getParameter("method"), "edit")) {
			report = getReport (RequestUtils.getStringParameter(request, "reportName"));
		}
		if (report == null){
			Log.debug("Report is null. Empty new report is instantiated");
			report = new Report ();
		}
		setRequestAttribute(request,NameConstants.REPORT_TEMPID);
		
		return report;
	}
	
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.BaseCommandController#onBind(javax.servlet.http.HttpServletRequest, java.lang.Object, org.springframework.validation.BindException)
	 * Primarily used to do data binding for report parameters. Also used to validate 
	 * the page entry each time a page is submitted for validation that requires 
	 * access to HttpServletRequest object.
	 */
	protected void onBind (HttpServletRequest request, Object command,
			BindException errors) {
		
		Report report = (Report) command;
		
		//Do validation if buttons other than previous button was clicked
		if (request.getParameter("_target0") == null){
			
//			if (performGeneralValidation(request, report, errors)){
//				Log.debug("performGeneralValidation (OK)");

			if (this.getCurrentPage (request) == 0) {
				if (performPage0Validation(request, report, errors)){
					Log.debug("performPage0Validation (OK)");
					onBindPage0(request, report, errors);
				}
			}else if (this.getCurrentPage (request) == 1) {
				Log.debug("performPage1Validation (OK)");
				if (performPage1Validation(request, report, errors)){
					onBindPage1(request, report, errors);
				}
			}
//			}else{
//				try {
//					request.setAttribute(NameConstants.REPORT_TEMPID, getTempID(request));
//					this.showPage(request, errors, 0);
//				}
//				catch (Exception e) {
//					errors.reject (NameConstants.ERROR_PROCESS_REQUEST, new Object[]{e.getMessage()},e.getMessage());						
//				}
//			}
			//If errors found, getTargetPage() will not be called, thus temp id has to be set here
			//else temp id will be empty
			if (errors.getErrorCount() > 0)	request.setAttribute(NameConstants.REPORT_TEMPID, getTempID(request));
			
		}
	}
	
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.AbstractWizardFormController#getTargetPage(javax.servlet.http.HttpServletRequest, java.lang.Object, org.springframework.validation.Errors, int)
	 */
	protected int getTargetPage (HttpServletRequest request, Object command,
			Errors errors, int currentPage) {
		
		request.setAttribute(NameConstants.REPORT_TEMPID, getTempID(request));
		Log.info("Current TargetPage : " + currentPage);
		
		try{
			
			//If there are binding errors refrain from navigation
			if (errors.getErrorCount() > 0)
				return currentPage;
			
			currentPage = super.getTargetPage(request, command, errors, currentPage);
			Log.info("New TargetPage : " + currentPage);
			
			Report report = (Report) command;
			switch (currentPage) {
			case 0:
				Log.debug("getTargetPage(0) : Do Nothing.");
				//This page will list all main properties of the report template for input
				//Nothing need to be done as it has been done in formBackingObject()
				break;
			case 1:
				//If the sub report already been populated before, do nothing
				//This is to handle the navigation back to Page 0 then back again to Page 1
				//Sub report will be cleared if navigation back to Page 0 changes the report source file
				if (report.getSubReports().size() > 0){
					Log.debug("getTargetPage(1) : Do Nothing. Sub report was loaded.");
					break;
				}
				// This page will list all the sub reports with file control for each sub report for uploading
				Log.debug("getTargetPage(1) : Get sub report param from report template.");
				String reportSourceFile = this.toAbsolutePath(report.getSourceFile());
				Log.debug("getTargetPage(1) : Report source file : " + reportSourceFile);
				File reportFile = new File(reportSourceFile);
				if (!reportFile.exists()){
					Log.debug("getTargetPage(1) : Report source file not exists");
					errors.reject(NameConstants.ERROR_TEMP_RPT_TEMPLATE_NOTFOUND, "Temporary report template was not found.");						
				}
				String oriFileName = reportFile.getName();			
				Log.debug("getTargetPage(1) : Report file name : " + oriFileName);
				try {
					JasperDesign design = JasperReportDesignUtil.instance.getJasperDesign(reportFile);
					List subReportParam = JasperReportDesignUtil.instance.getSubReportParam(design);
					Log.debug("Total sub reports : " + subReportParam.size());
					if (subReportParam.size() > 0){
						for(int i=0; i < subReportParam.size(); i++){
							SubReport subreport = new SubReport(report.getName(),(String)subReportParam.get(i));
							report.addSubReport(subreport);
						}
					}
				}catch (JRException e) {
					errors.rejectValue("sourceFile",NameConstants.ERROR_LOAD_REPORT,new Object[]{oriFileName},"Error while loading report template.");
				}catch (ReportException e) {
					errors.reject (NameConstants.ERROR_PROCESS_REQUEST, new Object[]{e.getMessage()},e.getMessage());						
				}			
				break;
			case 2: 
				Log.debug("getTargetPage(2) : Do Nothing.");
				//This page will list all roles for assignment of roles
				// Do Nothing
				break;
			default:
			}
		} catch (Exception e) {
			Log.warn("Error in getTargetPage(" + currentPage + ").");
			errors.reject(NameConstants.ERROR_PROCESS_REQUEST, new Object[] { e.getMessage() }, e.getMessage());
			return currentPage;
		}
		return currentPage;
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.web.servlet.mvc.AbstractWizardFormController#processFinish(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
	 *      org.springframework.validation.BindException)
	 */
	protected ModelAndView processFinish (HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
	throws Exception {
		Report report = (Report) command;	
		Locale locale = request.getLocale ();
		
		try{
				//Rename the report source file
				setActualReportFileName(report, request);
				List subReportList = report.getSubReports();
				for (int i = 0; i < subReportList.size(); i++){
					SubReport subReport = (SubReport)subReportList.get(i);
					//Rename the sub report source file
					setActualSubReportFileName(subReport, request);
				}
				
				//Save to database
				try {
					this.getReportManager ().saveReport (report);
					//Process the report templates
					if (!commitReportTemplates(request, report)){
						Log.warn("Error while committing temporary report templates.");
						errors.reject(NameConstants.ERROR_COMMIT_REPORT, "Error while committing temporary report templates.");
						return showFormEx (request, response, errors);
					}
				}
				catch (ReportException e) {
					report.setVersion(null);
					Log.warn("Error saving report to database. " + e.getMessage());
					errors.rejectValue ("name", NameConstants.ERROR_EXISTING_REPORT, new Object[] {
							report.getName()}, "duplicate report");
					deleteTempDirectory(request,report.getName());
					return showFormEx (request, response, errors);
				}
				
				if (StringUtils.equals (request.getParameter ("method"), "add")) {
					saveMessage (request, getText (NameConstants.SUCC_REPORT_SAVE, report.getName(), locale));
				}else{					
					saveMessage (request, getText (NameConstants.SUCC_REPORT_UPDATE, report.getName(), locale));
				}
				
			return getRedirectView(request,command);
			
		}catch (Exception e) {
			Log.warn ("Error saving report. " + e.getMessage ());
			errors.reject (NameConstants.ERROR_PROCESS_REQUEST, new Object[] { e
					.getMessage () }, e.getMessage ());
			return showFormEx (request, response, errors);
		}
	}
	
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.AbstractWizardFormController#processCancel(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?