javax.validation.constraints.Pattern Java Examples

The following examples show how to use javax.validation.constraints.Pattern. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Constraint.java    From para with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #2
Source File: UserController.java    From Taroco with Apache License 2.0 6 votes vote down vote up
/**
 * 发送手机验证码
 *
 * @param mobile
 * @return
 */
@RequestMapping("/smsCode/{mobile}")
@ResponseBody
public ResponseEntity<Response> smsCode(@Pattern (regexp = MOBILE_REG, message = "请输入正确的手机号")
                                        @PathVariable String mobile) {
    Object tempCode = redisRepository.get(CacheConstants.DEFAULT_CODE_KEY + mobile);
    if (tempCode != null) {
        log.error("用户:{}验证码未失效{}", mobile, tempCode);
        return ResponseEntity.ok(Response.failure("验证码: " + tempCode + " 未失效,请失效后再次申请"));
    }
    if (userTransferService.findUserByMobile(mobile) == null) {
        log.error("根据用户手机号:{}, 查询用户为空", mobile);
        return ResponseEntity.ok(Response.failure("手机号不存在"));
    }
    String code = RandomUtil.randomNumbers(6);
    log.info("短信发送请求消息中心 -> 手机号:{} -> 验证码:{}", mobile, code);
    redisRepository.setExpire(CacheConstants.DEFAULT_CODE_KEY + mobile, code, CacheConstants.DEFAULT_EXPIRE_SECONDS);
    return ResponseEntity.ok(Response.success(code));
}
 
Example #3
Source File: DeviceResource.java    From devicehive-java-server with Apache License 2.0 6 votes vote down vote up
/**
 * Implementation of <a href="http://www.devicehive.com/restful#Reference/Device/register">DeviceHive RESTful API:
 * Device: register</a> Registers a device. If device with specified identifier has already been registered, it gets
 * updated in case when valid key is provided in the authorization header.
 *
 * @param deviceUpdate In the request body, supply a Device resource. See <a href="http://www.devicehive
 *                     .com/restful#Reference/Device/register">
 * @param deviceId   Device unique identifier.
 * @return response code 201, if successful
 */
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@PreAuthorize("isAuthenticated() and hasPermission(null, 'REGISTER_DEVICE')")
@ApiOperation(value = "Register device", notes = "Registers or updates a device. For initial device registration, only 'name' property is required.")
@ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "Authorization token", required = true, dataType = "string", paramType = "header")
})
@ApiResponses({
        @ApiResponse(code = 204, message = "If successful, this method returns an empty response body."),
        @ApiResponse(code = 400, message = "If request is malformed"),
        @ApiResponse(code = 401, message = "If request is not authorized"),
        @ApiResponse(code = 403, message = "If principal doesn't have permissions")
})
Response register(
        @ApiParam(value = "Device body", required = true, defaultValue = "{}")
        @JsonPolicyApply(JsonPolicyDef.Policy.DEVICE_SUBMITTED)
        DeviceUpdate deviceUpdate,
        @ApiParam(name = "id", value = "Device unique identifier.", required = true)
        @PathParam("id")
        @Pattern(regexp = "[a-zA-Z0-9-]+", message = DEVICE_ID_CONTAINS_INVALID_CHARACTERS)
        String deviceId);
 
Example #4
Source File: BaseMatchOperator.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
/**
 * Setter function for compare comparator. Allowed values are lte, lt, eq, ne, gt,
 * gte
 * <p>
 * *
 */
@Pattern(regexp = "lte|lt|eq|ne|gt|gte", message = "Value has to be one of lte, lt, eq, ne, gt, gte")
public void setCmp(String cmp)
{
  if (cmp.equals("lt")) {
    setTypeLT();
  } else if (cmp.equals("lte")) {
    setTypeLTE();
  } else if (cmp.equals("eq")) {
    setTypeEQ();
  } else if (cmp.equals("ne")) {
    setTypeEQ();
  } else if (cmp.equals("gt")) {
    setTypeGT();
  } else if (cmp.equals("gte")) {
    setTypeGTE();
  } else {
    setTypeEQ();
  }
}
 
