001 /******************************************************************************* 002 * Portions created by Sebastian Thomschke are copyright (c) 2005-2011 Sebastian 003 * Thomschke. 004 * 005 * All Rights Reserved. This program and the accompanying materials 006 * are made available under the terms of the Eclipse Public License v1.0 007 * which accompanies this distribution, and is available at 008 * http://www.eclipse.org/legal/epl-v10.html 009 * 010 * Contributors: 011 * Sebastian Thomschke - initial implementation. 012 *******************************************************************************/ 013 package net.sf.oval.constraint; 014 015 import java.text.DateFormat; 016 import java.text.ParseException; 017 import java.util.Calendar; 018 import java.util.Date; 019 020 import net.sf.oval.ConstraintTarget; 021 import net.sf.oval.Validator; 022 import net.sf.oval.configuration.annotation.AbstractAnnotationCheck; 023 import net.sf.oval.context.OValContext; 024 025 /** 026 * @author Sebastian Thomschke 027 */ 028 public class FutureCheck extends AbstractAnnotationCheck<Future> 029 { 030 private static final long serialVersionUID = 1L; 031 032 private long tolerance; 033 034 @Override 035 public void configure(final Future constraintAnnotation) 036 { 037 super.configure(constraintAnnotation); 038 setTolerance(constraintAnnotation.tolerance()); 039 } 040 041 /** 042 * {@inheritDoc} 043 */ 044 @Override 045 protected ConstraintTarget[] getAppliesToDefault() 046 { 047 return new ConstraintTarget[]{ConstraintTarget.VALUES}; 048 } 049 050 /** 051 * @return the tolerance 052 */ 053 public long getTolerance() 054 { 055 return tolerance; 056 } 057 058 /** 059 * {@inheritDoc} 060 */ 061 public boolean isSatisfied(final Object validatedObject, final Object valueToValidate, final OValContext context, 062 final Validator validator) 063 { 064 if (valueToValidate == null) return true; 065 066 final long now = System.currentTimeMillis() - tolerance; 067 068 // check if the value is a Date 069 if (valueToValidate instanceof Date) // return ((Date) value).after(new Date()); 070 return ((Date) valueToValidate).getTime() > now; 071 072 // check if the value is a Calendar 073 if (valueToValidate instanceof Calendar) return ((Calendar) valueToValidate).getTime().getTime() > now; 074 075 // see if we can extract a date based on the object's String representation 076 final String stringValue = valueToValidate.toString(); 077 try 078 { 079 // return DateFormat.getDateTimeInstance().parse(stringValue).after(new Date()); 080 return DateFormat.getDateTimeInstance().parse(stringValue).getTime() > now; 081 } 082 catch (final ParseException ex) 083 { 084 return false; 085 } 086 } 087 088 /** 089 * @param tolerance the tolerance to set 090 */ 091 public void setTolerance(final long tolerance) 092 { 093 this.tolerance = tolerance; 094 } 095 }