Search in sources :

Example 21 with Annotation

use of java.lang.annotation.Annotation in project Hystrix by Netflix.

the class CacheInvocationParameterTest method testCacheInvocationParameterConstructor.

@Test
public void testCacheInvocationParameterConstructor() throws NoSuchMethodException {
    // given
    Class<?> rawType = String.class;
    Object value = "test";
    Method method = CacheInvocationParameterTest.class.getDeclaredMethod("stabMethod", String.class);
    method.setAccessible(true);
    Annotation[] annotations = method.getParameterAnnotations()[0];
    int position = 0;
    // when
    CacheInvocationParameter cacheInvocationParameter = new CacheInvocationParameter(rawType, value, annotations, position);
    // then
    assertEquals(rawType, cacheInvocationParameter.getRawType());
    assertEquals(value, cacheInvocationParameter.getValue());
    assertEquals(annotations[0], cacheInvocationParameter.getCacheKeyAnnotation());
    assertTrue(cacheInvocationParameter.hasCacheKeyAnnotation());
    assertTrue(cacheInvocationParameter.getAnnotations().contains(annotations[0]));
    try {
        cacheInvocationParameter.getAnnotations().clear();
        fail();
    } catch (Throwable e) {
    // getAnnotations should return immutable set.
    }
}
Also used : Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) Test(org.junit.Test)

Example 22 with Annotation

use of java.lang.annotation.Annotation in project android_frameworks_base by ParanoidAndroid.

the class Filter method addAnnotatedPorts.

private final void addAnnotatedPorts() {
    Class filterClass = getClass();
    Annotation annotation;
    for (Field field : filterClass.getDeclaredFields()) {
        if ((annotation = field.getAnnotation(GenerateFieldPort.class)) != null) {
            GenerateFieldPort generator = (GenerateFieldPort) annotation;
            addFieldGenerator(generator, field);
        } else if ((annotation = field.getAnnotation(GenerateProgramPort.class)) != null) {
            GenerateProgramPort generator = (GenerateProgramPort) annotation;
            addProgramGenerator(generator, field);
        } else if ((annotation = field.getAnnotation(GenerateProgramPorts.class)) != null) {
            GenerateProgramPorts generators = (GenerateProgramPorts) annotation;
            for (GenerateProgramPort generator : generators.value()) {
                addProgramGenerator(generator, field);
            }
        }
    }
}
Also used : Field(java.lang.reflect.Field) Annotation(java.lang.annotation.Annotation)

Example 23 with Annotation

use of java.lang.annotation.Annotation 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 24 with Annotation

use of java.lang.annotation.Annotation in project jersey by jersey.

the class ExecutorProviders method createInjectionBindings.

/**
     * Create qualified {@link java.util.concurrent.ExecutorService} and {@link java.util.concurrent.ScheduledExecutorService}
     * injection bindings based on the registered providers implementing the
     * {@link org.glassfish.jersey.spi.ExecutorServiceProvider} and/or
     * {@link org.glassfish.jersey.spi.ScheduledExecutorServiceProvider} SPI.
     * <p>
     * This method supports creation of qualified injection bindings based on custom
     * {@link javax.inject.Qualifier qualifier annotations} attached to the registered provider implementation classes
     * as well as named injection bindings based on the {@link javax.inject.Named} qualifier annotation attached to the
     * registered provider implementation classes.
     * </p>
     *
     * @param injectionManager application's injection manager.
     */
