com.google.protobuf.WireFormat Java Examples

The following examples show how to use com.google.protobuf.WireFormat. 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: MapEntryLite.java    From jprotobuf with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the field.
 *
 * @param <T> the generic type
 * @param input the input
 * @param extensionRegistry the extension registry
 * @param type the type
 * @param value the value
 * @return the t
 * @throws IOException Signals that an I/O exception has occurred.
 */
@SuppressWarnings("unchecked")
static <T> T parseField(CodedInputStream input, ExtensionRegistryLite extensionRegistry, WireFormat.FieldType type,
        T value) throws IOException {
    switch (type) {
        case MESSAGE:
            int length = input.readRawVarint32();
            final int oldLimit = input.pushLimit(length);
            Codec<? extends Object> codec = ProtobufProxy.create(value.getClass());
            T ret = (T) codec.decode(input.readRawBytes(length));
            input.popLimit(oldLimit);
            return ret;
        case ENUM:
            return (T) (java.lang.Integer) input.readEnum();
        case GROUP:
            throw new RuntimeException("Groups are not allowed in maps.");
        default:
            return (T) CodedConstant.readPrimitiveField(input, type, true);
    }
}
 
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: WalletProtobufSerializer.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Cheap test to see if input stream is a wallet. This checks for a magic value at the beginning of the stream.
 *
 * @param is
 *            input stream to test
 * @return true if input stream is a wallet
 */
public static boolean isWallet(InputStream is) {
    try {
        final CodedInputStream cis = CodedInputStream.newInstance(is);
        final int tag = cis.readTag();
        final int field = WireFormat.getTagFieldNumber(tag);
        if (field != 1) // network_identifier
            return false;
        final String network = cis.readString();
        return NetworkParameters.fromID(network) != null;
    } catch (IOException x) {
        return false;
    }
}
 
Example #4
Source File: MapEntry.java    From jprotobuf with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a new metadata.
 *
 * @param descriptor the descriptor
 * @param defaultInstance the default instance
 * @param keyType the key type
 * @param valueType the value type
 */
public Metadata(Descriptor descriptor, MapEntry<K, V> defaultInstance, WireFormat.FieldType keyType,
        WireFormat.FieldType valueType) {
    super(keyType, defaultInstance.key, valueType, defaultInstance.value);
    this.descriptor = descriptor;
    this.parser = new AbstractParser<MapEntry<K, V>>() {

        @Override
        public MapEntry<K, V> parsePartialFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry)
                throws InvalidProtocolBufferException {
            return new MapEntry<K, V>(Metadata.this, input, extensionRegistry);
        }
    };
}
 
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 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 #9
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 #10
Source File: WalletProtobufSerializer.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Cheap test to see if input stream is a wallet. This checks for a magic value at the beginning of the stream.
 *
 * @param is input stream to test
 * @return true if input stream is a wallet
 */
public static boolean isWallet(InputStream is) {
    try {
        final CodedInputStream cis = CodedInputStream.newInstance(is);
        final int tag = cis.readTag();
        final int field = WireFormat.getTagFieldNumber(tag);
        if (field != 1) // network_identifier
            return false;
        final String network = cis.readString();
        return NetworkParameters.fromID(network) != null;
    } catch (IOException x) {
        return false;
    }
}
 
Example #11
Source File: TrackManager.java    From trekarta with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void saveData(OutputStream outputStream, FileDataSource source, @Nullable ProgressListener progressListener) throws Exception {
    if (source.tracks.size() != 1)
        throw new Exception("Only single track can be saved in mtrack format");
    Track track = source.tracks.get(0);
    if (progressListener != null)
        progressListener.onProgressStarted(track.points.size());
    CodedOutputStream output = CodedOutputStream.newInstance(outputStream);
    output.writeUInt32(FIELD_VERSION, VERSION);
    int progress = 0;
    for (Track.TrackPoint point : track.points) {
        output.writeTag(FIELD_POINT, WireFormat.WIRETYPE_LENGTH_DELIMITED);
        output.writeRawVarint32(getSerializedPointSize(point));
        output.writeInt32(FIELD_POINT_LATITUDE, point.latitudeE6);
        output.writeInt32(FIELD_POINT_LONGITUDE, point.longitudeE6);
        output.writeFloat(FIELD_POINT_ALTITUDE, point.elevation);
        output.writeFloat(FIELD_POINT_SPEED, point.speed);
        output.writeFloat(FIELD_POINT_BEARING, point.bearing);
        output.writeFloat(FIELD_POINT_ACCURACY, point.accuracy);
        output.writeUInt64(FIELD_POINT_TIMESTAMP, point.time);
        if (!point.continuous)
            //noinspection ConstantConditions
            output.writeBool(8, point.continuous);
        progress++;
        if (progressListener != null)
            progressListener.onProgressChanged(progress);
    }
    output.writeBytes(FIELD_NAME, ByteString.copyFromUtf8(track.name));
    output.writeUInt32(FIELD_COLOR, track.style.color);
    output.writeFloat(FIELD_WIDTH, track.style.width);
    output.flush();
    outputStream.close();
    if (progressListener != null)
        progressListener.onProgressFinished();
}
 
