Java Code Examples for com.google.protobuf.Message#writeTo()

The following examples show how to use com.google.protobuf.Message#writeTo() . 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: ProtoOutputFormatterCallback.java    From bazel with Apache License 2.0 6 votes vote down vote up
private void writeData(Message message) throws IOException {
  switch (outputType) {
    case BINARY:
      message.writeTo(outputStream);
      break;
    case TEXT:
      TextFormat.print(message, printStream);
      break;
    case JSON:
      jsonPrinter.appendTo(message, printStream);
      printStream.append('\n');
      break;
    default:
      throw new IllegalStateException("Unknown outputType " + outputType.formatName());
  }
}
 
Example 2
Source File: ProtocolBufferMessageBodyProvider.java    From dropwizard-protobuf with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(
    final Message m,
    final Class<?> type,
    final Type genericType,
    final Annotation[] annotations,
    final MediaType mediaType,
    final MultivaluedMap<String, Object> httpHeaders,
    final OutputStream entityStream)
    throws IOException {

  if (mediaType.getSubtype().contains("text-format")) {
    entityStream.write(m.toString().getBytes(StandardCharsets.UTF_8));
  } else if (mediaType.getSubtype().contains("json-format")) {
    final String formatted = JsonFormat.printer().omittingInsignificantWhitespace().print(m);
    entityStream.write(formatted.getBytes(StandardCharsets.UTF_8));
  } else {
    m.writeTo(entityStream);
  }
}
 
Example 3
Source File: ProtoBufSerializer.java    From AutoLoadCache with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] serialize(CacheWrapper<Object> obj) throws Exception {
    val byteBuf = writePool.borrowObject();
    byteBuf.resetIndex();
    byteBuf.writeInt(obj.getExpire());
    byteBuf.writeLong(obj.getLastLoadTime());
    Object cacheObj = obj.getCacheObject();
    if (cacheObj instanceof Message) {
        Message message = (Message) cacheObj;
        message.writeTo(new ByteBufOutputStream(byteBuf));
    } else if (cacheObj != null) {
        byteBuf.writeBytes(MAPPER.writeValueAsBytes(cacheObj));
    }
    val bytes = byteBuf.readableBytes();
    writePool.returnObject(byteBuf);
    return bytes;
}
 
Example 4
Source File: ProtobufEncoder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private DataBuffer encodeValue(Message message, DataBufferFactory bufferFactory, boolean delimited) {

		DataBuffer buffer = bufferFactory.allocateBuffer();
		boolean release = true;
		try {
			if (delimited) {
				message.writeDelimitedTo(buffer.asOutputStream());
			}
			else {
				message.writeTo(buffer.asOutputStream());
			}
			release = false;
			return buffer;
		}
		catch (IOException ex) {
			throw new IllegalStateException("Unexpected I/O error while writing to data buffer", ex);
		}
		finally {
			if (release) {
				DataBufferUtils.release(buffer);
			}
		}
	}
 
Example 5
Source File: ProtoBufFile.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
/**
 * Save a protobuf message to file.
 *
 * @param msg  protobuf message
 * @param sync if sync flush data to disk
 * @return true if save success
 */
public boolean save(final Message msg, final boolean sync) throws IOException {
    // Write message into temp file
    final File file = new File(this.path + ".tmp");
    try (final FileOutputStream fOut = new FileOutputStream(file);
            final BufferedOutputStream output = new BufferedOutputStream(fOut)) {
        final byte[] lenBytes = new byte[4];

        // name len + name
        final String fullName = msg.getDescriptorForType().getFullName();
        final int nameLen = fullName.length();
        Bits.putInt(lenBytes, 0, nameLen);
        output.write(lenBytes);
        output.write(fullName.getBytes());
        // msg len + msg
        final int msgLen = msg.getSerializedSize();
        Bits.putInt(lenBytes, 0, msgLen);
        output.write(lenBytes);
        msg.writeTo(output);
        if (sync) {
            fOut.getFD().sync();
        }
    }

    return Utils.atomicMoveFile(file, new File(this.path));
}
 
