Java Examples for javax.validation.constraints.Pattern

The following java examples will help you to understand the usage of javax.validation.constraints.Pattern. These source code samples are taken from different open source projects.

Example 1
Project: capedwarf-green-master  File: PatternConstraintValidator.java View source code
protected Pattern createPattern(javax.validation.constraints.Pattern parameters) {
    javax.validation.constraints.Pattern.Flag flags[] = parameters.flags();
    int intFlag = 0;
    for (javax.validation.constraints.Pattern.Flag flag : flags) {
        intFlag = intFlag | flag.getValue();
    }
    try {
        return java.util.regex.Pattern.compile(parameters.regexp(), intFlag);
    } catch (PatternSyntaxException e) {
        throw new IllegalArgumentException("Invalid regular expression.", e);
    }
}
Example 2
Project: hibernate-validator-master  File: URLValidatorTest.java View source code
private void assertDefaultURLConstraintValidatorOverridden(Configuration config, DelegatingConstraintValidatorFactory constraintValidatorFactory) {
    Validator validator = config.buildValidatorFactory().getValidator();
    Set<ConstraintViolation<Foo>> constraintViolations = validator.validate(new Foo());
    assertNumberOfViolations(constraintViolations, 0);
    assertEquals(constraintValidatorFactory.requestedConstraintValidators.size(), // @URL is a composing constraint, a @Pattern validator impl will also be requested
    2, "Wrong number of requested validator instances");
    assertTrue(constraintValidatorFactory.requestedConstraintValidators.contains(RegexpURLValidator.class), "The wrong validator type has been requested.");
}
Example 3
Project: google-web-toolkit-svnmirror-master  File: ApiCompatibilityChecker.java View source code
/**
   * This is a hack to make the ApiChecker able to find the javax.validation
   * sources, which we include through an external jar file.
   */
private Set<Resource> getJavaxValidationCompilationUnits(TreeLogger logger) throws UnableToCompleteException, NotFoundException, IOException {
    Set<Resource> resources = new HashSet<Resource>();
    if (extraSourceJars != null) {
        Resources extra = new JarFileResources(extraSourceJars, Collections.singleton(""), new HashSet<String>(Arrays.asList("javax/validation/Configuration.java", "javax/validation/MessageInterpolator.java", "javax/validation/Validation.java", "javax/validation/ValidatorContext.java", "javax/validation/ValidatorFactory.java", "javax/validation/ValidationProviderResolver.java", "javax/validation/bootstrap/GenericBootstrap.java", "javax/validation/bootstrap/ProviderSpecificBootstrap.java", "javax/validation/constraints/Pattern.java", "javax/validation/spi/BootstrapState.java", "javax/validation/spi/ConfigurationState.java", "javax/validation/spi/ValidationProvider.java")), logger);
        Set<Resource> loaded = extra.getResources();
        System.out.println("Found " + loaded.size() + " new resources");
        resources.addAll(loaded);
    }
    return resources;
}
Example 4
Project: gwt-bean-validators-master  File: PatternValidator.java View source code
@Override
public void initialize(final Pattern parameters) {
    final Pattern.Flag[] flags = parameters.flags();
    final StringBuilder flagString = new StringBuilder();
    for (final Pattern.Flag flag : flags) {
        flagString.append(this.toString(flag));
    }
    try {
        this.pattern = RegExp.compile(parameters.regexp(), flagString.toString());
    } catch (final RuntimeException e) {
        throw LOG.getInvalidRegularExpressionException(e);
    }
    this.escapedRegexp = InterpolationHelper.escapeMessageParameter(parameters.regexp());
}
Example 5
Project: gwt-master  File: ApiCompatibilityChecker.java View source code
/**
   * This is a hack to make the ApiChecker able to find the javax.validation
   * sources, which we include through an external jar file.
   */
private Set<Resource> getJavaxValidationCompilationUnits(TreeLogger logger) throws UnableToCompleteException, NotFoundException, IOException {
    Set<Resource> resources = new HashSet<Resource>();
    if (extraSourceJars != null) {
        Resources extra = new JarFileResources(extraSourceJars, Collections.singleton(""), new HashSet<String>(Arrays.asList("javax/validation/Configuration.java", "javax/validation/MessageInterpolator.java", "javax/validation/Validation.java", "javax/validation/ValidatorContext.java", "javax/validation/ValidatorFactory.java", "javax/validation/ValidationProviderResolver.java", "javax/validation/bootstrap/GenericBootstrap.java", "javax/validation/bootstrap/ProviderSpecificBootstrap.java", "javax/validation/constraints/Pattern.java", "javax/validation/spi/BootstrapState.java", "javax/validation/spi/ConfigurationState.java", "javax/validation/spi/ValidationProvider.java")), logger);
        Set<Resource> loaded = extra.getResources();
        System.out.println("Found " + loaded.size() + " new resources");
        resources.addAll(loaded);
    }
    return resources;
}
Example 6
Project: gwt-sandbox-master  File: ApiCompatibilityChecker.java View source code
/**
   * This is a hack to make the ApiChecker able to find the javax.validation
   * sources, which we include through an external jar file.
   */
private Set<Resource> getJavaxValidationCompilationUnits(TreeLogger logger) throws UnableToCompleteException, NotFoundException, IOException {
    Set<Resource> resources = new HashSet<Resource>();
    if (extraSourceJars != null) {
        Resources extra = new JarFileResources(extraSourceJars, Collections.singleton(""), new HashSet<String>(Arrays.asList("javax/validation/Configuration.java", "javax/validation/MessageInterpolator.java", "javax/validation/Validation.java", "javax/validation/ValidatorContext.java", "javax/validation/ValidatorFactory.java", "javax/validation/ValidationProviderResolver.java", "javax/validation/bootstrap/GenericBootstrap.java", "javax/validation/bootstrap/ProviderSpecificBootstrap.java", "javax/validation/constraints/Pattern.java", "javax/validation/spi/BootstrapState.java", "javax/validation/spi/ConfigurationState.java", "javax/validation/spi/ValidationProvider.java")), logger);
        Set<Resource> loaded = extra.getResources();
        System.out.println("Found " + loaded.size() + " new resources");
        resources.addAll(loaded);
    }
    return resources;
}
Example 7
Project: gwt.svn-master  File: ApiCompatibilityChecker.java View source code
/**
   * This is a hack to make the ApiChecker able to find the javax.validation
   * sources, which we include through an external jar file.
   */
private Set<Resource> getJavaxValidationCompilationUnits(TreeLogger logger) throws UnableToCompleteException, NotFoundException, IOException {
    Set<Resource> resources = new HashSet<Resource>();
    if (extraSourceJars != null) {
        Resources extra = new JarFileResources(extraSourceJars, Collections.singleton(""), new HashSet<String>(Arrays.asList("javax/validation/Configuration.java", "javax/validation/MessageInterpolator.java", "javax/validation/Validation.java", "javax/validation/ValidatorContext.java", "javax/validation/ValidatorFactory.java", "javax/validation/ValidationProviderResolver.java", "javax/validation/bootstrap/GenericBootstrap.java", "javax/validation/bootstrap/ProviderSpecificBootstrap.java", "javax/validation/constraints/Pattern.java", "javax/validation/spi/BootstrapState.java", "javax/validation/spi/ConfigurationState.java", "javax/validation/spi/ValidationProvider.java")), logger);
        Set<Resource> loaded = extra.getResources();
        System.out.println("Found " + loaded.size() + " new resources");
        resources.addAll(loaded);
    }
    return resources;
}
Example 8
Project: scalagwt-gwt-master  File: ApiCompatibilityChecker.java View source code
/**
   * This is a hack to make the ApiChecker able to find the javax.validation
   * sources, which we include through an external jar file.
   */
private Set<Resource> getJavaxValidationCompilationUnits(TreeLogger logger) throws UnableToCompleteException, NotFoundException, IOException {
    Set<Resource> resources = new HashSet<Resource>();
    if (extraSourceJars != null) {
        Resources extra = new JarFileResources(extraSourceJars, Collections.singleton(""), new HashSet<String>(Arrays.asList("javax/validation/Configuration.java", "javax/validation/MessageInterpolator.java", "javax/validation/Validation.java", "javax/validation/ValidatorContext.java", "javax/validation/ValidatorFactory.java", "javax/validation/ValidationProviderResolver.java", "javax/validation/bootstrap/GenericBootstrap.java", "javax/validation/bootstrap/ProviderSpecificBootstrap.java", "javax/validation/constraints/Pattern.java", "javax/validation/spi/BootstrapState.java", "javax/validation/spi/ConfigurationState.java", "javax/validation/spi/ValidationProvider.java")), logger);
        Set<Resource> loaded = extra.getResources();
        System.out.println("Found " + loaded.size() + " new resources");
        resources.addAll(loaded);
    }
    return resources;
}
Example 9
Project: formio-master  File: RegexValidatorTest.java View source code
@Test
public void testValidate() {
    String myEmailPattern = "[a-z]+\\.[a-z]+@[a-z]+\\.[a-z]+";
    RegexValidator validator = RegexValidator.getInstance(myEmailPattern, Pattern.Flag.CASE_INSENSITIVE);
    assertValid(validator.validate(value("john.SMITH@email.cz")));
    assertValid(validator.validate(value((String) null)));
    String invalidValue = "john@email";
    InterpolatedMessage msg = assertInvalid(validator.validate(value(invalidValue)));
    assertEquals(value((String) null).getElementName(), msg.getElementName());
    assertEquals(Severity.ERROR, msg.getSeverity());
    assertEquals(3, msg.getMessageParameters().size());
    assertEquals(invalidValue, msg.getMessageParameters().get(AbstractValidator.CURRENT_VALUE_ARG));
    assertEquals(myEmailPattern, msg.getMessageParameters().get(RegexValidator.REGEXP_ARG));
    assertEquals(Pattern.Flag.CASE_INSENSITIVE, ((Pattern.Flag[]) msg.getMessageParameters().get(RegexValidator.FLAGS_ARG))[0]);
    assertEquals("{" + Pattern.class.getName() + ".message}", msg.getMessageKey());
    assertEquals(myEmailPattern, validator.getRegexp());
    assertEquals(1, validator.getPatternFlags().length);
    assertEquals(Pattern.Flag.CASE_INSENSITIVE, validator.getPatternFlags()[0]);
}
Example 10
Project: ORCID-Source-master  File: TextPatternValidator.java View source code
@Override
public void initialize(TextPattern parameters) {
    Pattern.Flag flags[] = parameters.flags();
    int intFlag = 0;
    for (Pattern.Flag flag : flags) {
        intFlag = intFlag | flag.getValue();
    }
    try {
        pattern = java.util.regex.Pattern.compile(parameters.regexp(), intFlag);
    } catch (PatternSyntaxException e) {
        throw new IllegalArgumentException("Invalid regular expression.", e);
    }
}
Example 11
Project: parkandrideAPI-master  File: PredictionRequest.java View source code
static Duration parseRelativeTime(String relativeTime) {
    Matcher matcher = java.util.regex.Pattern.compile(HHMM_PATTERN).matcher(relativeTime);
    if (matcher.matches()) {
        int hours = parseOptionalInt(matcher.group(2));
        int minutes = Integer.parseInt(matcher.group(3));
        return standardHours(hours).plus(standardMinutes(minutes));
    } else {
        return Duration.ZERO;
    }
}
Example 12
Project: valdr-bean-validation-master  File: PatternDecoratorTest.java View source code
/**
   * See method name.
   */
