Search in sources :

Example 36 with ParameterizedTypeName

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

the class EntityMetaGenerator method generateType.

private void generateType(TypeSpec.Builder builder, TypeName targetName) {
    CodeBlock.Builder block = CodeBlock.builder().add("new $T<$T>($T.class, $S)\n", TypeBuilder.class, targetName, targetName, entity.tableName());
    block.add(".setBaseType($T.class)\n", ClassName.get(typeElement)).add(".setCacheable($L)\n", entity.isCacheable()).add(".setImmutable($L)\n", entity.isImmutable()).add(".setReadOnly($L)\n", entity.isReadOnly()).add(".setStateless($L)\n", entity.isStateless()).add(".setView($L)\n", entity.isView());
    String factoryName = entity.classFactoryName();
    if (!Names.isEmpty(factoryName)) {
        block.add(".setFactory(new $L())\n", ClassName.bestGuess(factoryName));
    } else if (entity.isImmutable()) {
        // returns this class as the builder
        TypeSpec.Builder supplier = TypeSpec.anonymousClassBuilder("").addSuperinterface(parameterizedTypeName(Supplier.class, typeName));
        supplier.addMethod(CodeGeneration.overridePublicMethod("get").returns(typeName).addStatement("return new $T()", typeName).build());
        block.add(".setBuilderFactory($L)\n", supplier.build());
        MethodSpec.Builder applyMethod = CodeGeneration.overridePublicMethod("apply").addParameter(typeName, "value").returns(targetName);
        // add embedded builder calls
        entity.attributes().stream().filter(AttributeDescriptor::isEmbedded).forEach(attribute -> graph.embeddedDescriptorOf(attribute).ifPresent(embedded -> embedded.builderType().ifPresent(type -> {
            String fieldName = attribute.fieldName() + "Builder";
            String methodName = attribute.setterName();
            applyMethod.addStatement("value.builder.$L(value.$L.build())", methodName, fieldName);
        })));
        applyMethod.addStatement(entity.builderType().isPresent() ? "return value.builder.build()" : "return value.build()");
        TypeSpec.Builder buildFunction = TypeSpec.anonymousClassBuilder("").addSuperinterface(parameterizedTypeName(Function.class, typeName, targetName)).addMethod(applyMethod.build());
        block.add(".setBuilderFunction($L)\n", buildFunction.build());
    } else {
        TypeSpec.Builder typeFactory = TypeSpec.anonymousClassBuilder("").addSuperinterface(parameterizedTypeName(Supplier.class, targetName)).addMethod(CodeGeneration.overridePublicMethod("get").addStatement("return new $T()", targetName).returns(targetName).build());
        block.add(".setFactory($L)\n", typeFactory.build());
    }
    ParameterizedTypeName proxyType = parameterizedTypeName(EntityProxy.class, targetName);
    TypeSpec.Builder proxyProvider = TypeSpec.anonymousClassBuilder("").addSuperinterface(parameterizedTypeName(Function.class, targetName, proxyType));
    MethodSpec.Builder proxyFunction = CodeGeneration.overridePublicMethod("apply").addParameter(targetName, "entity").returns(proxyType);
    if (entity.isImmutable() || entity.isUnimplementable()) {
        proxyFunction.addStatement("return new $T(entity, $L)", proxyType, TYPE_NAME);
    } else {
        proxyFunction.addStatement("return entity.$L", PROXY_NAME);
    }
    proxyProvider.addMethod(proxyFunction.build());
    block.add(".setProxyProvider($L)\n", proxyProvider.build());
    if (entity.tableAttributes().length > 0) {
        StringJoiner joiner = new StringJoiner(",", "new String[] {", "}");
        for (String attribute : entity.tableAttributes()) {
            joiner.add("\"" + attribute + "\"");
        }
        block.add(".setTableCreateAttributes($L)\n", joiner.toString());
    }
    if (entity.tableUniqueIndexes().length > 0) {
        StringJoiner joiner = new StringJoiner(",", "new String[] {", "}");
        for (String attribute : entity.tableUniqueIndexes()) {
            joiner.add("\"" + attribute + "\"");
        }
        block.add(".setTableUniqueIndexes($L)\n", joiner.toString());
    }
    attributeNames.forEach(name -> block.add(".addAttribute($L)\n", name));
    expressionNames.forEach(name -> block.add(".addExpression($L)\n", name));
    block.add(".build()");
    ParameterizedTypeName type = parameterizedTypeName(Type.class, targetName);
    builder.addField(FieldSpec.builder(type, TYPE_NAME, Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).initializer("$L", block.build()).build());
}
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) NumericAttribute(io.requery.meta.NumericAttribute) 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) StringAttribute(io.requery.meta.StringAttribute) MethodSpec(com.squareup.javapoet.MethodSpec) TypeBuilder(io.requery.meta.TypeBuilder) CodeBlock(com.squareup.javapoet.CodeBlock) Function(io.requery.util.function.Function) Supplier(io.requery.util.function.Supplier) StringJoiner(java.util.StringJoiner) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 37 with ParameterizedTypeName

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

