Search in sources :

Example 21 with ParameterizedTypeName

use of com.squareup.javapoet.ParameterizedTypeName in project tiger by google.

the class Utils method getDependencyInfoByGeneric.

/**
   * Return {@link NewDependencyInfo} for the generalized {@link NewBindingKey} for
   * the give key. Null if not applicable or not exist.
   */
public static NewDependencyInfo getDependencyInfoByGeneric(SetMultimap<NewBindingKey, NewDependencyInfo> dependencies, NewBindingKey key) {
    TypeName typeName = key.getTypeName();
    Preconditions.checkArgument(key.getQualifier() == null, String.format("Binding to %s is supposed to be resolved through generic type of %s" + "but has non-null qualifier.", key, typeName));
    if (typeName instanceof ParameterizedTypeName) {
        ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;
        ClassName rawTypeName = parameterizedTypeName.rawType;
        NewBindingKey rawKey = NewBindingKey.get(rawTypeName);
        if (dependencies.containsKey(rawKey)) {
            NewDependencyInfo dependencyInfo = Iterables.getOnlyElement(dependencies.get(rawKey));
            TypeName formalTypeName = dependencyInfo.getDependant().getTypeName();
            Preconditions.checkState(formalTypeName instanceof ParameterizedTypeName, String.format("Formal type %s is not of type ParameterizedTypeName. Related actual type is %s", formalTypeName, parameterizedTypeName));
            Map<TypeVariableName, TypeName> mapTypeVariableToSpecialized = getMapFromTypeVariableToSpecialized(parameterizedTypeName, (ParameterizedTypeName) formalTypeName);
            Set<NewBindingKey> specializedDependencies = specializeIfNeeded(dependencyInfo.getDependencies(), mapTypeVariableToSpecialized);
            return new NewDependencyInfo(key, specializedDependencies, dependencyInfo.getSourceClassElement(), dependencyInfo.getProvisionMethodElement(), dependencyInfo.getType());
        }
    }
    return null;
}
Also used : TypeName(com.squareup.javapoet.TypeName) WildcardTypeName(com.squareup.javapoet.WildcardTypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) ArrayTypeName(com.squareup.javapoet.ArrayTypeName) ClassName(com.squareup.javapoet.ClassName) TypeVariableName(com.squareup.javapoet.TypeVariableName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName)

Example 22 with ParameterizedTypeName

use of com.squareup.javapoet.ParameterizedTypeName in project tiger by google.

the class Utils method isMap.

/**
   * Returns if key is a map with type variables.
   */
public static boolean isMap(NewBindingKey key) {
    TypeName typeName = key.getTypeName();
    if (!(typeName instanceof ParameterizedTypeName)) {
        return false;
    }
    ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;
    return parameterizedTypeName.rawType.equals(ClassName.get(Map.class));
}
Also used : TypeName(com.squareup.javapoet.TypeName) WildcardTypeName(com.squareup.javapoet.WildcardTypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) ArrayTypeName(com.squareup.javapoet.ArrayTypeName) Map(java.util.Map) HashMap(java.util.HashMap) IntoMap(dagger.multibindings.IntoMap) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName)

Example 23 with ParameterizedTypeName

use of com.squareup.javapoet.ParameterizedTypeName in project requery by requery.

the class EntityGenerator method generateListeners.

