userreportvalidateformcontroller.java

来自「Java的框架」· Java 代码 · 共 390 行

JAVA
390
字号
package mcaps.core.reporting.webapp.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import mcap.core.base.webapp.controller.BaseFormController;
import mcap.core.logging.Log;
import mcap.core.reporting.model.Report;
import mcap.core.reporting.model.SubReport;
import mcap.core.reporting.service.ReportManager;
import mcap.core.reporting.util.NameConstants;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextException;
import org.springframework.validation.BindException;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.jasperreports.JasperReportsMultiFormatView;

/**
  * @deprecated  This class is no longer used. Its functionality has been replaced by 
 * mcaps.core.reporting.webapp.controller.UserReportFormController that handles the 
 * validation as well.
  * 
 * Implementation of BaseFormController that interacts with the 
 * ReportManager to handle request to query database for report
 * information to enable the displaying of report information in 
 * the web page as well as to provide form input validation when
 * the web page is submitted. 
 * 
 * The valid input will cause a redirection to the UserReportFormController
 * for generation of report via a web page which perform an auto 
 * submit of the form to the UserReportFormController.
 * 
 * The input submitted and information pertaining to the report will be 
 * placed into the session attribute in order for the redirected web page 
 * to read the input parameter and also the report information and in turn
 * re-submit to the UserReportFormController
 *  
 * @author jov
 * @date Jan 12, 2006
 * @version 1.0.1.0
 */
public class UserReportValidateFormController extends BaseFormController {

	private ReportManager reportManager;

	/**
	 * 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;
	}
	
	//===========================================================================================================
	//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)
			throw new ApplicationContextException(
					"Must set reportManager bean property on " + getClass());
		if (this.reportManager.getRootDir() == null)
			this.reportManager.setRootDir(getServletContext().getRealPath("/"));

	}

	//----------------------------------------------------------------------
	// ----------------------------------------------------------------------

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.BaseCommandController#onBind(javax.servlet.http.HttpServletRequest, java.lang.Object, org.springframework.validation.BindException)
	 */
	protected void onBind (HttpServletRequest request, Object command, BindException errors) {
			Enumeration paramNames = request.getParameterNames();
	    
		while (paramNames.hasMoreElements()) {
			String name = (String) paramNames.nextElement();
			if ((name.startsWith("_")) && (!name.endsWith("_valueClassName"))) {
	      	String value = request.getParameter(name);
				String valueType = request.getParameter(name
						+ "_valueClassName");
	        //perform field validation
				String msg = validateParameter(value, valueType);
				if (msg != null) {
					errors.reject(msg, new Object[] { name.substring(1) },
							"Invalid input for " + name.substring(1));
				}
	        }
	      }
	
	  		}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.AbstractFormController#processFormSubmission(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
	 * Checks for an action that should be executed without respect to binding errors, like a cancel action.
	 */
	public ModelAndView processFormSubmission(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		if (request.getParameter("cancel") != null) {
			return new ModelAndView(getCancelView());
	  	}
		return super.processFormSubmission(request, response, command, errors);
	}

	public ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		
		Report report = (Report) command;
		String uri = request.getRequestURI ();
		String format = uri.substring (uri.lastIndexOf (".") + 1);

		Map model = new HashMap ();
		model.put ("format", format);
	  
		Enumeration paramNames = request.getParameterNames();
    
		while(paramNames.hasMoreElements()) {
      String paramName = (String)paramNames.nextElement();
      if ((paramName.startsWith("_")) && (!paramName.endsWith("_valueClassName"))){
        String value = request.getParameter(paramName);
				String name = paramName.substring(1);
				Object obj = null;
        if (value != null){
        	if (value.length() > 0){
						obj = getValue(value,request.getParameter(paramName + "_valueClassName"));
        	}
        }
				Log.info("Param Name Value : " + name + ";" + obj);
				model.put (name, obj);
      }
  	}
		
		
		ServletContext servletContext = getServletContext();
		ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext (servletContext);
		DataSource ds = (DataSource) ctx.getBean("dataSource");
		//JndiTemplate jndiTemplate = new JndiTemplate();
//		DataSource ds = (DataSource)jndiTemplate.lookup("java:comp/env/jdbc/" + report.getJndiDataSourceName());
		Log.info("DataSource is null : " + (ds==null));
		JasperReportsMultiFormatView view = new JasperReportsMultiFormatView();
		String binaryFile = report.getSourceFile().substring(0,report.getSourceFile().lastIndexOf("."));
		binaryFile += ".jasper";
		
		view.setUrl(binaryFile);
		
		Report detailedReport = this.getReportManager().getReport(report.getName());
		
		//set sub report urls
		Properties props = new Properties();
		for (int i=0; i < detailedReport.getSubReports().size(); i++){
			SubReport subReport = (SubReport)detailedReport.getSubReports().get(i);
			if ((subReport.getSourceFile() != null) || (subReport.getSourceFile().length() > 0)){
				props.setProperty(subReport.getName(),subReport.getSourceFile());
				Log.info("Subreport : " + subReport.getName() + ";" + subReport.getSourceFile());
			}
		}
		if (props.size() > 0) view.setSubReportUrls(props);
		
		view.setJdbcDataSource(ds);
		view.setApplicationContext(this.getApplicationContext());
		
