com.baidu.bjf.remoting.protobuf.FieldType Java Examples

The following examples show how to use com.baidu.bjf.remoting.protobuf.FieldType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CodeGenerator.java    From jprotobuf with Apache License 2.0 6 votes vote down vote up
/**
 * Check {@link FieldType} is validate to class type of {@link Field}
 * 
 * @param type
 * @param field
 */
private void checkType(FieldType type, Field field) {
    Class<?> cls = field.getType();

    if (type == FieldType.OBJECT || type == FieldType.ENUM) {
        return;
    }

    String javaType = type.getJavaType();
    if (Integer.class.getSimpleName().equals(javaType)) {
        if (cls.getSimpleName().equals("int") || Integer.class.getSimpleName().equals(cls.getSimpleName())) {
            return;
        }
        throw new IllegalArgumentException(getMismatchTypeErroMessage(type, field));
    }
    if (!javaType.equalsIgnoreCase(cls.getSimpleName())) {
        throw new IllegalArgumentException(getMismatchTypeErroMessage(type, field));
    }
}
 
Example #2
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 6 votes vote down vote up
public static <K, V> void putMapValue(CodedInputStream input, Map<K, V> map,
        com.google.protobuf.WireFormat.FieldType keyType, K defaultKey,
        com.google.protobuf.WireFormat.FieldType valueType, V defalutValue, EnumHandler<V> handler)
        throws IOException {
    com.baidu.bjf.remoting.protobuf.MapEntry<K, V> valuesDefaultEntry = com.baidu.bjf.remoting.protobuf.MapEntry
            .<K, V> newDefaultInstance(null, keyType, defaultKey, valueType, defalutValue);

    com.baidu.bjf.remoting.protobuf.MapEntry<K, V> values =
            input.readMessage(valuesDefaultEntry.getParserForType(), null);

    Object value = values.getValue();
    if (handler != null) {
        V value1 = handler.handle((int) value);
        map.put(values.getKey(), value1);
    } else {
        map.put(values.getKey(), values.getValue());
    }


}
 
Example #3
Source File: AbstractCodeGenerator.java    From jprotobuf with Apache License 2.0 6 votes vote down vote up
/**
 * Check {@link FieldType} is validate to class type of {@link Field}.
 *
 * @param type the type
 * @param field the field
 */
protected void checkType(FieldType type, Field field) {
    Class<?> cls = field.getType();

    if (type == FieldType.OBJECT || type == FieldType.ENUM) {
        return;
    }

    String javaType = type.getJavaType();
    if (Integer.class.getSimpleName().equals(javaType)) {
        if (cls.getSimpleName().equals("int") || Integer.class.getSimpleName().equals(cls.getSimpleName())) {
            return;
        }
        throw new IllegalArgumentException(getMismatchTypeErroMessage(type, field));
    }
    if (!javaType.equalsIgnoreCase(cls.getSimpleName())) {
        throw new IllegalArgumentException(getMismatchTypeErroMessage(type, field));
    }
}
 
Example #4
Source File: ProtobufProxyUtils.java    From jprotobuf with Apache License 2.0 5 votes vote down vote up
/**
 * Process protobuf type.
 *
 * @param cls the cls
 * @return the string
 */
public static String processProtobufType(Class<?> cls) {
    FieldType fieldType = TYPE_MAPPING.get(cls);
    if (fieldType != null) {
        return fieldType.getType();
    }

    return cls.getSimpleName();
}
 
