001/*
002 * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Guillaume Renard
018 */
019package org.nuxeo.ecm.platform.ui.web.component.date;
020
021import java.util.Calendar;
022import java.util.Date;
023
024import javax.faces.component.StateHolder;
025import javax.faces.component.UIComponent;
026import javax.faces.context.FacesContext;
027import javax.faces.validator.Validator;
028import javax.faces.validator.ValidatorException;
029
030import com.sun.faces.util.MessageFactory;
031
032/**
033 * A date validator to invalidate dates of which year has five digits.
034 *
035 * @since 5.7.2
036 */
037public class DateTimeValidator implements Validator, StateHolder {
038
039    public static final String VALIDATOR_ID = "NxDateValidator";
040
041    public static final String OUT_OF_RANGE_MESSAGE_ID = "error.dateYear.invalidValue";
042
043    private boolean transientValue = false;
044
045    @Override
046    public Object saveState(FacesContext context) {
047        return null;
048    }
049
050    @Override
051    public void restoreState(FacesContext context, Object state) {
052    }
053
054    @Override
055    public boolean isTransient() {
056        return transientValue;
057    }
058
059    @Override
060    public void setTransient(boolean newTransientValue) {
061        transientValue = newTransientValue;
062    }
063
064    @Override
065    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
066        if ((context == null) || (component == null)) {
067            throw new NullPointerException();
068        }
069        if (value != null) {
070            Date date = (Date) value;
071            Calendar c = Calendar.getInstance();
072            c.setTime(date);
073            final int year = c.get(Calendar.YEAR);
074            if (year > 9999) {
075                throw new ValidatorException(MessageFactory.getMessage(context, OUT_OF_RANGE_MESSAGE_ID, year));
076            }
077        }
078    }
079}