Search in sources :

Example 46 with TypeName

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

the class EntityMetaGenerator method generateProperties.

private void generateProperties(AttributeDescriptor attribute, AttributeDescriptor parent, TypeMirror typeMirror, TypeName targetName, TypeName attributeName, CodeBlock.Builder block) {
    String prefix = "";
    if (parent != null) {
        prefix = parent.getterName() + "().";
    }
    // boxed get/set using Objects
    Class propertyClass = propertyClassFor(typeMirror);
    ParameterizedTypeName propertyType = propertyName(propertyClass, targetName, attributeName);
    TypeSpec.Builder builder = TypeSpec.anonymousClassBuilder("").addSuperinterface(propertyType);
    boolean isNullable = typeMirror.getKind().isPrimitive() && attribute.isNullable();
    boolean useGetter = entity.isUnimplementable() || entity.isImmutable();
    boolean useSetter = entity.isUnimplementable();
    String getName = prefix + (useGetter ? attribute.getterName() : attribute.fieldName());
    String setName = prefix + (useSetter ? attribute.setterName() : attribute.fieldName());
    new GeneratedProperty(getName, setName, targetName, attributeName).setNullable(isNullable).setReadOnly(entity.isImmutable()).setUseMethod(useGetter).build(builder);
    // additional primitive get/set if the type is primitive
    if (propertyClass != Property.class) {
        TypeName primitiveType = TypeName.get(attribute.typeMirror());
        String name = Names.upperCaseFirst(attribute.typeMirror().toString());
        new GeneratedProperty(getName, setName, targetName, primitiveType).setMethodSuffix(name).setReadOnly(entity.isImmutable()).setUseMethod(useGetter).build(builder);
    }
    block.add(".setProperty($L)\n", builder.build());
    block.add(".setPropertyName($S)\n", attribute.element().getSimpleName());
    // property state get/set
    if (!entity.isStateless()) {
        ClassName stateClass = ClassName.get(PropertyState.class);
        TypeSpec.Builder stateType = TypeSpec.anonymousClassBuilder("").addSuperinterface(parameterizedTypeName(Property.class, targetName, stateClass));
        String fieldName = prefix + propertyStateFieldName(attribute);
        new GeneratedProperty(fieldName, targetName, stateClass).build(stateType);
        block.add(".setPropertyState($L)\n", stateType.build());
    }
    if (!entity.isImmutable()) {
        return;
    }
    // if immutable add setter for the builder
    String propertyName = attribute.fieldName();
    TypeName builderName = typeName;
    useSetter = false;
    String parameterSuffix = null;
    Optional<TypeMirror> builderType = entity.builderType();
    if (builderType.isPresent()) {
        parameterSuffix = ".builder";
        if (parent != null) {
            parameterSuffix = "." + parent.fieldName() + "Builder";
        }
        propertyName = attribute.setterName();
        useSetter = true;
        TypeElement element = elements.getTypeElement(builderType.get().toString());
        if (element != null) {
            for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) {
                List<? extends VariableElement> parameters = method.getParameters();
                String name = Names.removeMethodPrefixes(method.getSimpleName());
                // (some builders have with<Property> setters so strip that
                if ((Names.matchesSetter("with", name)) || name.equalsIgnoreCase(attribute.fieldName()) && parameters.size() == 1) {
                    propertyName = method.getSimpleName().toString();
                    break;
                } else if (Names.matchesSetter("set", name) || name.equalsIgnoreCase(attribute.fieldName()) && parameters.size() == 1) {
                    propertyName = method.getSimpleName().toString();
                    break;
                }
            }
        } else {
            // prefixed, prefix boolean types with is
            if (ImmutableAnnotationKind.IMMUTABLE.isPresent(entity.element())) {
                propertyName = attribute.fieldName();
                String getterName = attribute.getterName().replaceFirst("get", "");
                if (attribute.typeMirror().getKind() == TypeKind.BOOLEAN) {
                    propertyName = "is" + Names.upperCaseFirst(propertyName);
                } else if (Names.isAllUpper(getterName)) {
                    propertyName = Names.lowerCaseFirst(getterName);
                }
            }
        }
    }
    propertyType = propertyName(propertyClass, builderName, attributeName);
    TypeSpec.Builder builderProperty = TypeSpec.anonymousClassBuilder("").addSuperinterface(propertyType);
    new GeneratedProperty(propertyName, builderName, attributeName).setWriteOnly(true).setUseMethod(useSetter).setAccessSuffix(parameterSuffix).build(builderProperty);
    if (propertyClass != Property.class) {
        TypeName primitiveType = TypeName.get(attribute.typeMirror());
        String name = Names.upperCaseFirst(attribute.typeMirror().toString());
        new GeneratedProperty(propertyName, builderName, primitiveType).setMethodSuffix(name).setAccessSuffix(parameterSuffix).setUseMethod(useSetter).setWriteOnly(true).build(builderProperty);
    }
    block.add(".setBuilderProperty($L)\n", builderProperty.build());
}
Also used : ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) TypeMirror(javax.lang.model.type.TypeMirror) ClassName(com.squareup.javapoet.ClassName) BooleanProperty(io.requery.proxy.BooleanProperty) LongProperty(io.requery.proxy.LongProperty) ByteProperty(io.requery.proxy.ByteProperty) FloatProperty(io.requery.proxy.FloatProperty) Property(io.requery.proxy.Property) IntProperty(io.requery.proxy.IntProperty) DoubleProperty(io.requery.proxy.DoubleProperty) ShortProperty(io.requery.proxy.ShortProperty) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 47 with TypeName

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

