Search in sources :

Example 1 with ContractProvider

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

the class ComponentBag method registerModel.

/**
     * Register a {@link ContractProvider contract provider model} for a given  class.
     *
     * @param componentClass  registered component class.
     * @param defaultPriority default component priority. If {@value ContractProvider#NO_PRIORITY},
     *                        the value from the component class {@link javax.annotation.Priority} annotation will be used
     *                        (if any).
     * @param contractMap     map of contracts and their binding priorities. If {@code null}, the contracts will
     *                        gathered by introspecting the component class. Content of the contract map
     *                        may be modified during the registration processing.
     * @param modelEnhancer   custom contract provider model enhancer.
     * @return {@code true} upon successful registration of a contract provider model for a given component class,
     *         {@code false} otherwise.
     */
private boolean registerModel(final Class<?> componentClass, final int defaultPriority, final Map<Class<?>, Integer> contractMap, final Inflector<ContractProvider.Builder, ContractProvider> modelEnhancer) {
    return Errors.process(() -> {
        if (models.containsKey(componentClass)) {
            Errors.error(LocalizationMessages.COMPONENT_TYPE_ALREADY_REGISTERED(componentClass), Severity.HINT);
            return false;
        }
        // Register contracts
        final ContractProvider model = modelFor(componentClass, defaultPriority, contractMap, modelEnhancer);
        // Apply registration strategy
        if (!registrationStrategy.test(model)) {
            return false;
        }
        models.put(componentClass, model);
        return true;
    });
}
Also used : ContractProvider(org.glassfish.jersey.model.ContractProvider)

Example 2 with ContractProvider

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

the class ComponentBag method modelFor.

/**
     * Create a contract provider for a given component class.
     *
     * @param componentClass  component class to create contract provider model for.
     * @param defaultPriority default component priority. If {@value ContractProvider#NO_PRIORITY},
     *                        the value from the component class {@link javax.annotation.Priority} annotation will be used
     *                        (if any).
     * @param contractMap     map of contracts and their binding priorities. If {@code null}, the contracts will
     *                        gathered by introspecting the component class. Content of the contract map
     *                        may be modified during the registration processing.
     * @param modelEnhancer   custom contract provider model enhancer.
     * @return contract provider model for the class.
     */
private static ContractProvider modelFor(final Class<?> componentClass, final int defaultPriority, final Map<Class<?>, Integer> contractMap, final Inflector<ContractProvider.Builder, ContractProvider> modelEnhancer) {
    Map<Class<?>, Integer> contracts = contractMap;
    if (contracts == null) {
        // introspect
        contracts = asMap(Providers.getProviderContracts(componentClass));
    } else {
        // filter custom contracts
        final Iterator<Class<?>> it = contracts.keySet().iterator();
        while (it.hasNext()) {
            final Class<?> contract = it.next();
            if (contract == null) {
                it.remove();
                continue;
            }
            boolean failed = false;
            if (!Providers.isSupportedContract(contract)) {
                Errors.error(LocalizationMessages.CONTRACT_NOT_SUPPORTED(contract, componentClass), Severity.WARNING);
                failed = true;
            }
            if (!contract.isAssignableFrom(componentClass)) {
                Errors.error(LocalizationMessages.CONTRACT_NOT_ASSIGNABLE(contract, componentClass), Severity.WARNING);
                failed = true;
            }
            if (failed) {
                it.remove();
            }
        }
    }
    final ContractProvider.Builder builder = ContractProvider.builder(componentClass).addContracts(contracts).defaultPriority(defaultPriority);
    // Process annotations (priority, name bindings, scope)
    final boolean useAnnotationPriority = defaultPriority == ContractProvider.NO_PRIORITY;
    for (Annotation annotation : componentClass.getAnnotations()) {
        if (annotation instanceof Priority) {
            if (useAnnotationPriority) {
                builder.defaultPriority(((Priority) annotation).value());
            }
        } else {
            for (Annotation metaAnnotation : annotation.annotationType().getAnnotations()) {
                if (metaAnnotation instanceof NameBinding) {
                    builder.addNameBinding(annotation.annotationType());
                }
                if (metaAnnotation instanceof Scope) {
                    builder.scope(annotation.annotationType());
                }
            }
        }
    }
    return modelEnhancer.apply(builder);
}
Also used : Scope(javax.inject.Scope) ContractProvider(org.glassfish.jersey.model.ContractProvider) Priority(javax.annotation.Priority) NameBinding(javax.ws.rs.NameBinding) Annotation(java.lang.annotation.Annotation)

Example 3 with ContractProvider

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

the class ProviderBinder method bindProviders.