@Test
public void shouldStoreThePatternForValueAttribute() {
    /*
     * javax.validation.constraints.Pattern uses the attribute 'regex' to define the pattern. However, for valdr the
     * pattern must be passed in the 'value' attribute.
     */
    // given
    regexPattern("abc");
    PatternDecorator decorator = new PatternDecorator(constraintAttributes);
    // when
    Set<Map.Entry<String, Object>> decoratedEntries = decorator.entrySet();
    // then
    assertThat(firstKeyFrom(decoratedEntries), is("value"));
}
Example 13
Project: AngularBeans-master  File: BeanValidationProcessor.java View source code
public void processBeanValidationParsing(Method method) {
    String modelName = CommonUtils.obtainFieldNameFromAccessor(method.getName());
    Annotation[] scannedAnnotations = method.getAnnotations();
    buffer.append("\nif (modelName === '").append(modelName).append("') {");
    for (Annotation a : scannedAnnotations) {
        if (!validationAnnotations.contains(a.annotationType())) {
            continue;
        }
        String name = (a.annotationType().getName());
        switch(name) {
            case "javax.validation.constraints.NotNull":
                buffer.append("\nentries[e].setAttribute('required', 'true');");
                break;
            case "org.hibernate.validator.constraints.Email":
                buffer.append("\nentries[e].setAttribute('type', 'email');");
                break;
            case "javax.validation.constraints.Pattern":
                String regex = ((Pattern) a).regexp();
                buffer.append("\nentries[e].setAttribute('ng-pattern', '").append(regex).append("');");
                break;
            case "javax.validation.constraints.Size":
                buffer.append("\nentries[e].setAttribute('required', 'true');");
                Size sizeConstraint = (Size) a;
                int maxLength = sizeConstraint.max();
                int minLength = sizeConstraint.min();
                if (minLength < 0) {
                    throw new IllegalArgumentException("The min parameter cannot be negative.");
                }
                if (maxLength < 0) {
                    throw new IllegalArgumentException("The max parameter cannot be negative.");
                }
                if (minLength > 0) {
                    buffer.append("\nentries[e].setAttribute('ng-minlength', '").append(minLength).append("');");
                }
                if (maxLength < Integer.MAX_VALUE) {
                    buffer.append("\nentries[e].setAttribute('ng-maxlength', '").append(maxLength).append("');");
                }
                break;
            case "javax.validation.constraints.DecimalMin":
                String dMin = ((DecimalMin) a).value();
                buffer.append("\nentries[e].setAttribute('min', '").append(dMin).append("');");
                break;
            case "javax.validation.constraints.DecimalMax":
                String dMax = ((DecimalMax) a).value();
                buffer.append("\nentries[e].setAttribute('max', '").append(dMax).append("');");
                break;
            case "javax.validation.constraints.Min":
                long min = ((Min) a).value();
                buffer.append("\nentries[e].setAttribute('min', '").append(min).append("');");
                break;
            case "javax.validation.constraints.Max":
                long max = ((Max) a).value();
                buffer.append("\nentries[e].setAttribute('max', '").append(max).append("');");
                break;
            default:
                break;
        }
    }
    buffer.append("\n}");
}
Example 14
Project: metrics-reporter-config-master  File: PredicateConfig.java View source code
public boolean allowString(String name) {
    if (color.equals("black")) {
        for (Pattern pat : cPatterns) {
            if (pat.matcher(name).matches()) {
                return false;
            }
        }
        return true;
    }
    if (color.equals("white")) {
        for (Pattern pat : cPatterns) {
            if (pat.matcher(name).matches()) {
                return true;
            }
        }
    }
    // trusting validator
    return false;
}
Example 15
Project: visural-wicket-master  File: JSR303AnnotatedPropertyModelBehavior.java View source code
private boolean addValidators(Component component) {
    if (FormComponent.class.isAssignableFrom(component.getClass())) {
        FormComponent fc = (FormComponent) component;
        Object model = component.getDefaultModel();
        if (model != null) {
            if (AbstractPropertyModel.class.isAssignableFrom(model.getClass())) {
                AbstractPropertyModel apm = (AbstractPropertyModel) model;
                if (apm.getPropertyField() != null) {
                    Annotation[] annots = apm.getPropertyField().getAnnotations();
                    Long min = null;
                    Long max = null;
                    for (Annotation a : annots) {
                        if (a.annotationType().getName().equals("javax.validation.constraints.NotNull")) {
                            IValidator v = newNotNullValidator();
                            if (v == null) {
                                fc.setRequired(true);
                            } else {
                                fc.add(v);
                            }
                        } else if (a.annotationType().getName().equals("javax.validation.constraints.Min")) {
                            min = ((Min) a).value();
                        } else if (a.annotationType().getName().equals("javax.validation.constraints.Max")) {
                            max = ((Max) a).value();
                        } else if (a.annotationType().getName().equals("javax.validation.constraints.Past")) {
                            fc.add(newPastValidator());
                        } else if (a.annotationType().getName().equals("javax.validation.constraints.Future")) {
                            fc.add(newFutureValidator());
                        } else if (a.annotationType().getName().equals("javax.validation.constraints.Pattern")) {
                            Pattern pattern = (Pattern) a;
                            fc.add(newPatternValidator(pattern.regexp()));
                        } else if (a.annotationType().getName().equals("javax.validation.constraints.Size")) {
                            Size size = (Size) a;
                            fc.add(newSizeValidator(size.min(), size.max()));
                        } else if (a.annotationType().getName().equals(getEmailAnnotationClassName())) {
                            fc.add(newEmailValidator());
                        }
                    }
                    if (max != null || min != null) {
                        fc.add(newMinMaxValidator(min, max));
                    }
                }
            }
            return true;
        }
    }
    return false;
}
Example 16
Project: event-collector-master  File: TestEvent.java View source code
@Test
public void testEventValidation() {
    String type = "test";
    String uuid = UUID.randomUUID().toString();
    String host = "test.local";
    DateTime time = new DateTime();
    Map<String, ?> data = Collections.emptyMap();
    assertValidates(new Event(type, uuid, host, time, data));
    assertFailsValidation(new Event(null, uuid, host, time, data), "type", "is missing", NotNull.class);
    assertFailsValidation(new Event(type, null, host, time, data), "uuid", "is missing", NotNull.class);
    assertFailsValidation(new Event(type, uuid, null, time, data), "host", "is missing", NotNull.class);
    assertFailsValidation(new Event(type, uuid, host, null, data), "timestamp", "is missing", NotNull.class);
    assertFailsValidation(new Event(type, uuid, host, time, null), "data", "is missing", NotNull.class);
    assertFailsValidation(new Event("hello!", uuid, host, time, data), "type", "must be alphanumeric", Pattern.class);
    assertFailsValidation(new Event("!hello", uuid, host, time, data), "type", "must be alphanumeric", Pattern.class);
    assertFailsValidation(new Event("0abc", uuid, host, time, data), "type", "must be alphanumeric", Pattern.class);
}
Example 17
Project: JMobster-master  File: PatternValidatorTest.java View source code
private void executeWrite(PatternValidator validator) {
    Pattern pattern = mockPattern(this.regexp, flags);
    if (this.overriddenRegexp.equals(NO_OVERRIDDEN)) {
        validator.write(pattern, Optional.empty());
    } else {
        OverridePattern overridePattern = mockOverride(this.overriddenRegexp);
        validator.write(pattern, new Optional<OverridePattern>(overridePattern));
    }
}
Example 18
Project: airlift-master  File: TestNodeConfig.java View source code
@Test
public void testValidations() {
    assertValidates(new NodeConfig().setEnvironment("test").setNodeId(UUID.randomUUID().toString()));
    assertFailsValidation(new NodeConfig().setNodeId("abc/123"), "nodeId", "is malformed", Pattern.class);
    assertFailsValidation(new NodeConfig(), "environment", "may not be null", NotNull.class);
    assertFailsValidation(new NodeConfig().setEnvironment("FOO"), "environment", "is malformed", Pattern.class);
    assertFailsValidation(new NodeConfig().setPool("FOO"), "pool", "is malformed", Pattern.class);
}
Example 19
Project: beanvalidation-tck-master  File: MethodValidationTest.java View source code
@Test
@SpecAssertion(section = Sections.CONSTRAINTDECLARATIONVALIDATIONPROCESS_VALIDATIONROUTINE_METHODCONSTRUCTORVALIDATION, id = "b")
public void constructorReturnValueValidationWithRedefinedDefaultGroupSequence() throws Exception {
    String className = "OrderServiceWithRedefinedDefaultGroupSequence";
    Constructor<OrderServiceWithRedefinedDefaultGroupSequence> constructor = OrderServiceWithRedefinedDefaultGroupSequence.class.getConstructor(String.class, Item.class, byte.class);
    OrderServiceWithRedefinedDefaultGroupSequence returnValue = new OrderServiceWithRedefinedDefaultGroupSequence("");
    Set<ConstraintViolation<OrderServiceWithRedefinedDefaultGroupSequence>> violations = getExecutableValidator().validateConstructorReturnValue(constructor, returnValue);
    //Only the constraints of the Basic group should fail
    assertCorrectConstraintTypes(violations, Size.class, ValidOrderService.class);
    assertCorrectPathNodeNames(violations, names(className, TestUtil.RETURN_VALUE_NODE_NAME), names(className, TestUtil.RETURN_VALUE_NODE_NAME, "name"));
    assertCorrectPathNodeKinds(violations, kinds(ElementKind.CONSTRUCTOR, ElementKind.RETURN_VALUE), kinds(ElementKind.CONSTRUCTOR, ElementKind.RETURN_VALUE, ElementKind.PROPERTY));
    returnValue = new OrderServiceWithRedefinedDefaultGroupSequence("valid");
    violations = getExecutableValidator().validateConstructorReturnValue(constructor, returnValue);
    //Now the constraints of the Default group should fail
    assertCorrectConstraintTypes(violations, Pattern.class, ValidRetailOrderService.class);
    assertCorrectPathNodeNames(violations, names(className, TestUtil.RETURN_VALUE_NODE_NAME), names(className, TestUtil.RETURN_VALUE_NODE_NAME, "name"));
    assertCorrectPathNodeKinds(violations, kinds(ElementKind.CONSTRUCTOR, ElementKind.RETURN_VALUE), kinds(ElementKind.CONSTRUCTOR, ElementKind.RETURN_VALUE, ElementKind.PROPERTY));
}
Example 20
Project: deltaspike-solder-master  File: RegexpConsideration.java View source code
public static final ArrayList<String> convertRegexFlags(int[] flags) {
    ArrayList<String> jsFlags = new ArrayList<String>();
    for (int flag : flags) {
        switch(flag) {
            case java.util.regex.Pattern.CASE_INSENSITIVE:
                jsFlags.add("i");
                break;
            case java.util.regex.Pattern.MULTILINE:
                jsFlags.add("m");
                break;
        }
    }
    return jsFlags;
}
Example 21
Project: podam-master  File: ValidatedPojoTest.java View source code
@Test
@Title("Podam should allow validation annotations customization")
public void podamShouldAllowValidationAnnotationsCustomization() throws Exception {
    @SuppressWarnings("unchecked") Class<AttributeStrategy<?>> strategy = (Class<AttributeStrategy<?>>) (Class<?>) PatternStrategy.class;
    PodamFactory podamFactory = podamFactorySteps.givenAPodamFactoryWithCustomStrategy(Pattern.class, strategy);
    ValidatedPatternPojo pojo = podamInvocationSteps.whenIInvokeTheFactoryForClass(ValidatedPatternPojo.class, podamFactory);
    podamValidationSteps.thePojoMustBeOfTheType(pojo, ValidatedPatternPojo.class);
    podamValidationSteps.thePojoMustBeOfTheType(pojo.getNumber(), String.class);
    podamValidationSteps.thePojoMustBeOfTheType(pojo.getIdentifier(), String.class);
    Validator validator = podamFactorySteps.givenAJavaxValidator();
    validatorSteps.thePojoShouldNotViolateAnyValidations(validator, pojo);
    podamFactorySteps.removeCustomStrategy(podamFactory, Pattern.class);
}
Example 22
Project: presto-master  File: TestLdapConfig.java View source code
@Test
public void testValidation() {
    assertValidates(new LdapConfig().setLdapUrl("ldaps://localhost").setUserBindSearchPattern("uid=${USER},ou=org,dc=test,dc=com").setUserBaseDistinguishedName("dc=test,dc=com").setGroupAuthorizationSearchPattern("&(objectClass=user)(memberOf=cn=group)(user=username)"));
    assertFailsValidation(new LdapConfig().setLdapUrl("ldap://"), "ldapUrl", "LDAP without SSL/TLS unsupported. Expected ldaps://", Pattern.class);
    assertFailsValidation(new LdapConfig().setLdapUrl("localhost"), "ldapUrl", "LDAP without SSL/TLS unsupported. Expected ldaps://", Pattern.class);
    assertFailsValidation(new LdapConfig().setLdapUrl("ldaps:/localhost"), "ldapUrl", "LDAP without SSL/TLS unsupported. Expected ldaps://", Pattern.class);
    assertFailsValidation(new LdapConfig(), "ldapUrl", "may not be null", NotNull.class);
    assertFailsValidation(new LdapConfig(), "userBindSearchPattern", "may not be null", NotNull.class);
}
Example 23
Project: jaxb-facets-master  File: ValidationFacetsFilter.java View source code
/**
     * Process a Facets annotation.
     * @param original Existing Facets annotation or null.
     * @param info Source for validation constraints.
     * @return Processed Annotation or null if no information available.
     */
