no.abmu.questionnaire.webflow.MuseumStatisticFormAction.java Source code

Java tutorial

Introduction

Here is the source code for no.abmu.questionnaire.webflow.MuseumStatisticFormAction.java

Source

/*$Id: MuseumStatisticFormAction.java 15562 2010-04-26 08:54:10Z 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.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.FireOrFireStartFieldData;
import no.abmu.questionnaire.domain.data.MuseumHovedOmraadeFieldData;
import no.abmu.questionnaire.domain.data.MuseumOrganizationFormFieldData;
import no.abmu.questionnaire.domain.data.TheftOrTheftAttemptFieldData;
import no.abmu.questionnaire.domain.data.YesNoPartlyFieldData;
import no.abmu.questionnaire.domain.data.SchoolHasFieldData;

import no.abmu.questionnaire.domain.util.LoggingOfFieldData;
import no.abmu.questionnaire.propertyeditors.MuseumStatisticPropertyEditorRegistrar;
import no.abmu.questionnaire.web.QuestionnaireCommand;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.support.DefaultPropertyEditorRegistrar;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.core.style.StylerUtils;
import org.springframework.validation.DataBinder;
import org.springframework.validation.Errors;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.springframework.webflow.core.collection.MutableAttributeMap;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

/**
 * MuseumStatisticFormAction.
 *  
 * @author Jens Vindvad, Jens.Vindvad@abm-utvikling.no
 * @author $Author: jens $
 * @version $Rev: 15562 $
 * $Date: 2010-04-26 10:54:10 +0200 (Mon, 26 Apr 2010) $
 * copyright ABM-Utvikling
 * @since 2006-
 */
public class MuseumStatisticFormAction extends QuestionnaireFormAction {

    private static final Log logger = (Log) LogFactory.getLog(MuseumStatisticFormAction.class);

    public MuseumStatisticFormAction() {
        super();
        logger.info("Init MuseumStatisticFormAction");
        if (super.getPropertyEditorRegistrar() == null) {
            DefaultPropertyEditorRegistrar registrar = new DefaultPropertyEditorRegistrar();
            super.setPropertyEditorRegistrar(registrar);
        }
    }

    public Event setupReferenceData(RequestContext context) throws Exception {

        logger.info("Executing custom setupReferenceData");

        ServletExternalContext servletContext = (ServletExternalContext) context.getExternalContext();
        HttpServletRequest request = (HttpServletRequest) servletContext.getNativeRequest();

        SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
        Locale currentLocale = sessionLocaleResolver.resolveLocale(request);

        //        PlaceHolderFieldDataList museumHovedomraader = new PlaceHolderFieldDataList(
        //                MuseumHovedOmraadeFieldData.getMuseumHovedOmraadeReferenceList(currentLocale));

        MutableAttributeMap requestScope = context.getRequestScope();
        requestScope.put("museumHovedomraader",
                MuseumHovedOmraadeFieldData.getMuseumHovedOmraadeReferenceList(currentLocale));
        requestScope.put("museumOrganizationForms",
                MuseumOrganizationFormFieldData.getMuseumOrganizationFormReferenceList(currentLocale));
        requestScope.put("yesNoPartly", YesNoPartlyFieldData.getYesNoPartlyReferenceList(currentLocale));
        requestScope.put("fireOrFireStart",
                FireOrFireStartFieldData.getFireOrFireStartReferenceList(currentLocale));
        requestScope.put("theftOrTheftAttempt",
                TheftOrTheftAttemptFieldData.getTheftOrTheftAttemptReferenceList(currentLocale));

        return success();
    }

