Search in sources :

Example 1 with MethodDescriptor

use of javax.validation.metadata.MethodDescriptor in project jersey by jersey.

the class DefaultConfiguredValidator method validateResult.

@Override
public void validateResult(final Object resource, final Invocable resourceMethod, final Object result) {
    if (configuration.getBootstrapConfiguration().isExecutableValidationEnabled()) {
        final Set<ConstraintViolation<Object>> constraintViolations = new HashSet<>();
        final Method handlingMethod = resourceMethod.getHandlingMethod();
        final BeanDescriptor beanDescriptor = getConstraintsForClass(resource.getClass());
        final MethodDescriptor methodDescriptor = beanDescriptor.getConstraintsForMethod(handlingMethod.getName(), handlingMethod.getParameterTypes());
        final Method definitionMethod = resourceMethod.getDefinitionMethod();
        if (methodDescriptor != null && methodDescriptor.hasConstrainedReturnValue() && validateOnExecutionHandler.validateMethod(resource.getClass(), definitionMethod, handlingMethod)) {
            constraintViolations.addAll(forExecutables().validateReturnValue(resource, handlingMethod, result));
            if (result instanceof Response) {
                constraintViolations.addAll(forExecutables().validateReturnValue(resource, handlingMethod, ((Response) result).getEntity()));
            }
        }
        if (!constraintViolations.isEmpty()) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }
}
Also used : Response(javax.ws.rs.core.Response) BeanDescriptor(javax.validation.metadata.BeanDescriptor) ConstraintViolation(javax.validation.ConstraintViolation) ConstraintViolationException(javax.validation.ConstraintViolationException) Method(java.lang.reflect.Method) MethodDescriptor(javax.validation.metadata.MethodDescriptor) HashSet(java.util.HashSet)

Example 2 with MethodDescriptor

use of javax.validation.metadata.MethodDescriptor in project jersey by jersey.

the class DefaultConfiguredValidator method onValidate.

// Invoked as the last validation interceptor method in the chain.
@Override
public void onValidate(final ValidationInterceptorContext ctx) {
    final Object resource = ctx.getResource();
    final Invocable resourceMethod = ctx.getInvocable();
    final Object[] args = ctx.getArgs();
    final Set<ConstraintViolation<Object>> constraintViolations = new HashSet<>();
    final BeanDescriptor beanDescriptor = getConstraintsForClass(resource.getClass());
    // Resource validation.
    if (beanDescriptor.isBeanConstrained()) {
        constraintViolations.addAll(validate(resource));
    }
    if (resourceMethod != null && configuration.getBootstrapConfiguration().isExecutableValidationEnabled()) {
        final Method handlingMethod = resourceMethod.getHandlingMethod();
        // Resource method validation - input parameters.
        final MethodDescriptor methodDescriptor = beanDescriptor.getConstraintsForMethod(handlingMethod.getName(), handlingMethod.getParameterTypes());
        if (methodDescriptor != null && methodDescriptor.hasConstrainedParameters()) {
            constraintViolations.addAll(forExecutables().validateParameters(resource, handlingMethod, args));
        }
    }
    if (!constraintViolations.isEmpty()) {
        throw new ConstraintViolationException(constraintViolations);
    }
}
Also used : Invocable(org.glassfish.jersey.server.model.Invocable) BeanDescriptor(javax.validation.metadata.BeanDescriptor) ConstraintViolation(javax.validation.ConstraintViolation) ConstraintViolationException(javax.validation.ConstraintViolationException) Method(java.lang.reflect.Method) MethodDescriptor(javax.validation.metadata.MethodDescriptor) HashSet(java.util.HashSet)

Example 3 with MethodDescriptor

use of javax.validation.metadata.MethodDescriptor in project tomee by apache.

the class CxfRsHttpListener method configureFactory.