Example #5
Source File: AbstractBaseMatchOperator.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
/**
 * Setter function for compare type. Allowed values are lte, lt, eq, ne, gt, gte<p> *
 */
@Pattern(regexp = "lte|lt|eq|ne|gt|gte", message = "Value has to be one of lte, lt, eq, ne, gt, gte")
public void setCmp(String cmp)
{
  if (cmp.equals("lt")) {
    setTypeLT();
  } else if (cmp.equals("lte")) {
    setTypeLTE();
  } else if (cmp.equals("eq")) {
    setTypeEQ();
  } else if (cmp.equals("ne")) {
    setTypeEQ();
  } else if (cmp.equals("gt")) {
    setTypeGT();
  } else if (cmp.equals("gte")) {
    setTypeGTE();
  } else {
    setTypeEQ();
  }
}
 
Example #6
Source File: Persons.java    From jaxrs-beanvalidation-javaee7 with Apache License 2.0 6 votes vote down vote up
@POST
@Path("create")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response createPerson(
        @FormParam("id")
        @NotNull(message = "{person.id.notnull}")
        @Pattern(regexp = "[0-9]+", message = "{person.id.pattern}")
        String id,
        @FormParam("name")
        @Size(min = 2, max = 50, message = "{person.name.size}")
        String name) {
    Person person = new Person();
    person.setId(Integer.valueOf(id));
    person.setName(name);
    persons.put(id, person);
    return Response.status(Response.Status.CREATED).entity(person).build();
}
 
Example #7
Source File: JavaxValidationModule.java    From jsonschema-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Determine a given text type's pattern.
 *
 * @param member the field or method to check
 * @return specified pattern (or null)
 * @see Pattern
 */
protected String resolveStringPattern(MemberScope<?, ?> member) {
    if (member.getType().isInstanceOf(CharSequence.class)) {
        Pattern patternAnnotation = this.getAnnotationFromFieldOrGetter(member, Pattern.class, Pattern::groups);
        if (patternAnnotation != null) {
            // @Pattern annotation was found, return its (mandatory) regular expression
            return patternAnnotation.regexp();
        }
        Email emailAnnotation = this.getAnnotationFromFieldOrGetter(member, Email.class, Email::groups);
        if (emailAnnotation != null && !".*".equals(emailAnnotation.regexp())) {
            // non-default regular expression on @Email annotation should also be considered
            return emailAnnotation.regexp();
        }
    }
    return null;
}
 
Example #8
Source File: PluginInfoController.java    From front50 with Apache License 2.0 5 votes vote down vote up
@PreAuthorize("@fiatPermissionEvaluator.isAdmin()")
@RequestMapping(value = "/{id}/releases/{releaseVersion}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.NO_CONTENT)
PluginInfo deleteRelease(
    @PathVariable String id,
    @PathVariable @Pattern(regexp = PluginInfo.Release.VERSION_PATTERN) String releaseVersion) {
  return pluginInfoService.deleteRelease(id, releaseVersion);
}
 
Example #9
Source File: TestLdapConfig.java    From presto with Apache License 2.0 5 votes vote down vote up
@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)"));

    assertValidates(new LdapConfig()
            .setLdapUrl("ldap://localhost")
            .setAllowInsecure(true)
            .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://")
                    .setAllowInsecure(false),
            "urlConfigurationValid",
            "Connecting to the LDAP server without SSL enabled requires `ldap.allow-insecure=true`",
            AssertTrue.class);

    assertFailsValidation(new LdapConfig().setLdapUrl("localhost"), "ldapUrl", "Invalid LDAP server URL. Expected ldap:// or ldaps://", Pattern.class);
    assertFailsValidation(new LdapConfig().setLdapUrl("ldaps:/localhost"), "ldapUrl", "Invalid LDAP server URL. Expected ldap:// or ldaps://", Pattern.class);

    assertFailsValidation(new LdapConfig(), "ldapUrl", "may not be null", NotNull.class);
}
 
