Custom Validator for Hibernate only runs on persist
spersch Feb 16, 2009 7:13 PMHi together,
first I want to introduce myself. I am Steffen Persch from Germany, I'm 22years old and I have been java coder for now 2,5 years and seam coder for 1year.
I was searching for a solution for my problem but I did not find anyone. I have written a custom Validator for Hibernate (code below) and it works, but only when I called my entityManager with a persist. What have I to do now that it will work with <s:validateAll> ?
Sry for my non perfect English, I hope you understand me.
Here my classes:
package de.dssc.validator; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; import org.hibernate.validator.ValidatorClass; @ValidatorClass(DSSCImageValidator.class) @Target({FIELD, METHOD}) @Retention(RUNTIME) @Documented public @interface ImageValidator { /** @return error message key */ String message() default "{validator.imageValidator}"; }
package de.dssc.validator; import java.util.*; import org.hibernate.validator.*; public class DSSCImageValidator implements Validator<ImageValidator> { private static final Set<byte[]> VALID_HEX_BYTES = new HashSet<byte[]>(); static { byte[] jpeg = {(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0}; VALID_HEX_BYTES.add(jpeg); byte[] jpegExif = {(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE1}; VALID_HEX_BYTES.add(jpegExif); byte[] jpegQM = {(byte) 0x4A, (byte) 0x46, (byte) 0x49, (byte) 0x46}; VALID_HEX_BYTES.add(jpegQM); } public boolean isAllowedType(byte[] firstBytes) { for (byte[] byteArr : VALID_HEX_BYTES) { if (Arrays.equals(byteArr, firstBytes)) { return true; } } return false; } public void initialize(ImageValidator arg0) { // TODO Auto-generated method stub } public boolean isValid(Object obj) { System.out.println("DSSC IMAGE VALIDATOR: Validator called!"); final byte[] imageData = (byte[]) obj; final byte[] firstBytes = Arrays.copyOfRange(imageData, 0, 4); if(!isAllowedType(firstBytes)) { return false; } return true; } }
And my field in the entity:
@Lob @Basic(fetch=FetchType.LAZY) @Column(columnDefinition = "MEDIUMBLOB") @ImageValidator(message = "pic error message") private byte[] picture;
Best regards
Steffen