Search in sources :

Example 1 with NotEmpty

use of javax.validation.constraints.NotEmpty in project podam by devopsfolks.

the class TypeManufacturerUtil method findAttributeStrategy.

/**
 * It returns a {@link AttributeStrategy} if one was specified in
 * annotations, or {@code null} otherwise.
 *
 * @param strategy
 *            The data provider strategy
 * @param annotations
 *            The list of annotations, irrelevant annotations will be removed
 * @param attributeType
 *            Type of attribute expected to be returned
 * @return {@link AttributeStrategy}, if {@link PodamStrategyValue} or bean
 *         validation constraint annotation was found among annotations
 * @throws IllegalAccessException
 *         if attribute strategy cannot be instantiated
 * @throws InstantiationException
 *         if attribute strategy cannot be instantiated
 * @throws SecurityException
 *         if access security is violated
 * @throws InvocationTargetException
 *         if invocation failed
 * @throws IllegalArgumentException
 *         if illegal argument provided to a constructor
 */
public static AttributeStrategy<?> findAttributeStrategy(DataProviderStrategy strategy, List<Annotation> annotations, Class<?> attributeType) throws InstantiationException, IllegalAccessException, SecurityException, IllegalArgumentException, InvocationTargetException {
    List<Annotation> localAnnotations = new ArrayList<Annotation>(annotations);
    List<Class<? extends Annotation>> annotationsToCheck = new ArrayList<Class<? extends Annotation>>();
    List<Class<? extends Annotation>> constraintAnnotationsWithoutRegisteredStrategy = new ArrayList<Class<? extends Annotation>>();
    Iterator<Annotation> localAnnotationsIter = localAnnotations.iterator();
    while (localAnnotationsIter.hasNext()) {
        Annotation annotation = localAnnotationsIter.next();
        if (annotation instanceof PodamStrategyValue) {
            PodamStrategyValue strategyAnnotation = (PodamStrategyValue) annotation;
            return strategyAnnotation.value().newInstance();
        }
        /* Podam annotation is present, this will be handled later by type manufacturers */
        if (annotation.annotationType().getAnnotation(PodamAnnotation.class) != null) {
            return null;
        }
        /* Find real class out of proxy */
        Class<? extends Annotation> annotationClass = annotation.getClass();
        if (Proxy.isProxyClass(annotationClass)) {
            Class<?>[] interfaces = annotationClass.getInterfaces();
            if (interfaces.length == 1) {
                @SuppressWarnings("unchecked") Class<? extends Annotation> tmp = (Class<? extends Annotation>) interfaces[0];
                annotationClass = tmp;
            }
        }
        AttributeStrategy<?> attrStrategy = strategy.getStrategyForAnnotation(annotationClass);
        if (null != attrStrategy) {
            return attrStrategy;
        } else {
            for (Class<?> iface : annotationClass.getInterfaces()) {
                if (Annotation.class.isAssignableFrom(iface)) {
                    @SuppressWarnings("unchecked") Class<? extends Annotation> tmp = (Class<? extends Annotation>) iface;
                    annotationsToCheck.add(tmp);
                }
            }
        }
        if (annotation.annotationType().getAnnotation(Constraint.class) != null) {
            if (annotation instanceof NotNull || annotation instanceof NotBlank || annotation instanceof NotEmpty || annotation.annotationType().getName().equals("org.hibernate.validator.constraints.NotEmpty") || annotation.annotationType().getName().equals("org.hibernate.validator.constraints.NotBlank")) {
                /* We don't need to do anything for NotNull constraint */
                localAnnotationsIter.remove();
            } else if (!NotNull.class.getPackage().equals(annotationClass.getPackage())) {
                constraintAnnotationsWithoutRegisteredStrategy.add(annotationClass);
            }
        } else {
            localAnnotationsIter.remove();
        }
    }
    Iterator<Class<? extends Annotation>> annotationsToCheckIter = annotationsToCheck.iterator();
    while (annotationsToCheckIter.hasNext()) {
        Class<? extends Annotation> annotationClass = annotationsToCheckIter.next();
        AttributeStrategy<?> attrStrategy = strategy.getStrategyForAnnotation(annotationClass);
        if (null != attrStrategy) {
            return attrStrategy;
        } else {
            for (Class<?> iface : annotationClass.getInterfaces()) {
                if (Annotation.class.isAssignableFrom(iface)) {
                    @SuppressWarnings("unchecked") Class<? extends Annotation> tmp = (Class<? extends Annotation>) iface;
                    annotationsToCheck.add(tmp);
                }
            }
        }
    }
    for (Class<? extends Annotation> constraintAnnotationWithoutRegisteredStrategy : constraintAnnotationsWithoutRegisteredStrategy) {
        /* This message is logged only when no applicable strategy is found for given annotation - neither for
             * the annotation itself nor for any interface it implements. */
        LOG.warn("Please, register AttributeStrategy for custom " + "constraint {}, in DataProviderStrategy! Value " + "will be left to null", constraintAnnotationWithoutRegisteredStrategy);
    }
    AttributeStrategy<?> retValue = null;
    if (!localAnnotations.isEmpty() && !Collection.class.isAssignableFrom(attributeType) && !Map.class.isAssignableFrom(attributeType) && !attributeType.isArray()) {
        retValue = new BeanValidationStrategy(attributeType);
    }
    return retValue;
}
Also used : Constraint(javax.validation.Constraint) NotNull(javax.validation.constraints.NotNull) Annotation(java.lang.annotation.Annotation) NotBlank(javax.validation.constraints.NotBlank) NotEmpty(javax.validation.constraints.NotEmpty)