private void configureFactory(final Collection<Object> givenAdditionalProviders, final ServiceConfiguration serviceConfiguration, final JAXRSServerFactoryBean factory, final WebBeansContext ctx, final Application application) {
    CxfUtil.configureEndpoint(factory, serviceConfiguration, CXF_JAXRS_PREFIX);
    boolean enforceCxfBvalMapper = false;
    if (ctx == null || !ctx.getBeanManagerImpl().isInUse()) {
        // activate bval
        boolean bvalActive = Boolean.parseBoolean(SystemInstance.get().getProperty("openejb.cxf.rs.bval.active", serviceConfiguration.getProperties().getProperty(CXF_JAXRS_PREFIX + "bval.active", "true")));
        if (factory.getFeatures() == null && bvalActive) {
            factory.setFeatures(new ArrayList<>());
        } else if (bvalActive) {
            // check we should activate it and user didn't configure it
            for (final Feature f : factory.getFeatures()) {
                if (BeanValidationFeature.class.isInstance(f)) {
                    bvalActive = false;
                    break;
                }
            }
            for (final Interceptor<?> i : factory.getInInterceptors()) {
                if (BeanValidationInInterceptor.class.isInstance(i)) {
                    bvalActive = false;
                    break;
                }
            }
            for (final Interceptor<?> i : factory.getOutInterceptors()) {
                if (BeanValidationOutInterceptor.class.isInstance(i)) {
                    bvalActive = false;
                    break;
                }
            }
        }
        if (bvalActive) {
            // bval doesn't need the actual instance so faking it to avoid to lookup the bean
            // todo: close the factory
            final BeanValidationProvider provider = new BeanValidationProvider();
            ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
            final Validator validator = validatorFactory.getValidator();
            final BeanValidationInInterceptor in = new JAXRSBeanValidationInInterceptor() {

                @Override
                protected Object getServiceObject(final Message message) {
                    return CxfRsHttpListener.this.getServiceObject(message);
                }
            };
            in.setProvider(provider);
            in.setServiceObject(FAKE_SERVICE_OBJECT);
            factory.getInInterceptors().add(in);
            final BeanValidationOutInterceptor out = new JAXRSBeanValidationOutInterceptor() {

                @Override
                protected Object getServiceObject(final Message message) {
                    return CxfRsHttpListener.this.getServiceObject(message);
                }

                @Override
                protected void handleValidation(final Message message, final Object resourceInstance, final Method method, final List<Object> arguments) {
                    final MethodDescriptor constraintsForMethod = validator.getConstraintsForClass(resourceInstance.getClass()).getConstraintsForMethod(method.getName(), method.getParameterTypes());
                    if (constraintsForMethod != null && constraintsForMethod.hasConstrainedReturnValue()) {
                        super.handleValidation(message, resourceInstance, method, arguments);
                    }
                }
            };
            out.setEnforceOnlyBeanConstraints(true);
            out.setProvider(provider);
            out.setServiceObject(FAKE_SERVICE_OBJECT);
            factory.getOutInterceptors().add(out);
            // and add a mapper to get back a 400 like for bval
            enforceCxfBvalMapper = true;
        }
    }
    final Collection<ServiceInfo> services = serviceConfiguration.getAvailableServices();
    final String staticSubresourceResolution = serviceConfiguration.getProperties().getProperty(CXF_JAXRS_PREFIX + STATIC_SUB_RESOURCE_RESOLUTION_KEY);
    if (staticSubresourceResolution != null) {
        factory.setStaticSubresourceResolution("true".equalsIgnoreCase(staticSubresourceResolution));
    }
    // resource comparator
    final String resourceComparator = serviceConfiguration.getProperties().getProperty(RESOURCE_COMPARATOR_KEY);
    if (resourceComparator != null) {
        try {
            ResourceComparator instance = (ResourceComparator) ServiceInfos.resolve(services, resourceComparator);
            if (instance == null) {
                instance = (ResourceComparator) Thread.currentThread().getContextClassLoader().loadClass(resourceComparator).newInstance();
            }
            factory.setResourceComparator(instance);
        } catch (final Exception e) {
            LOGGER.error("Can't create the resource comparator " + resourceComparator, e);
        }
    }
    // static resources
    final String staticResources = serviceConfiguration.getProperties().getProperty(STATIC_RESOURCE_KEY);
    if (staticResources != null) {
        final String[] resources = staticResources.split(",");
        for (final String r : resources) {
            final String trimmed = r.trim();
            if (!trimmed.isEmpty()) {
                staticResourcesList.add(Pattern.compile(trimmed));
            }
        }
    }
    // providers
    Set<String> providersConfig = null;
    {
        final String provider = serviceConfiguration.getProperties().getProperty(PROVIDERS_KEY);
        if (provider != null) {
            providersConfig = new HashSet<>();
            for (final String p : Arrays.asList(provider.split(","))) {
                providersConfig.add(p.trim());
            }
        }
        {
            if (GLOBAL_PROVIDERS != null) {
                if (providersConfig == null) {
                    providersConfig = new HashSet<>();
                }
                providersConfig.addAll(Arrays.asList(GLOBAL_PROVIDERS.split(",")));
            }
        }
    }
    // another property to configure the scanning of providers but this one is consistent with current cxf config
    // the other one is more generic but need another file
    final String key = CXF_JAXRS_PREFIX + "skip-provider-scanning";
    final boolean ignoreAutoProviders = "true".equalsIgnoreCase(SystemInstance.get().getProperty(key, serviceConfiguration.getProperties().getProperty(key, "false")));
    final List<Object> additionalProviders = new ArrayList<Object>(ignoreAutoProviders ? Collections.EMPTY_LIST : givenAdditionalProviders);
    for (final Class<?> clzz : application.getClasses()) {
        if (isProvider(clzz) && !additionalProviders.contains(clzz)) {
            additionalProviders.add(clzz);
        }
    }
    List<Object> providers = null;
    if (providersConfig != null) {
        providers = ServiceInfos.resolve(services, providersConfig.toArray(new String[providersConfig.size()]), OpenEJBProviderFactory.INSTANCE);
        if (providers != null && additionalProviders != null && !additionalProviders.isEmpty()) {
            providers.addAll(providers(serviceConfiguration.getAvailableServices(), additionalProviders, ctx));
        }
    }
    if (providers == null) {
        providers = new ArrayList<>(4);
        if (additionalProviders != null && !additionalProviders.isEmpty()) {
            providers.addAll(providers(serviceConfiguration.getAvailableServices(), additionalProviders, ctx));
        }
    }
    if (!ignoreAutoProviders) {
        addMandatoryProviders(providers, serviceConfiguration);
        if (enforceCxfBvalMapper) {
            if (!shouldSkipProvider(CxfResponseValidationExceptionMapper.class.getName())) {
                providers.add(new CxfResponseValidationExceptionMapper());
            }
        }
    }
    SystemInstance.get().fireEvent(new ExtensionProviderRegistration(AppFinder.findAppContextOrWeb(Thread.currentThread().getContextClassLoader(), AppFinder.AppContextTransformer.INSTANCE), providers));
    if (!providers.isEmpty()) {
        factory.setProviders(providers);
    }
}
Also used : Message(org.apache.cxf.message.Message) JAXRSBeanValidationOutInterceptor(org.apache.cxf.jaxrs.validation.JAXRSBeanValidationOutInterceptor) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) BeanValidationFeature(org.apache.cxf.validation.BeanValidationFeature) Feature(org.apache.cxf.feature.Feature) EJBRestServiceInfo(org.apache.openejb.server.rest.EJBRestServiceInfo) ServiceInfo(org.apache.openejb.assembler.classic.ServiceInfo) Arrays.asList(java.util.Arrays.asList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) List(java.util.List) JAXRSBeanValidationOutInterceptor(org.apache.cxf.jaxrs.validation.JAXRSBeanValidationOutInterceptor) Interceptor(org.apache.cxf.interceptor.Interceptor) BeanValidationInInterceptor(org.apache.cxf.validation.BeanValidationInInterceptor) JAXRSBeanValidationInInterceptor(org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor) BeanValidationOutInterceptor(org.apache.cxf.validation.BeanValidationOutInterceptor) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) BeanValidationFeature(org.apache.cxf.validation.BeanValidationFeature) BeanValidationInInterceptor(org.apache.cxf.validation.BeanValidationInInterceptor) JAXRSBeanValidationInInterceptor(org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor) ResourceComparator(org.apache.cxf.jaxrs.ext.ResourceComparator) ValidatorFactory(javax.validation.ValidatorFactory) Method(java.lang.reflect.Method) MethodDescriptor(javax.validation.metadata.MethodDescriptor) JAXRSBeanValidationInInterceptor(org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor) ResponseConstraintViolationException(org.apache.cxf.validation.ResponseConstraintViolationException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) EndpointException(org.apache.cxf.endpoint.EndpointException) ServletException(javax.servlet.ServletException) BusException(org.apache.cxf.BusException) InjectionException(javax.enterprise.inject.InjectionException) BeanValidationProvider(org.apache.cxf.validation.BeanValidationProvider) JAXRSBeanValidationOutInterceptor(org.apache.cxf.jaxrs.validation.JAXRSBeanValidationOutInterceptor) BeanValidationOutInterceptor(org.apache.cxf.validation.BeanValidationOutInterceptor) ExtensionProviderRegistration(org.apache.openejb.server.cxf.rs.event.ExtensionProviderRegistration) Validator(javax.validation.Validator)

