Search in sources :

Example 31 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project dagger by square.

the class ModuleAdapterProcessor method injectsInitializer.

private CodeBlock injectsInitializer(Object[] injects) {
    CodeBlock.Builder result = CodeBlock.builder().add("{ ");
    for (Object injectableType : injects) {
        TypeMirror typeMirror = (TypeMirror) injectableType;
        String key = isInterface(typeMirror) ? GeneratorKeys.get(typeMirror) : GeneratorKeys.rawMembersKey(typeMirror);
        result.add("$S, ", key);
    }
    result.add("}");
    return result.build();
}
Also used : TypeMirror(javax.lang.model.type.TypeMirror) CodeBlock(com.squareup.javapoet.CodeBlock) Util.typeToString(dagger.internal.codegen.Util.typeToString) Util.elementToString(dagger.internal.codegen.Util.elementToString)

Example 32 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project vue-gwt by Axellience.

the class AbstractVueComponentFactoryGenerator method createStaticGetMethod.

/**
 * Create a static get method that can be used to retrieve an instance of our Factory.
 * Factory retrieved using this method do NOT support injection.
 * @param vueFactoryClassName The type name of our generated {@link VueFactory}
 * @param vueFactoryBuilder The builder to create our {@link VueFactory} class
 * @param staticInitParameters Parameters from the init method when called on static
 * initialization (when the factory is not injected)
 */
private void createStaticGetMethod(ClassName vueFactoryClassName, Builder vueFactoryBuilder, List<CodeBlock> staticInitParameters) {
    MethodSpec.Builder getBuilder = MethodSpec.methodBuilder("get").addModifiers(Modifier.STATIC, Modifier.PUBLIC).returns(vueFactoryClassName);
    getBuilder.beginControlFlow("if ($L == null)", INSTANCE_PROP);
    getBuilder.addStatement("$L = new $T()", INSTANCE_PROP, vueFactoryClassName);
    getBuilder.addCode("$L.init(", INSTANCE_PROP);
    boolean isFirst = true;
    for (CodeBlock staticInitParameter : staticInitParameters) {
        if (!isFirst)
            getBuilder.addCode(", ");
        getBuilder.addCode(staticInitParameter);
        isFirst = false;
    }
    getBuilder.addCode(");");
    getBuilder.endControlFlow();
    getBuilder.addStatement("return $L", INSTANCE_PROP);
    vueFactoryBuilder.addMethod(getBuilder.build());
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) CodeBlock(com.squareup.javapoet.CodeBlock)

Example 33 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project arez by arez.

the class ComponentDescriptor method buildEqualsMethod.

