ImageConstraint extends Constraint<File> { @Override @NonNull public Set<Violation> validate() throws UnsupportedException { final Set<Violation> violations = new HashSet<>(); if (0 == minWidth && 0 == minHeight && Integer.MAX_VALUE == maxWidth && Integer.MAX_VALUE == maxHeight) { return violations; } else { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(object.getPath(), options); final int width = options.outWidth; final int height = options.outHeight; if ((0 != minWidth && width <= minWidth) || (0 != minHeight && height <= minHeight)) { violations.add(new Violation(propertyName, object, String.format(minMessage, minWidth, minHeight), ERROR_CODE_SIZE_TOO_SMALL)); } else if ((0 != maxWidth && width >= maxWidth) || (0 != maxHeight && height >= maxHeight)) { violations.add(new Violation(propertyName, object, String.format(maxMessage, maxWidth, maxHeight), ERROR_CODE_SIZE_TOO_BIG)); } } return violations; } ImageConstraint(@NonNull File object, @NonNull String propertyName); @Override @NonNull Set<Violation> validate(); void setMinWidth(int minWidth); void setMinHeight(int minHeight); void setMaxWidth(int maxWidth); void setMaxHeight(int maxHeight); void setMinMessage(String minMessage); void setMaxMessage(String maxMessage); static final String ERROR_CODE_SIZE_TOO_SMALL; static final String ERROR_CODE_SIZE_TOO_BIG; }
@Test public void validateIsValid() throws Exception { assertEmpty("Is valid", getImageConstraint(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE).validate()); }
@Test public void validateWithMinWidthConstraint() throws Exception { assertNotEmpty("Is invalid", getImageConstraint(400, 0, Integer.MAX_VALUE, Integer.MAX_VALUE).validate()); }
@Test public void validateWithMaxWidthConstraint() throws Exception { assertNotEmpty("Is invalid", getImageConstraint(0, 0, 10, Integer.MAX_VALUE).validate()); }
@Test public void validateWithMinHeightConstraint() throws Exception { assertNotEmpty("Is invalid", getImageConstraint(0, 300, Integer.MAX_VALUE, Integer.MAX_VALUE).validate()); }
@Test public void validateWithMaxHeightConstraint() throws Exception { assertNotEmpty("Is invalid", getImageConstraint(0, 0, Integer.MAX_VALUE, 10).validate()); }