Example #5
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 5 votes vote down vote up
/**
 * Write a single tag-value pair to the stream.
 *
 * @param output The output stream.
 * @param type The field's type.
 * @param number The field's number.
 * @param value Object representing the field's value. Must be of the exact type which would be returned by
 *            {@link Message#getField(Descriptors.FieldDescriptor)} for this field.
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void writeElement(final CodedOutputStream output, final WireFormat.FieldType type, final int number,
        final Object value) throws IOException {
    // Special case for groups, which need a start and end tag; other fields
    // can just use writeTag() and writeFieldNoTag().
    if (type == WireFormat.FieldType.GROUP) {
        output.writeGroup(number, (MessageLite) value);
    } else {
        output.writeTag(number, getWireFormatForFieldType(type, false));
        writeElementNoTag(output, type, value);
    }
}
 
Example #6
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 5 votes vote down vote up
/**
 * write list to {@link CodedOutputStream} object.
 *
 * @param out target output stream to write
 * @param order field order
 * @param type field type
 * @param list target list object to be serialized
 * @param packed the packed
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void writeToList(CodedOutputStream out, int order, FieldType type, Collection list, boolean packed)
        throws IOException {
    if (list == null || list.isEmpty()) {
        return;
    }
    
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    CodedOutputStream newInstance = CodedOutputStream.newInstance(baos, 0);
    for (Object object : list) {
        if (object == null) {
            throw new NullPointerException("List can not include Null value.");
        }
        writeObject(newInstance, order, type, object, true, !packed);
    }
    newInstance.flush();
    byte[] byteArray = baos.toByteArray();
    

    if (packed) {
        out.writeUInt32NoTag(makeTag(order, WireFormat.WIRETYPE_LENGTH_DELIMITED));
        out.writeUInt32NoTag(byteArray.length); 
    }

    out.write(byteArray, 0, byteArray.length);

}
 
Example #7
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 5 votes vote down vote up
/**
 * Compute map size.
 *
 * @param <K> the key type
 * @param <V> the value type
 * @param order the order
 * @param map the map
 * @param keyType the key type
 * @param defaultKey the default key
 * @param valueType the value type
 * @param defalutValue the defalut value
 * @return the int
 */
public static <K, V> int computeMapSize(int order, Map<K, V> map, com.google.protobuf.WireFormat.FieldType keyType,
        K defaultKey, com.google.protobuf.WireFormat.FieldType valueType, V defalutValue) {
    int size = 0;
    for (java.util.Map.Entry<K, V> entry : map.entrySet()) {
        com.baidu.bjf.remoting.protobuf.MapEntry<K, V> valuesDefaultEntry = com.baidu.bjf.remoting.protobuf.MapEntry
                .<K, V> newDefaultInstance(null, keyType, defaultKey, valueType, defalutValue);

        com.baidu.bjf.remoting.protobuf.MapEntry<K, V> values =
                valuesDefaultEntry.newBuilderForType().setKey(entry.getKey()).setValue(entry.getValue()).build();

        size += com.google.protobuf.CodedOutputStream.computeMessageSize(order, values);
    }
    return size;
}
 
Example #8
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 5 votes vote down vote up
/**
 * Compute list size.
 *
 * @param order the order
 * @param list the list
 * @param type the type
 * @param debug the debug
 * @param path the path
 * @param packed the packed
 * @param sizeOnly the size only if true will not include order size and tag size
 * @return the int
 */
public static int computeListSize(int order, Collection list, FieldType type, boolean debug, File path, boolean packed,
        boolean sizeOnly) {
    int size = 0;
    if (list == null || list.isEmpty()) {
        return size;
    }

    int dataSize = 0;
    for (Object object : list) {
        dataSize += computeSize(order, object, type, debug, path);
    }
    size += dataSize;
    if (type != FieldType.OBJECT) {
        if (packed) {
            if (!sizeOnly) {
                size += com.google.protobuf.CodedOutputStream.computeInt32SizeNoTag(dataSize);
                int tag = CodedConstant.makeTag(order,
                        WireFormat.WIRETYPE_LENGTH_DELIMITED);
                size += com.google.protobuf.CodedOutputStream.computeUInt32SizeNoTag(tag);
            }
        } else {
            size += list.size() * CodedOutputStream.computeTagSize(order);
        }
    }
    return size;
}
 
Example #9
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the filed type.
 *
 * @param type the type
 * @param isList the is list
 * @return the filed type
 */
