001package media.validation;
002
003import javax.validation.ConstraintValidator;
004import javax.validation.ConstraintValidatorContext;
005import java.io.IOException;
006import java.io.InputStream;
007import java.net.URLConnection;
008
009public class ImageValidator implements ConstraintValidator<Image, InputStream> {
010
011    @Override
012    public void initialize(Image constraintAnnotation) {
013
014    }
015
016    @Override
017    public boolean isValid(InputStream value, ConstraintValidatorContext context) {
018        String mime;
019
020        if (value == null) return true;
021        try {
022            mime = URLConnection.guessContentTypeFromStream(value);
023        } catch (IOException e) {
024            throw new RuntimeException(e);
025        }
026
027        return mime != null && mime.startsWith("image/");
028    }
029}