Example #10
Source File: OpenApiClientGenerator.java    From spring-openapi with MIT License 5 votes vote down vote up
private FieldSpec.Builder getStringBasedSchemaField(String fieldName, Schema innerSchema, TypeSpec.Builder typeSpecBuilder) {
	if (innerSchema.getFormat() == null) {
		ClassName stringClassName = ClassName.get(JAVA_LANG_PKG, "String");
		FieldSpec.Builder fieldBuilder = FieldSpec.builder(stringClassName, fieldName, Modifier.PRIVATE);
		if (innerSchema.getPattern() != null) {
			fieldBuilder.addAnnotation(AnnotationSpec.builder(Pattern.class)
					.addMember("regexp", "$S", innerSchema.getPattern())
					.build()
			);
		}
		if (innerSchema.getMinLength() != null || innerSchema.getMaxLength() != null) {
			AnnotationSpec.Builder sizeAnnotationBuilder = AnnotationSpec.builder(Size.class);
			if (innerSchema.getMinLength() != null) {
				sizeAnnotationBuilder.addMember("min", "$L", innerSchema.getMinLength());
			}
			if (innerSchema.getMaxLength() != null) {
				sizeAnnotationBuilder.addMember("max", "$L", innerSchema.getMaxLength());
			}
			fieldBuilder.addAnnotation(sizeAnnotationBuilder.build());
		}
		enrichWithGetSet(typeSpecBuilder, stringClassName, fieldName);
		return fieldBuilder;
	} else if (equalsIgnoreCase(innerSchema.getFormat(), "date")) {
		ClassName localDateClassName = ClassName.get(JAVA_TIME_PKG, "LocalDate");
		enrichWithGetSet(typeSpecBuilder, localDateClassName, fieldName);
		return FieldSpec.builder(localDateClassName, fieldName, Modifier.PRIVATE);
	} else if (equalsIgnoreCase(innerSchema.getFormat(), "date-time")) {
		ClassName localDateTimeClassName = ClassName.get(JAVA_TIME_PKG, "LocalDateTime");
		enrichWithGetSet(typeSpecBuilder, localDateTimeClassName, fieldName);
		return FieldSpec.builder(localDateTimeClassName, fieldName, Modifier.PRIVATE);
	}
	throw new IllegalArgumentException(String.format("Error parsing string based property [%s]", fieldName));
}
 
Example #11
Source File: DnsV1Endpoint.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("zone/cidr")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = DnsOperationDescriptions.DELETE_DNS_ZONE_BY_SUBNET, produces = MediaType.APPLICATION_JSON, notes = FreeIpaNotes.FREEIPA_NOTES,
        nickname = "deleteDnsZoneBySubnetV1")
void deleteDnsZoneBySubnet(@QueryParam("environment") @NotEmpty String environmentCrn,
        @QueryParam("subnet") @NotEmpty
        @Pattern(regexp = "(^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\/([0-9]|[1-2][0-9]|3[0-2]))$)",
                message = "Must be in valid CIDR format eg. 192.168.1.0/24") String subnet);
 
Example #12
Source File: CreateAttributeRequest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@CopyAnnotations(exclude = {CheckForNull.class, Nullable.class, Pattern.class})
@Pattern(
    regexp =
        "bool|categorical|categorical_mref|compound|date|date_time|decimal|email|enum|file|html|hyperlink|int|long|mref|one_to_many|script|string|text|xref")
@Nullable
@CheckForNull
public abstract String getType();
 
