Search in sources :

Example 91 with Annotation

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

the class ObjCRuntime method bind.

public static void bind(Class<?> c) {
    for (Method method : c.getDeclaredMethods()) {
        Bridge bridge = method.getAnnotation(Bridge.class);
        if (bridge != null && (bridge.symbol() == null || "".equals(bridge.symbol()))) {
            Class<?>[] paramTypes = method.getParameterTypes();
            if (paramTypes.length >= 2) {
                // or (super, selector).
                if (paramTypes[1] == Selector.class) {
                    String symbol = null;
                    if (paramTypes[0] == ObjCSuper.class) {
                        symbol = "objc_msgSendSuper";
                    } else if (ObjCObject.class.isAssignableFrom(paramTypes[0])) {
                        // self should be an instance of ObjCObject
                        symbol = "objc_msgSend";
                    } else if (paramTypes[0] == long.class) {
                        // Also allow @Pointer long as type of self
                        Annotation[] paramAnnos = method.getParameterAnnotations()[0];
                        for (Annotation a : paramAnnos) {
                            if (a.annotationType() == Pointer.class) {
                                symbol = "objc_msgSend";
                                break;
                            }
                        }
                    }
                    if (symbol != null) {
                        // special stret versions of objc_msgSend/objc_msgSendSuper.
                        if (isStret(method)) {
                            symbol += "_stret";
                        }
                        long f = Runtime.resolveBridge("objc", symbol, method);
                        VM.bindBridgeMethod(method, f);
                    }
                }
            }
        }
    }
    Bro.bind(c);
}
Also used : Method(java.lang.reflect.Method) Bridge(org.robovm.rt.bro.annotation.Bridge) Annotation(java.lang.annotation.Annotation)

Example 92 with Annotation

use of java.lang.annotation.Annotation in project byte-buddy by raphw.

the class AgentBuilderInitializationStrategySelfInjectionDispatcherTest method setUp.

@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    when(builder.initializer((any(ByteCodeAppender.class)))).thenReturn((DynamicType.Builder) appendedBuilder);
    when(injectorFactory.resolve()).thenReturn(classInjector);
    when(dynamicType.getTypeDescription()).thenReturn(instrumented);
    Map<TypeDescription, byte[]> auxiliaryTypes = new HashMap<TypeDescription, byte[]>();
    auxiliaryTypes.put(dependent, FOO);
    auxiliaryTypes.put(independent, BAR);
    when(dynamicType.getAuxiliaryTypes()).thenReturn(auxiliaryTypes);
    Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = new HashMap<TypeDescription, LoadedTypeInitializer>();
    loadedTypeInitializers.put(instrumented, instrumentedInitializer);
    loadedTypeInitializers.put(dependent, dependentInitializer);
    loadedTypeInitializers.put(independent, independentInitializer);
    when(dynamicType.getLoadedTypeInitializers()).thenReturn(loadedTypeInitializers);
    when(instrumented.getName()).thenReturn(Qux.class.getName());
    when(classInjector.inject(any(Map.class))).then(new Answer<Map<TypeDescription, Class<?>>>() {

        @Override
        public Map<TypeDescription, Class<?>> answer(InvocationOnMock invocationOnMock) throws Throwable {
            Map<TypeDescription, Class<?>> loaded = new HashMap<TypeDescription, Class<?>>();
            for (TypeDescription typeDescription : ((Map<TypeDescription, byte[]>) invocationOnMock.getArguments()[0]).keySet()) {
                if (typeDescription.equals(dependent)) {
                    loaded.put(dependent, Foo.class);
                } else if (typeDescription.equals(independent)) {
                    loaded.put(independent, Bar.class);
                } else {
                    throw new AssertionError();
                }
            }
            return loaded;
        }
    });
    Annotation eagerAnnotation = mock(AuxiliaryType.SignatureRelevant.class);
    when(eagerAnnotation.annotationType()).thenReturn((Class) AuxiliaryType.SignatureRelevant.class);
    when(independent.getDeclaredAnnotations()).thenReturn(new AnnotationList.ForLoadedAnnotations(eagerAnnotation));
    when(dependent.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty());
    when(instrumentedInitializer.isAlive()).thenReturn(true);
}
Also used : HashMap(java.util.HashMap) DynamicType(net.bytebuddy.dynamic.DynamicType) Annotation(java.lang.annotation.Annotation) AnnotationList(net.bytebuddy.description.annotation.AnnotationList) LoadedTypeInitializer(net.bytebuddy.implementation.LoadedTypeInitializer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) AuxiliaryType(net.bytebuddy.implementation.auxiliary.AuxiliaryType) TypeDescription(net.bytebuddy.description.type.TypeDescription) HashMap(java.util.HashMap) Map(java.util.Map) Before(org.junit.Before)