the class EntityMetaGenerator method generateJunctionType.

private Optional<TypeName> generateJunctionType(AttributeDescriptor attribute, EntityDescriptor referenced, Set<AttributeDescriptor> mappings) {
    TypeName typeName = null;
    Optional<AssociativeEntityDescriptor> descriptor = attribute.associativeEntity();
    if (descriptor.isPresent()) {
        Optional<TypeMirror> mirror = descriptor.get().type();
        if (mirror.isPresent()) {
            typeName = guessAnyTypeName(entity.typeName().packageName(), mirror.get());
        } else {
            // generate a special type for the junction table (with attributes)
            graph.referencingEntity(attribute).ifPresent(referencing -> {
                JoinEntityGenerator generator = new JoinEntityGenerator(processingEnv, nameResolver, entity, referencing, attribute);
                try {
                    generator.generate();
                } catch (IOException e) {
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.toString());
                    throw new RuntimeException(e);
                }
            });
            typeName = nameResolver.joinEntityName(descriptor.get(), entity, referenced);
        }
    } else if (mappings.size() == 1) {
        descriptor = mappings.iterator().next().associativeEntity();
        if (descriptor.isPresent()) {
            Optional<TypeMirror> mirror = descriptor.get().type();
            if (mirror.isPresent()) {
                typeName = guessAnyTypeName(entity.typeName().packageName(), mirror.get());
            } else {
                typeName = nameResolver.joinEntityName(descriptor.get(), referenced, entity);
            }
        }
    }
    return Optional.ofNullable(typeName);
}
Also used : ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) Optional(java.util.Optional) TypeMirror(javax.lang.model.type.TypeMirror) IOException(java.io.IOException)

Example 48 with TypeName

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

the class EntityMetaGenerator method generate.