@Nonnull
private MethodSpec buildEqualsMethod() throws ArezProcessorException {
    final String idMethod = getIdMethodName();
    final MethodSpec.Builder method = MethodSpec.methodBuilder("equals").addModifiers(Modifier.PUBLIC, Modifier.FINAL).addAnnotation(Override.class).addParameter(Object.class, "o", Modifier.FINAL).returns(TypeName.BOOLEAN);
    final ClassName generatedClass = ClassName.get(getPackageName(), getArezClassName());
    final CodeBlock.Builder codeBlock = CodeBlock.builder();
    codeBlock.beginControlFlow("if ( this == o )");
    codeBlock.addStatement("return true");
    codeBlock.nextControlFlow("else if ( null == o || !(o instanceof $T) )", generatedClass);
    codeBlock.addStatement("return false");
    codeBlock.nextControlFlow("else");
    codeBlock.addStatement("final $T that = ($T) o;", generatedClass, generatedClass);
    final TypeKind kind = null != _componentId ? _componentId.getReturnType().getKind() : TypeKind.LONG;
    if (kind == TypeKind.DECLARED || kind == TypeKind.TYPEVAR) {
        codeBlock.addStatement("return null != $N() && $N().equals( that.$N() )", idMethod, idMethod, idMethod);
    } else {
        codeBlock.addStatement("return $N() == that.$N()", idMethod, idMethod);
    }
    codeBlock.endControlFlow();
    if (_requireEquals) {
        method.addCode(codeBlock.build());
    } else {
        final CodeBlock.Builder guardBlock = CodeBlock.builder();
        guardBlock.beginControlFlow("if ( $T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME);
        guardBlock.add(codeBlock.build());
        guardBlock.nextControlFlow("else");
        guardBlock.addStatement("return super.equals( o )");
        guardBlock.endControlFlow();
        method.addCode(guardBlock.build());
    }
    return method.build();
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) ClassName(com.squareup.javapoet.ClassName) CodeBlock(com.squareup.javapoet.CodeBlock) TypeKind(javax.lang.model.type.TypeKind) Nonnull(javax.annotation.Nonnull)

Example 34 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project glide by bumptech.

the class RequestBuilderGenerator method generateGeneratedRequestOptionEquivalent.

/**
 * Generates a particular method with  an equivalent name and arguments to the given method
 * from the generated {@code com.bumptech.glide.request.BaseRequestBuilder} subclass.
 */
private MethodSpec generateGeneratedRequestOptionEquivalent(MethodSpec requestOptionMethod) {
    CodeBlock callRequestOptionsMethod = CodeBlock.builder().add(".$N(", requestOptionMethod.name).add(FluentIterable.from(requestOptionMethod.parameters).transform(new Function<ParameterSpec, String>() {

        @Override
        public String apply(ParameterSpec input) {
            return input.name;
        }
    }).join(Joiner.on(", "))).add(");\n").build();
    MethodSpec.Builder result = MethodSpec.methodBuilder(requestOptionMethod.name).addJavadoc(processorUtil.generateSeeMethodJavadoc(requestOptionsClassName, requestOptionMethod)).addModifiers(Modifier.PUBLIC).varargs(requestOptionMethod.varargs).addAnnotations(FluentIterable.from(requestOptionMethod.annotations).filter(new Predicate<AnnotationSpec>() {

        @Override
        public boolean apply(AnnotationSpec input) {
            return !input.type.equals(TypeName.get(Override.class)) && // non-final to allow for mocking.
            !input.type.equals(TypeName.get(SafeVarargs.class)) && // We need to combine warnings below.
            !input.type.equals(TypeName.get(SuppressWarnings.class));
        }
    }).toList()).addTypeVariables(requestOptionMethod.typeVariables).addParameters(requestOptionMethod.parameters).returns(generatedRequestBuilderOfTranscodeType).beginControlFlow("if (getMutableOptions() instanceof $T)", requestOptionsClassName).addCode("this.requestOptions = (($T) getMutableOptions())", requestOptionsClassName).addCode(callRequestOptionsMethod).nextControlFlow("else").addCode(CodeBlock.of("this.requestOptions = new $T().apply(this.requestOptions)", requestOptionsClassName)).addCode(callRequestOptionsMethod).endControlFlow().addStatement("return this");
    AnnotationSpec suppressWarnings = buildSuppressWarnings(requestOptionMethod);
    if (suppressWarnings != null) {
        result.addAnnotation(suppressWarnings);
    }
    return result.build();
}
Also used : ParameterSpec(com.squareup.javapoet.ParameterSpec) MethodSpec(com.squareup.javapoet.MethodSpec) CodeBlock(com.squareup.javapoet.CodeBlock) AnnotationSpec(com.squareup.javapoet.AnnotationSpec) Predicate(com.google.common.base.Predicate)

Example 35 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project wire by square.

the class JavaGenerator method fieldInitializer.

private CodeBlock fieldInitializer(ProtoType type, @Nullable Object value) {
    TypeName javaType = typeName(type);
    if (value instanceof List) {
        CodeBlock.Builder builder = CodeBlock.builder();
        builder.add("$T.asList(", Arrays.class);
        boolean first = true;
        for (Object o : (List<?>) value) {
            if (!first)
                builder.add(",");
            first = false;
            builder.add("\n$>$>$L$<$<", fieldInitializer(type, o));
        }
        builder.add(")");
        return builder.build();
    } else if (value instanceof Map) {
        CodeBlock.Builder builder = CodeBlock.builder();
        builder.add("new $T.Builder()", javaType);
        for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
            ProtoMember protoMember = (ProtoMember) entry.getKey();
            Field field = schema.getField(protoMember);
            CodeBlock valueInitializer = fieldInitializer(field.getType(), entry.getValue());
            builder.add("\n$>$>.$L($L)$<$<", fieldName(type, field), valueInitializer);
        }
        builder.add("\n$>$>.build()$<$<");
        return builder.build();
    } else if (javaType.equals(TypeName.BOOLEAN)) {
        return CodeBlock.of("$L", value != null ? value : false);
    } else if (javaType.equals(TypeName.INT)) {
        return CodeBlock.of("$L", optionValueToInt(value));
    } else if (javaType.equals(TypeName.LONG)) {
        return CodeBlock.of("$LL", optionValueToLong(value));
    } else if (javaType.equals(TypeName.FLOAT)) {
        if (value == null) {
            return CodeBlock.of("0.0f");
        } else if ("inf".equals(value)) {
            return CodeBlock.of("Float.POSITIVE_INFINITY");
        } else if ("-inf".equals(value)) {
            return CodeBlock.of("Float.NEGATIVE_INFINITY");
        } else if ("nan".equals(value) || "-nan".equals(value)) {
            return CodeBlock.of("Float.NaN");
        } else {
            return CodeBlock.of("$Lf", String.valueOf(value));
        }
    } else if (javaType.equals(TypeName.DOUBLE)) {
        if (value == null) {
            return CodeBlock.of("0.0d");
        } else if ("inf".equals(value)) {
            return CodeBlock.of("Double.POSITIVE_INFINITY");
        } else if ("-inf".equals(value)) {
            return CodeBlock.of("Double.NEGATIVE_INFINITY");
        } else if ("nan".equals(value) || "-nan".equals(value)) {
            return CodeBlock.of("Double.NaN");
        } else {
            return CodeBlock.of("$Ld", String.valueOf(value));
        }
    } else if (javaType.equals(STRING)) {
        return CodeBlock.of("$S", value != null ? value : "");
    } else if (javaType.equals(BYTE_STRING)) {
        if (value == null) {
            return CodeBlock.of("$T.EMPTY", ByteString.class);
        } else {
            return CodeBlock.of("$T.decodeBase64($S)", ByteString.class, ByteString.encodeString(String.valueOf(value), Charsets.ISO_8859_1).base64());
        }
    } else if (isEnum(type) && value != null) {
        return CodeBlock.of("$T.$L", javaType, value);
    } else {
        throw new IllegalStateException(type + " is not an allowed scalar type");
    }
}
Also used : WireField(com.squareup.wire.WireField) Field(com.squareup.wire.schema.Field) TypeName(com.squareup.javapoet.TypeName) WildcardTypeName(com.squareup.javapoet.WildcardTypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) CacheBuilder(com.google.common.cache.CacheBuilder) CodeBlock(com.squareup.javapoet.CodeBlock) ProtoMember(com.squareup.wire.schema.ProtoMember) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

CodeBlock (com.squareup.javapoet.CodeBlock)42 MethodSpec (com.squareup.javapoet.MethodSpec)19 TypeMirror (javax.lang.model.type.TypeMirror)13 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)11 TypeName (com.squareup.javapoet.TypeName)10 CompilationAbstractTest (com.google.auto.value.extension.serializable.serializer.utils.CompilationAbstractTest)8 ClassName (com.squareup.javapoet.ClassName)8 WireField (com.squareup.wire.WireField)8 Field (com.squareup.wire.schema.Field)8 ByteString (okio.ByteString)8 Test (org.junit.Test)8 JvmLanguages.builtInAdapterString (com.squareup.wire.schema.internal.JvmLanguages.builtInAdapterString)7 ArrayList (java.util.ArrayList)7 Serializer (com.google.auto.value.extension.serializable.serializer.interfaces.Serializer)6 ParameterSpec (com.squareup.javapoet.ParameterSpec)6 AnnotationSpec (com.squareup.javapoet.AnnotationSpec)4 TypeSpec (com.squareup.javapoet.TypeSpec)3 Element (javax.lang.model.element.Element)3 Predicate (com.google.common.base.Predicate)2 FieldSpec (com.squareup.javapoet.FieldSpec)2