    @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);
        MuseumStatisticPropertyEditorRegistrar registrar = new MuseumStatisticPropertyEditorRegistrar();
        registrar.setRequestContext(context);
        registrar.registerCustomEditors(registry);
        super.registerPropertyEditors(context, registry);

        logger.info("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ");
        logger.info("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ");
    }

    /**
     * Bind incoming request parameters to allowed fields of the form object and then validate the bound form object if
     * a validator is configured.
     * <p>
     * NOTE: This action method is not designed to be overidden and might become <code>final</code> in a future
     * version of Spring Web Flow. If you need to execute custom bind and validate logic have your flow call this method
     * along with your own custom methods as part of a single action chain. Alternatively, override the
     * {@link #doBind(RequestContext, DataBinder)} or {@link #doValidate(RequestContext, Object, Errors)} hooks.
     * @param context the action execution context, for accessing and setting data in "flow scope" or "request scope"
     * @return "success" when binding and validation is successful, "error" if there were binding and/or validation
     * errors
     * @throws Exception an <b>unrecoverable</b> exception occured, either checked or unchecked
     */
    public Event bindAndValidate(RequestContext context) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("Executing Local bindAndValidate");
        }
        logger.debug("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB");
        logger.debug("RequestContext before getting formObject");
        logger.debug(context);
        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);

        doBind(context, binder);

        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();
    }

    /**
     * Put given errors instance in the configured scope of given context.
     */
    private void putFormErrors(RequestContext context, Errors errors) {
        if (logger.isDebugEnabled()) {
            logger.debug("Exectute Local putFormErrors ==> Putting form errors instance in scope "
                    + getFormErrorsScope());
        }
        getFormObjectAccessor(context).putFormErrors(errors, getFormErrorsScope());
    }

    /**
     * Bind allowed parameters in the external context request parameter map to the form object using given binder.
     * @param context the action execution context, for accessing and setting data in "flow scope" or "request scope"
     * @param binder the data binder to use
     * @throws Exception when an unrecoverable exception occurs
     */
    protected void doBind(RequestContext context, DataBinder binder) throws Exception {
        logger.debug("Execute local doBind");
        if (logger.isDebugEnabled()) {
            logger.debug("Binding allowed request parameters in "
                    + StylerUtils.style(context.getExternalContext().getRequestParameterMap())
                    + " to form object with name '" + binder.getObjectName() + "', pre-bind formObject toString = "
                    + binder.getTarget());
            if (binder.getAllowedFields() != null && binder.getAllowedFields().length > 0) {
                logger.debug("(Allowed fields are " + StylerUtils.style(binder.getAllowedFields()) + ")");
            } else {
                logger.debug("(Any field is allowed)");
            }
        }
        logger.debug("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBb");
        logger.debug("BBBBBBBBB Value of binder befor binding BBBBBBBBBBBBBBBBBBb");
        logger.debug("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBb");
        logger.debug(binder);
        binder.bind(new MutablePropertyValues(context.getRequestParameters().asMap()));
        logger.debug("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBb");
        logger.debug("BBBBBBBBB Value of binder after binding BBBBBBBBBBBBBBBBBBb");
        logger.debug("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBb");
        logger.debug(binder);

        if (logger.isDebugEnabled()) {
            logger.debug("Binding completed for form object with name '" + binder.getObjectName()
                    + "', post-bind formObject toString = " + binder.getTarget());
            logger.debug("There are [" + binder.getErrors().getErrorCount() + "] errors, details: "
                    + binder.getErrors().getAllErrors());
        }
    }

    /**
     * Create a new binder instance for the given form object and request context. Can be overridden to plug in custom
     * DataBinder subclasses.
     * <p>
     * Default implementation creates a standard WebDataBinder, and invokes
     * {@link #initBinder(RequestContext, DataBinder)} and {@link #registerPropertyEditors(PropertyEditorRegistry)}.
     * @param context the action execution context, for accessing and setting data in "flow scope" or "request scope"
     * @param formObject the form object to bind onto
     * @return the new binder instance
     * @throws Exception when an unrecoverable exception occurs
     * @see WebDataBinder
     * @see #initBinder(RequestContext, DataBinder)
     * @see #setMessageCodesResolver(MessageCodesResolver)
     */
    /*    
        protected DataBinder createBinder(RequestContext context, Object formObject) throws Exception {
    DataBinder binder = new CustomDataBinder(formObject, getFormObjectName());
    if (getMessageCodesResolver() != null) {
        binder.setMessageCodesResolver(getMessageCodesResolver());
    }
    initBinder(context, binder);
    registerPropertyEditors(context, binder);
    return binder;
        }
    */

    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) + "]");
        }

    }
}