Example 2 with NotEmpty

use of javax.validation.constraints.NotEmpty in project graylog2-server by Graylog2.

the class AuthzRolesResource method getUsersForRole.

@GET
@ApiOperation(value = "Get a paginated list of users for a role")
@Path("/{roleId}/assignees")
@Produces(MediaType.APPLICATION_JSON)
@RequiresPermissions(RestPermissions.USERS_LIST)
public PaginatedResponse<UserOverviewDTO> getUsersForRole(@ApiParam(name = "roleId") @PathParam("roleId") @NotEmpty String roleId, @ApiParam(name = "page") @QueryParam("page") @DefaultValue("1") int page, @ApiParam(name = "per_page") @QueryParam("per_page") @DefaultValue("50") int perPage, @ApiParam(name = "query") @QueryParam("query") @DefaultValue("") String query, @ApiParam(name = "sort", value = "The field to sort the result on", required = true, allowableValues = "username,full_name,email") @DefaultValue(AuthzRoleDTO.FIELD_NAME) @QueryParam("sort") String sort, @ApiParam(name = "order", value = "The sort direction", allowableValues = "asc, desc") @DefaultValue("asc") @QueryParam("order") String order) {
    SearchQuery searchQuery;
    try {
        searchQuery = userSearchQueryParser.parse(query);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException("Invalid argument in search query: " + e.getMessage());
    }
    final PaginatedList<UserOverviewDTO> result = paginatedUserService.findPaginatedByRole(searchQuery, page, perPage, sort, order, ImmutableSet.of(roleId));
    final Set<String> roleIds = result.stream().flatMap(u -> u.roles().stream()).collect(Collectors.toSet());
    final Map<String, String> rolesMap = authzRolesService.findPaginatedByIds(new SearchQuery(""), 0, 0, AuthzRoleDTO.FIELD_NAME, "asc", roleIds).stream().collect(Collectors.toMap(AuthzRoleDTO::id, AuthzRoleDTO::name));
    final List<UserOverviewDTO> users = result.stream().map(u -> {
        final Set<String> roleNames = u.roles().stream().map(rolesMap::get).collect(Collectors.toSet());
        return u.toBuilder().roles(roleNames).build();
    }).collect(Collectors.toList());
    final PaginatedList<UserOverviewDTO> enrichedResult = new PaginatedList<>(users, result.pagination().total(), result.pagination().page(), result.pagination().perPage());
    return PaginatedResponse.create("users", enrichedResult, query);
}
Also used : SearchQuery(org.graylog2.search.SearchQuery) PathParam(javax.ws.rs.PathParam) NotBlank(javax.validation.constraints.NotBlank) Produces(javax.ws.rs.Produces) SearchQueryParser(org.graylog2.search.SearchQueryParser) GET(javax.ws.rs.GET) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) ApiParam(io.swagger.annotations.ApiParam) HashMap(java.util.HashMap) NotAllowedException(javax.ws.rs.NotAllowedException) NotEmpty(javax.validation.constraints.NotEmpty) Inject(javax.inject.Inject) ApiOperation(io.swagger.annotations.ApiOperation) PaginatedList(org.graylog2.database.PaginatedList) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) SearchQueryField(org.graylog2.search.SearchQueryField) USERS_ROLESEDIT(org.graylog2.shared.security.RestPermissions.USERS_ROLESEDIT) Map(java.util.Map) AuditEvent(org.graylog2.audit.jersey.AuditEvent) DefaultValue(javax.ws.rs.DefaultValue) BadRequestException(javax.ws.rs.BadRequestException) Api(io.swagger.annotations.Api) SearchQuery(org.graylog2.search.SearchQuery) DELETE(javax.ws.rs.DELETE) ImmutableSet(com.google.common.collect.ImmutableSet) Logger(org.slf4j.Logger) ImmutableMap(com.google.common.collect.ImmutableMap) Set(java.util.Set) RestResource(org.graylog2.shared.rest.resources.RestResource) Collectors(java.util.stream.Collectors) PaginatedUserService(org.graylog2.users.PaginatedUserService) NotFoundException(javax.ws.rs.NotFoundException) Objects(java.util.Objects) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) UserService(org.graylog2.shared.users.UserService) AuditEventTypes(org.graylog2.audit.AuditEventTypes) ValidationException(org.graylog2.plugin.database.ValidationException) RestPermissions(org.graylog2.shared.security.RestPermissions) Optional(java.util.Optional) PUT(javax.ws.rs.PUT) PaginatedResponse(org.graylog2.rest.models.PaginatedResponse) RequiresAuthentication(org.apache.shiro.authz.annotation.RequiresAuthentication) User(org.graylog2.plugin.database.users.User) UserOverviewDTO(org.graylog2.users.UserOverviewDTO) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) UserOverviewDTO(org.graylog2.users.UserOverviewDTO) BadRequestException(javax.ws.rs.BadRequestException) PaginatedList(org.graylog2.database.PaginatedList) Path(javax.ws.rs.Path) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation)

