Search in sources :

Example 21 with VariableElement

use of javax.lang.model.element.VariableElement in project realm-java by realm.

the class ClassMetaData method checkListTypes.

private boolean checkListTypes() {
    for (VariableElement field : fields) {
        if (Utils.isRealmList(field) || Utils.isRealmResults(field)) {
            // Check for missing generic (default back to Object)
            if (Utils.getGenericTypeQualifiedName(field) == null) {
                Utils.error("No generic type supplied for field", field);
                return false;
            }
            // Check that the referenced type is a concrete class and not an interface
            TypeMirror fieldType = field.asType();
            List<? extends TypeMirror> typeArguments = ((DeclaredType) fieldType).getTypeArguments();
            String genericCanonicalType = typeArguments.get(0).toString();
            TypeElement typeElement = elements.getTypeElement(genericCanonicalType);
            if (typeElement.getSuperclass().getKind() == TypeKind.NONE) {
                Utils.error("Only concrete Realm classes are allowed in RealmLists. " + "Neither interfaces nor abstract classes are allowed.", field);
                return false;
            }
        }
    }
    return true;
}
Also used : TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) VariableElement(javax.lang.model.element.VariableElement) DeclaredType(javax.lang.model.type.DeclaredType)

Example 22 with VariableElement

use of javax.lang.model.element.VariableElement 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 23 with VariableElement

use of javax.lang.model.element.VariableElement 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)

Example 24 with VariableElement

use of javax.lang.model.element.VariableElement in project requery by requery.

the class EntityType method factoryArguments.

@Override
public List<String> factoryArguments() {
    List<String> names = new ArrayList<>();
    ExecutableElement method = factoryMethod().orElseThrow(IllegalStateException::new);
    // TODO need more validation here
    // now match the builder fields to the parameters...
    Map<Element, AttributeDescriptor> map = new LinkedHashMap<>(attributes);
    for (VariableElement parameter : method.getParameters()) {
        // straight forward case type and name are the same
        Element matched = null;
        for (Map.Entry<Element, AttributeDescriptor> entry : map.entrySet()) {
            AttributeDescriptor attribute = entry.getValue();
            String fieldName = attribute.fieldName();
            if (fieldName.equalsIgnoreCase(parameter.getSimpleName().toString())) {
                names.add(fieldName);
                matched = entry.getKey();
            }
        }
        if (matched != null) {
            map.remove(matched);
        }
    }
    // didn't work likely because the parameter names are missing
    if (names.isEmpty()) {
        // for kotlin data classes add processable element field names in order
        if (isUnimplementable()) {
            ElementFilter.methodsIn(element().getEnclosedElements()).stream().filter(this::isMethodProcessable).forEach(getter -> names.addAll(map.entrySet().stream().filter(entry -> entry.getKey().equals(getter)).map(entry -> entry.getValue().fieldName()).collect(Collectors.toList())));
        } else {
            for (Map.Entry<Element, AttributeDescriptor> entry : map.entrySet()) {
                names.add(0, entry.getValue().fieldName());
            }
        }
    }
    return names;
}
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) ExecutableElement(javax.lang.model.element.ExecutableElement) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) ArrayList(java.util.ArrayList) VariableElement(javax.lang.model.element.VariableElement) LinkedHashMap(java.util.LinkedHashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 25 with VariableElement

use of javax.lang.model.element.VariableElement in project roboguice by roboguice.

the class GuiceAnnotationProcessor method addMethodOrConstructorToAnnotationDatabase.

private void addMethodOrConstructorToAnnotationDatabase(String annotationClassName, Element injectionPoint) {
    String injectionPointName = injectionPoint.getSimpleName().toString();
    for (VariableElement variable : ((ExecutableElement) injectionPoint).getParameters()) {
        String parameterTypeName = getTypeName((TypeElement) ((DeclaredType) variable.asType()).asElement());
        bindableClasses.add(parameterTypeName);
        injectionPointName += ":" + parameterTypeName;
    }
    TypeElement typeElementRequiringScanning = (TypeElement) injectionPoint.getEnclosingElement();
    String typeElementName = getTypeName(typeElementRequiringScanning);
    //System.out.printf("Type: %s, injection: %s \n",typeElementName, injectionPointName);
    if (injectionPointName.startsWith("<init>")) {
        addToInjectedConstructors(annotationClassName, typeElementName, injectionPointName);
    } else {
        addToInjectedMethods(annotationClassName, typeElementName, injectionPointName);
    }
}
Also used : TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) String(java.lang.String) VariableElement(javax.lang.model.element.VariableElement) DeclaredType(javax.lang.model.type.DeclaredType)

Aggregations

VariableElement (javax.lang.model.element.VariableElement)248 ExecutableElement (javax.lang.model.element.ExecutableElement)75 TypeElement (javax.lang.model.element.TypeElement)75 TypeMirror (javax.lang.model.type.TypeMirror)72 GeneratedVariableElement (com.google.devtools.j2objc.types.GeneratedVariableElement)35 Element (javax.lang.model.element.Element)35 Expression (com.google.devtools.j2objc.ast.Expression)30 SimpleName (com.google.devtools.j2objc.ast.SimpleName)28 JVar (com.helger.jcodemodel.JVar)25 InfixExpression (com.google.devtools.j2objc.ast.InfixExpression)23 ArrayList (java.util.ArrayList)23 PostfixExpression (com.google.devtools.j2objc.ast.PostfixExpression)16 PrefixExpression (com.google.devtools.j2objc.ast.PrefixExpression)16 JInvocation (com.helger.jcodemodel.JInvocation)16 DeclaredType (javax.lang.model.type.DeclaredType)16 JBlock (com.helger.jcodemodel.JBlock)15 AbstractJClass (com.helger.jcodemodel.AbstractJClass)14 SingleVariableDeclaration (com.google.devtools.j2objc.ast.SingleVariableDeclaration)13 Elements (javax.lang.model.util.Elements)13 VariableDeclarationStatement (com.google.devtools.j2objc.ast.VariableDeclarationStatement)12