private void generateListeners(MethodSpec.Builder constructor) {
    for (Map.Entry<Element, ? extends ListenerDescriptor> entry : entity.listeners().entrySet()) {
        for (Annotation annotation : entry.getValue().listenerAnnotations()) {
            String annotationName = annotation.annotationType().getSimpleName().replace("Persist", "Insert").replace("Remove", "Delete");
            String methodName = Names.lowerCaseFirst(annotationName);
            // avoid hardcoding the package name here
            Element listener = elements.getTypeElement(PreInsertListener.class.getCanonicalName());
            PackageElement packageElement = elements.getPackageOf(listener);
            // generate the listener name
            String packageName = packageElement.getQualifiedName().toString();
            ClassName listenerName = ClassName.get(packageName, annotationName + "Listener");
            ParameterizedTypeName getterType = ParameterizedTypeName.get(listenerName, typeName);
            TypeSpec.Builder listenerBuilder = TypeSpec.anonymousClassBuilder("").addSuperinterface(getterType).addMethod(CodeGeneration.overridePublicMethod(methodName).addParameter(typeName, "entity").addStatement("$L()", entry.getKey().getSimpleName()).build());
            constructor.addStatement("$L.modifyListeners().add$L($L)", PROXY_NAME, annotationName + "Listener", listenerBuilder.build());
        }
    }
}
Also used : ClassName(com.squareup.javapoet.ClassName) PreInsertListener(io.requery.proxy.PreInsertListener) Map(java.util.Map) Annotation(java.lang.annotation.Annotation) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 24 with ParameterizedTypeName

use of com.squareup.javapoet.ParameterizedTypeName in project requery by requery.

the class EntityGenerator method generateProxyMethods.