public static String getFiledType(FieldType type, boolean isList) {
    // add null check
    String defineType = type.getJavaType();
    if (isList) {
        defineType = "Collection";
    }
    
    return defineType;
    
}
 
Example #10
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 5 votes vote down vote up
/**
 * Compute the number of bytes that would be needed to encode a single tag/value pair of arbitrary type.
 *
 * @param type The field's type.
 * @param number The field's number.
 * @param value Object representing the field's value. Must be of the exact type which would be returned by
 *            {@link Message#getField(Descriptors.FieldDescriptor)} for this field.
 * @return the int
 */
public static int computeElementSize(final WireFormat.FieldType type, final int number, final Object value) {
    int tagSize = CodedOutputStream.computeTagSize(number);
    if (type == WireFormat.FieldType.GROUP) {
        // Only count the end group tag for proto2 messages as for proto1 the end
        // group tag will be counted as a part of getSerializedSize().
        tagSize *= 2;
    }
    return tagSize + computeElementSizeNoTag(type, value);
}
 
Example #11
Source File: ProtobufProxyUtils.java    From jprotobuf with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if is object type.
 *
 * @param cls the cls
 * @return true, if is object type
 */
public static boolean isObjectType(Class<?> cls) {
    FieldType fieldType = TYPE_MAPPING.get(cls);
    if (fieldType != null) {
        return false;
    }

    return true;
}
 
Example #12
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 5 votes vote down vote up
/**
 * get mapped type defined java expression.
 * 
 * @param order field order
 * @param type field type
 * @param express java expression
 * @param isList is field type is a {@link List}
 * @param isMap is field type is a {@link Map}
 * @return full java expression
 */
public static String getMappedTypeDefined(int order, FieldType type, String express, boolean isList,
        boolean isMap) {
    StringBuilder code = new StringBuilder();
    String fieldName = getFieldName(order);
    if ((type == FieldType.STRING || type == FieldType.BYTES) && !isList) {
        // add null check
        code.append("com.google.protobuf.ByteString ").append(fieldName).append(" = null")
                .append(CodeGenerator.JAVA_LINE_BREAK);
        code.append("if (!CodedConstant.isNull(").append(express).append(")) {").append(CodeGenerator.LINE_BREAK);

        String method = "copyFromUtf8";
        if (type == FieldType.BYTES) {
            method = "copyFrom";
        }
        code.append(fieldName).append(" = com.google.protobuf.ByteString.").append(method).append("(")
                .append(express).append(")").append(CodeGenerator.JAVA_LINE_BREAK);
        code.append("}").append(CodeGenerator.LINE_BREAK);
        return code.toString();
    }
    // add null check
    String defineType = type.getJavaType();
    if (isList) {
        defineType = "List";
    } else if (isMap) {
        defineType = "Map";
    }
    code.setLength(0);
    code.append(defineType).append(" ").append(fieldName).append(" = null").append(CodeGenerator.JAVA_LINE_BREAK);
    code.append("if (!CodedConstant.isNull(").append(express).append(")) {").append(CodeGenerator.LINE_BREAK);
    code.append(fieldName).append(" = ").append(express).append(CodeGenerator.JAVA_LINE_BREAK);
    code.append("}").append(CodeGenerator.LINE_BREAK);
    return code.toString();
}
 
Example #13
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the mapped type size.
 *
 * @param field field
 * @param order field order
 * @param type field type
 * @param isList is field type is a {@link List}
 * @param isMap the is map
 * @param debug debug mode if true enable debug.
 * @param path the path
 * @return full java expression
 */
