Skip to content

Instantly share code, notes, and snippets.

@marcospereira
Created November 3, 2011 09:22
Show Gist options
  • Save marcospereira/1336117 to your computer and use it in GitHub Desktop.
Save marcospereira/1336117 to your computer and use it in GitHub Desktop.
Unique validation for Play!Framework
package utils.validation;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import net.sf.oval.configuration.annotation.Constraint;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.PARAMETER })
@Constraint(checkWith = UniqueCheck.class)
public @interface Unique {
String message() default UniqueCheck.message;
}
package utils.validation;
import java.lang.reflect.Field;
import play.db.jpa.JPQL;
import play.db.jpa.Model;
import net.sf.oval.Validator;
import net.sf.oval.context.OValContext;
import net.sf.oval.context.FieldContext;
import net.sf.oval.exception.OValException;
import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
public class UniqueCheck extends AbstractAnnotationCheck<Unique> {
final static String message = "validation.unique";
@Override
public boolean isSatisfied(Object validatedObject, Object value,
OValContext context, Validator validator) throws OValException {
if (value == null) {
return true;
}
Model validatedModel = (Model) validatedObject;
Field field = field(context);
String fieldName = field.getName();
Object fieldValue = fieldValue(field, validatedObject);
Object[] params = { fieldValue };
Model model = JPQL.instance.find(validatedModel.getClass().getName(), fieldName + " = ?", params).first();
if (model == null) {
return true;
}
if (model.id.equals(validatedModel.id)) { // same object
return true;
}
return false;
}
private Object fieldValue(Field field, Object validatedObject) {
try {
return field.get(validatedObject);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private Field field(OValContext context) {
return ((FieldContext) context).getField();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment