Search in sources :

Example 11 with ContractProvider

use of org.glassfish.jersey.model.ContractProvider in project jersey by jersey.

the class ApplicationHandler method filterNameBound.

/**
     * Takes collection of all filters/interceptors (either request/reader or response/writer)
     * and separates out all name-bound filters/interceptors, returns them as a separate MultivaluedMap,
     * mapping the name-bound annotation to the list of name-bound filters/interceptors. The same key values
     * are also added into the inverse map passed in {@code inverseNameBoundMap}.
     * <p/>
     * Note, the name-bound filters/interceptors are removed from the original filters/interceptors collection.
     * If non-null collection is passed in the postMatching parameter (applicable for filters only),
     * this method also removes all the global
     * postMatching filters from the original collection and adds them to the collection passed in the postMatching
     * parameter.
     *
     * @param all                     Collection of all filters to be processed.
     * @param preMatchingFilters      Collection into which pre-matching filters should be added.
     * @param componentBag            Component bag
     * @param applicationNameBindings Collection of name binding annotations attached to the JAX-RS application.
     * @param inverseNameBoundMap     Inverse name bound map into which the name bound providers should be inserted. The keys
     *                                are providers (filters, interceptor)
     * @return {@link MultivaluedMap} of all name-bound filters.
     */
private static <T> MultivaluedMap<Class<? extends Annotation>, RankedProvider<T>> filterNameBound(final Iterable<RankedProvider<T>> all, final Collection<RankedProvider<ContainerRequestFilter>> preMatchingFilters, final ComponentBag componentBag, final Collection<Class<? extends Annotation>> applicationNameBindings, final MultivaluedMap<RankedProvider<T>, Class<? extends Annotation>> inverseNameBoundMap) {
    final MultivaluedMap<Class<? extends Annotation>, RankedProvider<T>> result = new MultivaluedHashMap<>();
    for (final Iterator<RankedProvider<T>> it = all.iterator(); it.hasNext(); ) {
        final RankedProvider<T> provider = it.next();
        Class<?> providerClass = provider.getProvider().getClass();
        final Set<Type> contractTypes = provider.getContractTypes();
        if (contractTypes != null && !contractTypes.contains(providerClass)) {
            providerClass = ReflectionHelper.theMostSpecificTypeOf(contractTypes);
        }
        ContractProvider model = componentBag.getModel(providerClass);
        if (model == null) {
            // the provider was (most likely) bound in HK2 externally
            model = ComponentBag.modelFor(providerClass);
        }
        final boolean preMatching = providerClass.getAnnotation(PreMatching.class) != null;
        if (preMatching && preMatchingFilters != null) {
            it.remove();
            preMatchingFilters.add(new RankedProvider<>((ContainerRequestFilter) provider.getProvider(), model.getPriority(ContainerRequestFilter.class)));
        }
        boolean nameBound = model.isNameBound();
        if (nameBound && !applicationNameBindings.isEmpty() && applicationNameBindings.containsAll(model.getNameBindings())) {
            // override the name-bound flag
            nameBound = false;
        }
        if (nameBound) {
            // not application-bound
            if (!preMatching) {
                it.remove();
                for (final Class<? extends Annotation> binding : model.getNameBindings()) {
                    result.add(binding, provider);
                    inverseNameBoundMap.add(provider, binding);
                }
            } else {
                LOGGER.warning(LocalizationMessages.PREMATCHING_ALSO_NAME_BOUND(providerClass));
            }
        }
    }
    return result;
}
Also used : ContractProvider(org.glassfish.jersey.model.ContractProvider) Annotation(java.lang.annotation.Annotation) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) RuntimeType(javax.ws.rs.RuntimeType) GenericType(javax.ws.rs.core.GenericType) Type(java.lang.reflect.Type) RankedProvider(org.glassfish.jersey.model.internal.RankedProvider) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter) PreMatching(javax.ws.rs.container.PreMatching)

Example 12 with ContractProvider

use of org.glassfish.jersey.model.ContractProvider in project jersey by jersey.

the class CommonConfig method processFeatureRegistration.