public static void createInjectionBindings(InjectionManager injectionManager) {
    /*
         * Add ExecutorService into DI framework.
         */
    Map<Class<? extends Annotation>, List<ExecutorServiceProvider>> executorProviderMap = getQualifierToProviderMap(injectionManager, ExecutorServiceProvider.class);
    for (Map.Entry<Class<? extends Annotation>, List<ExecutorServiceProvider>> qualifierToProviders : executorProviderMap.entrySet()) {
        Class<? extends Annotation> qualifierAnnotationClass = qualifierToProviders.getKey();
        Iterator<ExecutorServiceProvider> bucketProviderIterator = qualifierToProviders.getValue().iterator();
        ExecutorServiceProvider executorProvider = bucketProviderIterator.next();
        logExecutorServiceProvider(qualifierAnnotationClass, bucketProviderIterator, executorProvider);
        SupplierInstanceBinding<ExecutorService> descriptor = Bindings.supplier(new ExecutorServiceSupplier(executorProvider)).in(Singleton.class).to(ExecutorService.class);
        Annotation qualifier = executorProvider.getClass().getAnnotation(qualifierAnnotationClass);
        if (qualifier instanceof Named) {
            descriptor.named(((Named) qualifier).value());
        } else {
            descriptor.qualifiedBy(qualifier);
        }
        injectionManager.register(descriptor);
    }
    /*
         * Add ScheduledExecutorService into DI framework.
         */
    Map<Class<? extends Annotation>, List<ScheduledExecutorServiceProvider>> schedulerProviderMap = getQualifierToProviderMap(injectionManager, ScheduledExecutorServiceProvider.class);
    for (Map.Entry<Class<? extends Annotation>, List<ScheduledExecutorServiceProvider>> qualifierToProviders : schedulerProviderMap.entrySet()) {
        Class<? extends Annotation> qualifierAnnotationClass = qualifierToProviders.getKey();
        Iterator<ScheduledExecutorServiceProvider> bucketProviderIterator = qualifierToProviders.getValue().iterator();
        ScheduledExecutorServiceProvider executorProvider = bucketProviderIterator.next();
        logScheduledExecutorProvider(qualifierAnnotationClass, bucketProviderIterator, executorProvider);
        SupplierInstanceBinding<ScheduledExecutorService> descriptor = Bindings.supplier(new ScheduledExecutorServiceSupplier(executorProvider)).in(Singleton.class).to(ScheduledExecutorService.class);
        if (!executorProviderMap.containsKey(qualifierAnnotationClass)) {
            // it is safe to register binding for ExecutorService too...
            descriptor.to(ExecutorService.class);
        }
        Annotation qualifier = executorProvider.getClass().getAnnotation(qualifierAnnotationClass);
        if (qualifier instanceof Named) {
            descriptor.named(((Named) qualifier).value());
        } else {
            descriptor.qualifiedBy(qualifier);
        }
        injectionManager.register(descriptor);
    }
}
Also used : Named(javax.inject.Named) ScheduledExecutorServiceProvider(org.glassfish.jersey.spi.ScheduledExecutorServiceProvider) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Annotation(java.lang.annotation.Annotation) ExecutorServiceProvider(org.glassfish.jersey.spi.ExecutorServiceProvider) ScheduledExecutorServiceProvider(org.glassfish.jersey.spi.ScheduledExecutorServiceProvider) Singleton(javax.inject.Singleton) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) List(java.util.List) LinkedList(java.util.LinkedList) HashMap(java.util.HashMap) Map(java.util.Map)

Example 25 with Annotation

use of java.lang.annotation.Annotation 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)

Aggregations

Annotation (java.lang.annotation.Annotation)1784 Method (java.lang.reflect.Method)412 ArrayList (java.util.ArrayList)245 Field (java.lang.reflect.Field)172 Test (org.junit.Test)164 Type (java.lang.reflect.Type)149 HashMap (java.util.HashMap)146 HashSet (java.util.HashSet)129 Map (java.util.Map)95 List (java.util.List)92 IOException (java.io.IOException)71 Set (java.util.Set)71 ParameterizedType (java.lang.reflect.ParameterizedType)62 InvocationTargetException (java.lang.reflect.InvocationTargetException)53 Collection (java.util.Collection)52 LinkedHashMap (java.util.LinkedHashMap)36 Collectors (java.util.stream.Collectors)36 Constructor (java.lang.reflect.Constructor)33 LinkedHashSet (java.util.LinkedHashSet)32 Optional (java.util.Optional)32