public static String getMappedTypeSize(FieldInfo field, int order, FieldType type, boolean isList, boolean isMap,
        boolean debug, File path) {
    String fieldName = getFieldName(order);

    String spath = "null";
    if (path != null) {
        spath = "new java.io.File(\"" + path.getAbsolutePath().replace('\\', '/') + "\")";
    }

    String typeString = type.getType().toUpperCase();
    if (isList) {
        return "CodedConstant.computeListSize(" + order + ", " + fieldName + ", FieldType." + typeString + ", "
                + Boolean.valueOf(debug) + ", " + spath + "," + Boolean.valueOf(field.isPacked()) + ")"
                + CodeGenerator.JAVA_LINE_BREAK;
    } else if (isMap) {

        String joinedSentence = getMapFieldGenericParameterString(field);
        return "CodedConstant.computeMapSize(" + order + ", " + fieldName + ", " + joinedSentence + ")"
                + CodeGenerator.JAVA_LINE_BREAK;
    }

    if (type == FieldType.OBJECT) {
        return "CodedConstant.computeSize(" + order + "," + fieldName + ", FieldType." + typeString + ","
                + Boolean.valueOf(debug) + "," + spath + ")" + CodeGenerator.JAVA_LINE_BREAK;
    }

    String t = type.getType();
    if (type == FieldType.STRING) {
        t = "String";
    }
    
    if (type == FieldType.BYTES) {
        t = "ByteArray";
    }
    t = capitalize(t);

    boolean enumSpecial = false;
    if (type == FieldType.ENUM) {
        if (EnumReadable.class.isAssignableFrom(field.getField().getType())) {
            String clsName = ClassHelper.getInternalName(field.getField().getType().getCanonicalName());
            fieldName = "((" + clsName + ") " + fieldName + ").value()";
            enumSpecial = true;
        }
    }
    if (!enumSpecial) {
        fieldName = fieldName + type.getToPrimitiveType();
    }

    return "com.google.protobuf.CodedOutputStream.compute" + t + "Size(" + order + "," + fieldName + ")"
            + CodeGenerator.JAVA_LINE_BREAK;
}
 
Example #14
Source File: TemplateCodeGenerator.java    From jprotobuf with Apache License 2.0 4 votes vote down vote up
/**
 * Inits the encode method template variable.
 */
protected void initEncodeMethodTemplateVariable() {

    Set<Integer> orders = new HashSet<Integer>();
    // encode method
    for (FieldInfo field : fields) {
        boolean isList = field.isList();
        boolean isMap = field.isMap();
        // check type
        if (!isList) {
            checkType(field.getFieldType(), field.getField());
        }

        if (orders.contains(field.getOrder())) {
            throw new IllegalArgumentException("Field order '" + field.getOrder() + "' on field"
                    + field.getField().getName() + " already exsit.");
        }
        // define field

        FieldType fieldType = field.getFieldType();
        String accessByField = getAccessByField("t", field.getField(), cls, field.isWildcardType());

        String fieldName = CodedConstant.getFieldName(field.getOrder());
        String encodeFieldType = CodedConstant.getFiledType(fieldType, isList);
        templator.setVariable("encodeFieldType", encodeFieldType);
        templator.setVariable("encodeFieldName", fieldName);
        templator.setVariable("encodeFieldGetter", accessByField);
        String writeValueToField = CodedConstant.getWriteValueToField(fieldType, accessByField, isList);
        templator.setVariable("writeValueToField", writeValueToField);

        if (field.isRequired()) {
            templator.setVariableOpt("checkNull",
                    CodedConstant.getRequiredCheck(field.getOrder(), field.getField()));
        } else {
            templator.setVariable("checkNull", "");
        }

        String calcSize = CodedConstant.getMappedTypeSize(field, field.getOrder(), field.getFieldType(), isList,
                isMap, debug, outputPath);
        templator.setVariable("calcSize", calcSize);

        // set write to byte
        String encodeWriteFieldValue = CodedConstant.getMappedWriteCode(field, "output", field.getOrder(),
                field.getFieldType(), isList, isMap);
        templator.setVariable("encodeWriteFieldValue", encodeWriteFieldValue);
        templator.addBlock("encodeFields");

    }
}
 