private void processFeatureRegistration(final Object component, final Class<?> componentClass) {
    final ContractProvider model = componentBag.getModel(componentClass);
    if (model.getContracts().contains(Feature.class)) {
        @SuppressWarnings("unchecked") final FeatureRegistration registration = (component != null) ? new FeatureRegistration((Feature) component) : new FeatureRegistration((Class<? extends Feature>) componentClass);
        newFeatureRegistrations.add(registration);
    }
}
Also used : ContractProvider(org.glassfish.jersey.model.ContractProvider) Feature(javax.ws.rs.core.Feature)

Example 13 with ContractProvider

use of org.glassfish.jersey.model.ContractProvider in project jersey by jersey.

the class ApplicationHandler method bindProvidersAndResources.

private void bindProvidersAndResources(final Iterable<ComponentProvider> componentProviders, final ComponentBag componentBag, final Collection<Class<?>> resourceClasses, final Collection<Object> resourceInstances) {
    JerseyResourceContext resourceContext = injectionManager.getInstance(JerseyResourceContext.class);
    Set<Class<?>> registeredClasses = runtimeConfig.getRegisteredClasses();
    /*
         * Check the {@code component} whether it is correctly configured for client or server {@link RuntimeType runtime}.
         */
    java.util.function.Predicate<Class<?>> correctlyConfigured = componentClass -> Providers.checkProviderRuntime(componentClass, componentBag.getModel(componentClass), RuntimeType.SERVER, !registeredClasses.contains(componentClass), resourceClasses.contains(componentClass));
    /*
         * Check the {@code resource class} whether it is correctly configured for client or server {@link RuntimeType runtime}.
         */
    BiPredicate<Class<?>, ContractProvider> correctlyConfiguredResource = (resourceClass, model) -> Providers.checkProviderRuntime(resourceClass, model, RuntimeType.SERVER, !registeredClasses.contains(resourceClass), true);
    Set<Class<?>> componentClassses = componentBag.getClasses(ComponentBag.excludeMetaProviders(injectionManager)).stream().filter(correctlyConfigured).collect(Collectors.toSet());
    // Merge programmatic resource classes with component classes.
    Set<Class<?>> classes = Collections.newSetFromMap(new IdentityHashMap<>());
    classes.addAll(componentClassses);
    classes.addAll(resourceClasses);
    // Bind classes.
    for (final Class<?> componentClass : classes) {
        ContractProvider model = componentBag.getModel(componentClass);
        if (bindWithComponentProvider(componentClass, model, componentProviders)) {
            continue;
        }
        if (resourceClasses.contains(componentClass)) {
            if (!Resource.isAcceptable(componentClass)) {
                LOGGER.warning(LocalizationMessages.NON_INSTANTIABLE_COMPONENT(componentClass));
                continue;
            }
            if (model != null && !correctlyConfiguredResource.test(componentClass, model)) {
                model = null;
            }
            resourceContext.unsafeBindResource(componentClass, model, injectionManager);
        } else {
            ProviderBinder.bindProvider(componentClass, model, injectionManager);
        }
    }
    // Merge programmatic resource instances with other component instances.
    Set<Object> instances = componentBag.getInstances(ComponentBag.excludeMetaProviders(injectionManager)).stream().filter(instance -> correctlyConfigured.test(instance.getClass())).collect(Collectors.toSet());
    instances.addAll(resourceInstances);
    // Bind instances.
    for (Object component : instances) {
        ContractProvider model = componentBag.getModel(component.getClass());
        if (resourceInstances.contains(component)) {
            if (model != null && !correctlyConfiguredResource.test(component.getClass(), model)) {
                model = null;
            }
            resourceContext.unsafeBindResource(component, model, injectionManager);
        } else {
            ProviderBinder.bindProvider(component, model, injectionManager);
        }
    }
}
Also used : JerseyResourceContext(org.glassfish.jersey.server.internal.JerseyResourceContext) ComponentBag(org.glassfish.jersey.model.internal.ComponentBag) RankedComparator(org.glassfish.jersey.model.internal.RankedComparator) SecurityContext(javax.ws.rs.core.SecurityContext) Errors(org.glassfish.jersey.internal.Errors) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) ModelProcessor(org.glassfish.jersey.server.model.ModelProcessor) ComponentProvider(org.glassfish.jersey.server.spi.ComponentProvider) Application(javax.ws.rs.core.Application) JerseyResourceContext(org.glassfish.jersey.server.internal.JerseyResourceContext) ContainerLifecycleListener(org.glassfish.jersey.server.spi.ContainerLifecycleListener) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter) InjectionManager(org.glassfish.jersey.internal.inject.InjectionManager) ContainerResponseFilter(javax.ws.rs.container.ContainerResponseFilter) RankedProvider(org.glassfish.jersey.model.internal.RankedProvider) JerseyRequestTimeoutHandler(org.glassfish.jersey.server.internal.JerseyRequestTimeoutHandler) ExecutorProviders(org.glassfish.jersey.process.internal.ExecutorProviders) Stages(org.glassfish.jersey.process.internal.Stages) Future(java.util.concurrent.Future) Ref(org.glassfish.jersey.internal.util.collection.Ref) ReaderInterceptor(javax.ws.rs.ext.ReaderInterceptor) Map(java.util.Map) ProviderBinder(org.glassfish.jersey.internal.inject.ProviderBinder) RequestProcessingContext(org.glassfish.jersey.server.internal.process.RequestProcessingContext) ModelErrors(org.glassfish.jersey.server.model.internal.ModelErrors) ApplicationEvent(org.glassfish.jersey.server.monitoring.ApplicationEvent) Values(org.glassfish.jersey.internal.util.collection.Values) ContainerResponseWriter(org.glassfish.jersey.server.spi.ContainerResponseWriter) LocalizationMessages(org.glassfish.jersey.server.internal.LocalizationMessages) IdentityHashMap(java.util.IdentityHashMap) RuntimeType(javax.ws.rs.RuntimeType) Collection(java.util.Collection) Version(org.glassfish.jersey.internal.Version) MessageBodyWorkers(org.glassfish.jersey.message.MessageBodyWorkers) Container(org.glassfish.jersey.server.spi.Container) Set(java.util.Set) ContractProvider(org.glassfish.jersey.model.ContractProvider) ResourceModel(org.glassfish.jersey.server.model.ResourceModel) Providers(org.glassfish.jersey.internal.inject.Providers) Logger(java.util.logging.Logger) ModelValidationException(org.glassfish.jersey.server.model.ModelValidationException) Collectors(java.util.stream.Collectors) ChainableStage(org.glassfish.jersey.process.internal.ChainableStage) PreMatching(javax.ws.rs.container.PreMatching) GenericType(javax.ws.rs.core.GenericType) DynamicFeature(javax.ws.rs.container.DynamicFeature) List(java.util.List) Principal(java.security.Principal) HttpHeaders(javax.ws.rs.core.HttpHeaders) Type(java.lang.reflect.Type) Annotation(java.lang.annotation.Annotation) MonitoringContainerListener(org.glassfish.jersey.server.internal.monitoring.MonitoringContainerListener) Spliterator(java.util.Spliterator) Resource(org.glassfish.jersey.server.model.Resource) CommonProperties(org.glassfish.jersey.CommonProperties) Configuration(javax.ws.rs.core.Configuration) Order(org.glassfish.jersey.model.internal.RankedComparator.Order) CompletableFuture(java.util.concurrent.CompletableFuture) AbstractBinder(org.glassfish.jersey.internal.inject.AbstractBinder) Singleton(javax.inject.Singleton) Binder(org.glassfish.jersey.internal.inject.Binder) Function(java.util.function.Function) Supplier(java.util.function.Supplier) HttpMethod(javax.ws.rs.HttpMethod) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) HashSet(java.util.HashSet) ApplicationEventListener(org.glassfish.jersey.server.monitoring.ApplicationEventListener) BiPredicate(java.util.function.BiPredicate) ReferencesInitializer(org.glassfish.jersey.server.internal.process.ReferencesInitializer) Value(org.glassfish.jersey.internal.util.collection.Value) ApplicationEventImpl(org.glassfish.jersey.server.internal.monitoring.ApplicationEventImpl) ExternalRequestScope(org.glassfish.jersey.server.spi.ExternalRequestScope) Routing(org.glassfish.jersey.server.internal.routing.Routing) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) LazyValue(org.glassfish.jersey.internal.util.collection.LazyValue) StreamSupport(java.util.stream.StreamSupport) WriterInterceptor(javax.ws.rs.ext.WriterInterceptor) Injections(org.glassfish.jersey.internal.inject.Injections) LinkedList(java.util.LinkedList) OutputStream(java.io.OutputStream) CompositeApplicationEventListener(org.glassfish.jersey.server.internal.monitoring.CompositeApplicationEventListener) Iterator(java.util.Iterator) ServiceConfigurationError(org.glassfish.jersey.internal.ServiceConfigurationError) ProcessingProviders(org.glassfish.jersey.server.internal.ProcessingProviders) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ReflectionHelper(org.glassfish.jersey.internal.util.ReflectionHelper) TimeUnit(java.util.concurrent.TimeUnit) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) ComponentModelValidator(org.glassfish.jersey.server.model.ComponentModelValidator) NameBinding(javax.ws.rs.NameBinding) CompositeBinder(org.glassfish.jersey.internal.inject.CompositeBinder) Stage(org.glassfish.jersey.process.internal.Stage) ServiceFinder(org.glassfish.jersey.internal.ServiceFinder) NullOutputStream(org.glassfish.jersey.message.internal.NullOutputStream) Collections(java.util.Collections) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) ContractProvider(org.glassfish.jersey.model.ContractProvider)