Example 6
Source File: ProtobufEncoder.java    From java-technology-stack with MIT License 6 votes vote down vote up
private DataBuffer encodeMessage(Message message, DataBufferFactory bufferFactory, boolean streaming) {
	DataBuffer buffer = bufferFactory.allocateBuffer();
	OutputStream outputStream = buffer.asOutputStream();
	try {
		if (streaming) {
			message.writeDelimitedTo(outputStream);
		}
		else {
			message.writeTo(outputStream);
		}
		return buffer;
	}
	catch (IOException ex) {
		throw new IllegalStateException("Unexpected I/O error while writing to data buffer", ex);
	}
}
 
Example 7
Source File: ProtobufTranslationImpl.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
void serializeMessage(OutputStream out, Message msg) throws IOException {
  // Serialize the protobuf message
  UnsynchronizedBuffer buffer = threadLocalBuffer.get();
  ByteString serializedMsg;
  try {
    msg.writeTo(buffer);
    // Make a bytestring from it
    serializedMsg = UnsafeByteOperations.unsafeWrap(buffer.toArray());
  } finally {
    buffer.reset();
  }

  // Wrap the serialized message in a WireMessage
  WireMessage wireMsg = WireMessage.newBuilder().setNameBytes(getClassNameBytes(msg.getClass()))
      .setWrappedMessage(serializedMsg).build();

  // Write the WireMessage to the provided OutputStream
  wireMsg.writeTo(out);
}
 
Example 8
Source File: ProtobufRedisCodec.java    From curiostack with MIT License 5 votes vote down vote up
private static void encodeTo(Message message, ByteBuf target) {
  try {
    message.writeTo(
        CodedOutputStream.newInstance(
            target.nioBuffer(target.writerIndex(), target.writableBytes())));
  } catch (IOException e) {
    throw new UncheckedIOException("Could not encode message.", e);
  }
}
 
Example 9
Source File: FakeSocket.java    From protobuf-socket-rpc with MIT License 5 votes vote down vote up
private void setMessage(Message message)
    throws IOException {
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  if (delimited) {
    message.writeDelimitedTo(os);
  } else {
    message.writeTo(os);
  }
  input = new ByteArrayInputStream(os.toByteArray());
}
 
Example 10
Source File: SocketConnectionTest.java    From protobuf-socket-rpc with MIT License 5 votes vote down vote up
private static void writeToOutputStream(Message message,
    ByteArrayOutputStream os, boolean isDelimited) throws IOException {
  if (isDelimited) {
    message.writeDelimitedTo(os);
  } else {
    message.writeTo(os);
  }
}
 
Example 11
Source File: OutputUtil.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Writes a proto to a file in binary format.
 */
public static void writeProtoBinaryToFile(File outputFile, Message proto)
    throws IOException {
  try (OutputStream prodOutputStream = new FileOutputStream(outputFile)) {
    proto.writeTo(prodOutputStream);
  }
}
 
Example 12
Source File: ProtoDiff.java    From metastore with Apache License 2.0 5 votes vote down vote up
private ByteString serializePayload(Message field) {
  ByteBuffer byteBuffer = ByteBuffer.allocate(field.getSerializedSize());
  try {
    CodedOutputStream stream = CodedOutputStream.newInstance(byteBuffer);
    field.writeTo(stream);
  } catch (IOException e) {
    throw new RuntimeException("failed to serialize unknown field with number ", e);
  }
  return ByteString.copyFrom(byteBuffer);
}
 
Example 13
Source File: FileUtils.java    From startup-os with Apache License 2.0 5 votes vote down vote up
/** Writes a proto to binary file. */
public void writeProtoBinary(Message proto, String path) throws IOException {
  File file = new File(path);
  if (file.getParent() != null) {
    mkdirs(file.getParent());
  }
  proto.writeTo(Files.newOutputStream(fileSystem.getPath(expandHomeDirectory(path))));
}
 
