001    
002    /*
003     * Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
004     *
005     * $Id: HostOrIP.java 2 2011-02-05 21:51:43Z archie.cobbs $
006     */
007    
008    package org.dellroad.stuff.validation;
009    
010    import java.lang.annotation.Documented;
011    import java.lang.annotation.ElementType;
012    import java.lang.annotation.Retention;
013    import java.lang.annotation.RetentionPolicy;
014    import java.lang.annotation.Target;
015    
016    import javax.validation.Constraint;
017    import javax.validation.Payload;
018    import javax.validation.ReportAsSingleViolation;
019    import javax.validation.constraints.Pattern;
020    
021    /**
022     * Validation constraint requiring a {@link String} to be either a valid fully-qualified DNS hostname
023     * or an IPv4 address.
024     */
025    @Documented
026    @Constraint(validatedBy = {})
027    @Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
028    @Retention(RetentionPolicy.RUNTIME)
029    @Pattern(regexp =
030        "^((([\\p{Alnum}]([-\\p{Alnum}]*[\\p{Alnum}])?)\\.)+([\\p{Alpha}]([-\\p{Alnum}]*[\\p{Alnum}])?))"
031      + "|("
032        + "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])" + "\\."
033        + "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])" + "\\."
034        + "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])" + "\\."
035        + "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"
036      + ")$")
037    @ReportAsSingleViolation
038    public @interface HostOrIP {
039    
040        String message() default "Not a valid hostname or IPv4 address";
041    
042        Class<?>[] groups() default {};
043    
044        Class<? extends Payload>[] payload() default {};
045    }
046