Search in sources :

Example 1 with CodeBlock

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

the class JavaGenerator method messageFieldsAndUnknownFieldsConstructor.

// Example:
//
// public SimpleMessage(int optional_int32, long optional_int64, ByteString unknownFields) {
//   super(ADAPTER, unknownFields);
//   this.optional_int32 = optional_int32;
//   this.optional_int64 = optional_int64;
// }
//
private MethodSpec messageFieldsAndUnknownFieldsConstructor(NameAllocator nameAllocator, MessageType type) {
    NameAllocator localNameAllocator = nameAllocator.clone();
    String adapterName = localNameAllocator.get("ADAPTER");
    String unknownFieldsName = localNameAllocator.newName("unknownFields");
    MethodSpec.Builder result = MethodSpec.constructorBuilder().addModifiers(PUBLIC).addStatement("super($N, $N)", adapterName, unknownFieldsName);
    for (OneOf oneOf : type.oneOfs()) {
        if (oneOf.fields().size() < 2)
            continue;
        CodeBlock.Builder fieldNamesBuilder = CodeBlock.builder();
        boolean first = true;
        for (Field field : oneOf.fields()) {
            if (!first)
                fieldNamesBuilder.add(", ");
            fieldNamesBuilder.add("$N", localNameAllocator.get(field));
            first = false;
        }
        CodeBlock fieldNames = fieldNamesBuilder.build();
        result.beginControlFlow("if ($T.countNonNull($L) > 1)", Internal.class, fieldNames);
        result.addStatement("throw new IllegalArgumentException($S)", "at most one of " + fieldNames + " may be non-null");
        result.endControlFlow();
    }
    for (Field field : type.fieldsAndOneOfFields()) {
        TypeName javaType = fieldType(field);
        String fieldName = localNameAllocator.get(field);
        ParameterSpec.Builder param = ParameterSpec.builder(javaType, fieldName);
        if (emitAndroid && field.isOptional()) {
            param.addAnnotation(NULLABLE);
        }
        result.addParameter(param.build());
        if (field.isRepeated() || field.type().isMap()) {
            result.addStatement("this.$1L = $2T.immutableCopyOf($1S, $1L)", fieldName, Internal.class);
        } else {
            result.addStatement("this.$1L = $1L", fieldName);
        }
    }
    result.addParameter(BYTE_STRING, unknownFieldsName);
    return result.build();
}
Also used : NameAllocator(com.squareup.javapoet.NameAllocator) OneOf(com.squareup.wire.schema.OneOf) WireField(com.squareup.wire.WireField) Field(com.squareup.wire.schema.Field) TypeName(com.squareup.javapoet.TypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) MethodSpec(com.squareup.javapoet.MethodSpec) ParameterSpec(com.squareup.javapoet.ParameterSpec) CodeBlock(com.squareup.javapoet.CodeBlock) ByteString(okio.ByteString)

Example 2 with CodeBlock

use of com.squareup.javapoet.CodeBlock in project auto by google.

the class FactoryWriter method addFactoryMethods.

private void addFactoryMethods(TypeSpec.Builder factory, FactoryDescriptor descriptor) {
    for (FactoryMethodDescriptor methodDescriptor : descriptor.methodDescriptors()) {
        MethodSpec.Builder method = MethodSpec.methodBuilder(methodDescriptor.name()).returns(TypeName.get(methodDescriptor.returnType())).varargs(methodDescriptor.isVarArgs());
        if (methodDescriptor.overridingMethod()) {
            method.addAnnotation(Override.class);
        }
        if (methodDescriptor.publicMethod()) {
            method.addModifiers(PUBLIC);
        }
        CodeBlock.Builder args = CodeBlock.builder();
        method.addParameters(parameters(methodDescriptor.passedParameters()));
        Iterator<Parameter> parameters = methodDescriptor.creationParameters().iterator();
        for (int argumentIndex = 1; parameters.hasNext(); argumentIndex++) {
            Parameter parameter = parameters.next();
            boolean checkNotNull = !parameter.nullable().isPresent();
            CodeBlock argument;
            if (methodDescriptor.passedParameters().contains(parameter)) {
                argument = CodeBlock.of(parameter.name());
                if (isPrimitive(parameter.type())) {
                    checkNotNull = false;
                }
            } else {
                ProviderField provider = descriptor.providers().get(parameter.key());
                argument = CodeBlock.of(provider.name());
                if (isProvider(parameter.type())) {
                    // Providers are checked for nullness in the Factory's constructor.
                    checkNotNull = false;
                } else {
                    argument = CodeBlock.of("$L.get()", argument);
                }
            }
            if (checkNotNull) {
                argument = CodeBlock.of("$T.checkNotNull($L, $L)", Preconditions.class, argument, argumentIndex);
            }
            args.add(argument);
            if (parameters.hasNext()) {
                args.add(", ");
            }
        }
        method.addStatement("return new $T($L)", methodDescriptor.returnType(), args.build());
        factory.addMethod(method.build());
    }
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) Preconditions(com.google.auto.factory.internal.Preconditions) CodeBlock(com.squareup.javapoet.CodeBlock)

Example 3 with CodeBlock

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