Example 14
Source File: ProtobufHttpMessageConverter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void writeInternal(Message message, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {

	MediaType contentType = outputMessage.getHeaders().getContentType();
	if (contentType == null) {
		contentType = getDefaultContentType(message);
		Assert.state(contentType != null, "No content type");
	}
	Charset charset = contentType.getCharset();
	if (charset == null) {
		charset = DEFAULT_CHARSET;
	}

	if (PROTOBUF.isCompatibleWith(contentType)) {
		setProtoHeader(outputMessage, message);
		CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputMessage.getBody());
		message.writeTo(codedOutputStream);
		codedOutputStream.flush();
	}
	else if (TEXT_PLAIN.isCompatibleWith(contentType)) {
		OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputMessage.getBody(), charset);
		TextFormat.print(message, outputStreamWriter);
		outputStreamWriter.flush();
		outputMessage.getBody().flush();
	}
	else if (this.protobufFormatSupport != null) {
		this.protobufFormatSupport.print(message, outputMessage.getBody(), contentType, charset);
		outputMessage.getBody().flush();
	}
}
 
Example 15
Source File: ProtobufHttpMessageConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected void writeInternal(Message message, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {

	MediaType contentType = outputMessage.getHeaders().getContentType();
	if (contentType == null) {
		contentType = getDefaultContentType(message);
		Assert.state(contentType != null, "No content type");
	}
	Charset charset = contentType.getCharset();
	if (charset == null) {
		charset = DEFAULT_CHARSET;
	}

	if (PROTOBUF.isCompatibleWith(contentType)) {
		setProtoHeader(outputMessage, message);
		CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputMessage.getBody());
		message.writeTo(codedOutputStream);
		codedOutputStream.flush();
	}
	else if (TEXT_PLAIN.isCompatibleWith(contentType)) {
		OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputMessage.getBody(), charset);
		TextFormat.print(message, outputStreamWriter);
		outputStreamWriter.flush();
		outputMessage.getBody().flush();
	}
	else if (this.protobufFormatSupport != null) {
		this.protobufFormatSupport.print(message, outputMessage.getBody(), contentType, charset);
		outputMessage.getBody().flush();
	}
}
 
Example 16
Source File: ProtoBufSerializePerformanceTest.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
private static void codecTest(Message msg, int loopTimes, Map<Class<?>, Parser<? extends Message>> parserMap) throws IOException {
    final long start = System.currentTimeMillis();
    for (int index = 0; index < loopTimes; index++) {
        // 这里需要简单模拟下解码过程
        final CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(buffer);
        writeTypeId(msg, codedOutputStream);
        msg.writeTo(codedOutputStream);

        final CodedInputStream inputStream = CodedInputStream.newInstance(buffer, 0, codedOutputStream.getTotalBytesWritten());
        final Class<?> messageClass = readType(inputStream);
        final Parser<?> parser = parserMap.get(messageClass);
        final Object decodeMsg = parser.parseFrom(inputStream);
    }
    System.out.println("codec " + loopTimes + " times cost timeMs " + (System.currentTimeMillis() - start));
}
 
Example 17
Source File: OutputWriterFactory.java    From deploymentmanager-autogen with Apache License 2.0 4 votes vote down vote up
@Override
void writeOutput(Message message) throws IOException {
  try (OutputStream stream = newOutputStream()) {
    message.writeTo(stream);
  }
}
 
Example 18
Source File: ToolUtil.java    From api-compiler with Apache License 2.0 4 votes vote down vote up
/** Writes a proto out to a file. */
public static void writeProto(Message content, String outputName) throws IOException {
  try (OutputStream outputStream = new FileOutputStream(outputName)) {
    content.writeTo(outputStream);
  }
}
 
Example 19
Source File: CodedDataOutputStream.java    From fastjgame with Apache License 2.0 4 votes vote down vote up
@Override
public void writeMessage(@Nonnull Message message) throws IOException {
    message.writeTo(codedOutputStream);
}
 
Example 20
Source File: ImhotepProtobufShipping.java    From imhotep with Apache License 2.0 4 votes vote down vote up
public static void sendProtobuf(Message request, OutputStream os) throws IOException {
    os.write(Bytes.intToBytes(request.getSerializedSize()));
    request.writeTo(os);
    os.flush();
}