Example #13
Source File: OrganizationController.java    From c4sg-services with MIT License 5 votes vote down vote up
@CrossOrigin
   @RequestMapping(value = "/search", produces = {"application/json"}, method = RequestMethod.GET)
   @ApiOperation(value = "Find organization by keyWord", notes = " Returns a list of organizations which has the keyword in name / description / country, AND, " +
           "which has the opportunities open, AND, which is located in the selected country. " +
           "The search result is sorted by organization name in ascending order.")
   public Page<OrganizationDTO> getOrganizations(
		@ApiParam(value = "Keyword in Name or description or country of organization to return", required = false) @RequestParam(required = false) String keyWord,
           @ApiParam(value = "Countries of organization to return") @RequestParam(required = false) List<String> countries,
           @ApiParam(value = "Opportunities open in the organization") @RequestParam(required = false) Boolean open,
           @ApiParam(value = "Status of the organization to return") @Pattern(regexp = "[ADPNC]") @RequestParam(required = false) String status,
           @ApiParam(value = "Category of the organization to return") @ListEntry @RequestParam(required = false) List<String> category,
           @ApiParam(value = "Results page you want to retrieve (0..N)") @RequestParam(required = false) Integer page,
           @ApiParam(value = "Number of records per page") @RequestParam(required = false) Integer size) {
	
   	System.out.println("************** OrganizationController.getOrganizations()" 
               + ": keyWord=" + keyWord 
               + "; countries=" + countries 
               + "; open=" + open 
               + "; status=" + status 
               + "; category=" + category 
               + "; page=" + page 
               + "; size=" + size                 
               + " **************");
   	
	try {
           return organizationService.findByCriteria(keyWord, countries, open, status, category, page, size);
	} catch (Exception e) {
		throw new BadRequestException(e.getMessage());
	}
}
 
Example #14
Source File: UserController.java    From c4sg-services with MIT License 5 votes vote down vote up
@CrossOrigin
 @RequestMapping(value = "/search", method = RequestMethod.GET)
 @ApiOperation(value = "Find a user by keyWord, skills, status, role or publicFlag", notes = "Returns a collection of users")
 public Page<UserDTO> getUsers(
 		@ApiParam(value = "Keyword like name , title, introduction, state, country") @RequestParam(required=false) String keyWord,
         @ApiParam(value = "Job Titles of the user")	@RequestParam(required = false)  List<Integer> jobTitles,
         @ApiParam(value = "Skills of the User") @RequestParam(required = false) List<Integer> skills,
         @ApiParam(value = "Countries of the User") @RequestParam(required = false) List<String> countries,
         @ApiParam(value = "Status of the User") @Pattern(regexp="[AD]")  @RequestParam(required = false) String status,
 		@ApiParam(value = "User Role") @Pattern(regexp="[VOA]") @RequestParam(required = false) String role,
@ApiParam(value = "User Public Flag") @Pattern(regexp="[YN]") @RequestParam(required = false) String publishFlag,
@ApiParam(value = "Results page you want to retrieve (0..N)", required=false) @RequestParam(required=false) Integer page,
 		@ApiParam(value = "Number of records per page", required=false) @RequestParam(required=false) Integer size) {
		
 	System.out.println("************** UserController.getUsers()" 
             + ": keyWord=" + keyWord  
             + "; jobTitles=" + jobTitles  
             + "; skills=" + skills
             + "; countries=" + countries  
             + "; status=" + status  
             + "; role=" + role  
             + "; publishFlag=" + publishFlag  
             + "; page=" + page  
             + "; size=" + size                  
             + " **************");
 	
     return userService.search(keyWord, jobTitles, skills, countries, status, role, publishFlag, page, size);
 }
 
Example #15
Source File: RegistrationsController.java    From guardedbox with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @param token A registration token.
 * @return The Registration corresponding to the introduced token.
 */
@GetMapping()
public RegistrationDto getRegistration(
        @RequestParam(name = "token", required = true) @NotBlank @Pattern(regexp = ALPHANUMERIC_PATTERN) @Size(min = ALPHANUMERIC_64BYTES_LENGTH, max = ALPHANUMERIC_64BYTES_LENGTH) String token) {

    return registrationsService.getAndCheckRegistrationByToken(token);

}
 
Example #16
Source File: ConstraintViolationsMvcBindingTest.java    From krazo with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link MvcUser} with an invalid last name.
 * <p>
 * This tests a bean validation constraint applied to the field of our
 * {@link BaseUser} superclass.
 */