private void generateProxyMethods(TypeSpec.Builder builder) {
    // add proxy field
    TypeName entityType = entity.isEmbedded() ? nameResolver.typeNameOf(parent) : typeName;
    TypeName proxyName = parameterizedTypeName(EntityProxy.class, entityType);
    FieldSpec.Builder proxyField = FieldSpec.builder(proxyName, PROXY_NAME, Modifier.PRIVATE, Modifier.FINAL, Modifier.TRANSIENT);
    if (!entity.isEmbedded()) {
        proxyField.initializer("new $T(this, $L)", proxyName, TYPE_NAME);
    }
    builder.addField(proxyField.build());
    for (AttributeDescriptor attribute : entity.attributes().values()) {
        boolean useField = attribute.isTransient() || attribute.isEmbedded();
        TypeMirror typeMirror = attribute.typeMirror();
        TypeName unboxedTypeName;
        if (attribute.isIterable()) {
            unboxedTypeName = parameterizedCollectionName(typeMirror);
        } else if (attribute.isOptional()) {
            unboxedTypeName = TypeName.get(tryFirstTypeArgument(attribute.typeMirror()));
        } else if (attribute.isEmbedded()) {
            EntityDescriptor embedded = graph.embeddedDescriptorOf(attribute).orElseThrow(IllegalStateException::new);
            unboxedTypeName = nameResolver.embeddedTypeNameOf(embedded, entity);
        } else {
            unboxedTypeName = nameResolver.tryGeneratedTypeName(typeMirror);
        }
        String attributeName = attribute.fieldName();
        String getterName = attribute.getterName();
        String fieldName = Names.upperCaseUnderscore(Names.removeMemberPrefixes(attributeName));
        if (entity.isEmbedded()) {
            fieldName = attributeFieldName(attribute);
        }
        // getter
        MethodSpec.Builder getter = MethodSpec.methodBuilder(getterName).addModifiers(Modifier.PUBLIC).returns(attribute.isOptional() ? TypeName.get(typeMirror) : unboxedTypeName);
        if (Mirrors.overridesMethod(types, typeElement, getterName)) {
            getter.addAnnotation(Override.class);
        }
        memberExtensions.forEach(extension -> extension.addToGetter(attribute, getter));
        if (useField) {
            if (attribute.isEmbedded()) {
                // have to cast to embedded type
                getter.addStatement("return ($T)this.$L", unboxedTypeName, attributeName);
            } else {
                getter.addStatement("return this.$L", attributeName);
            }
        } else if (attribute.isOptional()) {
            getter.addStatement("return $T.ofNullable($L.get($L))", Optional.class, PROXY_NAME, fieldName);
        } else {
            getter.addStatement("return $L.get($L)", PROXY_NAME, fieldName);
        }
        builder.addMethod(getter.build());
        // setter
        String setterName = attribute.setterName();
        // if read only don't generate a public setter
        boolean readOnly = entity.isReadOnly() || attribute.isReadOnly();
        // edge case check if it's interface and we need to implement the setter
        if (entity.element().getKind().isInterface() && ElementFilter.methodsIn(entity.element().getEnclosedElements()).stream().anyMatch(element -> element.getSimpleName().toString().equals(setterName))) {
            readOnly = false;
        }
        if (!readOnly) {
            TypeName setTypeName = unboxedTypeName;
            boolean castType = false;
            // use wildcard generic collection type if necessary
            if (setTypeName instanceof ParameterizedTypeName) {
                ParameterizedTypeName parameterizedName = (ParameterizedTypeName) setTypeName;
                List<TypeName> arguments = parameterizedName.typeArguments;
                List<TypeName> wildcards = new ArrayList<>();
                for (TypeName argument : arguments) {
                    if (!(argument instanceof WildcardTypeName)) {
                        Elements elements = processingEnv.getElementUtils();
                        TypeElement element = elements.getTypeElement(argument.toString());
                        if (element != null && element.getKind() == ElementKind.INTERFACE) {
                            wildcards.add(WildcardTypeName.subtypeOf(argument));
                        } else {
                            wildcards.add(argument);
                        }
                    } else {
                        wildcards.add(argument);
                    }
                }
                TypeName[] array = new TypeName[wildcards.size()];
                setTypeName = ParameterizedTypeName.get(parameterizedName.rawType, wildcards.toArray(array));
                castType = true;
            }
            String paramName = Names.lowerCaseFirst(Names.removeMemberPrefixes(attributeName));
            MethodSpec.Builder setter = MethodSpec.methodBuilder(setterName).addModifiers(Modifier.PUBLIC).addParameter(setTypeName, paramName);
            if (useField) {
                setter.addStatement("this.$L = $L", attributeName, paramName);
            } else {
                if (castType) {
                    setter.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build());
                    setter.addStatement("$L.set($L, ($T)$L)", PROXY_NAME, fieldName, unboxedTypeName, paramName);
                } else {
                    setter.addStatement("$L.set($L, $L)", PROXY_NAME, fieldName, paramName);
                }
            }
            memberExtensions.forEach(extension -> extension.addToSetter(attribute, setter));
            PropertyNameStyle style = entity.propertyNameStyle();
            if (style == PropertyNameStyle.FLUENT || style == PropertyNameStyle.FLUENT_BEAN) {
                setter.addStatement("return this");
                setter.returns(typeName);
            }
            builder.addMethod(setter.build());
        }
    }
    MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC);
    if (entity.isEmbedded()) {
        constructor.addParameter(ParameterSpec.builder(proxyName, "proxy").build());
        constructor.addStatement("this.$L = proxy", PROXY_NAME);
        entity.attributes().values().stream().filter(attribute -> !attribute.isTransient()).forEach(attribute -> {
            ParameterizedTypeName attributeType = ParameterizedTypeName.get(ClassName.get(Attribute.class), nameResolver.typeNameOf(parent), resolveAttributeType(attribute));
            constructor.addParameter(ParameterSpec.builder(attributeType, attribute.name()).build());
            constructor.addStatement("this.$L = $L", attributeFieldName(attribute), attribute.name());
        });
    }
    generateListeners(constructor);
    // initialize the generated embedded entities
    entity.attributes().values().stream().filter(AttributeDescriptor::isEmbedded).forEach(attribute -> graph.embeddedDescriptorOf(attribute).ifPresent(embedded -> {
        ClassName embeddedName = nameResolver.embeddedTypeNameOf(embedded, entity);
        String format = embedded.attributes().values().stream().map(attr -> Names.upperCaseUnderscore(embeddedAttributeName(attribute, attr))).collect(Collectors.joining(", ", "$L = new $T($L, ", ")"));
        constructor.addStatement(format, attribute.fieldName(), embeddedName, PROXY_NAME);
    }));
    builder.addMethod(constructor.build());
}
Also used : EntityProxy(io.requery.proxy.EntityProxy) FieldSpec(com.squareup.javapoet.FieldSpec) ClassName(com.squareup.javapoet.ClassName) WildcardTypeName(com.squareup.javapoet.WildcardTypeName) Elements(javax.lang.model.util.Elements) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Map(java.util.Map) PropertyNameStyle(io.requery.PropertyNameStyle) ElementFilter(javax.lang.model.util.ElementFilter) javax.lang.model.element(javax.lang.model.element) Persistable(io.requery.Persistable) ParameterSpec(com.squareup.javapoet.ParameterSpec) Entity(io.requery.Entity) MethodSpec(com.squareup.javapoet.MethodSpec) Set(java.util.Set) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) IOException(java.io.IOException) Attribute(io.requery.meta.Attribute) PropertyState(io.requery.proxy.PropertyState) TypeSpec(com.squareup.javapoet.TypeSpec) Collectors(java.util.stream.Collectors) TypeMirror(javax.lang.model.type.TypeMirror) List(java.util.List) PreInsertListener(io.requery.proxy.PreInsertListener) AnnotationSpec(com.squareup.javapoet.AnnotationSpec) StringJoiner(java.util.StringJoiner) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) Annotation(java.lang.annotation.Annotation) TypeName(com.squareup.javapoet.TypeName) Optional(java.util.Optional) WildcardTypeName(com.squareup.javapoet.WildcardTypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) Optional(java.util.Optional) MethodSpec(com.squareup.javapoet.MethodSpec) Attribute(io.requery.meta.Attribute) ArrayList(java.util.ArrayList) Elements(javax.lang.model.util.Elements) FieldSpec(com.squareup.javapoet.FieldSpec) TypeMirror(javax.lang.model.type.TypeMirror) ClassName(com.squareup.javapoet.ClassName) WildcardTypeName(com.squareup.javapoet.WildcardTypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) PropertyNameStyle(io.requery.PropertyNameStyle)