private Facets filterFacets(Facets original, AnnotationSource info) {
    Map<String, Object> annoValues = new HashMap<String, Object>(AnnotationUtils.getAnnotationValues(Facets.class, original));
    boolean override = false;
    String[] enums = new String[0];
    try {
        enums = original.enumeration();
    } catch (Exception e) {
    }
    if (enums.length <= 0) {
        if (info.readAnnotation(AssertFalse.class) != null) {
            override = true;
            annoValues.put("enumeration", new String[] { "false", "0" });
        } else if (info.readAnnotation(AssertTrue.class) != null) {
            override = true;
            annoValues.put("enumeration", new String[] { "true", "1" });
        }
    }
    long fractions = Facets.VOID_LONG;
    try {
        fractions = original.fractionDigits();
    } catch (Exception e) {
    }
    if (fractions == Facets.VOID_LONG) {
        if (info.readAnnotation(Digits.class) != null) {
            override = true;
            annoValues.put("fractionDigits", (Long) (long) info.readAnnotation(Digits.class).fraction());
        }
    }
    long length = Facets.VOID_LONG;
    try {
        length = original.length();
    } catch (Exception e) {
    }
    if (length == Facets.VOID_LONG) {
        if (info.readAnnotation(Size.class) != null) {
            Size size = info.readAnnotation(Size.class);
            if (size.max() == size.min()) {
                override = true;
                annoValues.put("length", (Long) (long) size.max());
            }
        }
    }
    long maxLength = Facets.VOID_LONG;
    try {
        maxLength = original.maxLength();
    } catch (Exception e) {
    }
    if (maxLength == Facets.VOID_LONG) {
        if (info.readAnnotation(Size.class) != null) {
            override = true;
            annoValues.put("maxLength", (Long) (long) info.readAnnotation(Size.class).max());
        }
    }
    long minLength = Facets.VOID_LONG;
    try {
        minLength = original.minLength();
    } catch (Exception e) {
    }
    if (minLength == Facets.VOID_LONG) {
        if (info.readAnnotation(Size.class) != null) {
            override = true;
            annoValues.put("minLength", (Long) (long) info.readAnnotation(Size.class).min());
        }
    }
    String maxInclusive = Facets.VOID_STRING;
    try {
        maxInclusive = original.maxInclusive();
    } catch (Exception e) {
    }
    if (Facets.VOID_STRING.equals(maxInclusive)) {
        if (info.readAnnotation(DecimalMax.class) != null) {
            override = true;
            annoValues.put("maxInclusive", info.readAnnotation(DecimalMax.class).value());
        } else if (info.readAnnotation(Max.class) != null) {
            override = true;
            annoValues.put("maxInclusive", Long.toString(info.readAnnotation(Max.class).value()));
        }
    }
    String minInclusive = Facets.VOID_STRING;
    try {
        minInclusive = original.minInclusive();
    } catch (Exception e) {
    }
    if (Facets.VOID_STRING.equals(minInclusive)) {
        if (info.readAnnotation(DecimalMin.class) != null) {
            override = true;
            annoValues.put("minInclusive", info.readAnnotation(DecimalMin.class).value());
        } else if (info.readAnnotation(Min.class) != null) {
            override = true;
            annoValues.put("minInclusive", Long.toString(info.readAnnotation(Min.class).value()));
        }
    }
    String pattern = Facets.VOID_STRING;
    try {
        pattern = original.pattern();
    } catch (Exception e) {
    }
    if (Facets.VOID_STRING.equals(pattern)) {
        if (info.readAnnotation(Pattern.class) != null) {
            override = true;
            annoValues.put("pattern", info.readAnnotation(Pattern.class).regexp());
        }
    }
    long totalDigits = Facets.VOID_LONG;
    try {
        totalDigits = original.totalDigits();
    } catch (Exception e) {
    }
    if (totalDigits == Facets.VOID_LONG) {
        if (info.readAnnotation(Digits.class) != null) {
            override = true;
            annoValues.put("totalDigits", (Long) (long) (info.readAnnotation(Digits.class).integer() + info.readAnnotation(Digits.class).fraction()));
        }
    }
    return override ? AnnotationUtils.createAnnotationProxy(Facets.class, annoValues) : original;
}
Example 24
Project: airship-master  File: TestAwsProvisionerConfig.java View source code
@Test
public void testProvisioningScriptPattern() throws Exception {
    AwsProvisionerConfig config = new AwsProvisionerConfig().setAirshipVersion("99.9").setAgentDefaultConfig("agent:config:1").setAwsCredentialsFile("aws.credentials").setAwsEndpoint("http://ytmnd.com").setAwsCoordinatorAmi("c-ami-0123abcd").setAwsCoordinatorKeypair("c-keypair").setAwsCoordinatorSecurityGroup("c-default").setProvisioningScriptsArtifact("foo:bar").setAwsCoordinatorDefaultInstanceType("c-t1.micro").setAwsAgentAmi("a-ami-0123abcd").setAwsAgentKeypair("a-keypair").setAwsAgentSecurityGroup("a-default").setAwsAgentDefaultInstanceType("a-t1.micro").setS3KeystoreBucket("bucket").setS3KeystorePath("path").setS3KeystoreRefreshInterval(new Duration(30, TimeUnit.SECONDS));
    assertFailsValidation(config, "provisioningScriptsArtifact", "Invalid provisioning script artifact", Pattern.class);
    config.setProvisioningScriptsArtifact("com.example:bar:1-SNAPSHOT");
    assertValidates(config);
}
Example 25
Project: jarchetypes-master  File: InputTextScanner.java View source code
public void scanForRegex(Class<?> archetype, Member member, WidgetDescriptor descriptor) {
    Pattern pattern = (Pattern) getAnnotation(Pattern.class, member);
    String regex = null;
    try {
        boolean isMethodAndHasNotNullAnnotation = member instanceof Method && (((Method) member).isAnnotationPresent(Pattern.class));
        boolean isGetterAndFieldHasNotNullAnnotation = member instanceof Method && ArchetypesUtils.isGetter(member.getName()) && ArchetypesUtils.getField(archetype, ArchetypesUtils.getFieldName(member)).isAnnotationPresent(Pattern.class);
        if (isMethodAndHasNotNullAnnotation || isGetterAndFieldHasNotNullAnnotation) {
            regex = pattern.regexp();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    descriptor.setAttribute("regex", regex);
}
Example 26
Project: soaba-master  File: SoaConfiguration.java View source code
@ValidationMethod(message = "deploymentGroups cannot be null and names can only contain letters, numbers, underscores, dashes or periods")
@JsonIgnore
public boolean isValidDeploymentGroups() {
    if (deploymentGroups == null) {
        return false;
    }
    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("^[a-zA-Z0-9_\\-.]+$");
    for (String group : deploymentGroups) {
        if (!pattern.matcher(group).matches()) {
            return false;
        }
    }
    return true;
}
Example 27
Project: soabase-master  File: SoaConfiguration.java View source code
@ValidationMethod(message = "deploymentGroups cannot be null and names can only contain letters, numbers, underscores, dashes or periods")
@JsonIgnore
public boolean isValidDeploymentGroups() {
    if (deploymentGroups == null) {
        return false;
    }
    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("^[a-zA-Z0-9_\\-.]+$");
    for (String group : deploymentGroups) {
        if (!pattern.matcher(group).matches()) {
            return false;
        }
    }
    return true;
}
Example 28
Project: springboot-dubbox-master  File: UserController.java View source code
/**
     * Registry user map.
     *
     * @param version    the version
     * @param password   the password
     * @param mobile     the mobile
     * @param captcha    the captcha
     * @param invitation the invitation
     * @return the map
     * @throws InvalidCaptchaException the invalid captcha exception
     */
@PostMapping(value = "", produces = "application/json; charset=UTF-8")
@ApiOperation(value = "注册用户")
public Map<String, Object> registryUser(@ApiParam(required = true, value = "版本", defaultValue = "v1") @PathVariable("version") String version, @Length(min = 6, max = 20, message = "密�长度为6到20") @ApiParam(required = true, value = "密�") @RequestParam("password") String password, @Pattern(regexp = "1(3[0-9]|4[57]|5[0-35-9]|7[01678]|8[0-9])\\d{8}", message = "手机��格�错误") @ApiParam(required = true, value = "手机�") @RequestParam("mobile") String mobile, @Pattern(regexp = "\\d{6}", message = "验��为6�数字") @ApiParam(required = true, value = "短信验��") @RequestParam("captcha") String captcha) throws InvalidCaptchaException {
    //校验验��
    captchaService.validCaptcha(mobile, captcha);
    TripUser user = new TripUser();
    user.setMobile(mobile);
    user.setPassword(passwordEncoder.encode(password));
    // 注册
    tripUserService.registryUser(mobile, passwordEncoder.encode(password));
    Map<String, Object> message = new HashMap<>();
    message.put(Message.RETURN_FIELD_CODE, ReturnCode.SUCCESS);
    return message;
}
Example 29
Project: cxf-master  File: JaxRs2Extension.java View source code
/**
     * This is essentially a duplicate of {@link io.swagger.jackson.ModelResolver.applyBeanValidatorAnnotations}.
     *
     * @param parameter
     * @param annotations
     */
private void applyBeanValidatorAnnotations(final Parameter parameter, final List<Annotation> annotations) {
    Map<String, Annotation> annos = new HashMap<>();
    if (annotations != null) {
        for (Annotation annotation : annotations) {
            annos.put(annotation.annotationType().getName(), annotation);
        }
    }
    if (annos.containsKey(NotNull.class.getName())) {
        parameter.setRequired(true);
    }
    if (parameter instanceof AbstractSerializableParameter) {
        AbstractSerializableParameter<?> serializable = (AbstractSerializableParameter<?>) parameter;
        if (annos.containsKey(Min.class.getName())) {
            Min min = (Min) annos.get(Min.class.getName());
            serializable.setMinimum(BigDecimal.valueOf(min.value()));
        }
        if (annos.containsKey(Max.class.getName())) {
            Max max = (Max) annos.get(Max.class.getName());
            serializable.setMaximum(BigDecimal.valueOf(max.value()));
        }
        if (annos.containsKey(Size.class.getName())) {
            Size size = (Size) annos.get(Size.class.getName());
            serializable.setMinimum(BigDecimal.valueOf(size.min()));
            serializable.setMaximum(BigDecimal.valueOf(size.max()));
            serializable.setMinItems(size.min());
            serializable.setMaxItems(size.max());
        }
        if (annos.containsKey(DecimalMin.class.getName())) {
            DecimalMin min = (DecimalMin) annos.get(DecimalMin.class.getName());
            if (min.inclusive()) {
                serializable.setMinimum(BigDecimal.valueOf(new Double(min.value())));
            } else {
                serializable.setExclusiveMinimum(!min.inclusive());
            }
        }
        if (annos.containsKey(DecimalMax.class.getName())) {
            DecimalMax max = (DecimalMax) annos.get(DecimalMax.class.getName());
            if (max.inclusive()) {
                serializable.setMaximum(BigDecimal.valueOf(new Double(max.value())));
            } else {
                serializable.setExclusiveMaximum(!max.inclusive());
            }
        }
        if (annos.containsKey(Pattern.class.getName())) {
            Pattern pattern = (Pattern) annos.get(Pattern.class.getName());
            serializable.setPattern(pattern.regexp());
        }
    }
}
Example 30
Project: graylog2-server-master  File: IndexSetConfig.java View source code
@JsonCreator
public static IndexSetConfig create(@Id @ObjectId @JsonProperty("_id") @Nullable String id, @JsonProperty("title") @NotBlank String title, @JsonProperty("description") @Nullable String description, @JsonProperty("writable") @Nullable Boolean isWritable, @JsonProperty(FIELD_INDEX_PREFIX) @Pattern(regexp = INDEX_PREFIX_REGEX) String indexPrefix, @JsonProperty("index_match_pattern") @Nullable String indexMatchPattern, @JsonProperty("index_wildcard") @Nullable String indexWildcard, @JsonProperty("shards") @Min(1) int shards, @JsonProperty("replicas") @Min(0) int replicas, @JsonProperty("rotation_strategy_class") @Nullable String rotationStrategyClass, @JsonProperty("rotation_strategy") @NotNull RotationStrategyConfig rotationStrategy, @JsonProperty("retention_strategy_class") @Nullable String retentionStrategyClass, @JsonProperty("retention_strategy") @NotNull RetentionStrategyConfig retentionStrategy, @JsonProperty(FIELD_CREATION_DATE) @NotNull ZonedDateTime creationDate, @JsonProperty("index_analyzer") @Nullable String indexAnalyzer, @JsonProperty("index_template_name") @Nullable String indexTemplateName, @JsonProperty("index_optimization_max_num_segments") @Nullable Integer maxNumSegments, @JsonProperty("index_optimization_disabled") @Nullable Boolean indexOptimizationDisabled) {
    return AutoValue_IndexSetConfig.builder().id(id).title(title).description(description).isWritable(isWritable == null ? true : isWritable).indexPrefix(indexPrefix).indexMatchPattern(indexMatchPattern).indexWildcard(indexWildcard).shards(shards).replicas(replicas).rotationStrategyClass(rotationStrategyClass).rotationStrategy(rotationStrategy).retentionStrategyClass(retentionStrategyClass).retentionStrategy(retentionStrategy).creationDate(creationDate).indexAnalyzer(isNullOrEmpty(indexAnalyzer) ? "standard" : indexAnalyzer).indexTemplateName(isNullOrEmpty(indexTemplateName) ? indexPrefix + "-template" : indexTemplateName).indexOptimizationMaxNumSegments(maxNumSegments == null ? 1 : maxNumSegments).indexOptimizationDisabled(indexOptimizationDisabled == null ? false : indexOptimizationDisabled).build();
}
Example 31
Project: jsondoc-master  File: JSONDocHibernateValidatorProcessor.java View source code
public static void processHibernateValidatorAnnotations(Field field, ApiObjectFieldDoc apiPojoFieldDoc) {
    try {
        Class.forName("org.hibernate.validator.constraints.NotBlank");
        if (field.isAnnotationPresent(AssertFalse.class)) {
            apiPojoFieldDoc.addFormat(AssertFalse_message);
        }
        if (field.isAnnotationPresent(AssertTrue.class)) {
            apiPojoFieldDoc.addFormat(AssertTrue_message);
        }
        if (field.isAnnotationPresent(NotNull.class)) {
            apiPojoFieldDoc.addFormat(NotNull_message);
        }
        if (field.isAnnotationPresent(Null.class)) {
            apiPojoFieldDoc.addFormat(Null_message);
        }
        if (field.isAnnotationPresent(Size.class)) {
            Size annotation = field.getAnnotation(Size.class);
            apiPojoFieldDoc.addFormat(String.format(Size_message, annotation.min(), annotation.max()));
        }
        if (field.isAnnotationPresent(NotBlank.class)) {
            apiPojoFieldDoc.addFormat(NotBlank_message);
        }
        if (field.isAnnotationPresent(NotEmpty.class)) {
            apiPojoFieldDoc.addFormat(NotEmpty_message);
        }
        if (field.isAnnotationPresent(Length.class)) {
            Length annotation = field.getAnnotation(Length.class);
            apiPojoFieldDoc.addFormat(String.format(Length_message, annotation.min(), annotation.max()));
        }
        if (field.isAnnotationPresent(Range.class)) {
            Range annotation = field.getAnnotation(Range.class);
            apiPojoFieldDoc.addFormat(String.format(Range_message, annotation.min(), annotation.max()));
        }
        if (field.isAnnotationPresent(DecimalMax.class)) {
            DecimalMax annotation = field.getAnnotation(DecimalMax.class);
            apiPojoFieldDoc.addFormat(String.format(DecimalMax_message, annotation.inclusive() ? "or equal to" : "", annotation.value()));
        }
        if (field.isAnnotationPresent(DecimalMin.class)) {
            DecimalMin annotation = field.getAnnotation(DecimalMin.class);
            apiPojoFieldDoc.addFormat(String.format(DecimalMin_message, annotation.inclusive() ? "or equal to" : "", annotation.value()));
        }
        if (field.isAnnotationPresent(Future.class)) {
            apiPojoFieldDoc.addFormat(Future_message);
        }
        if (field.isAnnotationPresent(Past.class)) {
            apiPojoFieldDoc.addFormat(Past_message);
        }
        if (field.isAnnotationPresent(Digits.class)) {
            Digits annotation = field.getAnnotation(Digits.class);
            apiPojoFieldDoc.addFormat(String.format(Digits_message, annotation.integer(), annotation.fraction()));
        }
        if (field.isAnnotationPresent(Max.class)) {
            Max annotation = field.getAnnotation(Max.class);
            apiPojoFieldDoc.addFormat(String.format(Max_message, annotation.value()));
        }
        if (field.isAnnotationPresent(Min.class)) {
            Min annotation = field.getAnnotation(Min.class);
            apiPojoFieldDoc.addFormat(String.format(Min_message, annotation.value()));
        }
        if (field.isAnnotationPresent(Pattern.class)) {
            Pattern annotation = field.getAnnotation(Pattern.class);
            apiPojoFieldDoc.addFormat(String.format(Pattern_message, annotation.regexp()));
        }
        if (field.isAnnotationPresent(Email.class)) {
            apiPojoFieldDoc.addFormat(Email_message);
        }
        if (field.isAnnotationPresent(URL.class)) {
            apiPojoFieldDoc.addFormat(URL_message);
        }
        if (field.isAnnotationPresent(CreditCardNumber.class)) {
            apiPojoFieldDoc.addFormat(CreditCardNumber_message);
        }
    } catch (ClassNotFoundException e) {
    }
}
Example 32
Project: mybatis-generator-example-master  File: ValidationAnnotationPlugin.java View source code
public void setPattern(Field field, IntrospectedColumn introspectedColumn) {
    String property = introspectedColumn.getJavaProperty();
    for (int i = 4; i < CONIFS.length; i++) {
        String[] temps = CONIFS[i].split("#");
        String pattern = temps[0].replace("@Pattern", "");
        for (int j = 1; j < temps.length; j++) {
            int idx = temps[j].indexOf(this.className + ":");
            if (idx >= 0 && temps[j].indexOf(property) > idx) {
                String[] tt = temps[j].split("[:,]");
                for (String ttt : tt) {
                    if (property.equals(ttt)) {
                        field.addAnnotation("@Pattern(regexp = \"" + pattern + "\", message = \"" + property + "�ֶ�ֵ��������������ʽ" + pattern + "\")");
                        break;
                    }
                }
                return;
            }
        }
    }
}
Example 33
Project: krasa-jaxb-tools-master  File: JaxbValidationsPlugins.java View source code
public void processType(XSSimpleType simpleType, JFieldVar field, String propertyName, String className) {
    if (!hasAnnotation(field, Size.class) && isSizeAnnotationApplicable(field)) {
        Integer maxLength = simpleType.getFacet("maxLength") == null ? null : Utils.parseInt(simpleType.getFacet("maxLength").getValue().value);
        Integer minLength = simpleType.getFacet("minLength") == null ? null : Utils.parseInt(simpleType.getFacet("minLength").getValue().value);
        Integer length = simpleType.getFacet("length") == null ? null : Utils.parseInt(simpleType.getFacet("length").getValue().value);
        if (maxLength != null && minLength != null) {
            log("@Size(" + minLength + "," + maxLength + "): " + propertyName + " added to class " + className);
            field.annotate(Size.class).param("min", minLength).param("max", maxLength);
        } else if (minLength != null) {
            log("@Size(" + minLength + ", null): " + propertyName + " added to class " + className);
            field.annotate(Size.class).param("min", minLength);
        } else if (maxLength != null) {
            log("@Size(null, " + maxLength + "): " + propertyName + " added to class " + className);
            field.annotate(Size.class).param("max", maxLength);
        } else if (length != null) {
            log("@Size(" + length + "," + length + "): " + propertyName + " added to class " + className);
            field.annotate(Size.class).param("min", length).param("max", length);
        }
    }
    if (jpaAnnotations && isSizeAnnotationApplicable(field)) {
        Integer maxLength = simpleType.getFacet("maxLength") == null ? null : Utils.parseInt(simpleType.getFacet("maxLength").getValue().value);
        if (maxLength != null) {
            log("@Column(null, " + maxLength + "): " + propertyName + " added to class " + className);
            field.annotate(Column.class).param("length", maxLength);
        }
    }
    XSFacet maxInclusive = simpleType.getFacet("maxInclusive");
    if (maxInclusive != null && Utils.isNumber(field) && isValidValue(maxInclusive) && !hasAnnotation(field, DecimalMax.class)) {
        log("@DecimalMax(" + maxInclusive.getValue().value + "): " + propertyName + " added to class " + className);
        field.annotate(DecimalMax.class).param("value", maxInclusive.getValue().value);
    }
    XSFacet minInclusive = simpleType.getFacet("minInclusive");
    if (minInclusive != null && Utils.isNumber(field) && isValidValue(minInclusive) && !hasAnnotation(field, DecimalMin.class)) {
        log("@DecimalMin(" + minInclusive.getValue().value + "): " + propertyName + " added to class " + className);
        field.annotate(DecimalMin.class).param("value", minInclusive.getValue().value);
    }
    XSFacet maxExclusive = simpleType.getFacet("maxExclusive");
    if (maxExclusive != null && Utils.isNumber(field) && isValidValue(maxExclusive) && !hasAnnotation(field, DecimalMax.class)) {
        JAnnotationUse annotate = field.annotate(DecimalMax.class);
        if (jsr349) {
            log("@DecimalMax(value = " + maxExclusive.getValue().value + ", inclusive = false): " + propertyName + " added to class " + className);
            annotate.param("value", maxExclusive.getValue().value);
            annotate.param("inclusive", false);
        } else {
            final BigInteger value = new BigInteger(maxExclusive.getValue().value).subtract(BigInteger.ONE);
            log("@DecimalMax(" + value.toString() + "): " + propertyName + " added to class " + className);
            annotate.param("value", value.toString());
        }
    }
    XSFacet minExclusive = simpleType.getFacet("minExclusive");
    if (minExclusive != null && Utils.isNumber(field) && isValidValue(minExclusive) && !hasAnnotation(field, DecimalMin.class)) {
        JAnnotationUse annotate = field.annotate(DecimalMin.class);
        if (jsr349) {
            log("@DecimalMin(value = " + minExclusive.getValue().value + ", inclusive = false): " + propertyName + " added to class " + className);
            annotate.param("value", minExclusive.getValue().value);
            annotate.param("inclusive", false);
        } else {
            final BigInteger value = new BigInteger(minExclusive.getValue().value).add(BigInteger.ONE);
            log("@DecimalMax(" + value.toString() + "): " + propertyName + " added to class " + className);
            annotate.param("value", value.toString());
        }
    }
    if (simpleType.getFacet("totalDigits") != null && Utils.isNumber(field)) {
        Integer totalDigits = simpleType.getFacet("totalDigits") == null ? null : Utils.parseInt(simpleType.getFacet("totalDigits").getValue().value);
        int fractionDigits = simpleType.getFacet("fractionDigits") == null ? 0 : Utils.parseInt(simpleType.getFacet("fractionDigits").getValue().value);
        if (!hasAnnotation(field, Digits.class)) {
            log("@Digits(" + totalDigits + "," + fractionDigits + "): " + propertyName + " added to class " + className);
            JAnnotationUse annox = field.annotate(Digits.class).param("integer", totalDigits);
            annox.param("fraction", fractionDigits);
        }
        if (jpaAnnotations) {
            field.annotate(Column.class).param("precision", totalDigits).param("scale", fractionDigits);
        }
    }
    /**
		 * <annox:annotate annox:class="javax.validation.constraints.Pattern"
		 * message="Name can only contain capital letters, numbers and the symbols '-', '_', '/', ' '"
		 * regexp="^[A-Z0-9_\s//-]*" />
		 */
    List<XSFacet> patternList = simpleType.getFacets("pattern");
    if (// More than one pattern
    patternList.size() > 1) {
        if ("String".equals(field.type().name())) {
            log("@Pattern: " + propertyName + " added to class " + className);
            final JAnnotationUse patternAnnotation = field.annotate(Pattern.class);
            StringBuilder sb = new StringBuilder();
            for (XSFacet xsFacet : patternList) {
                final String value = xsFacet.getValue().value;
                // cxf-codegen fix
                if (!"\\c+".equals(value)) {
                    sb.append("(").append(replaceXmlProprietals(value)).append(")|");
                }
            }
            patternAnnotation.param("regexp", sb.substring(0, sb.length() - 1));
        }
    } else if (simpleType.getFacet("pattern") != null) {
        String pattern = simpleType.getFacet("pattern").getValue().value;
        if ("String".equals(field.type().name())) {
            // cxf-codegen fix
            if (!"\\c+".equals(pattern)) {
                log("@Pattern(" + pattern + "): " + propertyName + " added to class " + className);
                if (!hasAnnotation(field, Pattern.class)) {
                    field.annotate(Pattern.class).param("regexp", replaceXmlProprietals(pattern));
                }
            }
        }
    } else if ("String".equals(field.type().name())) {
        final List<XSFacet> enumerationList = simpleType.getFacets("enumeration");
        if (// More than one pattern
        enumerationList.size() > 1) {
            log("@Pattern: " + propertyName + " added to class " + className);
            final JAnnotationUse patternListAnnotation = field.annotate(Pattern.class);
            StringBuilder sb = new StringBuilder();
            for (XSFacet xsFacet : enumerationList) {
                final String value = xsFacet.getValue().value;
                // cxf-codegen fix
                if (!"\\c+".equals(value)) {
                    sb.append("(").append(replaceXmlProprietals(value)).append(")|");
                }
            }
            patternListAnnotation.param("regexp", sb.substring(0, sb.length() - 1));
        } else if (simpleType.getFacet("enumeration") != null) {
            final String pattern = simpleType.getFacet("enumeration").getValue().value;
            // cxf-codegen fix
            if (!"\\c+".equals(pattern)) {
                log("@Pattern(" + pattern + "): " + propertyName + " added to class " + className);
                field.annotate(Pattern.class).param("regexp", replaceXmlProprietals(pattern));
            }
        }
    }
}
Example 34
Project: para-master  File: Constraint.java View source code
/**
	 * Builds a new constraint from the annotation data.
	 * @param anno JSR-303 annotation instance
	 * @return a new constraint
	 */
public static Constraint fromAnnotation(Annotation anno) {
    if (anno instanceof Min) {
        return min(((Min) anno).value());
    } else if (anno instanceof Max) {
        return max(((Max) anno).value());
    } else if (anno instanceof Size) {
        return size(((Size) anno).min(), ((Size) anno).max());
    } else if (anno instanceof Digits) {
        return digits(((Digits) anno).integer(), ((Digits) anno).fraction());
    } else if (anno instanceof Pattern) {
        return pattern(((Pattern) anno).regexp());
    } else {
        return new Constraint(VALIDATORS.get(anno.annotationType()), simplePayload(VALIDATORS.get(anno.annotationType()))) {

            public boolean isValid(Object actualValue) {
                return true;
            }
        };
    }
}
Example 35
Project: shop-repo-master  File: KundeResource.java View source code
@GET
public Response findKunden(@QueryParam(KUNDEN_NACHNAME_QUERY_PARAM) @Pattern(regexp = AbstractKunde.NACHNAME_PATTERN, message = "{kunde.nachname.pattern}") String nachname, @QueryParam(KUNDEN_PLZ_QUERY_PARAM) @Pattern(regexp = "\\d{5}", message = "{adresse.plz}") String plz, @QueryParam(KUNDEN_EMAIL_QUERY_PARAM) @Email(message = "{kunde.email}") String email) {
    List<? extends AbstractKunde> kunden = null;
    AbstractKunde kunde = null;
    if (!Strings.isNullOrEmpty(nachname)) {
        kunden = ks.findKundenByNachname(nachname, FetchType.NUR_KUNDE);
    } else if (!Strings.isNullOrEmpty(plz)) {
        kunden = ks.findKundenByPLZ(plz);
    } else if (!Strings.isNullOrEmpty(email)) {
        kunde = ks.findKundeByEmail(email);
    } else {
        kunden = ks.findAllKunden(FetchType.NUR_KUNDE, OrderType.ID);
    }
    Object entity = null;
    Link[] links = null;
    if (kunden != null) {
        for (AbstractKunde k : kunden) {
            setStructuralLinks(k, uriInfo);
        }
        entity = new GenericEntity<List<? extends AbstractKunde>>(kunden) {
        };
        links = getTransitionalLinksKunden(kunden, uriInfo);
    } else if (kunde != null) {
        entity = kunde;
        links = getTransitionalLinks(kunde, uriInfo);
    }
    return Response.ok(entity).links(links).build();
}
Example 36
Project: candlepin-master  File: CandlepinSwaggerModelConverter.java View source code
protected void applyBeanValidatorAnnotations(Property property, Annotation[] annotations) {
    Map<String, Annotation> annos = new HashMap<String, Annotation>();
    if (annotations != null) {
        for (Annotation anno : annotations) {
            annos.put(anno.annotationType().getName(), anno);
        }
    }
    if (annos.containsKey("javax.validation.constraints.NotNull")) {
        property.setRequired(true);
    }
    if (annos.containsKey("javax.validation.constraints.Min")) {
        if (property instanceof AbstractNumericProperty) {
            Min min = (Min) annos.get("javax.validation.constraints.Min");
            AbstractNumericProperty ap = (AbstractNumericProperty) property;
            ap.setMinimum(new Double(min.value()));
        }
    }
    if (annos.containsKey("javax.validation.constraints.Max")) {
        if (property instanceof AbstractNumericProperty) {
            Max max = (Max) annos.get("javax.validation.constraints.Max");
            AbstractNumericProperty ap = (AbstractNumericProperty) property;
            ap.setMaximum(new Double(max.value()));
        }
    }
    if (annos.containsKey("javax.validation.constraints.Size")) {
        Size size = (Size) annos.get("javax.validation.constraints.Size");
        if (property instanceof AbstractNumericProperty) {
            AbstractNumericProperty ap = (AbstractNumericProperty) property;
            ap.setMinimum(new Double(size.min()));
            ap.setMaximum(new Double(size.max()));
        } else if (property instanceof StringProperty) {
            StringProperty sp = (StringProperty) property;
            sp.minLength(new Integer(size.min()));
            sp.maxLength(new Integer(size.max()));
        } else if (property instanceof ArrayProperty) {
            ArrayProperty sp = (ArrayProperty) property;
            sp.setMinItems(size.min());
            sp.setMaxItems(size.max());
        }
    }
    if (annos.containsKey("javax.validation.constraints.DecimalMin")) {
        DecimalMin min = (DecimalMin) annos.get("javax.validation.constraints.DecimalMin");
        if (property instanceof AbstractNumericProperty) {
            AbstractNumericProperty ap = (AbstractNumericProperty) property;
            ap.setMinimum(new Double(min.value()));
        }
    }
    if (annos.containsKey("javax.validation.constraints.DecimalMax")) {
        DecimalMax max = (DecimalMax) annos.get("javax.validation.constraints.DecimalMax");
        if (property instanceof AbstractNumericProperty) {
            AbstractNumericProperty ap = (AbstractNumericProperty) property;
            ap.setMaximum(new Double(max.value()));
        }
    }
    if (annos.containsKey("javax.validation.constraints.Pattern")) {
        Pattern pattern = (Pattern) annos.get("javax.validation.constraints.Pattern");
        if (property instanceof StringProperty) {
            StringProperty ap = (StringProperty) property;
            ap.setPattern(pattern.regexp());
        }
    }
}
Example 37
Project: swagger-core-master  File: ModelResolver.java View source code
protected void applyBeanValidatorAnnotations(Property property, Annotation[] annotations) {
    Map<String, Annotation> annos = new HashMap<String, Annotation>();
    if (annotations != null) {
        for (Annotation anno : annotations) {
            annos.put(anno.annotationType().getName(), anno);
        }
    }
    if (annos.containsKey("javax.validation.constraints.NotNull")) {
        property.setRequired(true);
    }
    if (annos.containsKey("javax.validation.constraints.Min")) {
        if (property instanceof AbstractNumericProperty) {
            Min min = (Min) annos.get("javax.validation.constraints.Min");
            AbstractNumericProperty ap = (AbstractNumericProperty) property;
            ap.setMinimum(new BigDecimal(min.value()));
        }
    }
    if (annos.containsKey("javax.validation.constraints.Max")) {
        if (property instanceof AbstractNumericProperty) {
            Max max = (Max) annos.get("javax.validation.constraints.Max");
            AbstractNumericProperty ap = (AbstractNumericProperty) property;
            ap.setMaximum(new BigDecimal(max.value()));
        }
    }
    if (annos.containsKey("javax.validation.constraints.Size")) {
        Size size = (Size) annos.get("javax.validation.constraints.Size");
        if (property instanceof AbstractNumericProperty) {
            AbstractNumericProperty ap = (AbstractNumericProperty) property;
            ap.setMinimum(new BigDecimal(size.min()));
            ap.setMaximum(new BigDecimal(size.max()));
        } else if (property instanceof StringProperty) {
            StringProperty sp = (StringProperty) property;
            sp.minLength(new Integer(size.min()));
            sp.maxLength(new Integer(size.max()));
        } else if (property instanceof ArrayProperty) {
            ArrayProperty sp = (ArrayProperty) property;
            sp.setMinItems(size.min());
            sp.setMaxItems(size.max());
        }
    }
    if (annos.containsKey("javax.validation.constraints.DecimalMin")) {
        DecimalMin min = (DecimalMin) annos.get("javax.validation.constraints.DecimalMin");
        if (property instanceof AbstractNumericProperty) {
            AbstractNumericProperty ap = (AbstractNumericProperty) property;
            ap.setMinimum(new BigDecimal(min.value()));
            ap.setExclusiveMinimum(!min.inclusive());
        }
    }
    if (annos.containsKey("javax.validation.constraints.DecimalMax")) {
        DecimalMax max = (DecimalMax) annos.get("javax.validation.constraints.DecimalMax");
        if (property instanceof AbstractNumericProperty) {
            AbstractNumericProperty ap = (AbstractNumericProperty) property;
            ap.setMaximum(new BigDecimal(max.value()));
            ap.setExclusiveMaximum(!max.inclusive());
        }
    }
    if (annos.containsKey("javax.validation.constraints.Pattern")) {
        Pattern pattern = (Pattern) annos.get("javax.validation.constraints.Pattern");
        if (property instanceof StringProperty) {
            StringProperty ap = (StringProperty) property;
            ap.setPattern(pattern.regexp());
        }
    }
}
Example 38
Project: plugin-validation-master  File: PropertyConstraintPlugin.java View source code
@Command(value = "Pattern", help = "Adds @Pattern constraint on the specified property")
public void addPatternConstraint(@Option(name = "onProperty", completer = PropertyCompleter.class, required = true) String property, @Option(name = "onAccessor", flagOnly = true) boolean onAccessor, @Option(name = "regexp", required = true) String regexp, @Option(name = "flags") Pattern.Flag[] flags, @Option(name = "message") String message, @Option(name = "groups", type = JAVA_CLASS) String[] groups, PipeOut pipeOut) throws FileNotFoundException {
    final Annotation<JavaClass> constraintAnnotation = addConstraintOnProperty(property, onAccessor, Pattern.class);
    setConstraintMessage(constraintAnnotation, message);
    constraintAnnotation.setStringValue("regexp", regexp);
    constraintAnnotation.getOrigin().addImport(Pattern.Flag.class);
    final StringBuilder flagsLiteral = new StringBuilder();
    flagsLiteral.append('{');
    if (flags != null) {
        int i = 0;
        for (Pattern.Flag oneFlag : flags) {
            flagsLiteral.append(oneFlag);
            if (i < (flags.length - 1)) {
                flagsLiteral.append(",");
            }
            i++;
        }
    }
    flagsLiteral.append('}');
    constraintAnnotation.setStringValue("flags", flagsLiteral.toString());
    javaSourceFacet.saveJavaSource(constraintAnnotation.getOrigin());
    outputConstraintAdded(pipeOut, property, Pattern.class);
}
Example 39
Project: eclipselink.runtime-master  File: AnnotationsProcessor.java View source code
/**
     * @since 2.6
     * @author Marcel Valovy
     * @param property property for which facets will be generated
     */
private void addFacets(Property property) {
    final JavaHasAnnotations element = property.getElement();
    if (helper.isAnnotationPresent(element, DecimalMin.class)) {
        DecimalMin a = (DecimalMin) helper.getAnnotation(element, DecimalMin.class);
        DecimalMinFacet facet = new DecimalMinFacet(a.value(), a.inclusive());
        property.addFacet(facet);
    }
    if (helper.isAnnotationPresent(element, DecimalMax.class)) {
        DecimalMax a = (DecimalMax) helper.getAnnotation(element, DecimalMax.class);
        DecimalMaxFacet facet = new DecimalMaxFacet(a.value(), a.inclusive());
        property.addFacet(facet);
    }
    if (helper.isAnnotationPresent(element, Digits.class)) {
        Digits a = (Digits) helper.getAnnotation(element, Digits.class);
        DigitsFacet facet = new DigitsFacet(a.integer(), a.fraction());
        property.addFacet(facet);
    }
    if (helper.isAnnotationPresent(element, Max.class)) {
        Max a = (Max) helper.getAnnotation(element, Max.class);
        MaxFacet facet = new MaxFacet(a.value());
        property.addFacet(facet);
    }
    if (helper.isAnnotationPresent(element, Min.class)) {
        Min a = (Min) helper.getAnnotation(element, Min.class);
        MinFacet facet = new MinFacet(a.value());
        property.addFacet(facet);
    }
    if (helper.isAnnotationPresent(element, NotNull.class)) {
        property.setNotNullAnnotated(true);
    }
    if (helper.isAnnotationPresent(element, Pattern.class)) {
        Pattern a = (Pattern) helper.getAnnotation(element, Pattern.class);
        PatternFacet facet = new PatternFacet(a.regexp(), a.flags());
        property.addFacet(facet);
    }
    /* Example:
            @Pattern.List({
                @Pattern(regexp = "first_expression", message = "first.Pattern.message"),
                @Pattern(regexp = "second_expression", message = "second.Pattern.message"),
                @Pattern(regexp = "third_expression", message = "third.Pattern.message")
        }) */
    if (helper.isAnnotationPresent(element, Pattern.List.class)) {
        Pattern.List a = (Pattern.List) helper.getAnnotation(element, Pattern.List.class);
        PatternListFacet facet = new PatternListFacet(new ArrayList<PatternFacet>());
        for (Pattern pat : a.value()) {
            PatternFacet pf = new PatternFacet(pat.regexp(), pat.flags());
            facet.addPattern(pf);
        }
        property.addFacet(facet);
    }
    if (helper.isAnnotationPresent(element, Size.class)) {
        Size a = (Size) helper.getAnnotation(element, Size.class);
        final int min = a.min();
        final int max = a.max();
        if (min != 0 || max != Integer.MAX_VALUE) {
            // Fixes generation of an empty facet.
            if ("java.lang.String".equals(property.getType().getName())) {
                // @Size serves for both length facet and occurs restriction.
                // For minLength, maxLength.
                SizeFacet facet = new SizeFacet(min, max);
                property.addFacet(facet);
            } else {
                // 0 is default minBoundary.
                if (min > 0)
                    property.setMinOccurs(min);
                // 2^31 is default maxBoundary.
                if (max < Integer.MAX_VALUE)
                    property.setMaxOccurs(max);
            }
        }
    }
}
Example 40
Project: databene-benerator-master  File: AnnotationMapper.java View source code
private void mapBeneratorParamAnnotation(Annotation annotation, InstanceDescriptor instanceDescriptor, Class<?> testClass) {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("mapDetails(" + annotation + ", " + instanceDescriptor + ")");
    try {
        Class<?> annotationType = annotation.annotationType();
        if (annotationType == Unique.class)
            instanceDescriptor.setDetailValue("unique", true);
        else if (annotationType == Granularity.class)
            instanceDescriptor.getLocalType(false).setDetailValue("granularity", String.valueOf(DescriptorUtil.convertType(((Granularity) annotation).value(), (SimpleTypeDescriptor) instanceDescriptor.getLocalType(false))));
        else if (annotationType == DecimalGranularity.class)
            instanceDescriptor.getLocalType(false).setDetailValue("granularity", String.valueOf(DescriptorUtil.convertType(((DecimalGranularity) annotation).value(), (SimpleTypeDescriptor) instanceDescriptor.getLocalType(false))));
        else if (annotationType == SizeDistribution.class)
            instanceDescriptor.getLocalType(false).setDetailValue("lengthDistribution", ((SizeDistribution) annotation).value());
        else if (annotationType == Pattern.class)
            mapPatternAnnotation((Pattern) annotation, instanceDescriptor);
        else if (annotationType == Size.class)
            mapSizeAnnotation((Size) annotation, instanceDescriptor);
        else if (annotationType == Source.class)
            mapSourceAnnotation((Source) annotation, instanceDescriptor, testClass);
        else if (annotationType == Values.class)
            mapValuesAnnotation((Values) annotation, instanceDescriptor);
        else if (annotationType == Offset.class)
            mapOffsetAnnotation((Offset) annotation, instanceDescriptor);
        else if (annotationType == MinDate.class)
            mapMinDateAnnotation((MinDate) annotation, instanceDescriptor);
        else if (annotationType == MaxDate.class)
            mapMaxDateAnnotation((MaxDate) annotation, instanceDescriptor);
        else if (annotationType == Last.class)
            instanceDescriptor.setMode(Mode.ignored);
        else if (!explicitlyMappedAnnotation(annotation))
            mapAnyValueTypeAnnotation(annotation, instanceDescriptor);
    } catch (Exception e) {
        throw new ConfigurationError("Error mapping annotation settings", e);
    }
}
Example 41
Project: flatpack-java-master  File: JavaScriptDialect.java View source code
private String getBuilderReturnType(EndpointDescription end) {
    // Convert a path like /api/2/foo/bar/{}/baz to FooBarBazMethod
    String path = end.getPath();
    String[] parts = path.split(Pattern.quote("/"));
    StringBuilder sb = new StringBuilder();
    sb.append(upcase(end.getMethod().toLowerCase()));
    for (int i = 3, j = parts.length; i < j; i++) {
        try {
            String part = parts[i];
            if (part.length() == 0) {
                continue;
            }
            StringBuilder decodedPart = new StringBuilder(URLDecoder.decode(part, "UTF8"));
            // Trim characters that aren't legal
            for (int k = decodedPart.length() - 1; k >= 0; k--) {
                if (!Character.isJavaIdentifierPart(decodedPart.charAt(k))) {
                    decodedPart.deleteCharAt(k);
                }
            }
            // Append the new name part, using camel-cased names
            String newPart = decodedPart.toString();
            if (sb.length() > 0) {
                newPart = upcase(newPart);
            }
            sb.append(newPart);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    sb.append("Request");
    return packageName + "." + upcase(sb.toString());
}
Example 42
Project: constant-contact-connector-master  File: ConstantContactConnector.java View source code
/**
     * Creates a contact.
     * <p/>
     * {@sample.xml ../../../doc/constantcontact-connector.xml.sample constantcontact:createContact}
     *
     * @param emailAddress      the email address to add, 80 characters max
     * @param contactLists      indicates which lists the Contact belongs to, the contact must be included in AT LEST one list
     * @param optInSource       use {@link OptInSource#ACTION_BY_CONTACT} if the contact is adding himself or herself, use {@link OptInSource#ACTION_BY_CUSTOMER} if you are adding the contacts on their behalf
     * @param emailType         the preferred type of email
     * @param firstName         the contact's first name, 50 characters max
     * @param middleName        the contact's middle name, 50 characters max
     * @param lastName          the contact's last name, 50 characters max
     * @param jobTitle          the contact's job title, 50 characters max
     * @param companyName       the contact's company name, 50 characters max
     * @param homePhone         the contact's home phone, 50 characters max
     * @param workPhone         the contact's work phone, 50 characters max
     * @param address1          the contact's address 1, 50 characters max
     * @param address2          the contact's address 2, 50 characters max
     * @param address3          the contact's address 3, 50 characters max
     * @param city              the contact's city, 50 characters max
     * @param stateCode         the contact's state code, must be a valid US/Canada State Code and must be consistent with CountryCode. 2 characters max as listed in http://ui.constantcontact.com/CCSubscriberAddFileFormat.jsp#states
     * @param stateName         the contact's state name, 50 characters max
     * @param countryCode       the contact's country code, must be a valid two character, lower case, Country Code. See: http://constantcontact.custhelp.com/cgi-bin/constantcontact.cfg/php/enduser/std_adp.php?p_faqid=3614
     * @param countryName       the contact's country name, 50 characters max
     * @param postalCode        the contact's postal code, 25 characters max
     * @param subPostalCode     the contact's sub postal code, 25 characters max
     * @param note              customer notes field. This field should only be visible to the Customer but not to the Contact.
     * @param customFieldValues up to 15 custom field values, each custom field value is 50 characters max
     * @throws ConstantContactException in case of error
     * @api.doc <a href="http://community.constantcontact.com/t5/Documentation/Creating-a-Contact/ba-p/25059">Creating a Contact</a>
     */
@Processor
@Override
public void createContact(@Size(max = 80) String emailAddress, @Size(min = 1) List<String> contactLists, @Optional @Default("ACTION_BY_CUSTOMER") OptInSource optInSource, @Optional EmailType emailType, @Size(max = 50) @Optional String firstName, @Size(max = 50) @Optional String middleName, @Size(max = 50) @Optional String lastName, @Size(max = 50) @Optional String jobTitle, @Size(max = 50) @Optional String companyName, @Size(max = 50) @Optional String homePhone, @Size(max = 50) @Optional String workPhone, @Size(max = 50) @Optional String address1, @Size(max = 50) @Optional String address2, @Size(max = 50) @Optional String address3, @Size(max = 50) @Optional String city, @Pattern(regexp = "[A-Z]{2}") @Optional String stateCode, @Size(max = 50) @Optional String stateName, @Optional String countryCode, @Size(max = 50) @Optional String countryName, @Size(max = 25) @Optional String postalCode, @Size(max = 25) @Optional String subPostalCode, @Optional String note, @Size(max = 15) @Optional List<String> customFieldValues) throws ConstantContactException {
    String createContactRequest = new ContactRequestBuilder().setEmailAddress(emailAddress).setOptInSource(optInSource).setFirstName(firstName).setMiddleName(middleName).setLastName(lastName).setJobTitle(jobTitle).setCompanyName(companyName).setHomePhone(homePhone).setWorkPhone(workPhone).setAddress1(address1).setAddress2(address2).setAddress3(address3).setCity(city).setStateCode(stateCode).setStateName(stateName).setCountryCode(countryCode).setCountryName(companyName).setPostalCode(postalCode).setSubPostalCode(subPostalCode).setNote(note).setCustomFieldValues(customFieldValues).setContactLists(contactLists).build();
    try {
        client.doPostRequest(resources.createContact(createContactRequest));
    } catch (UnsupportedEncodingException e) {
        throw new ConstantContactException("Error while encoding the HTTP Post request body: " + createContactRequest, e);
    }
}
Example 43
Project: dev-examples-master  File: PatternBean.java View source code
/**
     * @return the text
     */
@Pattern(regexp = "[a-z].*")
public String getValue() {
    return value;
}
Example 44
Project: Resteasy-master  File: ValidationComplexInterfaceSub.java View source code
@Pattern(regexp = "[a-c]+")
public String postOverride(String s) {
    return s;
}
Example 45
Project: resthub-spring-stack-master  File: AModel.java View source code
@Pattern(regexp = ".*")
public String getField2() {
    return field2;
}
Example 46
Project: components-master  File: GraphBean.java View source code
/**
     * @return the value
     */
@Size(min = 1, message = SHORT_MSG)
@Pattern(regexp = ".*Value", message = PATTERN_MSG, groups = Group.class)
public String getValue() {
    return value;
}
Example 47
Project: prime-arquillian-master  File: PatternClientValidationConstraint.java View source code
public String getValidatorId() {
    return Pattern.class.getSimpleName();
}
Example 48
Project: arquillian-examples-master  File: HelloWorld.java View source code
@NotNull
@NotEmpty
@Pattern(regexp = "[A-Za-z]*", message = "must contain only letters")
public String getLetters() {
    return letters;
}
Example 49
Project: arquillian-showcase-master  File: Contact.java View source code
@Pattern(regexp = "^\\d{3}-\\d{3}-\\d{4}")
public String getPhone() {
    return phone;
}
Example 50
Project: jsonschema2pojo-master  File: PatternRule.java View source code
@Override
public JFieldVar apply(String nodeName, JsonNode node, JFieldVar field, Schema currentSchema) {
    if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()) {
        JAnnotationUse annotation = field.annotate(Pattern.class);
        annotation.param("regexp", node.asText());
    }
    return field;
}
Example 51
Project: richfaces-master  File: GraphBean.java View source code
/**
     * @return the value
     */
@Size(min = 1, message = SHORT_MSG)
@Pattern(regexp = ".*Value", message = PATTERN_MSG, groups = Group.class)
public String getValue() {
    return value;
}
Example 52
Project: tomee-master  File: BusinessBean.java View source code
public void doStuff(@Pattern(regexp = "valid") final String txt) {
    System.out.println("Received: " + txt);
}
Example 53
Project: hibernate-orm-master  File: Address.java View source code
@Size(max = 5)
@Pattern(regexp = "[0-9]+")
@NotNull
public String getZip() {
    return zip;
}
Example 54
Project: jboss-seam-2.3.0.Final-Hibernate.3-master  File: User.java View source code
@Id
@Size(min = 5, max = 15)
@Pattern(regexp = "^\\w*$", message = "not a valid username")
public String getUsername() {
    return username;
}
Example 55
Project: monitor-event-tap-master  File: Event.java View source code
@JsonProperty
@NotNull(message = "is missing")
@Pattern(regexp = "[A-Za-z][A-Za-z0-9]*", message = "must be alphanumeric")
public String getType() {
    return type;
}
Example 56
Project: ovirt-engine-master  File: Bond.java View source code
@Override
@Pattern(regexp = BusinessEntitiesDefinitions.BOND_NAME_PATTERN, message = "NETWORK_BOND_NAME_BAD_FORMAT")
public String getName() {
    return super.getName();
}
Example 57
Project: rakam-master  File: LdapConfig.java View source code
@NotNull
@Pattern(regexp = "^ldap(s)?://.*", message = "The URL is invalid. Expected ldaps:// or ldap://")
public String getLdapUrl() {
    return ldapUrl;
}
Example 58
Project: richfaces-qa-master  File: PatternBean.java View source code
@Pattern(regexp = "[a-z].*", message = VALIDATION_MSG)
@Override
public String getValue() {
    return value;
}
Example 59
Project: spring-xd-master  File: SyslogSourceOptionsMetadata.java View source code
@Pattern(regexp = "(3164|5424)")
public String getRfc() {
    return rfc;
}
Example 60
Project: tapestry-model-master  File: Thing2.java View source code
@Pattern(regexp = "[a-z]+")
public String getName() {
    return name;
}
Example 61
Project: jaxrs-beanvalidation-javaee6-master  File: Persons.java View source code
@GET
@Path("{id}")
public Person getPerson(@PathParam("id") @Pattern(regexp = "[0-9]+", message = "The id must be a valid number") String id) {
    return persons.get(id);
}
Example 62
Project: jaxrs-beanvalidation-javaee7-master  File: Persons.java View source code
@GET
@Path("{id}")
public Person getPerson(@PathParam("id") @NotNull(message = "The id must not be null") @Pattern(regexp = "[0-9]+", message = "The id must be a valid number") String id) {
    return persons.get(id);
}
Example 63
Project: nocket-master  File: AllComponents.java View source code
@NotNull
@Pattern(regexp = "[A-Za-z]*")
@Size(min = 2, max = 20)
public String getTextfield() {
    return textfield;
}
Example 64
Project: openjpa-master  File: ConstraintPattern.java View source code
@Pattern(regexp = "^[0-9]+$", flags = Pattern.Flag.CASE_INSENSITIVE, message = "can only contain numeric characters")
public String getZipcode() {
    return zipcode;
}
Example 65
Project: spring-reference-master  File: Order.java View source code
@NotBlank
@Length(min = 5, max = 30)
@Pattern(regexp = "[a-zA-Z\\s]*", message = "Only characters allowed")
public String getCustomer() {
    return customer;
}
Example 66
Project: anudc-master  File: AddressPart.java View source code
/**
	 * getType
	 *
	 * Get the address part type
	 *
	 * <pre>
	 * Version	Date		Developer				Description
	 * 0.1		03/10/2012	Genevieve Turner(GT)	Initial
	 * </pre>
	 * 
	 * @return the type
	 */
@NotNull(message = "Address parts must have a type")
@Pattern(regexp = "^addressLine|text|telephoneNumber|faxNumber$", message = "An address part must be of the type addressLine, text, telephoneNumber, or faxNumber")
@XmlAttribute
public String getType() {
    return type;
}
Example 67
Project: BlackboardVCPortlet-master  File: TelephonyForm.java View source code
@Pattern(regexp = "[0-9\\*\\#\\,]*", message = "{org.jasig.portlet.blackboardvcportlet.validations.pin.defaultmessage}")
@Length(max = 64)
public String getChairPIN() {
    return chairPIN;
}
Example 68
Project: bullsfirst-server-java-master  File: Person.java View source code
// ----- Getters and Setters -----
@NotNull
@Size(min = MIN_LENGTH, max = MAX_LENGTH)
@Pattern(regexp = "[a-zA-Z]+", message = "First name must only contain letters")
@Column(nullable = false, length = MAX_LENGTH)
public String getFirstName() {
    return firstName;
}
Example 69
Project: clinic-softacad-master  File: Address.java View source code
@Size(max = 5)
@Pattern(regexp = "[0-9]+")
@NotNull
public String getZip() {
    return zip;
}
Example 70
Project: hibernate-core-ogm-master  File: Address.java View source code
@Size(max = 5)
@Pattern(regexp = "[0-9]+")
@NotNull
public String getZip() {
    return zip;
}
Example 71
Project: seam-booking-ogm-master  File: User.java View source code
@Id
@NotNull
@Size(min = 3, max = 15)
@Pattern(regexp = "^\\w*$", message = "not a valid username")
public String getUsername() {
    return username;
}
Example 72
Project: shopb2b-master  File: Admin.java View source code
@NotEmpty(groups = { BaseEntity.Save.class })
@Pattern(regexp = "^[0-9a-z_A-Z\\u4e00-\\u9fa5]+$")
@Length(min = 2, max = 20)
@Column(nullable = false, updatable = false, unique = true)
public String getUsername() {
    return this.username;
}
Example 73
Project: head-master  File: Question.java View source code
@javax.validation.constraints.NotNull
@javax.validation.constraints.Pattern(regexp = "^.*[^\\s]+.*$")
@javax.validation.constraints.Size(max = 1000)
public String getText() {
    return questionDetail.getText();
}
Example 74
Project: mifos-head-master  File: Question.java View source code
@javax.validation.constraints.NotNull
@javax.validation.constraints.Pattern(regexp = "^.*[^\\s]+.*$")
@javax.validation.constraints.Size(max = 1000)
public String getText() {
    return questionDetail.getText();
}
Example 75
Project: eloquentia-master  File: Page.java View source code
@NotNull
@Size(min = 1, max = 140)
@Pattern(regexp = "[a-z0-9\\-]+([\\/]?[a-z0-9\\-])+")
public String getUri() {
    return uri;
}
Example 76
Project: jersey-master  File: ContactCard.java View source code
@Pattern(message = "{contact.wrong.phone}", regexp = "[0-9]{3,9}")
public String getPhone() {
    return phone;
}
Example 77
Project: mojarra-master  File: UserBean.java View source code
@NotNull(groups = Order.class)
@Pattern(regexp = "[0-9]+", message = "{validator.numbers}", groups = Order.class)
@Size(min = 5, max = 5, groups = Order.class)
public String getZipCode() {
    return zipCode;
}
Example 78
Project: perecoder-master  File: DataSourceSyncParameters.java View source code
@NotNull
@Pattern(regexp = TABLE_NAME_PATTERN, flags = Pattern.Flag.CASE_INSENSITIVE)
public String getTocTableName() {
    return retrieveParameter(TOC_TABLE_NAME.name, String.class);
}
Example 79
Project: spring-cloud-stream-modules-master  File: HdfsSinkProperties.java View source code
@Pattern(regexp = "(?i)(GZIP|SNAPPY|BZIP2|LZO|SLZO)", message = "codec must be one of GZIP, SNAPPY, BZIP2, LZO, or SLZO (case-insensitive)")
public String getCodec() {
    return codec;
}
Example 80
Project: tapestry5-hotel-booking-master  File: Booking.java View source code
@NotNull(message = "Credit card number is required")
@Size(min = 16, max = 16, message = "Credit card number must 16 digits long")
@Pattern(regexp = "^\\d*$", message = "Credit card number must be numeric")
public String getCreditCardNumber() {
    return creditCardNumber;
}
Example 81
Project: testkata-master  File: Booking.java View source code
@Pattern(regexp = "[0-9]{16}", message = "{invalidCreditCardPattern}")
public String getCreditCard() {
    return creditCard;
}
Example 82
Project: Annotations-master  File: JSR303Test.java View source code
/**
         * Do nothing.
         * @param text Some text
         * @return Some data
         */
@NotNull
public int foo(@NotNull @Pattern(regexp = "\\d+") @JSR303Test.NoMeaning final String text) {
    return -1;
}
Example 83
Project: gbif-api-master  File: User.java View source code
@NotNull
@Pattern(regexp = EMAIL_PATTERN)
public String getEmail() {
    return email;
}
Example 84
Project: Magazzino-master  File: Article.java View source code
@NotNull
@Size(min = 3, max = 15)
@Pattern(regexp = "^\\w*$", message = "it has to be a number")
public String getPack() {
    return pack;
}
Example 85
Project: jspxcms304-master  File: User.java View source code
@Pattern(regexp = "[F,M]")
@Length(max = 1)
@Column(name = "f_gender", length = 1)
public String getGender() {
    return this.gender;
}
Example 86
Project: glassfish-main-master  File: ConfigBeanJMXSupport.java View source code
public String pattern() {
    final javax.validation.constraints.Pattern pat = mMethod.getAnnotation(javax.validation.constraints.Pattern.class);
    return pat == null ? null : pat.regexp();
}
Example 87
Project: glassfish-master  File: ConfigBeanJMXSupport.java View source code
public String pattern() {
    final javax.validation.constraints.Pattern pat = mMethod.getAnnotation(javax.validation.constraints.Pattern.class);
    return pat == null ? null : pat.regexp();
}
Example 88
Project: Payara-master  File: ConfigBeanJMXSupport.java View source code
public String pattern() {
    final javax.validation.constraints.Pattern pat = mMethod.getAnnotation(javax.validation.constraints.Pattern.class);
    return pat == null ? null : pat.regexp();
}