Example 4 with MethodDescriptor

use of javax.validation.metadata.MethodDescriptor in project tomee by apache.

the class BValInterceptor method invoke.

@AroundInvoke
public Object invoke(final InvocationContext context) throws Exception {
    Method method = context.getMethod();
    Class<?> targetClass = getTargetClass(context);
    final ClassValidationData validationData = new ClassValidationData(targetClass);
    if (validationData.getJwtConstraints().size() > 0) {
        final Class<?> constraintsClazz = new ClassValidationGenerator(validationData).generate().stream().filter(aClass -> aClass.getName().endsWith("ReturnConstraints")).findFirst().orElseThrow(MissingConstraintsException::new);
        try {
            final Method constraintsClazzMethod = constraintsClazz.getMethod(method.getName(), method.getParameterTypes());
            targetClass = constraintsClazz;
            method = constraintsClazzMethod;
        } catch (NoSuchMethodException | SecurityException e) {
            // this is ok.  it means there are no return value constraints
            return context.proceed();
        }
    }
    if (!isExecutableValidated(targetClass, method, this::computeIsMethodValidated)) {
        return context.proceed();
    }
    final MethodDescriptor constraintsForMethod = validator.getConstraintsForClass(targetClass).getConstraintsForMethod(method.getName(), method.getParameterTypes());
    if (!DescriptorManager.isConstrained(constraintsForMethod)) {
        return context.proceed();
    }
    initExecutableValidator();
    if (constraintsForMethod.hasConstrainedParameters()) {
        final Set<ConstraintViolation<Object>> violations = executableValidator.validateParameters(context.getTarget(), method, context.getParameters());
        if (!violations.isEmpty()) {
            throw new ConstraintViolationException(violations);
        }
    }
    final Object result = context.proceed();
    if (constraintsForMethod.hasConstrainedReturnValue()) {
        final Set<ConstraintViolation<Object>> violations = executableValidator.validateReturnValue(context.getTarget(), method, result);
        if (!violations.isEmpty()) {
            throw new ConstraintViolationException(violations);
        }
    }
    return result;
}
Also used : Method(java.lang.reflect.Method) AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) MethodDescriptor(javax.validation.metadata.MethodDescriptor) ConstraintViolation(javax.validation.ConstraintViolation) ConstraintViolationException(javax.validation.ConstraintViolationException) AroundInvoke(javax.interceptor.AroundInvoke)

Aggregations

Method (java.lang.reflect.Method)4 MethodDescriptor (javax.validation.metadata.MethodDescriptor)4 HashSet (java.util.HashSet)3 ConstraintViolation (javax.validation.ConstraintViolation)3 ConstraintViolationException (javax.validation.ConstraintViolationException)3 BeanDescriptor (javax.validation.metadata.BeanDescriptor)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 Arrays.asList (java.util.Arrays.asList)1 LinkedHashSet (java.util.LinkedHashSet)1 List (java.util.List)1 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)1 InjectionException (javax.enterprise.inject.InjectionException)1 AnnotatedMethod (javax.enterprise.inject.spi.AnnotatedMethod)1 AroundInvoke (javax.interceptor.AroundInvoke)1 ServletException (javax.servlet.ServletException)1 Validator (javax.validation.Validator)1 ValidatorFactory (javax.validation.ValidatorFactory)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 Response (javax.ws.rs.core.Response)1