Example #12
Source File: WalletProtobufSerializer.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Cheap test to see if input stream is a wallet. This checks for a magic value at the beginning of the stream.
 *
 * @param is
 *            input stream to test
 * @return true if input stream is a wallet
 */
public static boolean isWallet(InputStream is) {
    try {
        final CodedInputStream cis = CodedInputStream.newInstance(is);
        final int tag = cis.readTag();
        final int field = WireFormat.getTagFieldNumber(tag);
        if (field != 1) // network_identifier
            return false;
        final String network = cis.readString();
        return NetworkParameters.fromID(network) != null;
    } catch (IOException x) {
        return false;
    }
}
 
Example #13
Source File: CodedConstant.java    From jprotobuf with Apache License 2.0 4 votes vote down vote up
/**
 * Write object to byte array by {@link FieldType}
 * 
 * @param out
 * @param order
 * @param type
 * @param o
 * @throws IOException
 */
public static void writeObject(CodedOutputStream out, int order, FieldType type, Object o, boolean list)
        throws IOException {
    if (o == null) {
        return;
    }

    if (type == FieldType.OBJECT) {

        Class cls = o.getClass();
        Codec target = ProtobufProxy.create(cls);

        out.writeRawVarint32(makeTag(order, WireFormat.WIRETYPE_LENGTH_DELIMITED));
        out.writeRawVarint32(target.size(o));

        target.writeTo(o, out);
        return;
    }

    if (type == FieldType.BOOL) {
        out.writeBool(order, (Boolean) o);
    } else if (type == FieldType.BYTES) {
        byte[] bb = (byte[]) o;
        out.writeBytes(order, ByteString.copyFrom(bb));
    } else if (type == FieldType.DOUBLE) {
        out.writeDouble(order, (Double) o);
    } else if (type == FieldType.FIXED32) {
        out.writeFixed32(order, (Integer) o);
    } else if (type == FieldType.FIXED64) {
        out.writeFixed64(order, (Long) o);
    } else if (type == FieldType.FLOAT) {
        out.writeFloat(order, (Float) o);
    } else if (type == FieldType.INT32) {
        out.writeInt32(order, (Integer) o);
    } else if (type == FieldType.INT64) {
        out.writeInt64(order, (Long) o);
    } else if (type == FieldType.SFIXED32) {
        out.writeSFixed32(order, (Integer) o);
    } else if (type == FieldType.SFIXED64) {
        out.writeSFixed64(order, (Long) o);
    } else if (type == FieldType.SINT32) {
        out.writeSInt32(order, (Integer) o);
    } else if (type == FieldType.SINT64) {
        out.writeSInt64(order, (Long) o);
    } else if (type == FieldType.STRING) {
        out.writeBytes(order, ByteString.copyFromUtf8(String.valueOf(o)));
    } else if (type == FieldType.UINT32) {
        out.writeUInt32(order, (Integer) o);
    } else if (type == FieldType.UINT64) {
        out.writeUInt64(order, (Long) o);
    } else if (type == FieldType.ENUM) {
        int value = 0;
        if (o instanceof EnumReadable) {
            value = ((EnumReadable) o).value();
        } else if (o instanceof Enum) {
            value = ((Enum) o).ordinal();
        }
        out.writeEnum(order, value);
    }
}
 