Example 14 with ContractProvider

use of org.glassfish.jersey.model.ContractProvider in project jersey by jersey.

the class CommonConfigTest method testRegisterClassNullContracts.

@Test
public void testRegisterClassNullContracts() throws Exception {
    config.register(ComplexEmptyProvider.class, (Class) null);
    final ContractProvider contractProvider = config.getComponentBag().getModel(ComplexEmptyProvider.class);
    final Set<Class<?>> contracts = contractProvider.getContracts();
    assertEquals(0, contracts.size());
}
Also used : ContractProvider(org.glassfish.jersey.model.ContractProvider) Test(org.junit.Test)

Example 15 with ContractProvider

use of org.glassfish.jersey.model.ContractProvider in project jersey by jersey.

the class CommonConfigTest method testRegisterInstancesContracts.

@Test
@SuppressWarnings("unchecked")
public void testRegisterInstancesContracts() throws Exception {
    try {
        config.register(null, ReaderInterceptor.class);
        fail("Cannot register null.");
    } catch (final IllegalArgumentException e) {
    // OK.
    }
    final ComplexEmptyProvider complexEmptyProvider = new ComplexEmptyProvider();
    config.register(complexEmptyProvider, ReaderInterceptor.class, ContainerRequestFilter.class, WriterInterceptor.class);
    final ContractProvider contractProvider = config.getComponentBag().getModel(ComplexEmptyProvider.class);
    final Set<Class<?>> contracts = contractProvider.getContracts();
    assertEquals(2, contracts.size());
    assertTrue(ReaderInterceptor.class + " is not registered.", contracts.contains(ReaderInterceptor.class));
    assertTrue(ContainerRequestFilter.class + " is not registered.", contracts.contains(ContainerRequestFilter.class));
    assertFalse(WriterInterceptor.class + " should not be registered.", contracts.contains(WriterInterceptor.class));
    assertTrue(config.getInstances().contains(complexEmptyProvider));
    assertTrue(config.getClasses().isEmpty());
}
Also used : WriterInterceptor(javax.ws.rs.ext.WriterInterceptor) ReaderInterceptor(javax.ws.rs.ext.ReaderInterceptor) ContractProvider(org.glassfish.jersey.model.ContractProvider) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter) Test(org.junit.Test)

Aggregations

ContractProvider (org.glassfish.jersey.model.ContractProvider)16 ContainerRequestFilter (javax.ws.rs.container.ContainerRequestFilter)10 Test (org.junit.Test)10 ReaderInterceptor (javax.ws.rs.ext.ReaderInterceptor)9 ExceptionMapper (javax.ws.rs.ext.ExceptionMapper)5 Annotation (java.lang.annotation.Annotation)4 RuntimeType (javax.ws.rs.RuntimeType)3 WriterInterceptor (javax.ws.rs.ext.WriterInterceptor)3 Type (java.lang.reflect.Type)2 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 Collections (java.util.Collections)2 List (java.util.List)2 Set (java.util.Set)2 Function (java.util.function.Function)2 Collectors (java.util.stream.Collectors)2 Singleton (javax.inject.Singleton)2 NameBinding (javax.ws.rs.NameBinding)2 PreMatching (javax.ws.rs.container.PreMatching)2 OutputStream (java.io.OutputStream)1