Java tutorial
/*$Id: QuestionnaireFormAction.java 15540 2010-04-20 15:24:26Z jens $*/ /* **************************************************************************** * * * (c) Copyright 2010 ABM-utvikling * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the * * Free Software Foundation; either version 2 of the License, or (at your * * option) any later version. * * * * This program is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * * Public License for more details. http://www.gnu.org/licenses/gpl.html * * * **************************************************************************** */ package no.abmu.questionnaire.webflow; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import no.abmu.questionnaire.domain.data.FieldData; import no.abmu.questionnaire.domain.data.QuestionnaireData; import no.abmu.questionnaire.domain.types.SchoolHas; import no.abmu.questionnaire.domain.util.LoggingOfFieldData; import no.abmu.questionnaire.propertyeditors.GrunnskoleStatisticPropertyEditorRegistrar; import no.abmu.questionnaire.propertyeditors.SchoolHasEditor; import no.abmu.questionnaire.propertyeditors.TestCustomNumberEditor; import no.abmu.questionnaire.service.QuestionnaireService; import no.abmu.questionnaire.web.QuestionnaireCommand; import no.abmu.util.test.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.batch.support.DefaultPropertyEditorRegistrar; import org.springframework.beans.PropertyEditorRegistry; import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.util.StopWatch; import org.springframework.validation.BindingResult; import org.springframework.validation.DataBinder; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import org.springframework.webflow.action.FormAction; import org.springframework.webflow.context.servlet.ServletExternalContext; import org.springframework.webflow.core.collection.ParameterMap; import org.springframework.webflow.execution.Event; import org.springframework.webflow.execution.RequestContext; /** * <code>QuestionnaireFormAction</code> takes care of webflow * form handling on Questionnaire schemas. * * @author Jens Vindvad, Jens.Vindvad@abm-utvikling.no * @author $Author: jens $ * @version $Rev: 15540 $ * @date $Date: 2010-04-20 17:24:26 +0200 (Tue, 20 Apr 2010) $ * @since 2008-01-25 * copyright ABM-Utvikling */ public class QuestionnaireFormAction extends FormAction { // standard European format private static final String EUROPEAN_DATE_PATTERN = "dd-MM-yyyy"; private static final Log logger = (Log) LogFactory.getLog(QuestionnaireFormAction.class); private QuestionnaireService questionnaireService; // private GrunnskoleStatisticPropertyEditorRegistrar grunnskoleStatisticPropertyEditorRegistrar; public void setQuestionnaireService(QuestionnaireService questionnaireService) { this.questionnaireService = questionnaireService; } public QuestionnaireService getQuestionnaireService() { return questionnaireService; } protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { if (logger.isDebugEnabled()) { logger.info("Executing initBinder"); } SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver(); Locale.setDefault(sessionLocaleResolver.resolveLocale(request)); if (logger.isDebugEnabled()) { logger.info("Setting locale:" + sessionLocaleResolver.resolveLocale(request)); } } // protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { // protected void initBinder(RequestContext context, DataBinder binder) { // super.initBinder(context, binder); // if (logger.isDebugEnabled()) { // logger.info("Executing initBinder"); // } // boolean allowEmpty = true; // boolean emptyAsNull = false; // // ServletExternalContext externalContext = (ServletExternalContext) context.getExternalContext(); // HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); // // SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver(); // Locale.setDefault(sessionLocaleResolver.resolveLocale(request)); // // if (logger.isDebugEnabled()) { // logger.info("Setting locale:"+sessionLocaleResolver.resolveLocale(request)); // } // // DecimalFormat decimalFormat = new DecimalFormat("#########0.00#######"); // DecimalFormat integerFormat = new DecimalFormat("#########0"); // // CustomNumberEditor doubleEditor = new TestCustomNumberEditor(Double.class, decimalFormat, allowEmpty); // CustomNumberEditor integerEditor = new TestCustomNumberEditor(Integer.class, integerFormat, allowEmpty); // CustomNumberEditor bigDecimalEditor = new TestCustomNumberEditor(BigDecimal.class, decimalFormat, allowEmpty); // CustomNumberEditor longEditor = new TestCustomNumberEditor(Long.class, integerFormat, allowEmpty); // // // binder.registerCustomEditor(Integer.class, integerEditor); // binder.registerCustomEditor(Double.class, doubleEditor); // binder.registerCustomEditor(BigDecimal.class, bigDecimalEditor); // binder.registerCustomEditor(Long.class, longEditor); // binder.registerCustomEditor(String.class, new StringTrimmerEditor(emptyAsNull)); // // } @Override public Event setupForm(RequestContext context) throws java.lang.Exception { logger.info("Executing custom setupForm"); logger.info("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"); ParameterMap parameterMap = context.getRequestParameters(); Map map = parameterMap.asMap(); Set<String> keys = map.keySet(); for (String key : keys) { Object value = map.get(key); logger.info("ParameterMap Key='" + key + "' value='" + (value == null ? "null" : value) + "'"); } logger.info("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"); // retrieve the form object Object formObject = getFormObject(context); logger.info("FormObject ==> " + formObject.getClass().getName()); if (!(formObject instanceof QuestionnaireCommand)) { logger.info("Reset form"); resetForm(context); } return super.setupForm(context); } protected Object createFormObject(RequestContext context) { if (logger.isDebugEnabled()) { logger.debug("Executing createFormObject"); } StopWatch stopWatch = new StopWatch(); stopWatch.start("createFormObject"); FlowVariables flowVariables = (FlowVariables) context.getFlowScope().get("flowVariables"); Long orgUnitId = flowVariables.getWorkingSchemaOrganisationUnitId(); String questionnaireNameAsString = flowVariables.getQuestionnaireNameAsString(); String schemaVersion = flowVariables.getQuestionnaireVersion(); // QuestionnaireCommand questionnaireCommand = flowVariables.getQuestionnaireCommand(); if (logger.isDebugEnabled()) { logger.debug("[createWebSchema] flowVariabels ==> " + flowVariables); } Assert.assertNotNull("orgUnitId", orgUnitId); Assert.assertNotNull("questionnaireNameAsString", questionnaireNameAsString); Assert.assertNotNull("schemaVersion", schemaVersion); String submitEvent = context.getRequestParameters().get("_eventId_submit.y"); if (submitEvent == null) { if (logger.isDebugEnabled()) { logger.debug("[createFormObject] submitEvent == null (formObject to user) "); } } else { if (logger.isDebugEnabled()) { logger.debug("[createFormObject] submitEvent != null (formObject from user)"); logger.debug("SubmitEvent='" + submitEvent + "'"); } } QuestionnaireCommand questionnaireCommand = getCommandFromDb(orgUnitId, questionnaireNameAsString, schemaVersion); try { stopWatch.stop(); logger.info("[createFormObject] tok [" + stopWatch.getTotalTimeMillis() + "] ms"); } catch (IllegalStateException e) { // Catch and log error. // logger.error("[formBackingObject] Error in stopWatch for user: " + loggedOn.toString()); logger.error("[formBackingObject] Error in stopWatch: " + e); } return questionnaireCommand; } // public Event bindAndValidate(RequestContext context) throws Exception { // if (logger.isDebugEnabled()) { // logger.debug("Executing Local bindAndValidate"); // } // Object formObject = getFormObject(context); // // logger.debug("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"); // logger.debug("RequestContext after getting formObject"); // logger.debug(context); // debugLoggingOfFormObject(formObject, "Start out FormObject of type QuestionnaireCommand"); // logger.debug("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"); // // DataBinder binder = createBinder(context, formObject); // // // logger.debug("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"); // logger.debug("RequestContext after createBinder formObject"); // logger.debug(context); // debugLoggingOfFormObject(formObject, "FormObject after createBinder"); // logger.debug("Start out binder"); // logger.debug(binder); // // logger.debug("202:"+context.getRequestParameters().get("fields[202].value")); // logger.debug("Got 202"); // // doBind(context, binder); // BindingResult bindingResult = binder.getBindingResult(); // logger.debug("supressed:"+bindingResult.getSuppressedFields().length+",:"); // Object field202 = bindingResult.getFieldValue("fields[202].value"); // logger.debug("error count:"+bindingResult.getErrorCount()+", value:"+field202+",target:"+bindingResult.getTarget()+",type:"+bindingResult.getFieldType("fields[202].value")); // // // logger.debug("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"); // logger.debug("RequestContext after doBind formObject"); // logger.debug(context); // debugLoggingOfFormObject(formObject, "FormObject after doBind"); // // // if (getValidator() != null && validationEnabled(context)) { // if (logger.isDebugEnabled()) { // logger.debug("Executing validation"); // } // doValidate(context, formObject, binder.getErrors()); // } else { // if (logger.isDebugEnabled()) { // if (getValidator() == null) { // logger.debug("No validator is configured, no validation will occur after binding"); // } else { // logger.debug("Validation was disabled for this bindAndValidate request"); // } // } // } //// putFormErrors(context, binder.getErrors()); // return binder.getErrors().hasErrors() ? error() : success(); // } private void debugLoggingOfFormObject(Object formObject, String message) { QuestionnaireCommand questionnaireCommand = (QuestionnaireCommand) formObject; logger.debug(message); Map<String, FieldData> fieldDataMap = questionnaireCommand.getFields(); Set<String> keys = fieldDataMap.keySet(); for (String key : keys) { FieldData fieldData = fieldDataMap.get(key); logger.debug("FieldData Key='" + key + "' code='" + fieldDataMap.get(key).getCode() + "' value=[" + LoggingOfFieldData.fieldDataValueAsString(fieldData) + "]"); } } // @Override // protected void registerPropertyEditors(RequestContext context, PropertyEditorRegistry registry) { // logger.info("Executing custom registerPropertyEditors"); // logger.info("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"); // logger.info("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"); // logger.info("RequestContext=[" + context.toString() + "]"); // logger.info("PropertyEditorRegistry=[" + registry.toString() + "]"); // logger.info("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"); // logger.info("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"); //// super.registerPropertyEditors(context, registry); // GrunnskoleStatisticPropertyEditorRegistrar registrar = new GrunnskoleStatisticPropertyEditorRegistrar(); // registrar.setRequestContext(context); // registrar.registerCustomEditors(registry); // super.setPropertyEditorRegistrar(registrar); // super.registerPropertyEditors(context, registry); // // logger.info("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"); // logger.info("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"); // } // protected void initBinder(RequestContext context, DataBinder binder) { // logger.info("Executing custom initBinder"); // // this.grunnskoleStatisticPropertyEditorRegistrar.registerCustomEditors(binder); //// binder.registerCustomEditor(SchoolHas.class, "fields[203].value", new SchoolHasEditor("203")); //// binder.registerCustomEditor(SchoolHas.class, "fields[202].value", new SchoolHasEditor("202")); //// binder.registerCustomEditor(BigDecimalFieldData.class, new BigDecimalEditor22(currentLocale)); // // super.initBinder(context, binder); // // } //public QuestionnaireFormAction() { // super(); // if (super.getPropertyEditorRegistrar() == null) { // DefaultPropertyEditorRegistrar registrar = new DefaultPropertyEditorRegistrar(); // super.setPropertyEditorRegistrar(registrar); // } // } /* protected void registerPropertyEditors(RequestContext context, PropertyEditorRegistry registry) { logger.info("Executing custom registerPropertyEditors"); // if (logger.isDebugEnabled()) { // logger.info("Executing custom registerPropertyEditors"); // } PropertyEditorRegistrar propertyEditorRegistrar = getPropertyEditorRegistrar(); if (propertyEditorRegistrar == null) { logger.info("propertyEditorRegistrar == null"); propertyEditorRegistrar = new MuseumStatisticPropertyEditorRegistrar(); setPropertyEditorRegistrar(propertyEditorRegistrar); } boolean allowEmpty = true; boolean emptyAsNull = false; ServletExternalContext servletContext = (ServletExternalContext) context.getExternalContext(); HttpServletRequest request = servletContext.getRequest(); SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver(); Locale currentLocale = sessionLocaleResolver.resolveLocale(request); Locale.setDefault(currentLocale); logger.debug("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"); logger.debug("Current locale ==> " + currentLocale.toString()); logger.debug("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"); // register a custom property editor to handle the date input SimpleDateFormat dateFormat = new SimpleDateFormat(EUROPEAN_DATE_PATTERN); // registry.registerCustomEditor(Date.class, new CustomDateEditor(DateUtil.EUROPEAN_DATEFORMAT, allowEmpty)); // BigDecimalEditor bigDecimalEditor = new BigDecimalEditor(currentLocale); DecimalFormat decimalFormat = new DecimalFormat("#########0.00#######"); DecimalFormat integerFormat = new DecimalFormat("#########0"); // DateFormat dateFormat = DateUtil.ISO_DATEFORMAT; // CustomDateEditor dateEditor = new CustomDateEditor(dateFormat, allowEmpty); DateEditor dateEditor = new DateEditor(); CustomNumberEditor doubleEditor = new CustomNumberEditor(Double.class, decimalFormat, allowEmpty); CustomNumberEditor integerEditor = new CustomNumberEditor(Integer.class, integerFormat, allowEmpty); // CustomNumberEditor bigDecimalEditor = new CustomNumberEditor(BigDecimal.class, decimalFormat, allowEmpty); CustomNumberEditor longEditor = new CustomNumberEditor(Long.class, integerFormat, allowEmpty); registry.registerCustomEditor(BigDecimal.class, new BigDecimalEditor22(currentLocale)); // registry.registerCustomEditor(Integer.class, integerEditor); // registry.registerCustomEditor(Double.class, doubleEditor); // registry.registerCustomEditor(Date.class, dateEditor); // registry.registerCustomEditor(DateType.class, dateEditor); // registry.registerCustomEditor(BigDecimal.class, bigDecimalEditor); // registry.registerCustomEditor(Long.class, longEditor); // registry.registerCustomEditor(String.class, new StringTrimmerEditor(emptyAsNull)); super.registerPropertyEditors(context, registry); } */ /* protected void registerPropertyEditors(PropertyEditorRegistry registry) { // register a custom property editor to handle the date input SimpleDateFormat dateFormat = new SimpleDateFormat(BIRTH_DATE_PATTERN); registry.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); } */ private QuestionnaireCommand getCommandFromDb(Long orgUnitId, String mainSchemaName, String schemaVersion) { Assert.assertNotNull("orgUnitId", orgUnitId); Assert.assertNotNull("mainSchemaName", mainSchemaName); Assert.assertNotNull("schemaVersion", schemaVersion); StopWatch stopWatch = new StopWatch(); stopWatch.start("createFormObjectFromDb"); QuestionnaireData questionnaireData = questionnaireService.getOrCreateQuestionnaireData(orgUnitId, mainSchemaName, schemaVersion); QuestionnaireCommand command = new QuestionnaireCommand(questionnaireData, orgUnitId); try { FieldData fieldData = command.getQuestionnaireData().getFieldData("103"); logger.info("getFieldData:" + fieldData + ", value:" + fieldData.getUntypedValue() + ", type:" + fieldData.getUntypedValue().getClass()); } catch (Exception e) { } try { stopWatch.stop(); logger.info("[getCommandFromDb] tok [" + stopWatch.getTotalTimeMillis() + "] ms"); } catch (IllegalStateException e) { // Catch and log error. // logger.error("[formBackingObject] Error in stopWatch for user: " + loggedOn.toString()); logger.error("[formBackingObject] Error in stopWatch: " + e); } return command; } public Event schemaProcessForSchoolLibrary(RequestContext context) throws Exception { if (logger.isDebugEnabled()) { logger.debug("Executing schemaProcessForSchoolLibrary"); } String field405 = context.getRequestParameters().get("fields[405].value"); String field226 = context.getRequestParameters().get("fields[226].value"); if (field405 == null || field226 == null) { if (logger.isDebugEnabled()) { logger.debug("field405==null or field226==null, user has to fill out full schema."); } return new Event(this, "fullSchema"); } if (field405.equals("false") && field226.equals("false")) { if (logger.isDebugEnabled()) { logger.debug("field405 and field226 are both false, user has to fill out short schema."); } return new Event(this, "shortSchema"); } return new Event(this, "fullSchema"); } // public GrunnskoleStatisticPropertyEditorRegistrar getGrunnskoleStatisticPropertyEditorRegistrar() { // return grunnskoleStatisticPropertyEditorRegistrar; // } // public void setGrunnskoleStatisticPropertyEditorRegistrar( // GrunnskoleStatisticPropertyEditorRegistrar grunnskoleStatisticPropertyEditorRegistrar) { // this.grunnskoleStatisticPropertyEditorRegistrar = grunnskoleStatisticPropertyEditorRegistrar; // } // @Override // protected void initBinder(RequestContext context, DataBinder binder) { // // TODO Auto-generated method stub // super.initBinder(context, binder); // this.setPropertyEditorRegistrar(new GrunnskoleStatisticPropertyEditorRegistrar()); // } }