/**
     * Bind all providers contained in {@code p roviderBag} (classes and instances) using injection manager. Configuration is
     * also committed.
     *
     * @param componentBag      bag of provider classes and instances.
     * @param constrainedTo     current runtime (client or server).
     * @param registeredClasses classes which are manually registered by the user (not found by the classpath scanning).
     * @param injectionManager  injection manager the binder will use to bind the providers into.
     */
public static void bindProviders(ComponentBag componentBag, RuntimeType constrainedTo, Set<Class<?>> registeredClasses, InjectionManager injectionManager) {
    Predicate<ContractProvider> filter = ComponentBag.EXCLUDE_EMPTY.and(ComponentBag.excludeMetaProviders(injectionManager));
    /*
         * Check the {@code component} whether it is correctly configured for client or server {@link RuntimeType runtime}.
         */
    Predicate<Class<?>> correctlyConfigured = componentClass -> Providers.checkProviderRuntime(componentClass, componentBag.getModel(componentClass), constrainedTo, registeredClasses == null || !registeredClasses.contains(componentClass), false);
    /*
         * These binder will be register to Bean Manager at the and of method because of a bulk registration to avoid register
         * each binder alone.
         */
    Collection<Binder> binderToRegister = new ArrayList<>();
    // Bind provider classes except for pure meta-providers and providers with empty contract models (e.g. resources)
    Set<Class<?>> classes = new LinkedHashSet<>(componentBag.getClasses(filter));
    if (constrainedTo != null) {
        classes = classes.stream().filter(correctlyConfigured).collect(Collectors.toSet());
    }
    for (final Class<?> providerClass : classes) {
        final ContractProvider model = componentBag.getModel(providerClass);
        binderToRegister.addAll(createProviderBinders(providerClass, model));
    }
    // Bind pure provider instances except for pure meta-providers and providers with empty contract models (e.g. resources)
    Set<Object> instances = componentBag.getInstances(filter);
    if (constrainedTo != null) {
        instances = instances.stream().filter(component -> correctlyConfigured.test(component.getClass())).collect(Collectors.toSet());
    }
    for (final Object provider : instances) {
        final ContractProvider model = componentBag.getModel(provider.getClass());
        binderToRegister.addAll(createProviderBinders(provider, model));
    }
    injectionManager.register(CompositeBinder.wrap(binderToRegister));
}
Also used : Arrays(java.util.Arrays) RuntimeType(javax.ws.rs.RuntimeType) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ComponentBag(org.glassfish.jersey.model.internal.ComponentBag) Set(java.util.Set) ContractProvider(org.glassfish.jersey.model.ContractProvider) Singleton(javax.inject.Singleton) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) List(java.util.List) Annotation(java.lang.annotation.Annotation) Collections(java.util.Collections) LinkedHashSet(java.util.LinkedHashSet) LinkedHashSet(java.util.LinkedHashSet) ContractProvider(org.glassfish.jersey.model.ContractProvider) ArrayList(java.util.ArrayList)

Example 4 with ContractProvider

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

the class CommonConfigTest method testRegisterClassBingingPriority.

@Test
public void testRegisterClassBingingPriority() throws Exception {
    try {
        final Class clazz = null;
        //noinspection ConstantConditions
        config.register(clazz, Priorities.USER);
        fail("Cannot register null.");
    } catch (final IllegalArgumentException e) {
    // OK.
    }
    for (final int priority : new int[] { Priorities.USER, Priorities.AUTHENTICATION }) {
        config.register(ComplexEmptyProvider.class, priority);
        final ContractProvider contractProvider = config.getComponentBag().getModel(ComplexEmptyProvider.class);
        final Set<Class<?>> contracts = contractProvider.getContracts();
        assertEquals(3, contracts.size());
        assertTrue(contracts.contains(ReaderInterceptor.class));
        assertTrue(contracts.contains(ContainerRequestFilter.class));
        assertTrue(contracts.contains(ExceptionMapper.class));
        // All priorities are the same.
        assertEquals(Priorities.USER, contractProvider.getPriority(ReaderInterceptor.class));
        assertEquals(Priorities.USER, contractProvider.getPriority(ContainerRequestFilter.class));
        assertEquals(Priorities.USER, contractProvider.getPriority(ExceptionMapper.class));
    }
}
Also used : ReaderInterceptor(javax.ws.rs.ext.ReaderInterceptor) ExceptionMapper(javax.ws.rs.ext.ExceptionMapper) ContractProvider(org.glassfish.jersey.model.ContractProvider) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter) Test(org.junit.Test)

Example 5 with ContractProvider

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

the class CommonConfigTest method testRegisterInstanceNullContracts.

@Test
@SuppressWarnings("unchecked")
public void testRegisterInstanceNullContracts() throws Exception {
    config.register(new ComplexEmptyProvider(), (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)

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