@Test
public void invalidMvcUserLastNameSuccess() {

    // create a user with a last name longer than 10 characters
    final MvcUser mvcUser = new MvcUser();
    mvcUser.setFirstName("John");
    mvcUser.setLastName("A last name longer than 10");

    // validate the user - we should see 1 violation due to the long last name
    final Set<ConstraintViolation<MvcUser>> errs = validator.validate(mvcUser);
    assertNotNull(errs);
    assertEquals("Expect 1 constraint violation from validation", errs.size(), 1);

    // create the metadata for our violation
    final ConstraintViolation<MvcUser> violation = errs.iterator().next();
    final ConstraintViolationMetadata metadata = ConstraintViolations.getMetadata(violation);
    assertNotNull("Violation metadata should not be null", metadata);

    // verify that lastName was the violated JAX-RS/MVC param
    final Optional<String> metadataViolatedParamName = metadata.getParamName();
    assertTrue("Violation metadata should contain the violated param name", metadataViolatedParamName.isPresent());
    assertEquals("Metadata violated param should be 'lastName'", "lastName", metadataViolatedParamName.get());

    // lastly, test for our MVC-ish annotations based on our constraint violation
    // metadata. we should find @MvcBinding from the getter method for lastName,
    // and @FormParam from the setter. Also test for annotations that we expect to
    // NOT be present
    assertTrue("@MvcBinding should be found on 'lastName'", metadata.hasAnnotation(MvcBinding.class));
    assertTrue("@FormParam should be found on 'lastName'", metadata.hasAnnotation(FormParam.class));
    assertFalse("@Pattern should not be found on 'lastName'", metadata.hasAnnotation(Pattern.class));

}
 
Example #17
Source File: ConstraintViolationsMvcBindingTest.java    From krazo with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link MvcUser} with an invalid first name.
 * <p>
 * This tests a bean validation constraint applied to the getter method of
 * the field in the {@link BaseUser} superclass.
 */
@Test
public void invalidMvcUserFirstNameSuccess() {

    // create a user with a first name longer than 10 characters
    final MvcUser mvcUser = new MvcUser();
    mvcUser.setFirstName("A first name that is longer than 10");
    mvcUser.setLastName("Doe");

    // validate the user - we should see 1 violation due to the long first name
    final Set<ConstraintViolation<MvcUser>> errs = validator.validate(mvcUser);
    assertNotNull(errs);
    assertEquals("Expect 1 constraint violation from validation", errs.size(), 1);

    // create the metadata for our violation
    final ConstraintViolation<MvcUser> violation = errs.iterator().next();
    final ConstraintViolationMetadata metadata = ConstraintViolations.getMetadata(violation);
    assertNotNull("Violation metadata should not be null", metadata);

    // verify that firstName was the violated JAX-RS/MVC param
    final Optional<String> metadataViolatedParamName = metadata.getParamName();
    assertTrue("Violation metadata should contain the violated param name", metadataViolatedParamName.isPresent());
    assertEquals("Metadata violated param should be 'firstName'", "firstName", metadataViolatedParamName.get());

    // lastly, test for our MVC-ish annotations based on our constraint violation
    // metadata. we should find @MvcBinding from the getter method for firstName,
    // and @FormParam from the setter. Also test for annotations that we expect to
    // NOT be present
    assertTrue("@MvcBinding should be found on 'firstName'", metadata.hasAnnotation(MvcBinding.class));
    assertTrue("@FormParam should be found on 'firstName'", metadata.hasAnnotation(FormParam.class));
    assertFalse("@Pattern should not be found on 'firstName'", metadata.hasAnnotation(Pattern.class));

}
 
Example #18
Source File: Persons.java    From jaxrs-beanvalidation-javaee7 with Apache License 2.0 5 votes vote down vote up
@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 #19
Source File: AccountServiceExposure.java    From swagger-maven-plugin with MIT License 5 votes vote down vote up
@PUT
@Path("{regNo}-{accountNo}")
@Produces({"application/hal+json"})
@Consumes(MediaType.APPLICATION_JSON)
@Operation(description = "Create new or update existing account",
        responses = @ApiResponse(responseCode = "404", description = "No updating possible"))
public Response createOrUpdate(@PathParam("regNo") @Pattern(regexp = "^[0-9]{4}$") String regNo,
                               @PathParam("accountNo") @Pattern(regexp = "^[0-9]+$") String accountNo,
                               @Valid AccountUpdateRepresentation account,
                               @Context UriInfo uriInfo, @Context Request request) {
    return Response.ok().build();
}
 