void generate(TypeSpec.Builder builder) {
    boolean metadataOnly = entity.isImmutable() || entity.isUnimplementable();
    TypeName targetName = metadataOnly ? ClassName.get(entity.element()) : typeName;
    List<QualifiedName> generatedEmbeddedTypes = new LinkedList<>();
    entity.attributes().values().stream().filter(attribute -> !attribute.isTransient()).forEach(attribute -> {
        String fieldName = upperCaseUnderscoreRemovePrefixes(attribute.fieldName());
        if (attribute.isForeignKey() && attribute.cardinality() != null) {
            graph.referencingEntity(attribute).flatMap(entity -> graph.referencingAttribute(attribute, entity)).ifPresent(foreignKey -> {
                String name = fieldName + "_ID";
                TypeMirror mirror = foreignKey.typeMirror();
                builder.addField(generateAttribute(attribute, null, targetName, name, mirror, true));
                expressionNames.add(name);
            });
        }
        if (attribute.isEmbedded()) {
            graph.embeddedDescriptorOf(attribute).ifPresent(embedded -> {
                generateEmbeddedAttributes(attribute, embedded, builder, targetName);
                if (!generatedEmbeddedTypes.contains(embedded.typeName())) {
                    generatedEmbeddedTypes.add(embedded.typeName());
                    generateEmbeddedEntity(embedded);
                }
            });
        } else {
            TypeMirror mirror = attribute.typeMirror();
            builder.addField(generateAttribute(attribute, null, targetName, fieldName, mirror, false));
            attributeNames.add(fieldName);
        }
    });
    generateType(builder, targetName);
}
Also used : EntityProxy(io.requery.proxy.EntityProxy) Modifier(javax.lang.model.element.Modifier) BooleanProperty(io.requery.proxy.BooleanProperty) FieldSpec(com.squareup.javapoet.FieldSpec) LongProperty(io.requery.proxy.LongProperty) VariableElement(javax.lang.model.element.VariableElement) ClassName(com.squareup.javapoet.ClassName) QueryAttribute(io.requery.meta.QueryAttribute) TypeBuilder(io.requery.meta.TypeBuilder) TypeElement(javax.lang.model.element.TypeElement) ReferentialAction(io.requery.ReferentialAction) HashSet(java.util.HashSet) Function(io.requery.util.function.Function) ByteProperty(io.requery.proxy.ByteProperty) Diagnostic(javax.tools.Diagnostic) Type(io.requery.meta.Type) FloatProperty(io.requery.proxy.FloatProperty) ElementFilter(javax.lang.model.util.ElementFilter) LinkedList(java.util.LinkedList) CodeBlock(com.squareup.javapoet.CodeBlock) Property(io.requery.proxy.Property) MethodSpec(com.squareup.javapoet.MethodSpec) IntProperty(io.requery.proxy.IntProperty) ExecutableElement(javax.lang.model.element.ExecutableElement) Supplier(io.requery.util.function.Supplier) 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) Order(io.requery.query.Order) QueryExpression(io.requery.meta.QueryExpression) TypeKind(javax.lang.model.type.TypeKind) CascadeAction(io.requery.CascadeAction) TypeMirror(javax.lang.model.type.TypeMirror) List(java.util.List) Cardinality(io.requery.meta.Cardinality) DoubleProperty(io.requery.proxy.DoubleProperty) StringJoiner(java.util.StringJoiner) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) TypeName(com.squareup.javapoet.TypeName) Optional(java.util.Optional) ShortProperty(io.requery.proxy.ShortProperty) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) TypeMirror(javax.lang.model.type.TypeMirror) LinkedList(java.util.LinkedList)

Example 49 with TypeName

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

the class AndroidParcelableExtension method generate.

@Override
public void generate(EntityDescriptor entity, TypeSpec.Builder builder) {
    // if not parcelable or the class implements itself don't implement it
    TypeElement typeElement = entity.element();
    if (entity.isImmutable() || !Mirrors.isInstance(types, typeElement, PACKAGE_ANDROID_OS + ".Parcelable") || Mirrors.overridesMethod(types, typeElement, "writeToParcel")) {
        return;
    }
    ClassName className = ClassName.bestGuess(entity.typeName().toString());
    // implement the parcelable interface
    TypeName creatorType = ParameterizedTypeName.get(ClassName.get(PACKAGE_ANDROID_OS, "Parcelable.Creator"), className);
    ClassName parcelName = ClassName.get(PACKAGE_ANDROID_OS, "Parcel");
    ClassName parcelableName = ClassName.get(PACKAGE_ANDROID_OS, "Parcelable");
    builder.addSuperinterface(parcelableName);
    TypeSpec.Builder creatorBuilder = TypeSpec.anonymousClassBuilder("").addSuperinterface(creatorType).addMethod(CodeGeneration.overridePublicMethod("createFromParcel").addParameter(ParameterSpec.builder(parcelName, "source").build()).addStatement("return PARCELER.readFromParcel(source)").returns(className).build()).addMethod(CodeGeneration.overridePublicMethod("newArray").addParameter(TypeName.INT, "size").addStatement("return new $T[size]", className).returns(ArrayTypeName.of(className)).build());
    builder.addField(FieldSpec.builder(creatorType, "CREATOR", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).initializer("$L", creatorBuilder.build()).build());
    builder.addMethod(CodeGeneration.overridePublicMethod("describeContents").returns(TypeName.INT).addStatement("return 0").build());
    builder.addMethod(CodeGeneration.overridePublicMethod("writeToParcel").returns(TypeName.VOID).addParameter(parcelName, "dest").addParameter(TypeName.INT, "flags").addStatement("PARCELER.writeToParcel(this, dest)").build());
    // add the parceler instance which uses the proxy to parcel the field data
    TypeName parcelerType = ParameterizedTypeName.get(ClassName.get(PACKAGE_PARCELER, "EntityParceler"), className);
    builder.addField(FieldSpec.builder(parcelerType, "PARCELER", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).initializer("new $T($L)", parcelerType, EntityGenerator.TYPE_NAME).build());
}
Also used : TypeName(com.squareup.javapoet.TypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) ArrayTypeName(com.squareup.javapoet.ArrayTypeName) TypeElement(javax.lang.model.element.TypeElement) ClassName(com.squareup.javapoet.ClassName) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 50 with TypeName

