Search in sources :

Example 1 with Parameter

use of org.glassfish.jersey.server.model.Parameter in project dropwizard by dropwizard.

the class ConstraintMessage method getMemberName.

/**
     * Gets a method parameter (or a parameter field) name, if the violation raised in it.
     */
private static Optional<String> getMemberName(ConstraintViolation<?> violation, Invocable invocable) {
    final int size = Iterables.size(violation.getPropertyPath());
    if (size < 2) {
        return Optional.empty();
    }
    final Path.Node parent = Iterables.get(violation.getPropertyPath(), size - 2);
    final Path.Node member = Iterables.getLast(violation.getPropertyPath());
    switch(parent.getKind()) {
        case PARAMETER:
            // Constraint violation most likely failed with a BeanParam
            final List<Parameter> parameters = invocable.getParameters();
            final Parameter param = parameters.get(parent.as(Path.ParameterNode.class).getParameterIndex());
            // Extract the failing *Param annotation inside the Bean Param
            if (param.getSource().equals(Parameter.Source.BEAN_PARAM)) {
                final Field field = FieldUtils.getField(param.getRawType(), member.getName(), true);
                return JerseyParameterNameProvider.getParameterNameFromAnnotations(field.getDeclaredAnnotations());
            }
            break;
        case METHOD:
            return Optional.of(member.getName());
    }
    return Optional.empty();
}
Also used : Path(javax.validation.Path) Field(java.lang.reflect.Field) Parameter(org.glassfish.jersey.server.model.Parameter)

Example 2 with Parameter

use of org.glassfish.jersey.server.model.Parameter in project dropwizard by dropwizard.

the class ConstraintMessage method determineStatus.

/**
     * Given a set of constraint violations and a Jersey {@link Invocable} where the constraint
     * occurred, determine the  HTTP Status code for the response. A return value violation is an
     * internal server error, an invalid request body is unprocessable entity, and any params that
     * are invalid means a bad request
     */
public static <T extends ConstraintViolation<?>> int determineStatus(Set<T> violations, Invocable invocable) {
    if (violations.size() > 0) {
        final ConstraintViolation<?> violation = violations.iterator().next();
        for (Path.Node node : violation.getPropertyPath()) {
            switch(node.getKind()) {
                case RETURN_VALUE:
                    return 500;
                case PARAMETER:
                    // Now determine if the parameter is the request entity
                    final int index = node.as(Path.ParameterNode.class).getParameterIndex();
                    final Parameter parameter = invocable.getParameters().get(index);
                    return parameter.getSource().equals(Parameter.Source.UNKNOWN) ? 422 : 400;
                default:
                    continue;
            }
        }
    }
    // This shouldn't hit, but if it does, we'll return a unprocessable entity
    return 422;
}
Also used : Path(javax.validation.Path) Parameter(org.glassfish.jersey.server.model.Parameter)

Example 3 with Parameter

use of org.glassfish.jersey.server.model.Parameter in project dropwizard by dropwizard.

the class DropwizardConfiguredValidator method getGroup.

/**
     * If the request entity is annotated with {@link Validated} then run
     * validations in the specified constraint group else validate with the
     * {@link Default} group
     */