		if (format.equals("html")){
			Map imagesMap = new HashMap();
			request.getSession().setAttribute("IMAGES_MAP", imagesMap);
			Map paramMap = new HashMap();
			paramMap.put(JRHtmlExporterParameter.IMAGES_MAP,imagesMap);
			paramMap.put(JRHtmlExporterParameter.IMAGES_URI, request.getContextPath() + "/report/getImage?image=");
			view.setExporterParameters(paramMap);
		}
		
		Log.info("Report Url : " + view.getUrl());
		
		return new ModelAndView(view,model);
	}
	

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.AbstractFormController#showForm(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.validation.BindException)
	 * Calling in case of validation errors, to show the form view again.
	 */
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors)
			throws Exception {

		// prevent ordinary users from calling a GET request
		// unless a bind error exists.
		if ((request.getRequestURI().indexOf("userReport") > -1)
				&& (request.getRemoteUser() == null)) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return null;
		}
		return super.showForm(request, response, errors);
	}

	/* (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 {
		
	  Report report = new Report();
		String reportName = request.getParameter("reportName");
		if (reportName != null) {
			report = reportManager.getReport(reportName);
			List list = reportManager.getReportParameters(reportName);
			request.setAttribute(NameConstants.REPORT_PARAM_LIST, list);
		}
		String uri = request.getRequestURI ();
		String format = uri.substring (uri.lastIndexOf (".") + 1);
		request.setAttribute(NameConstants.REPORT_FORMAT, format);
				
		return report;
	}
	
	/**
	 * Validate the parameter value against the value type name.
	 * @param value the value of the parameter
	 * @param valueType the value class name for the parameter
	 * @return return error message if parameter is invalid; return null if parameter is valid
	 */
	private String validateParameter(String value, String valueType) {
		if (valueType.equals("java.lang.Boolean")) {
			if (value.equals("true")) {
				return null;
			} else if (value.equals("false")) {
				return null;
			} else {
				return "errors.validate.boolean";
			}
		} else if (valueType.equals("java.util.Date")) {
			SimpleDateFormat fmt = new SimpleDateFormat();
			try {
				fmt.parse(value);
			} catch (ParseException e) {
				return "errors.validate.date";
			}
			return null;
		} else if (valueType.equals("java.lang.Double")) {
			try {
				new Double(value);
			} catch (NumberFormatException e) {
				return "errors.validate.double";
			}
			return null;
		} else if (valueType.equals("java.lang.Float")) {
			try {
				new Float(value);
			} catch (NumberFormatException e) {
				return "errors.validate.float";
			}
			return null;
		} else if (valueType.equals("java.lang.Integer")) {
			try {
				new Integer(value);
			} catch (NumberFormatException e) {
				return "errors.validate.integer";
			}
			return null;
		} else if (valueType.equals("java.lang.Long")) {
			try {
				new Long(value);
			} catch (NumberFormatException e) {
				return "errors.validate.long";
			}
			return null;
		} else if (valueType.equals("java.lang.Short")) {
			try {
				new Short(value);
			} catch (NumberFormatException e) {
				return "errors.validate.short";
			}
			return null;
		} else if (valueType.equals("java.lang.Number")) {
			try {
				new Integer(value);
			} catch (NumberFormatException e) {
				return "errors.validate.number";
			}
			return null;
		}
		return null;
	}

	/**
	 * @param value
	 * @param valueClassName
	 * @return
	 */
	private Object getValue(String value, String valueClassName){
		
		if (valueClassName.equals("java.lang.Boolean")){
			Boolean rslt = null;
			if (!isNullOrEmpty(value)){
				rslt = new Boolean(value);
			}
			return rslt;
		}else if (valueClassName.equals("java.util.Date")){		
			Date rslt = null;
			if (!isNullOrEmpty(value)){
				SimpleDateFormat fmt = new SimpleDateFormat();
				try {
					rslt = fmt.parse(value);
				}
				catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return rslt;
		}else if (valueClassName.equals("java.lang.Double")){
			Double rslt = null;
			if (!isNullOrEmpty(value)){
				rslt = new Double(value);
			}
			return rslt;
		}else if (valueClassName.equals("java.lang.Float")){
			Float rslt = null;
			if (!isNullOrEmpty(value)){
				rslt = new Float(value);
			}
			return rslt;
		}else if (valueClassName.equals("java.lang.Integer")){
			Integer rslt = null;
			if (!isNullOrEmpty(value)){
				rslt = new Integer(value);
			}
			return rslt;
		}else if (valueClassName.equals("java.lang.Long")){
			Long rslt = null;
			if (!isNullOrEmpty(value)){
				rslt = new Long(value);
			}
			return rslt;
		}else if (valueClassName.equals("java.lang.Short")){
			Short rslt = null;
			if (!isNullOrEmpty(value)){
				rslt = new Short(value);
			}
			return rslt;
		}else if (valueClassName.equals("java.lang.Number")){
			Integer rslt = null;
			if (!isNullOrEmpty(value)){
				rslt = new Integer(value);
			}
			return rslt;
		}
		return value;
	}
	
	/**
	 * @param value
	 * @return
	 */
	private boolean isNullOrEmpty(String value){
		return ((value == null) || (value.length() < 1));
	}
	
}

⌨️ 快捷键说明

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