the class AbstractVueComponentFactoryGenerator method generate.

/**
 * Generate our {@link VueFactory} class.
 * @param component The {@link VueComponent} class to generate {@link VueComponentOptions} from
 */
public void generate(TypeElement component) {
    ClassName vueFactoryClassName = componentFactoryName(component);
    Builder vueFactoryBuilder = createFactoryBuilderClass(component, vueFactoryClassName);
    createProperties(vueFactoryClassName, vueFactoryBuilder);
    List<CodeBlock> staticInitParameters = createInitMethod(component, vueFactoryBuilder);
    createStaticGetMethod(vueFactoryClassName, vueFactoryBuilder, staticInitParameters);
    vueFactoryBuilder.addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addAnnotation(Inject.class).build());
    // Build the ComponentOptions class
    GeneratorsUtil.toJavaFile(filer, vueFactoryBuilder, vueFactoryClassName, component);
}
Also used : Builder(com.squareup.javapoet.TypeSpec.Builder) ClassName(com.squareup.javapoet.ClassName) CodeBlock(com.squareup.javapoet.CodeBlock)

Example 4 with CodeBlock

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

the class VueComponentFactoryGenerator method createInitMethod.

@Override
protected List<CodeBlock> createInitMethod(TypeElement component, Builder vueFactoryClassBuilder) {
    MethodSpec.Builder initBuilder = MethodSpec.methodBuilder("init").addModifiers(Modifier.PROTECTED).addAnnotation(Inject.class);
    List<CodeBlock> initParametersCall = new LinkedList<>();
    // Get options
    initBuilder.addStatement("$T<$T> componentOptions = $T.getOptions()", VueComponentOptions.class, component.asType(), componentJsTypeName(component));
    processCustomizeOptions(component, initBuilder, initParametersCall);
    // Extend the parent Component
    Optional<ClassName> superFactoryType = getSuperComponentType(component).map(GeneratorsNameUtil::componentFactoryName);
    if (superFactoryType.isPresent()) {
        initBuilder.addParameter(superFactoryType.get(), "superFactory");
        initBuilder.addStatement("jsConstructor = superFactory.getJsConstructor().extendJavaComponent($L)", "componentOptions");
        initParametersCall.add(CodeBlock.of("$T.get()", superFactoryType.get()));
    } else {
        initBuilder.addStatement("jsConstructor = $T.extendJavaComponent($L)", Vue.class, "componentOptions");
    }
    Component componentAnnotation = component.getAnnotation(Component.class);
    if (hasInjectedDependencies)
        registerDependenciesProvider(component, initBuilder, initParametersCall);
    registerLocalComponents(component, initBuilder, initParametersCall);
    registerLocalDirectives(componentAnnotation, initBuilder);
    MethodSpec initMethod = initBuilder.build();
    vueFactoryClassBuilder.addMethod(initMethod);
    return initParametersCall;
}
Also used : GeneratorsNameUtil(com.axellience.vuegwt.processors.utils.GeneratorsNameUtil) MethodSpec(com.squareup.javapoet.MethodSpec) CodeBlock(com.squareup.javapoet.CodeBlock) ClassName(com.squareup.javapoet.ClassName) VueComponent(com.axellience.vuegwt.core.client.component.VueComponent) Component(com.axellience.vuegwt.core.annotations.component.Component) LinkedList(java.util.LinkedList)

Example 5 with CodeBlock

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

the class RequestBuilderGenerator method buildSuppressWarnings.

@Nullable
private AnnotationSpec buildSuppressWarnings(MethodSpec requestOptionMethod) {
    Set<String> suppressions = new HashSet<>();
    if (requestOptionMethod.annotations.contains(AnnotationSpec.builder(SuppressWarnings.class).build())) {
        for (AnnotationSpec annotation : requestOptionMethod.annotations) {
            if (annotation.type.equals(TypeName.get(SuppressWarnings.class))) {
                List<CodeBlock> codeBlocks = annotation.members.get("value");
                suppressions.addAll(FluentIterable.from(codeBlocks).transform(new Function<CodeBlock, String>() {

                    @Override
                    public String apply(CodeBlock input) {
                        return input.toString();
                    }
                }).toSet());
            }
        }
    }
    if (requestOptionMethod.annotations.contains(AnnotationSpec.builder(SafeVarargs.class).build())) {
        suppressions.add("unchecked");
        suppressions.add("varargs");
    }
    if (suppressions.isEmpty()) {
        return null;
    }
    // Enforce ordering across compilers (Internal and External compilers end up disagreeing on the
    // order produced by the Set additions above.)
    ArrayList<String> suppressionsList = new ArrayList<>(suppressions);
    Collections.sort(suppressionsList);
    AnnotationSpec.Builder builder = AnnotationSpec.builder(SuppressWarnings.class);
    for (String suppression : suppressionsList) {
        builder.addMember("value", "$S", suppression);
    }
    return builder.build();
}
Also used : CodeBlock(com.squareup.javapoet.CodeBlock) ArrayList(java.util.ArrayList) AnnotationSpec(com.squareup.javapoet.AnnotationSpec) HashSet(java.util.HashSet) Nullable(javax.annotation.Nullable)

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