Example #14
Source File: ReflectiveCodec.java    From jprotobuf with Apache License 2.0 4 votes vote down vote up
private void writeTo(FieldInfo fieldInfo, Object value, CodedOutputStream out) throws IOException {
	FieldType fieldType = fieldInfo.getFieldType();
	int order = fieldInfo.getOrder();

	if (value instanceof List) {
		// if check list
		CodedConstant.writeToList(out, order, fieldType, (List) value);
		return;
	}

	switch (fieldType) {
	case DOUBLE:
		out.writeDouble(order, (Double) value);
		break;
	case BYTES:
		ByteString bytes = ByteString.copyFrom((byte[]) value);
		out.writeBytes(order, bytes);
		break;
	case STRING:
		ByteString string = ByteString.copyFromUtf8(value.toString());
		out.writeBytes(order, string);
		break;
	case BOOL:
		out.writeBool(order, (Boolean) value);
		break;
	case FIXED32:
		out.writeFixed32(order, (Integer) value);
		break;
	case SFIXED32:
		out.writeSFixed32(order, (Integer) value);
		break;
	case SINT32:
		out.writeSInt32(order, (Integer) value);
		break;
	case INT32:
		out.writeInt32(order, (Integer) value);
		break;
	case UINT32:
		out.writeUInt32(order, (Integer) value);
		break;
	case FIXED64:
		out.writeFixed64(order, (Long) value);
		break;
	case SFIXED64:
		out.writeSFixed64(order, (Long) value);
		break;
	case SINT64:
		out.writeSInt64(order, (Long) value);
		break;
	case INT64:
		out.writeInt64(order, (Long) value);
		break;
	case UINT64:
		out.writeUInt64(order, (Long) value);
		break;
	case ENUM:
		int i;
		i = getEnumValue(value);
		out.writeEnum(order, i);
		break;
	case FLOAT:
		out.writeFloat(order, (Float) value);
		break;
	case OBJECT:
		Class c = value.getClass();
		ReflectiveCodec codec = new ReflectiveCodec(c);
		out.writeRawVarint32(CodedConstant.makeTag(order, WireFormat.WIRETYPE_LENGTH_DELIMITED));
		out.writeRawVarint32(codec.size(value));
		codec.writeTo(value, out);
		break;
	default:
		throw new IOException("Unknown field type on field '" + fieldInfo.getField().getName() + "'");
	}

}
 
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
/**
 * 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 #17
Source File: TrackManager.java    From trekarta with GNU General Public License v3.0 4 votes vote down vote up
@NonNull
@Override
public FileDataSource loadData(InputStream inputStream, String filePath) throws Exception {
    long propertiesOffset = 0L;
    Track track = new Track();
    CodedInputStream input = CodedInputStream.newInstance(inputStream);
    boolean done = false;
    while (!done) {
        long offset = input.getTotalBytesRead();
        int tag = input.readTag();
        int field = WireFormat.getTagFieldNumber(tag);
        switch (field) {
            case 0:
                done = true;
                break;
            default: {
                throw new com.google.protobuf.InvalidProtocolBufferException("Unsupported proto field: " + tag);
            }
            case FIELD_VERSION: {
                // skip version
                input.skipField(tag);
                break;
            }
            case FIELD_POINT: {
                int length = input.readRawVarint32();
                int oldLimit = input.pushLimit(length);
                readPoint(track, input);
                input.popLimit(oldLimit);
                input.checkLastTagWas(0);
                break;
            }
            case FIELD_NAME: {
                propertiesOffset = offset;
                track.name = input.readBytes().toStringUtf8();
                break;
            }
            case FIELD_COLOR: {
                track.style.color = input.readUInt32();
                break;
            }
            case FIELD_WIDTH: {
                track.style.width = input.readFloat();
                break;
            }
        }
    }
    inputStream.close();
    track.id = 31 * filePath.hashCode() + 1;
    FileDataSource dataSource = new FileDataSource();
    dataSource.name = track.name;
    dataSource.tracks.add(track);
    track.source = dataSource;
    dataSource.propertiesOffset = propertiesOffset;
    return dataSource;
}
 
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: TrackManager.java    From trekarta with GNU General Public License v3.0 4 votes vote down vote up
private void readPoint(Track track, CodedInputStream input) throws IOException {
    int latitudeE6 = 0;
    int longitudeE6 = 0;
    boolean continuous = true;
    float altitude = Float.NaN;
    float speed = Float.NaN;
    float bearing = Float.NaN;
    float accuracy = Float.NaN;
    long timestamp = 0L;

    boolean done = false;
    while (!done) {
        int tag = input.readTag();
        int field = WireFormat.getTagFieldNumber(tag);
        switch (field) {
            case 0:
                done = true;
                break;
            default: {
                throw new com.google.protobuf.InvalidProtocolBufferException("Unsupported proto field: " + tag);
            }
            case FIELD_POINT_LATITUDE: {
                latitudeE6 = input.readInt32();
                break;
            }
            case FIELD_POINT_LONGITUDE: {
                longitudeE6 = input.readInt32();
                break;
            }
            case FIELD_POINT_ALTITUDE: {
                altitude = input.readFloat();
                break;
            }
            case FIELD_POINT_SPEED: {
                speed = input.readFloat();
                break;
            }
            case FIELD_POINT_BEARING: {
                bearing = input.readFloat();
                break;
            }
            case FIELD_POINT_ACCURACY: {
                accuracy = input.readFloat();
                break;
            }
            case FIELD_POINT_TIMESTAMP: {
                timestamp = input.readUInt64();
                break;
            }
            case FIELD_POINT_CONTINUOUS: {
                continuous = input.readBool();
                break;
            }
        }
    }
    track.addPointFast(continuous, latitudeE6, longitudeE6, altitude, speed, bearing, accuracy, timestamp);
}
 
Example #20
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 #21
Source File: MapEntryLite.java    From jprotobuf with Apache License 2.0 3 votes vote down vote up
/**
 * Instantiates a new metadata.
 *
 * @param keyType the key type
 * @param defaultKey the default key
 * @param valueType the value type
 * @param defaultValue the default value
 */