Example #20
Source File: ConstraintViolationsMvcBindingTest.java    From ozark with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link MvcUser} with an invalid first name.
 * <p>
 * This tests a bean validation constraint applied to the getter method of
 * the field in the {@link BaseUser} superclass.
 */
@Test
public void invalidMvcUserFirstNameSuccess() {

    // create a user with a first name longer than 10 characters
    final MvcUser mvcUser = new MvcUser();
    mvcUser.setFirstName("A first name that is longer than 10");
    mvcUser.setLastName("Doe");

    // validate the user - we should see 1 violation due to the long first name
    final Set<ConstraintViolation<MvcUser>> errs = validator.validate(mvcUser);
    assertNotNull(errs);
    assertEquals("Expect 1 constraint violation from validation", errs.size(), 1);

    // create the metadata for our violation
    final ConstraintViolation<MvcUser> violation = errs.iterator().next();
    final ConstraintViolationMetadata metadata = ConstraintViolations.getMetadata(violation);
    assertNotNull("Violation metadata should not be null", metadata);

    // verify that firstName was the violated JAX-RS/MVC param
    final Optional<String> metadataViolatedParamName = metadata.getParamName();
    assertTrue("Violation metadata should contain the violated param name", metadataViolatedParamName.isPresent());
    assertEquals("Metadata violated param should be 'firstName'", "firstName", metadataViolatedParamName.get());

    // lastly, test for our MVC-ish annotations based on our constraint violation
    // metadata. we should find @MvcBinding from the getter method for firstName,
    // and @FormParam from the setter. Also test for annotations that we expect to
    // NOT be present
    assertTrue("@MvcBinding should be found on 'firstName'", metadata.hasAnnotation(MvcBinding.class));
    assertTrue("@FormParam should be found on 'firstName'", metadata.hasAnnotation(FormParam.class));
    assertFalse("@Pattern should not be found on 'firstName'", metadata.hasAnnotation(Pattern.class));

}
 
Example #21
Source File: ConstraintViolationsMvcBindingTest.java    From ozark with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link MvcUser} with an invalid last name.
 * <p>
 * This tests a bean validation constraint applied to the field of our
 * {@link BaseUser} superclass.
 */
@Test
public void invalidMvcUserLastNameSuccess() {

    // create a user with a last name longer than 10 characters
    final MvcUser mvcUser = new MvcUser();
    mvcUser.setFirstName("John");
    mvcUser.setLastName("A last name longer than 10");

    // validate the user - we should see 1 violation due to the long last name
    final Set<ConstraintViolation<MvcUser>> errs = validator.validate(mvcUser);
    assertNotNull(errs);
    assertEquals("Expect 1 constraint violation from validation", errs.size(), 1);

    // create the metadata for our violation
    final ConstraintViolation<MvcUser> violation = errs.iterator().next();
    final ConstraintViolationMetadata metadata = ConstraintViolations.getMetadata(violation);
    assertNotNull("Violation metadata should not be null", metadata);

    // verify that lastName was the violated JAX-RS/MVC param
    final Optional<String> metadataViolatedParamName = metadata.getParamName();
    assertTrue("Violation metadata should contain the violated param name", metadataViolatedParamName.isPresent());
    assertEquals("Metadata violated param should be 'lastName'", "lastName", metadataViolatedParamName.get());

    // lastly, test for our MVC-ish annotations based on our constraint violation
    // metadata. we should find @MvcBinding from the getter method for lastName,
    // and @FormParam from the setter. Also test for annotations that we expect to
    // NOT be present
    assertTrue("@MvcBinding should be found on 'lastName'", metadata.hasAnnotation(MvcBinding.class));
    assertTrue("@FormParam should be found on 'lastName'", metadata.hasAnnotation(FormParam.class));
    assertFalse("@Pattern should not be found on 'lastName'", metadata.hasAnnotation(Pattern.class));

}
 
