001/* 002 * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl-2.1.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * Guillaume Renard 016 */ 017package org.nuxeo.ecm.platform.ui.web.component.date; 018 019import java.util.Calendar; 020import java.util.Date; 021 022import javax.faces.component.StateHolder; 023import javax.faces.component.UIComponent; 024import javax.faces.context.FacesContext; 025import javax.faces.validator.Validator; 026import javax.faces.validator.ValidatorException; 027 028import com.sun.faces.util.MessageFactory; 029 030/** 031 * A date validator to invalidate dates of which year has five digits. 032 * 033 * @since 5.7.2 034 */ 035public class DateTimeValidator implements Validator, StateHolder { 036 037 public static final String VALIDATOR_ID = "NxDateValidator"; 038 039 public static final String OUT_OF_RANGE_MESSAGE_ID = "error.dateYear.invalidValue"; 040 041 private boolean transientValue = false; 042 043 @Override 044 public Object saveState(FacesContext context) { 045 return null; 046 } 047 048 @Override 049 public void restoreState(FacesContext context, Object state) { 050 } 051 052 @Override 053 public boolean isTransient() { 054 return transientValue; 055 } 056 057 @Override 058 public void setTransient(boolean newTransientValue) { 059 transientValue = newTransientValue; 060 } 061 062 @Override 063 public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { 064 if ((context == null) || (component == null)) { 065 throw new NullPointerException(); 066 } 067 if (value != null) { 068 Date date = (Date) value; 069 Calendar c = Calendar.getInstance(); 070 c.setTime(date); 071 final int year = c.get(Calendar.YEAR); 072 if (year > 9999) { 073 throw new ValidatorException(MessageFactory.getMessage(context, OUT_OF_RANGE_MESSAGE_ID, year)); 074 } 075 } 076 } 077}