Package org.apache.myfaces.commons.validator

Source Code of org.apache.myfaces.commons.validator.AbstractDateRestrictionValidator

/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file 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.
*/
package org.apache.myfaces.commons.validator;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.ValueHolder;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.DateTimeConverter;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.apache.myfaces.buildtools.maven2.plugin.builder.annotation.JSFProperty;
import org.apache.myfaces.buildtools.maven2.plugin.builder.annotation.JSFValidator;
import org.apache.myfaces.commons.validator.model.DateListProvider;

/**
* Validate that the date entered is within a given restriction.
*
*
*/
@JSFValidator(
   name = "mcv:validateDateRestriction",
   clazz = "org.apache.myfaces.commons.validator.DateRestrictionValidator",
   bodyContent = "empty",
   tagClass = "org.apache.myfaces.commons.validator.ValidateDateRestrictionTag",
   tagHandler = "org.apache.myfaces.commons.validator.ValidateDateRestrictionTagHandler",
   serialuidtag = "6805174635196400967L")
public abstract class AbstractDateRestrictionValidator extends ValidatorBase
{

    public static final String VALIDATOR_ID = "org.apache.myfaces.commons.validator.DateRestriction";

    /**
     * <p>The message identifier of the {@link javax.faces.application.FacesMessage}
     * to be created if the valid days  value check fails.  The message format
     * string for this message may optionally include <code>{0}</code>,
     * <code>{1}</code> and <code>{3}</code> placeholders,
     * which will be replaced by user input, component label and configured
     * days value.</p>
     */
    public static final String DAY_MESSAGE_ID = "org.apache.myfaces.commons.validator.DateRestrictionValidator.DAY";

    /**
     * <p>The message identifier of the {@link javax.faces.application.FacesMessage}
     * to be created if the valid month value check fails.  The message format
     * string for this message may optionally include <code>{0}</code>,
     * <code>{1}</code> and <code>{3}</code> placeholders,
     * which will be replaced by user input, component label and configured
     * month value.</p>
     */
    public static final String MONTH_MESSAGE_ID = "org.apache.myfaces.commons.validator.DateRestrictionValidator.MONTH";

    /**
     * <p>The message identifier of the {@link javax.faces.application.FacesMessage}
     * to be created if the valid weekdays value check fails.  The message format
     * string for this message may optionally include <code>{0}</code>,
     * <code>{1}</code> and <code>{3}</code> placeholders,
     * which will be replaced by user input, component label and configured
     * weekdays value.</p>
     */
    public static final String WEEKDAY_MESSAGE_ID = "org.apache.myfaces.commons.validator.DateRestrictionValidator.WEEKDAY";

    /**
     * Construct a {@link Validator} with no preconfigured limits.
     */
    public AbstractDateRestrictionValidator()
    {
        super();
        _initMaps();
    }

    /**
     * Specify the month which are invalid for your use case.
     * The attribute takes a whitespace delimited list of months.
     * Possible values are jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec.
     *
     */
    @JSFProperty(deferredValueType="java.lang.Object")
    public abstract String[] getInvalidMonths();

    public abstract void setInvalidMonths(String[] invalidMonths);

    /**
     * Specify the weekdays which are invalid for your use case.
     * The attribute takes whitespace delimited list of weekdays.
     * Possible values are sun, mon, tue, wed, thu, fri, sat.
     *
     */
    @JSFProperty(deferredValueType="java.lang.Object")
    public abstract String[] getInvalidDaysOfWeek();

    public abstract void setInvalidDaysOfWeek(String[] invalidDaysOfWeek);

    /**
     * To specifiy a concrete List of Dates, use the invalidDays attribute and wire it
     * to a DateListProvider implementation. This returns a list of dates, which are invalid.
     *
     */
    @JSFProperty
    public abstract DateListProvider getInvalidDays();

    public abstract void setInvalidDays(DateListProvider invalidDays);

    /**
     * @exception IllegalArgumentException if <code>value</code> is not of type
     * {@link java.util.Date}
     */
    public void validate(FacesContext context, UIComponent component,
            Object value) throws ValidatorException
    {
        if ((context == null) || (component == null))
        {
            throw new NullPointerException(("NULL_FACESCONTEXT_OR_UICOMPONENT"));
        }

        if (value != null)
        {
            Calendar calendar = getCalendar();
            calendar.setTime(getDateValue(value));
            Date convertedDate = calendar.getTime();

            String weekday = _dayMap.get(calendar.get(Calendar.DAY_OF_WEEK));
            if (_getInvalidDaysOfWeek().contains(weekday))
            {
                throw new ValidatorException(getWrongWeekDayMessage(context,
                        component, value, weekday));
            }

            String month = _monthMap.get(calendar.get(Calendar.MONTH));
            if (_getInvalidMonths().contains(month))
            {
                throw new ValidatorException(getWrongMonthMessage(context,
                        component, value, month));
            }

            DateListProvider dlp = getInvalidDays();
            List<Date> dates = null;
            if (dlp != null)
            {
                dates = dlp.getDateList(context, calendar, calendar.getTime(),
                        calendar.getTime());
            }

            if (dates != null)
            {
                for (Date date : dates)
                {
                    //range is only one submitted day...
                    if (!date.before(convertedDate)
                            && !date.after(convertedDate))
                    {
                        throw new ValidatorException(getWrongDayMessage(
                                context, component, value, date));
                    }
                }
            }
        }
    }

