Java 类javax.validation.constraints.Pattern 实例源码
项目:aml
文件:AbstractGenerator.java
private void addJsr303Annotations(final INamedParam parameter,
final JVar argumentVariable) {
if (isNotBlank(parameter.getPattern())) {
JAnnotationUse patternAnnotation = argumentVariable.annotate(Pattern.class);
patternAnnotation.param("regexp", parameter.getPattern());
}
final Integer minLength = parameter.getMinLength();
final Integer maxLength = parameter.getMaxLength();
if ((minLength != null) || (maxLength != null)) {
final JAnnotationUse sizeAnnotation = argumentVariable
.annotate(Size.class);
if (minLength != null) {
sizeAnnotation.param("min", minLength);
}
if (maxLength != null) {
sizeAnnotation.param("max", maxLength);
}
}
final BigDecimal minimum = parameter.getMinimum();
if (minimum != null) {
addMinMaxConstraint(parameter, "minimum", Min.class, minimum,
argumentVariable);
}
final BigDecimal maximum = parameter.getMaximum();
if (maximum != null) {
addMinMaxConstraint(parameter, "maximum", Max.class, maximum,
argumentVariable);
}
if (parameter.isRequired()) {
argumentVariable.annotate(NotNull.class);
}
}
项目:c4sg-services
文件:UserController.java
@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 = "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
+ "; status=" + status
+ "; role=" + role
+ "; publishFlag=" + publishFlag
+ "; page=" + page
+ "; size=" + size
+ " **************");
return userService.search(keyWord, jobTitles, skills, status, role, publishFlag, page, size);
}
项目:c4sg-services
文件:ProjectController.java
@CrossOrigin
@RequestMapping(value = "/search", method = RequestMethod.GET)
@ApiOperation(value = "Find ACTIVE project by keyWord or skills", notes = "Returns a collection of active projects")
public Page<ProjectDTO> getProjects(
@ApiParam(value = "Keyword of the project") @RequestParam(required=false) String keyWord,
@ApiParam(value = "Job Titles of the project") @RequestParam(required = false) List<Integer> jobTitles,
@ApiParam(value = "Skills of the project") @RequestParam(required = false) List<Integer> skills,
@ApiParam(value = "Status of the project") @Pattern(regexp="[AC]") @RequestParam(required = false) String status,
@ApiParam(value = "Location of the project") @Pattern(regexp="[YN]") @RequestParam(required = false) String remote,
@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("************** ProjectController.getProjects()"
+ ": keyWord=" + keyWord
+ "; jobTitles=" + jobTitles
+ "; skills=" + skills
+ "; status=" + status
+ "; remote=" + remote
+ "; page=" + page
+ "; size=" + size
+ " **************");
return projectService.search(keyWord, jobTitles, skills, status, remote, page, size);
}
项目:randomito-all
文件:PatternAnnotationPostProcessor.java
@Override
public Object process(AnnotationInfo ctx, Object value) throws Exception {
if (!ctx.isAnnotationPresent(Pattern.class)) {
return value;
}
// String regexp = ctx.getAnnotation(Pattern.class).regexp();
// Generex generex = new Generex(regexp);
// for (int i = 0; i < REGEX_GENERATION_TRY; i++) {
// try {
// return generex.random();
// } catch (StackOverflowError e) {
// //TODO: fix Generex#prepareRandom() causing stackoverflow
// // known bug in Generex lib...let's try again.
// }
// }
// System.out.println("failed to generate regex: " + regexp);
return value;
}
项目:geeMVC-Java-MVC-Framework
文件:PatternValidationAdapter.java
@Override
public void validate(Pattern patternAnnotation, String name, ValidationContext validationCtx, Errors e) {
Object value = validationCtx.value(name);
if (value == null || Str.isEmpty(patternAnnotation.regexp()))
return;
String pattern = patternAnnotation.regexp();
Pattern.Flag[] flags = patternAnnotation.flags();
int flagBits = 0;
for (Pattern.Flag flag : flags) {
flagBits |= flag.getValue();
}
java.util.regex.Pattern regexPattern = java.util.regex.Pattern.compile(pattern, flagBits);
Matcher m = regexPattern.matcher(String.valueOf(value));
if (!m.matches())
e.add(name, patternAnnotation.message());
}
项目:apex-malhar
文件:AbstractBaseMatchOperator.java
/**
* 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();
}
}
项目:apex-malhar
文件:BaseMatchOperator.java
/**
* 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();
}
}
项目:soabase
文件:SoaConfiguration.java
@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;
}
项目:motech
文件:FieldProcessor.java
private String getValidationValue(String displayName, Annotation annotation) {
String property;
if (hasProperty(annotation, VALUE)) {
property = VALUE;
} else if (annotation instanceof Pattern) {
property = REGEXP;
} else if (annotation instanceof Size) {
switch (displayName) {
case "mds.field.validation.minLength":
property = MIN;
break;
case "mds.field.validation.maxLength":
property = MAX;
break;
default:
throw new IllegalArgumentException(
"The @Size annotation can be used only on fields with String type."
);
}
} else {
throw new IllegalArgumentException("Not found correct property in annotation: " + annotation);
}
return getAnnotationValue(annotation, property);
}
项目:gwt-bean-validators
文件:EmailValidator.java
@Override
public void initialize(final Email emailAnnotation) {
super.initialize(emailAnnotation);
final Pattern.Flag[] flags = emailAnnotation.flags();
final StringBuilder flagString = new StringBuilder();
for (final Pattern.Flag flag : flags) {
flagString.append(this.toString(flag));
}
// we only apply the regexp if there is one to apply
if (!".*".equals(emailAnnotation.regexp()) || emailAnnotation.flags().length > 0) {
try {
this.pattern = RegExp.compile(emailAnnotation.regexp(), flagString.toString());
} catch (final RuntimeException e) {
throw LOG.getInvalidRegularExpressionException(e);
}
}
}
项目:nest-old
文件:TestObject.java
@Test
public void testMatchPattern() {
Set<ConstraintViolation<ObjectWithValidation>> violations = validator.validate(obj, Pattern.class);
assertNotNull(violations);
assertEquals(violations.size(), 1);
if (runPeformance) {
long time = System.currentTimeMillis();
for (int index = 0; index < 10000; index++) {
validator.validate(obj, Pattern.class);
}
long used = System.currentTimeMillis() - time;
System.out.println("Hibernate Validator [MatchPattern] check used " + used + "ms, avg. " + ((double) used)
/ 10000 + "ms.");
}
}
项目:splinter
文件:PostResource.java
@POST
@Path("/{id}/edit")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Template(name= "/post/single")
public Response editPostAction(@PathParam("id") int id,
@FormParam("title")
@Pattern(regexp = "^(?!\\s*$).+", message = "empty string") String title,
@FormParam("content")
@Pattern(regexp = "^(?!\\s*$).+", message = "empty string") String content){
Post post=Post.findById(id);
post.setTitle(title);
post.setContent(content);
post.saveIt();
URI targetURIForRedirection = URI.create(RESOURCE_PATH + post.getId());
return Response.seeOther(targetURIForRedirection).build();
}
项目:para
文件:Constraint.java
/**
* 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;
}
};
}
}
项目:cananolab
文件:CustomPatternValidator.java
public void initialize(PatternMatchIfNotNullNotEmpty parameters) {
Pattern.Flag flags[] = parameters.flags();
int intFlag = 0;
for ( Pattern.Flag flag : flags ) {
intFlag = intFlag | flag.getValue();
}
String regexp = resolveRegexp(parameters);
messageSource = parameters.messageSource();
messageKey = parameters.messageKey();
try {
pattern = java.util.regex.Pattern.compile(regexp, intFlag );
}
catch ( PatternSyntaxException e ) {
throw new IllegalArgumentException( "Invalid regular expression.", e );
}
}
项目:jaxrs-beanvalidation-javaee7
文件:Persons.java
@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();
}
项目:jaxrs-beanvalidation-javaee7
文件:Persons.java
@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();
}
项目:devicehive-java-server
文件:DeviceResource.java
/**
* 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);
项目:GitHub
文件:PatternRule.java
@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;
}
项目:REST-Web-Services
文件:UserSearchServiceImpl.java
/**
* {@inheritDoc}
*/
@Override
public User getUserByUsername(
@NotBlank @Pattern(regexp = "[a-zA-Z0-9_-]{6,36}") final String username
) throws ResourceNotFoundException {
log.info("Called with username {}", username);
return this.userRepository.findByUsernameIgnoreCaseAndEnabledTrue(username)
.map(ServiceUtils::toUserDto)
.orElseThrow(() -> new ResourceNotFoundException("No user found with username " + username));
}
项目:REST-Web-Services
文件:UserSearchServiceImpl.java
/**
* {@inheritDoc}
*/
@Override
public boolean existsUserByUsername(
@NotBlank @Pattern(regexp = "[a-zA-Z0-9_-]{6,36}") final String username
) {
log.info("Called with username {}", username);
return this.userRepository.existsByUsernameIgnoreCase(username);
}
项目:REST-Web-Services
文件:UserSearchServiceImpl.java
/**
* {@inheritDoc}
*/
@Override
public String getUserPassword(
@NotBlank @Pattern(regexp = "[a-zA-Z0-9_-]{6,36}") final String username
) throws ResourceNotFoundException {
log.info("Called with username {}", username);
return this.userRepository.findByUsernameIgnoreCaseAndEnabledTrue(username)
.map(UserEntity::getPassword)
.orElseThrow(() -> new ResourceNotFoundException("No user found with username " + username));
}
项目:spring-rest-commons-options
文件:ValidatorFactory.java
private static Optional<Validator> getValidator(Annotation annotation) {
Validator validator = null;
if (isValidable(annotation)) {
if (annotation instanceof Range || annotation instanceof Length) {
validator = new RangeValidator(annotation);
} else if (annotation instanceof Pattern) {
validator = new PatternValidator(annotation);
} else {
validator = new DefaultValidator(annotation);
}
}
return Optional.ofNullable(validator);
}
项目:c4sg-services
文件:OrganizationController.java
@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", required = false) @RequestParam(required = false) List<String> countries,
@ApiParam(value = "Opportunities open in the organization", required = false) @RequestParam(required = false) Boolean open,
@ApiParam(value = "Status of the organization to return", required = false) @Pattern(regexp="[ADPNC]") @RequestParam(required = false) String status,
@ApiParam(value = "Category of the organization to return", required = false) @ListEntry @RequestParam(required = false) List<String> category,
@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("************** 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());
}
}
项目:minijax
文件:MinijaxConstraintDescriptor.java
private static MinijaxConstraintDescriptor<Pattern> buildPatternValidator(final Pattern pattern, final Class<?> valueClass) {
if (CharSequence.class.isAssignableFrom(valueClass)) {
return new MinijaxConstraintDescriptor<>(pattern, new PatternValidator(pattern));
}
throw new ValidationException("Unsupported type for @Pattern annotation: " + valueClass);
}
项目:mid-tier
文件:VirtualAccountServiceExposure.java
@GET
@Path("{virtualAccountNumber}")
@Produces({"application/hal+json", "application/hal+json;concept=virtualaccount;v=1", "application/hal+json;concept=virtualaccount;v=2"})
@ApiOperation(value = "gets the information from a single position", response = VirtualAccountRepresentation.class,
authorizations = {
@Authorization(value = "oauth2", scopes = {}),
@Authorization(value = "oauth2-cc", scopes = {}),
@Authorization(value = "oauth2-ac", scopes = {}),
@Authorization(value = "oauth2-rop", scopes = {}),
@Authorization(value = "Bearer")
},
extensions = {@Extension(name = "roles", properties = {
@ExtensionProperty(name = "customer", value = "customer allows getting own information"),
@ExtensionProperty(name = "advisor", value = "advisor allows getting all information")}
)},
produces = "application/hal+json, application/hal+json;concept=virtualaccount;v=1, application/hal+json;concept=virtualaccount;v=2",
notes = "obtain a single customer back in a default projection, which is VirtualAccount version 2" +
" Supported projections and versions are:" +
" VirtualAccount in version1 and VirtualAccount in version 2" +
" The format of the default version is .... - The Accept Header is not marked as required in the " +
"swagger - but it is needed - we are working on a solution to that", nickname = "getVirtualAccount")
@ApiResponses(value = {
@ApiResponse(code = 404, message = "virtualaccount not found.")
})
public Response get(@Context UriInfo uriInfo, @Context Request request,
@PathParam("virtualAccountNumber") @Pattern(regexp = "^[0-9]*$") String virtualAccountNumber,
@HeaderParam("Accept") String accept) {
LOGGER.info("Default version of virtualaccount collected");
return accountProducers.getOrDefault(accept, this::handleUnsupportedContentType)
.getResponse(uriInfo, request, virtualAccountNumber);
}
项目:mid-tier
文件:CustomerServiceExposure.java
@GET
@Path("{customerNo}")
@Produces({"application/hal+json", "application/hal+json;concept=customer;v=1", "application/hal+json;concept=customer;v=2"})
@ApiOperation(value = "gets the information from a single customer", response = CustomerRepresentation.class,
authorizations = {
@Authorization(value = "oauth2", scopes = {}),
@Authorization(value = "oauth2-cc", scopes = {}),
@Authorization(value = "oauth2-ac", scopes = {}),
@Authorization(value = "oauth2-rop", scopes = {}),
@Authorization(value = "Bearer")
},
extensions = {@Extension(name = "roles", properties = {
@ExtensionProperty(name = "customer", value = "customer allows getting own information"),
@ExtensionProperty(name = "advisor", value = "advisor allows getting all information")}
)},
produces = "application/hal+json, application/hal+json;concept=customer;v=1, application/hal+json;concept=customer;v=2",
notes = "obtain a single customer back in a default projection, which is Customer version 2" +
" Supported projections and versions are:" +
" Customer in version1 and Customer in version 2" +
" The format of the default version is .... - The Accept Header is not marked as required in the " +
"swagger - but it is needed - we are working on a solution to that", nickname = "getCustomer")
@ApiResponses(value = {
@ApiResponse(code = 404, message = "No customer found.")
})
public Response get(@Context UriInfo uriInfo, @Context Request request,
@PathParam("customerNo") @Pattern(regexp = "^[0-9]{10}$") String customerNo,
@HeaderParam("Accept") String accept) {
LOGGER.info("Default version of customer collected");
return customerProducers.getOrDefault(accept, this::handleUnsupportedContentType).getResponse(uriInfo, request, customerNo);
}
项目:mid-tier
文件:AccountServiceExposure.java
@GET
@Path("{regNo}-{accountNo}")
@Produces({"application/hal+json", "application/hal+json;concept=account;v=1", "application/hal+json;concept=account;v=2"})
@ApiOperation(value = "gets the information from a single account", response = AccountRepresentation.class,
authorizations = {
@Authorization(value = "oauth2", scopes = {}),
@Authorization(value = "oauth2-cc", scopes = {}),
@Authorization(value = "oauth2-ac", scopes = {}),
@Authorization(value = "oauth2-rop", scopes = {}),
@Authorization(value = "Bearer")
},
extensions = {@Extension(name = "roles", properties = {
@ExtensionProperty(name = "customer", value = "customer allows getting own account"),
@ExtensionProperty(name = "advisor", value = "advisor allows getting every account")}
)},
produces = "application/hal+json, application/hal+json;concept=account;v=1, application/hal+json;concept=account;v=2",
notes = "obtain a single account back in a default projection, which is Account version 2" +
" Supported projections and versions are:" +
" AccountSparse in version1 and Account in version 2" +
" The format of the default version is .... - The Accept Header is not marked as required in the " +
"swagger - but it is needed - we are working on a solution to that", nickname = "getAccount")
@ApiResponses(value = {
@ApiResponse(code = 404, message = "No account found.")
})
public Response get(@Context UriInfo uriInfo, @Context Request request,
@PathParam("regNo") @Pattern(regexp = "^[0-9]{4}$") String regNo,
@PathParam("accountNo") @Pattern(regexp = "^[0-9]+$") String accountNo,
@HeaderParam("Accept") String accept) {
LOGGER.info("Default version of account collected");
return accountProducers.getOrDefault(accept, this::handleUnsupportedContentType).getResponse(uriInfo, request, regNo, accountNo);
}
项目:mid-tier
文件:LocationServiceExposure.java
@GET
@Path("{latitude}-{longitude}")
@Produces({"application/hal+json", "application/hal+json;concept=location;v=1", "application/hal+json;concept=location;v=2"})
@ApiOperation(value = "gets the information from a single position", response = LocationRepresentation.class,
authorizations = {
@Authorization(value = "oauth2", scopes = {}),
@Authorization(value = "oauth2-cc", scopes = {}),
@Authorization(value = "oauth2-ac", scopes = {}),
@Authorization(value = "oauth2-rop", scopes = {}),
@Authorization(value = "Bearer")
},
extensions = {@Extension(name = "roles", properties = {
@ExtensionProperty(name = "customer", value = "customer allows getting own information"),
@ExtensionProperty(name = "advisor", value = "advisor allows getting all information")}
)},
produces = "application/hal+json, application/hal+json;concept=location;v=1, application/hal+json;concept=location;v=2",
notes = "obtain a single customer back in a default projection, which is Location version 2" +
" Supported projections and versions are:" +
" Location in version1 and Location in version 2" +
" The format of the default version is .... - The Accept Header is not marked as required in the " +
"swagger - but it is needed - we are working on a solution to that", nickname = "getLocation")
@ApiResponses(value = {
@ApiResponse(code = 404, message = "location not found.")
})
public Response get(@Context UriInfo uriInfo, @Context Request request,
@PathParam("latitude") @Pattern(regexp = "^[0-9]+.[0-9]+,[0-9]*$") String latitude,
@PathParam("longitude") @Pattern(regexp = "^[0-9]+.[0-9]+,[0-9]*$") String longitude,
@HeaderParam("Accept") String accept) {
LOGGER.info("Default version of location collected");
return locationProducers.getOrDefault(accept, this::handleUnsupportedContentType)
.getResponse(uriInfo, request, latitude, longitude);
}
项目:Hibernate_Validation_API_Annotation_Simple
文件:Employee.java
@Column(length=15)
@Type(type="string")
@NotNull(message="Name is Required")
@Size(min=4,max=10,message="Name Must be in 5 to 10 chars only")
@Pattern(regexp="ps[A-Z]*",message="Name Must be Starts with ps")
public String getName() {
return name;
}
项目:oma-riista-web
文件:Municipality.java
@Id
@Override
@Pattern(regexp = "^\\d{0,3}$")
@Access(value = AccessType.PROPERTY)
@Column(name = "official_code", length = 3, nullable = false, updatable = false)
public String getId() {
return id;
}
项目:oma-riista-web
文件:ExternalAuthenticationController.java
@RequestMapping(value = "/api/v1/export/account",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> validate(
@RequestParam @NotBlank String username,
@RequestParam @NotBlank String password,
@RequestParam @Pattern(regexp = Patterns.IPV4) String remoteAddress,
@RequestParam(required = false) @Pattern(regexp = "\\d+") String otp,
@RequestParam(required = false) Boolean otpRequired) {
LOG.info("Received request for /api/v1/export/account: username={} otpRequired={} otp={} remoteAddress={}",
username, otpRequired, otp, remoteAddress);
final ExternalAuthenticationRequest authenticationRequest = new ExternalAuthenticationRequest();
authenticationRequest.setUsername(username);
authenticationRequest.setPassword(password);
authenticationRequest.setRemoteAddress(remoteAddress);
authenticationRequest.setOtp(otp);
authenticationRequest.setRequireOtp(otpRequired != null ? otpRequired : false);
try {
return checkExternalAuthenticationFeature.checkAuthentication(authenticationRequest);
} catch (Exception ex) {
LOG.error("External authentication failed for username=" + username, ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ExternalAuthenticationFailure.unknownError());
}
}
项目:my-paper
文件:Member.java
/**
* 获取用户名
*
* @return 用户名
*/
@NotEmpty(groups = Save.class)
@Pattern(regexp = "^[0-9a-z_A-Z\\u4e00-\\u9fa5]+$")
@Column(nullable = false, updatable = false, unique = true, length = 100)
public String getUsername() {
return username;
}
项目:my-paper
文件:Member.java
/**
* 获取密码
*
* @return 密码
*/
@NotEmpty(groups = Save.class)
@Pattern(regexp = "^[^\\s&\"<>]+$")
@Column(nullable = false)
public String getPassword() {
return password;
}
项目:my-paper
文件:Admin.java
/**
* 获取用户名
*
* @return 用户名
*/
@NotEmpty(groups = Save.class)
@Pattern(regexp = "^[0-9a-z_A-Z\\u4e00-\\u9fa5]+$")
@Length(min = 2, max = 20)
@Column(nullable = false, updatable = false, unique = true, length = 100)
public String getUsername() {
return username;
}
项目:my-paper
文件:Admin.java
/**
* 获取密码
*
* @return 密码
*/
@NotEmpty(groups = Save.class)
@Pattern(regexp = "^[^\\s&\"<>]+$")
@Length(min = 4, max = 20)
@Column(nullable = false)
public String getPassword() {
return password;
}
项目:my-paper
文件:Product.java
/**
* 获取编号
*
* @return 编号
*/
@JsonProperty
@Field(store = Store.YES, index = Index.UN_TOKENIZED)
@Pattern(regexp = "[\\s\\S]*")
@Length(max = 100)
@Column(nullable = false, unique = true, length = 100)
public String getSn() {
return sn;
}
项目:aml
文件:ParameterValidationGenerator.java
protected void addValidation(final INamedParam parameter,
final JVar argumentVariable) {
if (isNotBlank(parameter.getPattern())) {
JAnnotationUse patternAnnotation = argumentVariable.annotate(Pattern.class);
patternAnnotation.param("regexp", parameter.getPattern());
}
final Integer minLength = parameter.getMinLength();
final Integer maxLength = parameter.getMaxLength();
if ((minLength != null) || (maxLength != null)) {
final JAnnotationUse sizeAnnotation = argumentVariable
.annotate(Size.class);
if (minLength != null) {
sizeAnnotation.param("min", minLength);
}
if (maxLength != null) {
sizeAnnotation.param("max", maxLength);
}
}
final BigDecimal minimum = parameter.getMinimum();
if (minimum != null) {
addMinMaxConstraint(parameter, "minimum", Min.class, minimum,
argumentVariable);
}
final BigDecimal maximum = parameter.getMaximum();
if (maximum != null) {
addMinMaxConstraint(parameter, "maximum", Max.class, maximum,
argumentVariable);
}
if (parameter.isRequired()) {
argumentVariable.annotate(NotNull.class);
}
}
项目:deprecated-mod-metadata
文件:InstanceStorageAPI.java
@Override
public void deleteInstanceStorageInstances(
@DefaultValue("en") @Pattern(regexp = "[a-zA-Z]{2}") String lang,
Map<String, String> okapiHeaders,
Handler<AsyncResult<Response>> asyncResultHandler,
Context vertxContext) throws Exception {
String tenantId = okapiHeaders.get(TENANT_HEADER);
if (blankTenantId(tenantId)) {
badRequestResult(asyncResultHandler, BLANK_TENANT_MESSAGE);
return;
}
vertxContext.runOnContext(v -> {
try {
PostgresClient postgresClient = PostgresClient.getInstance(
vertxContext.owner(), TenantTool.calculateTenantId(tenantId));
postgresClient.mutate(String.format("TRUNCATE TABLE %s_%s.instance",
tenantId, "inventory_storage"),
reply -> {
asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(
InstanceStorageResource.DeleteInstanceStorageInstancesResponse
.noContent().build()));
});
}
catch(Exception e) {
asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(
InstanceStorageResource.DeleteInstanceStorageInstancesResponse
.withPlainInternalServerError(e.getMessage())));
}
});
}
项目:japi
文件:PatternValid.java
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("\""));
}
}
}
项目:AngularBeans
文件:BeanValidationProcessor.java
@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));
}