Example #22
Source File: PluginInfoController.java    From front50 with Apache License 2.0 5 votes vote down vote up
@PreAuthorize("@fiatPermissionEvaluator.isAdmin()")
@RequestMapping(value = "/{id}/releases/{releaseVersion}", method = RequestMethod.PUT)
PluginInfo.Release preferReleaseVersion(
    @PathVariable String id,
    @PathVariable @Pattern(regexp = PluginInfo.Release.VERSION_PATTERN) String releaseVersion,
    @RequestParam(value = "preferred") boolean preferred) {
  return pluginInfoService.preferReleaseVersion(id, releaseVersion, preferred);
}
 
Example #23
Source File: PatternValid.java    From japi with MIT License 5 votes vote down vote up
private String getDes(String str){
    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("[a-z]{6,7}\\s*[=]\\s*");
    Matcher matcher = pattern.matcher(str);
    boolean isFindRegexp = false;
    int beginIndex = -1,endIndex = -1,count = 0;
    while (matcher.find()) {
        count++;
        if (!isFindRegexp && matcher.group().matches("message\\s*[=]\\s*")) {
            isFindRegexp = true;
            beginIndex = matcher.end();
            continue;
        }
        if(isFindRegexp){
            endIndex = matcher.start();
            break;
        }
    }
    if(count==1){
        return str.substring(beginIndex+1,str.lastIndexOf("\""));
    }else{
        if(endIndex==-1){
            return str.substring(beginIndex+1,str.lastIndexOf("\""));
        }else{
            str = str.substring(beginIndex,endIndex);
            return str.substring(1,str.lastIndexOf("\""));
        }
    }
}
 
Example #24
Source File: BeanValidationProcessor.java    From AngularBeans with GNU Lesser General Public License v3.0 5 votes vote down vote up
@PostConstruct
public void init() {
	validationAnnotations = new HashSet<>();
	validationAnnotations.addAll(Arrays.asList(NotNull.class, Size.class,
			Pattern.class, DecimalMin.class, DecimalMax.class, Min.class,
			Max.class));

}
 
Example #25
Source File: PatternAnnotationHandler.java    From easy-random with MIT License 5 votes vote down vote up
@Override
public Randomizer<?> getRandomizer(Field field) {
    Class<?> fieldType = field.getType();
    Pattern patternAnnotation = ReflectionUtils
            .getAnnotation(field, Pattern.class);

    final String regex = patternAnnotation.regexp();
    if (fieldType.equals(String.class)) {
        return new RegularExpressionRandomizer(regex, random.nextLong());
    }
    return null;
}
 
Example #26
Source File: PatternPropertyValidator.java    From dolphin-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(final Pattern annotation) {
    Assert.requireNonNull(annotation, "annotation");

    int flags = combineFlags(annotation.flags());
    pattern = java.util.regex.Pattern.compile(annotation.regexp(), flags);
}
 
Example #27
Source File: PatternPropertyValidator.java    From dolphin-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Combines a given set of javax.validation.constraints.Pattern.Flag instances into one bitmask suitable for
 * java.util.regex.Pattern consumption.
 *
 * @param flags - list of javax.validation.constraints.Pattern.Flag instances to combine
 * @return combined bitmask for regex flags
 */
private int combineFlags(final Pattern.Flag[] flags) {
    int combined = 0;
    for (Pattern.Flag f : flags) {
        combined |= f.getValue();
    }
    return combined;
}
 
Example #28
Source File: LabelRequest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@NotEmpty(message = "labelRequest.key.required")
@Size(max = 50, message = "labelRequest.key.invalidSize")
@Pattern(regexp = "^[a-zA-Z0-9_]*$", message = "labelRequest.key.invalidCharacters")
@Override
public String getKey() {
    return super.getKey();
}
 
Example #29
Source File: Persons.java    From jaxrs-beanvalidation-javaee7 with Apache License 2.0 5 votes vote down vote up
@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 #30
Source File: Constraint.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new map representing a {@link Pattern} validation constraint.
 * @param regex a regular expression
 * @return a map
 */
static Map<String, Object> patternPayload(final Object regex) {
	if (regex == null) {
		return null;
	}
	Map<String, Object> payload = new LinkedHashMap<>();
	payload.put("value", regex);
	payload.put("message", MSG_PREFIX + VALIDATORS.get(Pattern.class));
	return payload;
}