Example 93 with Annotation

use of java.lang.annotation.Annotation in project byte-buddy by raphw.

the class AgentBuilderInitializationStrategyTest method testMinimalRegistrationIndependentType.

@Test
@SuppressWarnings("unchecked")
public void testMinimalRegistrationIndependentType() throws Exception {
    Annotation eagerAnnotation = mock(AuxiliaryType.SignatureRelevant.class);
    when(eagerAnnotation.annotationType()).thenReturn((Class) AuxiliaryType.SignatureRelevant.class);
    TypeDescription independent = mock(TypeDescription.class), dependent = mock(TypeDescription.class);
    when(independent.getDeclaredAnnotations()).thenReturn(new AnnotationList.ForLoadedAnnotations(eagerAnnotation));
    when(dependent.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty());
    Map<TypeDescription, byte[]> map = new HashMap<TypeDescription, byte[]>();
    map.put(independent, QUX);
    map.put(dependent, BAZ);
    when(dynamicType.getAuxiliaryTypes()).thenReturn(map);
    ClassInjector classInjector = mock(ClassInjector.class);
    when(injectorFactory.resolve()).thenReturn(classInjector);
    when(classInjector.inject(Collections.singletonMap(independent, QUX))).thenReturn(Collections.<TypeDescription, Class<?>>singletonMap(independent, Foo.class));
    LoadedTypeInitializer loadedTypeInitializer = mock(LoadedTypeInitializer.class);
    when(dynamicType.getLoadedTypeInitializers()).thenReturn(Collections.singletonMap(independent, loadedTypeInitializer));
    AgentBuilder.InitializationStrategy.Minimal.INSTANCE.register(dynamicType, classLoader, injectorFactory);
    verify(classInjector).inject(Collections.singletonMap(independent, QUX));
    verifyNoMoreInteractions(classInjector);
    verify(loadedTypeInitializer).onLoad(Foo.class);
    verifyNoMoreInteractions(loadedTypeInitializer);
}
Also used : LoadedTypeInitializer(net.bytebuddy.implementation.LoadedTypeInitializer) HashMap(java.util.HashMap) AuxiliaryType(net.bytebuddy.implementation.auxiliary.AuxiliaryType) TypeDescription(net.bytebuddy.description.type.TypeDescription) Annotation(java.lang.annotation.Annotation) AnnotationList(net.bytebuddy.description.annotation.AnnotationList) ClassInjector(net.bytebuddy.dynamic.loading.ClassInjector) Test(org.junit.Test)

Example 94 with Annotation

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

the class EntityType method addAnnotationElement.