public Metadata(WireFormat.FieldType keyType, K defaultKey, WireFormat.FieldType valueType, V defaultValue) {
    this.keyType = keyType;
    this.defaultKey = defaultKey;
    this.valueType = valueType;
    this.defaultValue = defaultValue;
}
 
Example #22
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 #23
Source File: MapEntry.java    From jprotobuf with Apache License 2.0 3 votes vote down vote up
/**
 *  Create a default MapEntry instance.
 *
 * @param descriptor the descriptor
 * @param keyType the key type
 * @param defaultKey the default key
 * @param valueType the value type
 * @param defaultValue the default value
 */
private MapEntry(Descriptor descriptor, WireFormat.FieldType keyType, K defaultKey, WireFormat.FieldType valueType,
        V defaultValue) {
    this.key = defaultKey;
    this.value = defaultValue;
    this.metadata = new Metadata<K, V>(descriptor, this, keyType, valueType);
}
 
Example #24
Source File: MapEntry.java    From jprotobuf with Apache License 2.0 3 votes vote down vote up
/**
 * Checks if is initialized.
 *
 * @param <V> the value type
 * @param metadata the metadata
 * @param value the value
 * @return true, if is initialized
 */
private static <V> boolean isInitialized(Metadata metadata, V value) {
    if (metadata.valueType.getJavaType() == WireFormat.JavaType.MESSAGE) {
        return value != null;
    }
    return true;
}
 
Example #25
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 #26
Source File: MapEntryLite.java    From jprotobuf with Apache License 2.0 2 votes vote down vote up
/**
 *  Creates a default MapEntryLite message instance.
 *
 * @param keyType the key type
 * @param defaultKey the default key
 * @param valueType the value type
 * @param defaultValue the default value
 */
private MapEntryLite(WireFormat.FieldType keyType, K defaultKey, WireFormat.FieldType valueType, V defaultValue) {
    this.metadata = new Metadata<K, V>(keyType, defaultKey, valueType, defaultValue);
    this.key = defaultKey;
    this.value = defaultValue;
}
 
Example #27
Source File: MapEntryLite.java    From jprotobuf with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a default MapEntryLite message instance.
 * 
 * This method is used by generated code to create the default instance for a map entry message. The created default
 * instance should be used to create new map entry messages of the same type. For each map entry message, only one
 * default instance should be created.
 *
 * @param <K> the key type
 * @param <V> the value type
 * @param keyType the key type
 * @param defaultKey the default key
 * @param valueType the value type
 * @param defaultValue the default value
 * @return the map entry lite
 */
public static <K, V> MapEntryLite<K, V> newDefaultInstance(WireFormat.FieldType keyType, K defaultKey,
        WireFormat.FieldType valueType, V defaultValue) {
    return new MapEntryLite<K, V>(keyType, defaultKey, valueType, defaultValue);
}
 
Example #28
Source File: MapEntryLite.java    From jprotobuf with Apache License 2.0 2 votes vote down vote up
/**
 * Serializes the provided key and value as though they were wrapped by a {@link MapEntryLite} to the output stream.
 * This helper method avoids allocation of a {@link MapEntryLite} built with a key and value and is called from
 * generated code directly.
 *
 * @param output the output
 * @param fieldNumber the field number
 * @param key the key
 * @param value the value
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void serializeTo(CodedOutputStream output, int fieldNumber, K key, V value) throws IOException {
    output.writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
    output.writeUInt32NoTag(computeSerializedSize(metadata, key, value));
    writeTo(output, metadata, key, value);
}
 
Example #29
Source File: MapEntry.java    From jprotobuf with Apache License 2.0 2 votes vote down vote up
/**
 * Create a default MapEntry instance. A default MapEntry instance should be created only once for each map entry
 * message type. Generated code should store the created default instance and use it later to create new MapEntry
 * messages of the same type.
 *
 * @param <K> the key type
 * @param <V> the value type
 * @param descriptor the descriptor
 * @param keyType the key type
 * @param defaultKey the default key
 * @param valueType the value type
 * @param defaultValue the default value
 * @return the map entry
 */
public static <K, V> MapEntry<K, V> newDefaultInstance(Descriptor descriptor, WireFormat.FieldType keyType,
        K defaultKey, WireFormat.FieldType valueType, V defaultValue) {
    return new MapEntry<K, V>(descriptor, keyType, defaultKey, valueType, defaultValue);
}