Example 25 with ParameterizedTypeName

use of com.squareup.javapoet.ParameterizedTypeName in project requery by requery.

the class EntityGenerator method generateMembers.

private void generateMembers(TypeSpec.Builder builder) {
    Modifier visibility = entity.isEmbedded() ? Modifier.PROTECTED : Modifier.PRIVATE;
    // generate property states
    if (!entity.isStateless()) {
        entity.attributes().values().stream().filter(attribute -> !attribute.isTransient()).forEach(attribute -> {
            TypeName stateType = ClassName.get(PropertyState.class);
            builder.addField(FieldSpec.builder(stateType, propertyStateFieldName(attribute), visibility).build());
        });
    }
    if (entity.isEmbedded() && !(entity.isImmutable() || entity.isUnimplementable())) {
        entity.attributes().values().stream().filter(attribute -> !attribute.isTransient()).forEach(attribute -> {
            ParameterizedTypeName attributeType = ParameterizedTypeName.get(ClassName.get(Attribute.class), nameResolver.typeNameOf(parent), resolveAttributeType(attribute));
            builder.addField(FieldSpec.builder(attributeType, attributeFieldName(attribute), Modifier.PRIVATE, Modifier.FINAL).build());
        });
    }
    // only generate for interfaces or if the entity is immutable but has no builder
    boolean generateMembers = typeElement.getKind().isInterface() || !entity.builderType().isPresent();
    Set<String> existingFieldNames = entity.attributes().keySet().stream().filter(it -> it.getKind() == ElementKind.FIELD).map(it -> it.getSimpleName().toString()).collect(Collectors.toSet());
    if (generateMembers) {
        for (Map.Entry<Element, ? extends AttributeDescriptor> entry : entity.attributes().entrySet()) {
            Element element = entry.getKey();
            AttributeDescriptor attribute = entry.getValue();
            if (element.getKind() == ElementKind.METHOD) {
                ExecutableElement methodElement = (ExecutableElement) element;
                TypeMirror typeMirror = methodElement.getReturnType();
                TypeName fieldName;
                if (attribute.isIterable()) {
                    fieldName = parameterizedCollectionName(typeMirror);
                } else if (attribute.isOptional()) {
                    typeMirror = tryFirstTypeArgument(attribute.typeMirror());
                    fieldName = TypeName.get(typeMirror);
                } else {
                    fieldName = nameResolver.tryGeneratedTypeName(typeMirror);
                }
                if (entity.isImmutable() || !existingFieldNames.contains(attribute.fieldName())) {
                    builder.addField(FieldSpec.builder(fieldName, attribute.fieldName(), visibility).build());
                }
            }
        }
    }
    if (entity.isImmutable()) {
        generateBuilder(builder, entity, "builder");
        entity.attributes().values().stream().filter(AttributeDescriptor::isEmbedded).forEach(attribute -> graph.embeddedDescriptorOf(attribute).ifPresent(embedded -> embedded.builderType().ifPresent(type -> {
            String fieldName = attribute.fieldName() + "Builder";
            generateBuilder(builder, embedded, fieldName);
        })));
    }
}
Also used : EntityProxy(io.requery.proxy.EntityProxy) FieldSpec(com.squareup.javapoet.FieldSpec) ClassName(com.squareup.javapoet.ClassName) WildcardTypeName(com.squareup.javapoet.WildcardTypeName) Elements(javax.lang.model.util.Elements) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Map(java.util.Map) PropertyNameStyle(io.requery.PropertyNameStyle) ElementFilter(javax.lang.model.util.ElementFilter) javax.lang.model.element(javax.lang.model.element) Persistable(io.requery.Persistable) ParameterSpec(com.squareup.javapoet.ParameterSpec) Entity(io.requery.Entity) MethodSpec(com.squareup.javapoet.MethodSpec) Set(java.util.Set) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) IOException(java.io.IOException) Attribute(io.requery.meta.Attribute) PropertyState(io.requery.proxy.PropertyState) TypeSpec(com.squareup.javapoet.TypeSpec) Collectors(java.util.stream.Collectors) TypeMirror(javax.lang.model.type.TypeMirror) List(java.util.List) PreInsertListener(io.requery.proxy.PreInsertListener) AnnotationSpec(com.squareup.javapoet.AnnotationSpec) StringJoiner(java.util.StringJoiner) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) Annotation(java.lang.annotation.Annotation) TypeName(com.squareup.javapoet.TypeName) Optional(java.util.Optional) WildcardTypeName(com.squareup.javapoet.WildcardTypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) Attribute(io.requery.meta.Attribute) TypeMirror(javax.lang.model.type.TypeMirror) Map(java.util.Map) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName)

Aggregations

ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)31 TypeName (com.squareup.javapoet.TypeName)23 ClassName (com.squareup.javapoet.ClassName)21 TypeSpec (com.squareup.javapoet.TypeSpec)14 MethodSpec (com.squareup.javapoet.MethodSpec)13 TypeElement (javax.lang.model.element.TypeElement)10 WildcardTypeName (com.squareup.javapoet.WildcardTypeName)9 TypeMirror (javax.lang.model.type.TypeMirror)8 Map (java.util.Map)6 ArrayTypeName (com.squareup.javapoet.ArrayTypeName)5 FieldSpec (com.squareup.javapoet.FieldSpec)5 ParameterSpec (com.squareup.javapoet.ParameterSpec)5 TypeVariableName (com.squareup.javapoet.TypeVariableName)5 ArrayList (java.util.ArrayList)5 HashSet (java.util.HashSet)5 Set (java.util.Set)5 Builder (com.squareup.javapoet.TypeSpec.Builder)4 Attribute (io.requery.meta.Attribute)4 AnnotationSpec (com.squareup.javapoet.AnnotationSpec)3 CodeBlock (com.squareup.javapoet.CodeBlock)3