    private Converter getConverter(FacesContext context, UIComponent component)
    {
        Converter converter = null;
        if (component instanceof ValueHolder)
        {
            converter = ((ValueHolder) component).getConverter();
        }

        if (converter == null)
        {
            // Use the DateTimeConverter's CONVERTER_ID, not Date.class,
            // because there is in fact not usually a converter registered
            // at Date.class
            converter = context.getApplication().createConverter(
                    DateTimeConverter.CONVERTER_ID);
        }

        assert (converter != null);

        return converter;
    }

    protected Calendar getCalendar()
    {
        //TODO: make it better
        return Calendar.getInstance();

    }

    /**
     * Parses the already converted value to a <code>java.util.Date</code>.
     * @param value converted value
     * @return fulltyped <code>java.util.Date</code>
     * @throws IllegalArgumentException
     */
    protected static Date getDateValue(Object value)
            throws IllegalArgumentException
    {
        if (value instanceof Date)
        {
            return ((Date) value);
        }

        throw new IllegalArgumentException("value is not a date type");
    }

    private FacesMessage getWrongWeekDayMessage(FacesContext context,
            UIComponent component, Object value, Object weekday)
    {
        Converter converter = getConverter(context, component);
        Object cWeekday = _getConvertedValue(context, component, converter,
                weekday);
        Object[] params = { cWeekday };
        return getFacesMessage(WEEKDAY_MESSAGE_ID, params);
    }

    private FacesMessage getWrongMonthMessage(FacesContext context,
            UIComponent component, Object value, Object month)
    {
        Converter converter = getConverter(context, component);
        Object cMonth = _getConvertedValue(context, component, converter, month);
        Object[] params = { cMonth };
        return getFacesMessage(MONTH_MESSAGE_ID, params);
    }

    private FacesMessage getWrongDayMessage(FacesContext context,
            UIComponent component, Object value, Object day)
    {
        Converter converter = getConverter(context, component);

        Object cValue = _getConvertedValue(context, component, converter, value);
        Object cDay = _getConvertedValue(context, component, converter, day);

        Object[] params = { cValue, cDay };

        return getFacesMessage(DAY_MESSAGE_ID, params);
    }

    private Object _getConvertedValue(FacesContext context,
            UIComponent component, Converter converter, Object value)
    {
        return converter.getAsString(context, component, value);
    }

    private final Set<String> _getInvalidMonths()
    {
        Set<String> monthSet = new HashSet<String>();
        String[] month = getInvalidMonths();
        if (month != null)
        {

            for (int i = 0; i < month.length; i++)
            {
                monthSet.add(month[i].toLowerCase());
            }
        }

        return monthSet;
    }

    private final Set<String> _getInvalidDaysOfWeek()
    {
        Set<String> daysOfWeekSet = new HashSet<String>();
        String[] daysOfWeek = getInvalidDaysOfWeek();
        if (daysOfWeek != null)
        {

            for (int i = 0; i < daysOfWeek.length; i++)
            {
                daysOfWeekSet.add(daysOfWeek[i].toLowerCase());
            }
        }

        return daysOfWeekSet;
    }

    private void _initMaps()
    {
        _dayMap = new HashMap<Integer, String>();
        _dayMap.put(Calendar.SUNDAY, "sun");
        _dayMap.put(Calendar.MONDAY, "mon");
        _dayMap.put(Calendar.TUESDAY, "tue");
        _dayMap.put(Calendar.WEDNESDAY, "wed");
        _dayMap.put(Calendar.THURSDAY, "thu");
        _dayMap.put(Calendar.FRIDAY, "fri");
        _dayMap.put(Calendar.SATURDAY, "sat");

        _monthMap = new HashMap<Integer, String>();
        _monthMap.put(Calendar.JANUARY, "jan");
        _monthMap.put(Calendar.FEBRUARY, "feb");
        _monthMap.put(Calendar.MARCH, "mar");
        _monthMap.put(Calendar.APRIL, "apr");
        _monthMap.put(Calendar.MAY, "may");
        _monthMap.put(Calendar.JUNE, "jun");
        _monthMap.put(Calendar.JULY, "jul");
        _monthMap.put(Calendar.AUGUST, "aug");
        _monthMap.put(Calendar.SEPTEMBER, "sep");
        _monthMap.put(Calendar.OCTOBER, "oct");
        _monthMap.put(Calendar.NOVEMBER, "nov");
        _monthMap.put(Calendar.DECEMBER, "dec");
    }

    private Map<Integer, String> _dayMap = null;
    private Map<Integer, String> _monthMap = null;
}
TOP

Related Classes of org.apache.myfaces.commons.validator.AbstractDateRestrictionValidator

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.