Example 3 with NotEmpty

use of javax.validation.constraints.NotEmpty in project minijax by minijax.

the class MinijaxConstraintDescriptor method build.

@SuppressWarnings("unchecked")
public static <T extends Annotation> MinijaxConstraintDescriptor<T> build(final AnnotatedType annotatedType, final T annotation) {
    final Constraint constraint = annotation.annotationType().getAnnotation(Constraint.class);
    if (constraint == null) {
        return null;
    }
    final Class<?> valueClass = ReflectionUtils.getRawType(annotatedType);
    final Class<?> annotationClass = annotation.annotationType();
    if (constraint.validatedBy().length > 0) {
        return buildDeclaredValidator(annotation, constraint.validatedBy()[0]);
    } else if (annotationClass == AssertFalse.class) {
        return (MinijaxConstraintDescriptor<T>) buildAssertFalseValidator((AssertFalse) annotation, valueClass);
    } else if (annotationClass == AssertTrue.class) {
        return (MinijaxConstraintDescriptor<T>) buildAssertTrueValidator((AssertTrue) annotation, valueClass);
    } else if (annotationClass == Max.class) {
        return (MinijaxConstraintDescriptor<T>) buildMaxValidator((Max) annotation, valueClass);
    } else if (annotationClass == Min.class) {
        return (MinijaxConstraintDescriptor<T>) buildMinValidator((Min) annotation, valueClass);
    } else if (annotationClass == NotBlank.class) {
        return (MinijaxConstraintDescriptor<T>) buildNotBlankValidator((NotBlank) annotation, valueClass);
    } else if (annotationClass == NotEmpty.class) {
        return (MinijaxConstraintDescriptor<T>) buildNotEmptyValidator((NotEmpty) annotation, valueClass);
    } else if (annotationClass == NotNull.class) {
        return (MinijaxConstraintDescriptor<T>) buildNotNullValidator((NotNull) annotation);
    } else if (annotationClass == Pattern.class) {
        return (MinijaxConstraintDescriptor<T>) buildPatternValidator((Pattern) annotation, valueClass);
    } else if (annotationClass == Size.class) {
        return (MinijaxConstraintDescriptor<T>) buildSizeValidator((Size) annotation, valueClass);
    } else {
        throw new ValidationException("Unrecognized constraint annotation: " + annotation);
    }
}
Also used : Pattern(javax.validation.constraints.Pattern) ValidationException(javax.validation.ValidationException) Constraint(javax.validation.Constraint) Max(javax.validation.constraints.Max) Size(javax.validation.constraints.Size) AssertTrue(javax.validation.constraints.AssertTrue) NotNull(javax.validation.constraints.NotNull) Min(javax.validation.constraints.Min) NotBlank(javax.validation.constraints.NotBlank) AssertFalse(javax.validation.constraints.AssertFalse) NotEmpty(javax.validation.constraints.NotEmpty)

Aggregations

NotBlank (javax.validation.constraints.NotBlank)3 NotEmpty (javax.validation.constraints.NotEmpty)3 Constraint (javax.validation.Constraint)2 NotNull (javax.validation.constraints.NotNull)2 Timed (com.codahale.metrics.annotation.Timed)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 Api (io.swagger.annotations.Api)1 ApiOperation (io.swagger.annotations.ApiOperation)1 ApiParam (io.swagger.annotations.ApiParam)1 Annotation (java.lang.annotation.Annotation)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 Objects (java.util.Objects)1 Optional (java.util.Optional)1 Set (java.util.Set)1 Collectors (java.util.stream.Collectors)1 Inject (javax.inject.Inject)1 ValidationException (javax.validation.ValidationException)1