Tagged: Bean Validation

a wrong hint from netbeans


https://netbeans.org/bugzilla/show_bug.cgi?id=262707

public class User {

    public void setUsername(final String username) {
        if (this.username != null) {
            throw new IllegalArgumentException(
                    "already has a username");
        }
        this.username = username;
    }

    @NotNull
    private String username;
}

NetBeans shows a hint for the line 4.

Unnecessary test for null – the expression is never null

That’s simply wrong. NetBeans see the @NotNull and he (or she) thinks the field will never null at any time.

args4j with BeanValidation


references

args4j

Annotate your @Options with some annotations defined in javax.validation.

@Option(name = "-buffer-capacity",
        usage = "each buffer's capacity in bytes")
@Min(1024)
private int bufferCapacity = 65536;

@Option(name = "-buffer-count", required = true,
        usage = "number of buffers to allocate")
@Min(1)
@Max(1024)
private int bufferCount;

BeanValidation

And then validate by yourself.

final Opts opts;
final ValidatorFactory factory
    = Validation.buildDefaultValidatorFactory();
final Validator validator = factory.getValidator();
final Set<ConstraintViolation<Opts>> violations
    = validator.validate(opts);
if (violations.stream().map(v -> {
    System.err.println("violation: " + v);
    return v;
}).count() > 0L) {
    return;
}

Validating email addresses with Bean Validation


References

/**
 * The regular expression for email addresses.
 */
public static final String EMAIL_ADDRESS_REGEXP =
    "^([_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*)"
    + "@([A-Za-z0-9]+(\\.[A-Za-z0-9]+)*)"
    + "(\\.[A-Za-z]{2,})$";

/**
 * email address.
 */
@Pattern(regexp = EMAIL_ADDRESS_REGEXP)
@Size(min = 6) // a@a.us
private String emailAddress;