Example #15
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 4 votes vote down vote up
/**
 * Compute the number of bytes that would be needed to encode a particular value of arbitrary type, excluding tag.
 *
 * @param type The field's type.
 * @param value Object representing the field's value. Must be of the exact type which would be returned by
 *            {@link Message#getField(Descriptors.FieldDescriptor)} for this field.
 * @return the int
 */
public static int computeElementSizeNoTag(final WireFormat.FieldType type, final Object value) {
    switch (type) {
        // Note: Minor violation of 80-char limit rule here because this would
        // actually be harder to read if we wrapped the lines.
        case DOUBLE:
            return CodedOutputStream.computeDoubleSizeNoTag((Double) value);
        case FLOAT:
            return CodedOutputStream.computeFloatSizeNoTag((Float) value);
        case INT64:
            return CodedOutputStream.computeInt64SizeNoTag((Long) value);
        case UINT64:
            return CodedOutputStream.computeUInt64SizeNoTag((Long) value);
        case INT32:
            return CodedOutputStream.computeInt32SizeNoTag((Integer) value);
        case FIXED64:
            return CodedOutputStream.computeFixed64SizeNoTag((Long) value);
        case FIXED32:
            return CodedOutputStream.computeFixed32SizeNoTag((Integer) value);
        case BOOL:
            return CodedOutputStream.computeBoolSizeNoTag((Boolean) value);
        case STRING:
            return CodedOutputStream.computeStringSizeNoTag((String) value);
        case GROUP:
            return CodedOutputStream.computeGroupSizeNoTag((MessageLite) value);
        case BYTES:
            if (value instanceof ByteString) {
                return CodedOutputStream.computeBytesSizeNoTag((ByteString) value);
            } else {
                if (value instanceof Byte[]) {
                    return computeLengthDelimitedFieldSize(((Byte[]) value).length);
                }
                return CodedOutputStream.computeByteArraySizeNoTag((byte[]) value);
            }
        case UINT32:
            return CodedOutputStream.computeUInt32SizeNoTag((Integer) value);
        case SFIXED32:
            return CodedOutputStream.computeSFixed32SizeNoTag((Integer) value);
        case SFIXED64:
            return CodedOutputStream.computeSFixed64SizeNoTag((Long) value);
        case SINT32:
            return CodedOutputStream.computeSInt32SizeNoTag((Integer) value);
        case SINT64:
            return CodedOutputStream.computeSInt64SizeNoTag((Long) value);

        case MESSAGE:
            if (value instanceof LazyField) {
                return CodedOutputStream.computeLazyFieldSizeNoTag((LazyField) value);
            } else {
                return computeObjectSizeNoTag(value);
            }

        case ENUM:
            if (value instanceof Internal.EnumLite) {
                return CodedOutputStream.computeEnumSizeNoTag(((Internal.EnumLite) value).getNumber());
            } else {
                if (value instanceof EnumReadable) {
                    return CodedOutputStream.computeEnumSizeNoTag(((EnumReadable) value).value());
                } else if (value instanceof Enum) {
                    return CodedOutputStream.computeEnumSizeNoTag(((Enum) value).ordinal());
                }

                return CodedOutputStream.computeEnumSizeNoTag((Integer) value);
            }
    }

    throw new RuntimeException("There is no way to get here, but the compiler thinks otherwise.");
}
 
Example #16
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 4 votes vote down vote up
/**
 * get object size by {@link FieldType}.
 *
 * @param order the order
 * @param o the o
 * @param type the type
 * @param list the list
 * @param debug the debug
 * @param path the path
 * @return the int
 */