the class GeneralInjectorGeneratorHubClone method generateProvisionMethodForSet.

/**
 * TODO: support set of builtin types.
 */
protected final void generateProvisionMethodForSet(BindingKey key, String suffix) {
    // logger.n("" + key +
    // " PackagedInjector: "
    // + getInjectorFor(key, referencingClass) + " SpecBuilder: " + componentSpecBuilder);
    ParameterizedTypeName type = (ParameterizedTypeName) key.getTypeName();
    Preconditions.checkArgument(type.rawType.equals(ClassName.get(Set.class)));
    TypeName elementType = Iterables.getOnlyElement(type.typeArguments);
    MethodSpec.Builder methodSpecBuilder = MethodSpec.methodBuilder(getProvisionMethodName(key) + suffix).addModifiers(suffix.isEmpty() ? Modifier.PUBLIC : Modifier.PRIVATE).returns(type);
    onProvisionMethodStart(methodSpecBuilder, key);
    methodSpecBuilder.addStatement("$T result = new $T<>()", type, HashSet.class);
    generateSetContributors(key, methodSpecBuilder);
    methodSpecBuilder.addStatement("return result");
    onProvisionMethodEnd(methodSpecBuilder, key);
    injectorBuilder.addMethod(methodSpecBuilder.build());
}
Also used : ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) MethodSpec(com.squareup.javapoet.MethodSpec) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName)

Example 38 with ParameterizedTypeName

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

the class GeneralInjectorGeneratorHubClone method generateMapContributors.

protected final void generateMapContributors(BindingKey key, ParameterizedTypeName returnType, MethodSpec.Builder methodSpecBuilder) {
    Set<DependencyInfo> dependencyInfos = utils.getDependencyInfo(dependencies, key);
    // TODO: remove this hack
    if (dependencyInfos == null) {
        dependencyInfos = new HashSet<>();
        logger.w("no dI for key: " + key);
    }
    Preconditions.checkNotNull(dependencyInfos, String.format("dependencyInfo not found for key: %s", key));
    TypeName mapKeyType = returnType.typeArguments.get(0);
    TypeName mapValueType = returnType.typeArguments.get(1);
    BindingKey mapValueKey = BindingKey.get(mapValueType);
    methodSpecBuilder.addStatement("$T mapKey", mapKeyType);
    methodSpecBuilder.addStatement("$T mapValue", mapValueType);
    for (DependencyInfo di : dependencyInfos) {
        if (utils.isMultibindsMethod(di.getProvisionMethodElement())) {
            continue;
        }
        AnnotationMirror mapKeyMirror = Utils.getAnnotationMirrorWithMetaAnnotation(di.getProvisionMethodElement(), MapKey.class);
        AnnotationValue unwrapValueAnnotationValue = Utils.getAnnotationValue(elements, mapKeyMirror, "unwrapValue");
        if (unwrapValueAnnotationValue != null && !((boolean) unwrapValueAnnotationValue.getValue())) {
            logger.e("unwrapValue = false not supported yet. Consider using set binding.");
            return;
        }
        AnnotationValue mapKey = Utils.getAnnotationValue(elements, mapKeyMirror, "value");
        logger.l(Kind.NOTE, "mapKey: %s", mapKey.toString());
        methodSpecBuilder.addStatement("mapKey = ($T) $L", mapKeyType, mapKey);
        if (utils.isMapWithBuiltinValueType(key)) {
            methodSpecBuilder.addStatement("mapValue = $L", createAnonymousBuiltinTypeForMultiBinding(mapValueKey, di));
        } else {
            addNewStatementToMethodSpec(methodSpecBuilder, di, "mapValue");
        }
        methodSpecBuilder.addStatement("result.put(mapKey, mapValue)");
    }
}
Also used : AnnotationMirror(javax.lang.model.element.AnnotationMirror) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) AnnotationValue(javax.lang.model.element.AnnotationValue)

Example 39 with ParameterizedTypeName

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

the class GeneralInjectorGeneratorHubClone method createAnonymousBuiltinType.

/**
 * Generate for either unique a binding or a contributor to a multi-binding. DependencyInfo is
 * null for unique one and non-null or multi-binding one. ReferencingClass is the opposite. For
 * multi-binding, referencing class is the module in dependency. Scope is null for unique binding.
 */