use of com.squareup.javapoet.TypeName in project epoxy by airbnb.

the class EpoxyProcessor method generateHashCode.

private MethodSpec generateHashCode(ClassToGenerateInfo helperClass) {
    Builder builder = MethodSpec.methodBuilder("hashCode").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).returns(int.class).addStatement("int result = super.hashCode()");
    for (AttributeInfo attributeInfo : helperClass.getAttributeInfo()) {
        if (!attributeInfo.useInHash()) {
            continue;
        }
        if (attributeInfo.getType() == DOUBLE) {
            builder.addStatement("long temp");
            break;
        }
    }
    for (AttributeInfo attributeInfo : helperClass.getAttributeInfo()) {
        TypeName type = attributeInfo.getType();
        if (!attributeInfo.useInHash() && type.isPrimitive()) {
            continue;
        }
        String name = attributeInfo.getName();
        if (attributeInfo.useInHash()) {
            if ((type == BYTE) || (type == CHAR) || (type == SHORT) || (type == INT)) {
                builder.addStatement("result = 31 * result + $L", name);
            } else if (type == LONG) {
                builder.addStatement("result = 31 * result + (int) ($L ^ ($L >>> 32))", name, name);
            } else if (type == FLOAT) {
                builder.addStatement("result = 31 * result + ($L != +0.0f " + "? Float.floatToIntBits($L) : 0)", name, name);
            } else if (type == DOUBLE) {
                builder.addStatement("temp = Double.doubleToLongBits($L)", name).addStatement("result = 31 * result + (int) (temp ^ (temp >>> 32))");
            } else if (type == BOOLEAN) {
                builder.addStatement("result = 31 * result + ($L ? 1 : 0)", name);
            } else if (type instanceof ArrayTypeName) {
                builder.addStatement("result = 31 * result + Arrays.hashCode($L)", name);
            } else {
                builder.addStatement("result = 31 * result + ($L != null ? $L.hashCode() : 0)", name, name);
            }
        } else {
            builder.addStatement("result = 31 * result + ($L != null ? 1 : 0)", name);
        }
    }
    return builder.addStatement("return result").build();
}
Also used : TypeName(com.squareup.javapoet.TypeName) ArrayTypeName(com.squareup.javapoet.ArrayTypeName) ArrayTypeName(com.squareup.javapoet.ArrayTypeName) Builder(com.squareup.javapoet.MethodSpec.Builder)

Aggregations

TypeName (com.squareup.javapoet.TypeName)63 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)54 ClassName (com.squareup.javapoet.ClassName)30 MethodSpec (com.squareup.javapoet.MethodSpec)27 TypeSpec (com.squareup.javapoet.TypeSpec)22 TypeMirror (javax.lang.model.type.TypeMirror)17 TypeElement (javax.lang.model.element.TypeElement)16 WildcardTypeName (com.squareup.javapoet.WildcardTypeName)14 ArrayTypeName (com.squareup.javapoet.ArrayTypeName)10 Map (java.util.Map)10 CodeBlock (com.squareup.javapoet.CodeBlock)9 FieldSpec (com.squareup.javapoet.FieldSpec)9 WireField (com.squareup.wire.WireField)9 Field (com.squareup.wire.schema.Field)9 ArrayList (java.util.ArrayList)9 HashSet (java.util.HashSet)7 List (java.util.List)7 Set (java.util.Set)7 AnnotationSpec (com.squareup.javapoet.AnnotationSpec)6 LinkedHashMap (java.util.LinkedHashMap)6