@Override
public void addAnnotationElement(TypeElement annotationElement, Element annotatedElement) {
    String qualifiedName = annotationElement.getQualifiedName().toString();
    Class<? extends Annotation> type;
    try {
        type = Class.forName(qualifiedName).asSubclass(Annotation.class);
    } catch (ClassNotFoundException e) {
        return;
    }
    switch(annotatedElement.getKind()) {
        case CLASS:
        case INTERFACE:
            annotations().put(type, annotatedElement.getAnnotation(type));
            break;
        case FIELD:
            if (annotatedElement.getModifiers().contains(Modifier.STATIC) || annotatedElement.getModifiers().contains(Modifier.FINAL)) {
                // check if this a requery annotation
                String packageName = Entity.class.getPackage().getName();
                if (annotationElement.getQualifiedName().toString().startsWith(packageName)) {
                    processingEnvironment.getMessager().printMessage(Diagnostic.Kind.ERROR, annotationElement.getQualifiedName() + " not applicable to static or final member", annotatedElement);
                }
            } else {
                VariableElement element = (VariableElement) annotatedElement;
                Optional<AttributeMember> attribute = computeAttribute(element);
                Annotation annotation = annotatedElement.getAnnotation(type);
                attribute.ifPresent(a -> a.annotations().put(type, annotation));
            }
            break;
        case METHOD:
            ExecutableElement element = (ExecutableElement) annotatedElement;
            Annotation annotation = annotatedElement.getAnnotation(type);
            if (ListenerAnnotations.all().anyMatch(a -> a.equals(type))) {
                ListenerMethod listener = listeners.computeIfAbsent(element, key -> new ListenerMethod(element));
                listener.annotations().put(type, annotation);
            } else if (isMethodProcessable(element)) {
                Optional<AttributeMember> attribute = computeAttribute(element);
                attribute.ifPresent(a -> a.annotations().put(type, annotation));
            }
            break;
    }
}
Also used : Transient(io.requery.Transient) Table(io.requery.Table) Modifier(javax.lang.model.element.Modifier) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) Elements(javax.lang.model.util.Elements) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Embedded(io.requery.Embedded) Diagnostic(javax.tools.Diagnostic) Map(java.util.Map) MirroredTypeException(javax.lang.model.type.MirroredTypeException) PropertyNameStyle(io.requery.PropertyNameStyle) NestingKind(javax.lang.model.element.NestingKind) ElementFilter(javax.lang.model.util.ElementFilter) LinkedHashSet(java.util.LinkedHashSet) Name(javax.lang.model.element.Name) View(io.requery.View) Entity(io.requery.Entity) ElementKind(javax.lang.model.element.ElementKind) ExecutableElement(javax.lang.model.element.ExecutableElement) Cacheable(javax.persistence.Cacheable) Set(java.util.Set) ReadOnly(io.requery.ReadOnly) Element(javax.lang.model.element.Element) Collectors(java.util.stream.Collectors) TypeKind(javax.lang.model.type.TypeKind) Objects(java.util.Objects) SourceVersion(javax.lang.model.SourceVersion) TypeMirror(javax.lang.model.type.TypeMirror) List(java.util.List) Stream(java.util.stream.Stream) Index(javax.persistence.Index) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) Annotation(java.lang.annotation.Annotation) Factory(io.requery.Factory) Optional(java.util.Optional) Embeddable(javax.persistence.Embeddable) Entity(io.requery.Entity) Optional(java.util.Optional) ExecutableElement(javax.lang.model.element.ExecutableElement) VariableElement(javax.lang.model.element.VariableElement) Annotation(java.lang.annotation.Annotation)

Example 95 with Annotation

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

the class EntityType method process.

