Search in sources :

Example 11 with Field

use of com.squareup.wire.schema.Field in project wire by square.

the class JavaGenerator method optionsField.

// Example:
//
// public static final FieldOptions FIELD_OPTIONS_FOO = new FieldOptions.Builder()
//     .setExtension(Ext_custom_options.count, 42)
//     .build();
//
private FieldSpec optionsField(ProtoType optionsType, String fieldName, Options options) {
    TypeName optionsJavaType = typeName(optionsType);
    CodeBlock.Builder initializer = CodeBlock.builder();
    initializer.add("$[new $T.Builder()", optionsJavaType);
    boolean empty = true;
    for (Map.Entry<ProtoMember, ?> entry : options.map().entrySet()) {
        if (entry.getKey().equals(FIELD_DEPRECATED) || entry.getKey().equals(PACKED)) {
            continue;
        }
        Field optionField = schema.getField(entry.getKey());
        initializer.add("\n.$L($L)", fieldName(optionsType, optionField), fieldInitializer(optionField.type(), entry.getValue()));
        empty = false;
    }
    initializer.add("\n.build()$]");
    if (empty)
        return null;
    return FieldSpec.builder(optionsJavaType, fieldName).addModifiers(PUBLIC, STATIC, FINAL).initializer(initializer.build()).build();
}
Also used : WireField(com.squareup.wire.WireField) Field(com.squareup.wire.schema.Field) TypeName(com.squareup.javapoet.TypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) CodeBlock(com.squareup.javapoet.CodeBlock) ProtoMember(com.squareup.wire.schema.ProtoMember) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) LinkedHashMap(java.util.LinkedHashMap)

Example 12 with Field

use of com.squareup.wire.schema.Field in project wire by square.

the class JavaGenerator method collidingFieldNames.

/** Returns the set of names that are not unique within {@code fields}. */
private Set<String> collidingFieldNames(ImmutableList<Field> fields) {
    Set<String> fieldNames = new LinkedHashSet<>();
    Set<String> collidingNames = new LinkedHashSet<>();
    for (Field field : fields) {
        if (!fieldNames.add(field.name())) {
            collidingNames.add(field.name());
        }
    }
    return collidingNames;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) WireField(com.squareup.wire.WireField) Field(com.squareup.wire.schema.Field) ByteString(okio.ByteString)

Example 13 with Field

use of com.squareup.wire.schema.Field 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)

Example 14 with Field

use of com.squareup.wire.schema.Field in project wire by square.

the class JavaGenerator method builderBuild.

// Example:
// 
// @Override
// public SimpleMessage build() {
// if (field_one == null) {
// throw missingRequiredFields(field_one, "field_one");
// }
// return new SimpleMessage(field_one, super.buildUnknownFields());
// }
// 
// The call to checkRequiredFields will be emitted only if the message has
// required fields. The constructor can also take instance of the builder
// rather than individual fields depending on how many fields there are.
// 
private MethodSpec builderBuild(NameAllocator nameAllocator, MessageType message, ClassName javaType) {
    MethodSpec.Builder result = MethodSpec.methodBuilder("build").addAnnotation(Override.class).addModifiers(PUBLIC).returns(javaType);
    List<Field> requiredFields = message.getRequiredFields();
    if (!requiredFields.isEmpty()) {
        CodeBlock.Builder conditionals = CodeBlock.builder().add("$[");
        CodeBlock.Builder missingArgs = CodeBlock.builder();
        for (int i = 0; i < requiredFields.size(); i++) {
            Field requiredField = requiredFields.get(i);
            if (i > 0)
                conditionals.add("\n|| ");
            conditionals.add("$L == null", nameAllocator.get(requiredField));
            if (i > 0)
                missingArgs.add(",\n");
            missingArgs.add("$1L, $2S", nameAllocator.get(requiredField), requiredField.getName());
        }
        result.beginControlFlow("if ($L)", conditionals.add("$]").build()).addStatement("throw $T.missingRequiredFields($L)", Internal.class, missingArgs.build()).endControlFlow();
    }
    boolean constructorTakesAllFields = constructorTakesAllFields(message);
    result.addCode("return new $T(", javaType);
    if (constructorTakesAllFields) {
        for (Field field : message.getFieldsAndOneOfFields()) {
            result.addCode("$L, ", nameAllocator.get(field));
        }
    } else {
        result.addCode("this, ");
    }
    result.addCode("super.buildUnknownFields());\n");
    return result.build();
}
Also used : WireField(com.squareup.wire.WireField) Field(com.squareup.wire.schema.Field) MethodSpec(com.squareup.javapoet.MethodSpec) Internal(com.squareup.wire.internal.Internal) CodeBlock(com.squareup.javapoet.CodeBlock)

Example 15 with Field

use of com.squareup.wire.schema.Field in project wire by square.

the class JavaGenerator method builder.

private TypeSpec builder(NameAllocator nameAllocator, MessageType type, ClassName javaType, ClassName builderType) {
    TypeSpec.Builder result = TypeSpec.classBuilder("Builder").addModifiers(PUBLIC, STATIC, FINAL);
    result.superclass(builderOf(javaType, builderType));
    for (Field field : type.getFieldsAndOneOfFields()) {
        String fieldName = nameAllocator.get(field);
        result.addField(fieldType(field), fieldName, PUBLIC);
    }
    result.addMethod(builderNoArgsConstructor(nameAllocator, type));
    for (Field field : type.fields()) {
        result.addMethod(setter(nameAllocator, builderType, null, field));
    }
    for (OneOf oneOf : type.getOneOfs()) {
        for (Field field : oneOf.getFields()) {
            result.addMethod(setter(nameAllocator, builderType, oneOf, field));
        }
    }
    result.addMethod(builderBuild(nameAllocator, type, javaType));
    return result.build();
}
Also used : WireField(com.squareup.wire.WireField) Field(com.squareup.wire.schema.Field) OneOf(com.squareup.wire.schema.OneOf) ByteString(okio.ByteString) JvmLanguages.builtInAdapterString(com.squareup.wire.schema.internal.JvmLanguages.builtInAdapterString) TypeSpec(com.squareup.javapoet.TypeSpec)

Aggregations

WireField (com.squareup.wire.WireField)23 Field (com.squareup.wire.schema.Field)23 ByteString (okio.ByteString)19 JvmLanguages.builtInAdapterString (com.squareup.wire.schema.internal.JvmLanguages.builtInAdapterString)17 MethodSpec (com.squareup.javapoet.MethodSpec)15 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)12 TypeName (com.squareup.javapoet.TypeName)12 CodeBlock (com.squareup.javapoet.CodeBlock)10 WildcardTypeName (com.squareup.javapoet.WildcardTypeName)10 NameAllocator (com.squareup.javapoet.NameAllocator)7 ClassName (com.squareup.javapoet.ClassName)4 Internal (com.squareup.wire.internal.Internal)4 ParameterSpec (com.squareup.javapoet.ParameterSpec)3 TypeSpec (com.squareup.javapoet.TypeSpec)3 OneOf (com.squareup.wire.schema.OneOf)3 ProtoMember (com.squareup.wire.schema.ProtoMember)3 ArrayList (java.util.ArrayList)3 LinkedHashMap (java.util.LinkedHashMap)3 ImmutableMap (com.google.common.collect.ImmutableMap)2 ProtoFile (com.squareup.wire.schema.ProtoFile)2