public static int computeSize(int order, Object o, FieldType type, boolean list, boolean debug, File path) {
    int size = 0;
    if (o == null) {
        return size;
    }

    if (type == FieldType.OBJECT) {
        Class cls = o.getClass();
        Codec target = ProtobufProxy.create(cls, debug, path);
        try {
            size = target.size(o);
            size = size + CodedOutputStream.computeRawVarint32Size(size);
            return size + CodedOutputStream.computeTagSize(order);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    if (type == FieldType.STRING) {
        size = CodedOutputStream.computeStringSizeNoTag(String.valueOf(o));
    } else if (type == FieldType.BOOL) {
        size = CodedOutputStream.computeBoolSizeNoTag(Boolean.valueOf(String.valueOf(o)));
    } else if (type == FieldType.BYTES) {
        byte[] bb = (byte[]) o;
        size = CodedOutputStream.computeBytesSizeNoTag(ByteString.copyFrom(bb));
    } else if (type == FieldType.DOUBLE) {
        size = CodedOutputStream.computeDoubleSizeNoTag(Double.valueOf(o.toString()));
    } else if (type == FieldType.FIXED32 || type == FieldType.INT32 || type == FieldType.SFIXED32
            || type == FieldType.SINT32 || type == FieldType.UINT32) {
        size = CodedOutputStream.computeInt32SizeNoTag(Integer.valueOf(o.toString()));
    } else if (type == FieldType.FIXED64 || type == FieldType.INT64 || type == FieldType.SFIXED64
            || type == FieldType.SINT64 || type == FieldType.UINT64) {
        size = CodedOutputStream.computeInt64SizeNoTag(Long.valueOf(o.toString()));
    } else if (type == FieldType.FLOAT) {
        size = CodedOutputStream.computeFloatSizeNoTag(Float.valueOf(o.toString()));
    } else if (type == FieldType.ENUM) {
        if (o instanceof EnumReadable) {
            size = CodedOutputStream.computeInt32SizeNoTag(((EnumReadable) o).value());
        } else if (o instanceof Enum) {
            size = CodedOutputStream.computeInt32SizeNoTag(((Enum) o).ordinal());
        }
    }

    return size;
}
 
Example #17
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 4 votes vote down vote up
/**
 * Write a field of arbitrary type, without its tag, to the stream.
 *
 * @param output The output stream.
 * @param type The field's type.
 * @param value Object representing the field's value. Must be of the exact type which would be returned by
 *            {@link Message#getField(Descriptors.FieldDescriptor)} for this field.
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void writeElementNoTag(final CodedOutputStream output, final WireFormat.FieldType type,
        final Object value) throws IOException {
    switch (type) {
        case DOUBLE:
            output.writeDoubleNoTag((Double) value);
            break;
        case FLOAT:
            output.writeFloatNoTag((Float) value);
            break;
        case INT64:
            output.writeInt64NoTag((Long) value);
            break;
        case UINT64:
            output.writeUInt64NoTag((Long) value);
            break;
        case INT32:
            output.writeInt32NoTag((Integer) value);
            break;
        case FIXED64:
            output.writeFixed64NoTag((Long) value);
            break;
        case FIXED32:
            output.writeFixed32NoTag((Integer) value);
            break;
        case BOOL:
            output.writeBoolNoTag((Boolean) value);
            break;
        case STRING:
            output.writeStringNoTag((String) value);
            break;
        // group not support yet
        // case GROUP : output.writeGroupNoTag ((MessageLite) value); break;
        case MESSAGE:
            writeObject(output, 0, FieldType.OBJECT, value, false, false);
            break;
        case BYTES:
            if (value instanceof ByteString) {
                output.writeBytesNoTag((ByteString) value);
            } else {
                byte[] v;
                if (value instanceof Byte[]) {
                    v = toByteArray((Byte[]) value);
                } else {
                    v = (byte[]) value;
                }
                output.writeByteArrayNoTag(v);
            }
            break;
        case UINT32:
            output.writeUInt32NoTag((Integer) value);
            break;
        case SFIXED32:
            output.writeSFixed32NoTag((Integer) value);
            break;
        case SFIXED64:
            output.writeSFixed64NoTag((Long) value);
            break;
        case SINT32:
            output.writeSInt32NoTag((Integer) value);
            break;
        case SINT64:
            output.writeSInt64NoTag((Long) value);
            break;

        case ENUM:
            if (value instanceof Internal.EnumLite) {
                output.writeEnumNoTag(((Internal.EnumLite) value).getNumber());
            } else {

                if (value instanceof EnumReadable) {
                    output.writeEnumNoTag(((EnumReadable) value).value());
                } else if (value instanceof Enum) {
                    output.writeEnumNoTag(((Enum) value).ordinal());
                } else {
                    output.writeEnumNoTag(((Integer) value).intValue());
                }

            }
            break;
    }
}
 
Example #18
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 4 votes vote down vote up
/**
 * Read a field of any primitive type for immutable messages from a CodedInputStream. Enums, groups, and embedded
 * messages are not handled by this method.
 *
 * @param input The stream from which to read.
 * @param type Declared type of the field.
 * @param checkUtf8 When true, check that the input is valid utf8.
 * @return An object representing the field's value, of the exact type which would be returned by
 *         {@link Message#getField(Descriptors.FieldDescriptor)} for this field.
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static Object readPrimitiveField(CodedInputStream input, final WireFormat.FieldType type, boolean checkUtf8)
        throws IOException {
    switch (type) {
        case DOUBLE:
            return input.readDouble();
        case FLOAT:
            return input.readFloat();
        case INT64:
            return input.readInt64();
        case UINT64:
            return input.readUInt64();
        case INT32:
            return input.readInt32();
        case FIXED64:
            return input.readFixed64();
        case FIXED32:
            return input.readFixed32();
        case BOOL:
            return input.readBool();
        case STRING:
            if (checkUtf8) {
                return input.readStringRequireUtf8();
            } else {
                return input.readString();
            }
        case BYTES:
            return input.readByteArray();
        case UINT32:
            return input.readUInt32();
        case SFIXED32:
            return input.readSFixed32();
        case SFIXED64:
            return input.readSFixed64();
        case SINT32:
            return input.readSInt32();
        case SINT64:
            return input.readSInt64();

        case GROUP:
            throw new IllegalArgumentException("readPrimitiveField() cannot handle nested groups.");
        case MESSAGE:
            throw new IllegalArgumentException("readPrimitiveField() cannot handle embedded messages.");
        case ENUM:
            // We don't handle enums because we don't know what to do if the
            // value is not recognized.
            throw new IllegalArgumentException("readPrimitiveField() cannot handle enums.");
    }

    throw new RuntimeException("There is no way to get here, but the compiler thinks otherwise.");
}
 
Example #19
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 3 votes vote down vote up
/**
 * Put map value.
 *
 * @param <K> the key type
 * @param <V> the value type
 * @param input the input
 * @param map the map
 * @param keyType the key type
 * @param defaultKey the default key
 * @param valueType the value type
 * @param defalutValue the defalut value
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static <K, V> void putMapValue(CodedInputStream input, Map<K, V> map,
        com.google.protobuf.WireFormat.FieldType keyType, K defaultKey,
        com.google.protobuf.WireFormat.FieldType valueType, V defalutValue) throws IOException {
    putMapValue(input, map, keyType, defaultKey, valueType, defalutValue, null);

}
 
Example #20
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 3 votes vote down vote up
/**
 * Write to map.
 *
 * @param <K> the key type
 * @param <V> the value type
 * @param output the output
 * @param order the order
 * @param map the map
 * @param keyType the key type
 * @param defaultKey the default key
 * @param valueType the value type
 * @param defalutValue the defalut value
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static <K, V> void writeToMap(CodedOutputStream output, int order, Map<K, V> map,
        com.google.protobuf.WireFormat.FieldType keyType, K defaultKey,
        com.google.protobuf.WireFormat.FieldType valueType, V defalutValue) throws IOException {
    com.baidu.bjf.remoting.protobuf.MapEntry<K, V> valuesDefaultEntry = com.baidu.bjf.remoting.protobuf.MapEntry
            .<K, V> newDefaultInstance(null, keyType, defaultKey, valueType, defalutValue);
    for (java.util.Map.Entry<K, V> entry : map.entrySet()) {
        com.baidu.bjf.remoting.protobuf.MapEntry<K, V> values =
                valuesDefaultEntry.newBuilderForType().setKey(entry.getKey()).setValue(entry.getValue()).build();
        output.writeMessage(order, values);
    }
}
 
Example #21
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 3 votes vote down vote up
/**
 * Given a field type, return the wire type.
 *
 * @param type the type
 * @param isPacked the is packed
 * @return the wire format for field type
 * @returns One of the {@code WIRETYPE_} constants defined in {@link WireFormat}.
 */
static int getWireFormatForFieldType(final WireFormat.FieldType type, boolean isPacked) {
    if (isPacked) {
        return WireFormat.WIRETYPE_LENGTH_DELIMITED;
    } else {
        return type.getWireType();
    }
}
 
Example #22
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 2 votes vote down vote up
/**
 * Write to list.
 *
 * @param out the out
 * @param order the order
 * @param type the type
 * @param list the list
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void writeToList(CodedOutputStream out, int order, FieldType type, Collection list) throws IOException {
    writeToList(out, order, type, list, false);
}
 
Example #23
Source File: FieldInfo.java    From jprotobuf with Apache License 2.0 2 votes vote down vote up
/**
 * set fieldType value to fieldType
 * 
 * @param fieldType the fieldType to set
 */
public void setFieldType(FieldType fieldType) {
    this.fieldType = fieldType;
}
 
Example #24
Source File: FieldInfo.java    From jprotobuf with Apache License 2.0 2 votes vote down vote up
/**
 * get the fieldType
 * 
 * @return the fieldType
 */
public FieldType getFieldType() {
    return fieldType;
}
 
Example #25
Source File: CodeGenerator.java    From jprotobuf with Apache License 2.0 2 votes vote down vote up
/**
 * get error message info by type not matched
 * 
 * @param type
 * @param field
 * @return error message for mismatch type
 */
private String getMismatchTypeErroMessage(FieldType type, Field field) {
    return "Type mismatch. @Protobuf required type '" + type.getJavaType() + "' but field type is '"
            + field.getType().getSimpleName() + "' of field name '" + field.getName() + "' on class "
            + field.getDeclaringClass().getCanonicalName();
}
 
Example #26
Source File: FieldInfo.java    From jprotobuf with Apache License 2.0 2 votes vote down vote up
/**
 * get the fieldType.
 *
 * @return the fieldType
 */
public FieldType getFieldType() {
    return fieldType;
}
 
Example #27
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 2 votes vote down vote up
/**
 * Write object.
 *
 * @param out the out
 * @param order the order
 * @param type the type
 * @param o the o
 * @param list the list
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void writeObject(CodedOutputStream out, int order, FieldType type, Object o, boolean list)
        throws IOException {
    writeObject(out, order, type, o, list, true);
}
 
Example #28
Source File: FieldInfo.java    From jprotobuf with Apache License 2.0 2 votes vote down vote up
/**
 * set fieldType value to fieldType.
 *
 * @param fieldType the fieldType to set
 */
public void setFieldType(FieldType fieldType) {
    this.fieldType = fieldType;
}
 
Example #29
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 2 votes vote down vote up
/**
 * get object size by {@link FieldType}.
 *
 * @param order the order
 * @param o the o
 * @param type the type
 * @param debug the debug
 * @param path the path
 * @return the int
 */
public static int computeSize(int order, Object o, FieldType type, boolean debug, File path) {
    return computeSize(order, o, type, false, debug, path);
}
 
Example #30
Source File: FieldInfo.java    From jprotobuf with Apache License 2.0 2 votes vote down vote up
/**
 * Checks if is object type.
 *
 * @return true, if is object type
 */
public boolean isObjectType() {
    return fieldType == FieldType.OBJECT;
}