THIS IS A TEST INSTANCE. ALL YOUR CHANGES WILL BE LOST!!!!
...
Code Block | ||||
---|---|---|---|---|
| ||||
package org.apache.openjpa.example.gallery.constraint; import java.util.Arrays; import java.util.List; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.apache.openjpa.example.gallery.model.Image; import org.apache.openjpa.example.gallery.model.ImageType; /** * Simple check that an Image is consistent in type, name, and format. */ public class ImageValidator implements ConstraintValidator<ImageConstraint, Image> { private List<ImageType> allowedTypes = null; /** * Configure the constraint validator based on the image * types it should support. * @param constraint the constraint definition */ public void initialize(ImageConstraint constraint) { allowedTypes = Arrays.asList(constraint.value()); } /** * Validate a specified value. */ public boolean isValid(Image value, ConstraintValidatorContext context) { if (value == null) { return true; } // All these fields will be pre-validated with @NotNull constraints // so they are safe to use without null checks. byte[] data = value.getData(); String fileName = value.getFileName(); ImageType type = value.getType(); // Verify the GIF type is correct5correct, has the correct extension and // the data header is either GIF87 or GIF89 if (allowedTypes.contains(ImageType.GIF) && type == ImageType.GIF && fileName.endsWith(".gif")) { if (data != null && data.length >= 6) { String gifHeader = new String(data, 0, 6); if (gifHeader.equalsIgnoreCase("GIF87a") || gifHeader.equalsIgnoreCase("GIF89a")) { return true; } } } // Verify the JPEG type is correct, has the correct extension and // the data begins with SOI & ends with EOI markers if (allowedTypes.contains(ImageType.JPEG) && value.getType() == ImageType.JPEG && (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg"))) { if (data.length >= 4 && data[0] == 0xff && data[1] == 0xd8 && data[data.length - 2] == 0xff && data[data.length - 1] == 0xd9) { return true; } } // Unknown file format return false; } } |
...