@Override
public Set<ElementValidator> process(ProcessingEnvironment processingEnvironment) {
    // create attributes for fields that have no annotations
    if (element().getKind().isInterface() || isImmutable() || isUnimplementable()) {
        ElementFilter.methodsIn(element().getEnclosedElements()).stream().filter(this::isMethodProcessable).forEach(this::computeAttribute);
    } else {
        // private/static/final members fields are skipped
        Set<VariableElement> elements = ElementFilter.fieldsIn(element().getEnclosedElements()).stream().filter(element -> !element.getModifiers().contains(Modifier.PRIVATE) && !element.getModifiers().contains(Modifier.STATIC) && (!element.getModifiers().contains(Modifier.FINAL) || isImmutable())).collect(Collectors.toSet());
        if (elements.isEmpty()) {
            // if nothing to process try the getters instead
            ElementFilter.methodsIn(element().getEnclosedElements()).stream().filter(this::isMethodProcessable).forEach(this::computeAttribute);
        } else {
            elements.forEach(this::computeAttribute);
        }
    }
    // find listener annotated methods
    ElementFilter.methodsIn(element().getEnclosedElements()).forEach(element -> ListenerAnnotations.all().forEach(annotation -> {
        if (element.getAnnotation(annotation) != null) {
            ListenerMethod listener = listeners.computeIfAbsent(element, key -> new ListenerMethod(element));
            listener.annotations().put(annotation, element.getAnnotation(annotation));
        }
    }));
    Set<ProcessableElement<?>> elements = new LinkedHashSet<>();
    attributes().values().forEach(attribute -> elements.add((ProcessableElement<?>) attribute));
    elements.addAll(listeners.values());
    Set<ElementValidator> validations = new LinkedHashSet<>();
    elements.forEach(element -> validations.addAll(element.process(processingEnvironment)));
    ElementValidator validator = new ElementValidator(element(), processingEnvironment);
    Entity entity = annotationOf(Entity.class).orElse(null);
    if (entity != null && !Names.isEmpty(entity.name()) && !SourceVersion.isIdentifier(entity.name())) {
        validator.error("Invalid class identifier " + entity.name(), Entity.class);
    }
    if (element().getNestingKind() == NestingKind.ANONYMOUS) {
        validator.error("Entity annotation cannot be applied to anonymous class");
    }
    if (element().getKind() == ElementKind.ENUM) {
        validator.error("Entity annotation cannot be applied to an enum class");
    }
    if (attributes.values().isEmpty()) {
        validator.warning("Entity contains no attributes");
    }
    if (!isReadOnly() && !isEmbedded() && attributes.values().size() == 1 && attributes.values().iterator().next().isGenerated()) {
        validator.warning("Entity contains only a single generated attribute may fail to persist");
    }
    checkReserved(tableName(), validator);
    validations.add(validator);
    return validations;
}
Also used : Transient(io.requery.Transient) Table(io.requery.Table) Modifier(javax.lang.model.element.Modifier) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) Elements(javax.lang.model.util.Elements) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Embedded(io.requery.Embedded) Diagnostic(javax.tools.Diagnostic) Map(java.util.Map) MirroredTypeException(javax.lang.model.type.MirroredTypeException) PropertyNameStyle(io.requery.PropertyNameStyle) NestingKind(javax.lang.model.element.NestingKind) ElementFilter(javax.lang.model.util.ElementFilter) LinkedHashSet(java.util.LinkedHashSet) Name(javax.lang.model.element.Name) View(io.requery.View) Entity(io.requery.Entity) ElementKind(javax.lang.model.element.ElementKind) ExecutableElement(javax.lang.model.element.ExecutableElement) Cacheable(javax.persistence.Cacheable) Set(java.util.Set) ReadOnly(io.requery.ReadOnly) Element(javax.lang.model.element.Element) Collectors(java.util.stream.Collectors) TypeKind(javax.lang.model.type.TypeKind) Objects(java.util.Objects) SourceVersion(javax.lang.model.SourceVersion) TypeMirror(javax.lang.model.type.TypeMirror) List(java.util.List) Stream(java.util.stream.Stream) Index(javax.persistence.Index) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) Annotation(java.lang.annotation.Annotation) Factory(io.requery.Factory) Optional(java.util.Optional) Embeddable(javax.persistence.Embeddable) LinkedHashSet(java.util.LinkedHashSet) Entity(io.requery.Entity) VariableElement(javax.lang.model.element.VariableElement)

Aggregations

Annotation (java.lang.annotation.Annotation)707 Method (java.lang.reflect.Method)171 ArrayList (java.util.ArrayList)99 Field (java.lang.reflect.Field)76 Test (org.junit.Test)66 Type (java.lang.reflect.Type)64 HashMap (java.util.HashMap)54 HashSet (java.util.HashSet)52 Map (java.util.Map)35 ParameterizedType (java.lang.reflect.ParameterizedType)34 List (java.util.List)30 Set (java.util.Set)27 InvocationTargetException (java.lang.reflect.InvocationTargetException)22 IOException (java.io.IOException)20 BindingAnnotation (com.google.inject.BindingAnnotation)17 AbstractModule (com.google.inject.AbstractModule)16 TypeElement (javax.lang.model.element.TypeElement)15 Injector (com.google.inject.Injector)14 MediaType (okhttp3.MediaType)14 AnnotatedElement (java.lang.reflect.AnnotatedElement)13