private Class<?>[] getGroup(Invocable invocable) {
    final ImmutableList.Builder<Class<?>[]> builder = ImmutableList.builder();
    for (Parameter parameter : invocable.getParameters()) {
        if (parameter.isAnnotationPresent(Validated.class)) {
            builder.add(parameter.getAnnotation(Validated.class).value());
        }
    }
    final ImmutableList<Class<?>[]> groups = builder.build();
    switch(groups.size()) {
        // No parameters were annotated with Validated, so validate under the default group
        case 0:
            return new Class<?>[] { Default.class };
        // A single parameter was annotated with Validated, so use their group
        case 1:
            return groups.get(0);
        // group.
        default:
            for (int i = 0; i < groups.size(); i++) {
                for (int j = i; j < groups.size(); j++) {
                    if (!Arrays.deepEquals(groups.get(i), groups.get(j))) {
                        throw new WebApplicationException("Parameters must have the same validation groups in " + invocable.getHandlingMethod().getName(), 500);
                    }
                }
            }
            return groups.get(0);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ImmutableList(com.google.common.collect.ImmutableList) Parameter(org.glassfish.jersey.server.model.Parameter) Default(javax.validation.groups.Default)

Example 4 with Parameter

use of org.glassfish.jersey.server.model.Parameter in project jersey by jersey.

the class ParamInjectionResolver method resolve.

@Override
@SuppressWarnings("unchecked")
public Object resolve(Injectee injectee) {
    AnnotatedElement annotated = injectee.getParent();
    Annotation[] annotations;
    if (annotated.getClass().equals(Constructor.class)) {
        annotations = ((Constructor) annotated).getParameterAnnotations()[injectee.getPosition()];
    } else {
        annotations = annotated.getDeclaredAnnotations();
    }
    Class componentClass = injectee.getInjecteeClass();
    Type genericType = injectee.getRequiredType();
    final Type targetGenericType;
    if (injectee.isFactory()) {
        targetGenericType = ReflectionHelper.getTypeArgument(genericType, 0);
    } else {
        targetGenericType = genericType;
    }
    final Class<?> targetType = ReflectionHelper.erasure(targetGenericType);
    final Parameter parameter = Parameter.create(componentClass, componentClass, hasEncodedAnnotation(injectee), targetType, targetGenericType, annotations);
    final Supplier<?> paramValueSupplier = valueSupplierProvider.getValueSupplier(parameter);
    if (paramValueSupplier != null) {
        if (injectee.isFactory()) {
            return paramValueSupplier;
        } else {
            return paramValueSupplier.get();
        }
    }
    return null;
}
Also used : Type(java.lang.reflect.Type) Constructor(java.lang.reflect.Constructor) AnnotatedElement(java.lang.reflect.AnnotatedElement) Parameter(org.glassfish.jersey.server.model.Parameter) Annotation(java.lang.annotation.Annotation)

Example 5 with Parameter

use of org.glassfish.jersey.server.model.Parameter in project jersey by jersey.

the class ParameterValueHelper method createValueProviders.

/**
     * Create list of parameter value providers for the given {@link Parameterized
     * parameterized} resource model component.
     *
     * @param injectionManager injection manager.
     * @param parameterized parameterized resource model component.
     * @return list of parameter value providers for the parameterized component.
     */
public static List<ParamValueFactoryWithSource<?>> createValueProviders(InjectionManager injectionManager, Parameterized parameterized) {
    if ((null == parameterized.getParameters()) || (0 == parameterized.getParameters().size())) {
        return Collections.emptyList();
    }
    List<ValueSupplierProvider> valueSupplierProviders = Providers.getProviders(injectionManager, ValueSupplierProvider.class).stream().sorted((o1, o2) -> o2.getPriority().getWeight() - o1.getPriority().getWeight()).collect(Collectors.toList());
    boolean entityParamFound = false;
    final List<ParamValueFactoryWithSource<?>> providers = new ArrayList<>(parameterized.getParameters().size());
    for (final Parameter parameter : parameterized.getParameters()) {
        final Parameter.Source parameterSource = parameter.getSource();
        entityParamFound = entityParamFound || Parameter.Source.ENTITY == parameterSource;
        final Supplier<?> valueSupplier = getParamValueSupplier(valueSupplierProviders, parameter);
        if (valueSupplier != null) {
            providers.add(wrapParamValueSupplier(valueSupplier, parameterSource));
        } else {
            providers.add(null);
        }
    }
    if (!entityParamFound && Collections.frequency(providers, null) == 1) {
        // Try to find entity if there is one unresolved parameter and the annotations are unknown
        final int entityParamIndex = providers.lastIndexOf(null);
        final Parameter parameter = parameterized.getParameters().get(entityParamIndex);
        if (Parameter.Source.UNKNOWN == parameter.getSource() && !parameter.isQualified()) {
            final Parameter overriddenParameter = Parameter.overrideSource(parameter, Parameter.Source.ENTITY);
            final Supplier<?> valueSupplier = getParamValueSupplier(valueSupplierProviders, overriddenParameter);
            if (valueSupplier != null) {
                providers.set(entityParamIndex, wrapParamValueSupplier(valueSupplier, overriddenParameter.getSource()));
            } else {
                providers.set(entityParamIndex, null);
            }
        }
    }
    return providers;
}
Also used : Iterator(java.util.Iterator) Collection(java.util.Collection) MappableException(org.glassfish.jersey.server.internal.process.MappableException) Providers(org.glassfish.jersey.internal.inject.Providers) Supplier(java.util.function.Supplier) Collectors(java.util.stream.Collectors) InjectionManager(org.glassfish.jersey.internal.inject.InjectionManager) ArrayList(java.util.ArrayList) List(java.util.List) MessageBodyProviderNotFoundException(org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException) Parameterized(org.glassfish.jersey.server.model.Parameterized) ProcessingException(javax.ws.rs.ProcessingException) WebApplicationException(javax.ws.rs.WebApplicationException) Parameter(org.glassfish.jersey.server.model.Parameter) Collections(java.util.Collections) NotSupportedException(javax.ws.rs.NotSupportedException) ArrayList(java.util.ArrayList) Parameter(org.glassfish.jersey.server.model.Parameter)

Aggregations

Parameter (org.glassfish.jersey.server.model.Parameter)10 Path (javax.validation.Path)3 ProcessingException (javax.ws.rs.ProcessingException)3 WebApplicationException (javax.ws.rs.WebApplicationException)2 ResourceMethod (org.glassfish.jersey.server.model.ResourceMethod)2 ImmutableList (com.google.common.collect.ImmutableList)1 Param (com.sun.research.ws.wadl.Param)1 Request (com.sun.research.ws.wadl.Request)1 Resource (com.sun.research.ws.wadl.Resource)1 Annotation (java.lang.annotation.Annotation)1 AnnotatedElement (java.lang.reflect.AnnotatedElement)1 Constructor (java.lang.reflect.Constructor)1 Field (java.lang.reflect.Field)1 Method (java.lang.reflect.Method)1 Type (java.lang.reflect.Type)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1