protected final TypeSpec createAnonymousBuiltinType(BindingKey key, @Nullable DependencyInfo dependencyInfo) {
    Preconditions.checkArgument(key.getTypeName() instanceof ParameterizedTypeName);
    boolean isMultiBinding = dependencyInfo != null;
    TypeName rawTypeName = ((ParameterizedTypeName) key.getTypeName()).rawType;
    Preconditions.checkArgument(utils.isProviderOrLazy(key), String.format("Built-in binding expected(Provider or Lazy), but get %s", key));
    boolean isLazy = rawTypeName.equals(ClassName.get(Lazy.class));
    BindingKey elementKey = utils.getElementKeyForParameterizedBinding(key);
    Preconditions.checkNotNull(elementKey);
    if (!isMultiBinding) {
        String provisionMethodName = getProvisionMethodName(elementKey);
        // utils.generateDebugInfoMethod(injectorBuilder,
        // "before" + provisionMethodName + generatedBindings.contains(provisionMethodName));
        generateProvisionMethodIfNeeded(elementKey);
    }
    // TODO: multi-threading.
    MethodSpec.Builder builderForGet = MethodSpec.methodBuilder("get").returns(elementKey.getTypeName()).addAnnotation(Override.class).addModifiers(Modifier.SYNCHRONIZED).addModifiers(Modifier.PUBLIC);
    if (isLazy) {
        builderForGet.beginControlFlow("if (var == null)");
    }
    if (!isMultiBinding) {
        Set<DependencyInfo> dIs = Utils.getDependencyInfosHandlingBox(dependencies, elementKey);
        if (dIs != null) {
            elementKey = Preconditions.checkNotNull(Iterables.getFirst(dIs, null), "key: " + elementKey + " dI: " + dIs).getDependant();
        }
        builderForGet.addStatement("var = $N()", getProvisionMethodName(elementKey));
    } else {
        /**
         * TODO: revisit the logic here, current, for Provide, Lazy and Optional, the key != {@link
         * DependencyInfo#getDependant()}.
         */
        addNewStatementToMethodSpec(builderForGet, dependencyInfo, "var");
    }
    if (isLazy) {
        builderForGet.endControlFlow();
    }
    builderForGet.addStatement("return var");
    return TypeSpec.anonymousClassBuilder("").addSuperinterface(key.getTypeName()).addField(elementKey.getTypeName(), "var", Modifier.PRIVATE).addMethod(builderForGet.build()).build();
}
Also used : Lazy(dagger.Lazy) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) MethodSpec(com.squareup.javapoet.MethodSpec) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName)

Example 40 with ParameterizedTypeName

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

the class DependencyCollector method collectionToMultimap.

/**
 * NOTE: the key of the returned map is of the raw type if the related
 * {@link DependencyInfo#getDependant()} is for a generic class.
 */
public static SetMultimap<BindingKey, DependencyInfo> collectionToMultimap(Collection<DependencyInfo> dependencies) {
    SetMultimap<BindingKey, DependencyInfo> result = HashMultimap.create();
    for (DependencyInfo info : dependencies) {
        BindingKey key = info.getDependant();
        TypeName typeName = key.getTypeName();
        // For generic type with type variable, only keep raw type.
        if (typeName instanceof ParameterizedTypeName) {
            ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;
            TypeName anyParameter = Preconditions.checkNotNull(Iterables.getFirst(parameterizedTypeName.typeArguments, null), String.format("ParameterizedTypeName of %s has no parameter.", key));
            if (anyParameter instanceof TypeVariableName) {
                typeName = parameterizedTypeName.rawType;
                key = BindingKey.get(typeName, key.getQualifier());
            }
        }
        result.put(key, info);
    }
    return result;
}
Also used : WildcardTypeName(com.squareup.javapoet.WildcardTypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) TypeVariableName(com.squareup.javapoet.TypeVariableName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName)

Aggregations

ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)136 TypeName (com.squareup.javapoet.TypeName)90 ClassName (com.squareup.javapoet.ClassName)53 MethodSpec (com.squareup.javapoet.MethodSpec)47 TypeSpec (com.squareup.javapoet.TypeSpec)29 WildcardTypeName (com.squareup.javapoet.WildcardTypeName)29 TypeElement (javax.lang.model.element.TypeElement)23 ArrayList (java.util.ArrayList)19 TypeMirror (javax.lang.model.type.TypeMirror)19 ArrayTypeName (com.squareup.javapoet.ArrayTypeName)15 HashSet (java.util.HashSet)14 Map (java.util.Map)14 List (java.util.List)12 Set (java.util.Set)12 FieldSpec (com.squareup.javapoet.FieldSpec)11 ParameterSpec (com.squareup.javapoet.ParameterSpec)11 TypeVariableName (com.squareup.javapoet.TypeVariableName)10 Element (javax.lang.model.element.Element)10 PackageElement (javax.lang.model.element.PackageElement)10 Builder (com.squareup.javapoet.TypeSpec.Builder)9