Java Code Examples for com.google.protobuf.Message#Builder

The following examples show how to use com.google.protobuf.Message#Builder . 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: ProtobufHttpMessageConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void merge(InputStream input, Charset charset, MediaType contentType,
		ExtensionRegistry extensionRegistry, Message.Builder builder)
		throws IOException, HttpMessageConversionException {

	if (contentType.isCompatibleWith(APPLICATION_JSON)) {
		this.jsonFormatter.merge(input, charset, extensionRegistry, builder);
	}
	else if (contentType.isCompatibleWith(APPLICATION_XML)) {
		this.xmlFormatter.merge(input, charset, extensionRegistry, builder);
	}
	else {
		throw new HttpMessageConversionException(
				"protobuf-java-format does not support parsing " + contentType);
	}
}
 
Example 2
Source File: TestUtils.java    From parquet-mr with Apache License 2.0 6 votes vote down vote up
public static Class<? extends Message> inferRecordsClass(MessageOrBuilder[] records) {
  Class<? extends Message> cls = null;

  for (MessageOrBuilder record : records) {
    Class<? extends Message> recordClass;
    if (record instanceof Message.Builder) {
      recordClass = ((Message.Builder) record).build().getClass();
    } else if (record instanceof Message) {
      recordClass = ((Message) record).getClass();
    } else {
      throw new RuntimeException("Illegal class " + record);
    }

    if (cls == null) {
      cls = recordClass;
    } else if (!cls.equals(recordClass)) {
      throw new RuntimeException("Class mismatch :" + cls + " and " + recordClass);
    }
  }
  return cls;
}
 
Example 3
Source File: SpringMockMvcUtil.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private static <E extends Message> E executeGet(MockMvc mockMvc, Message.Builder builder, MockHttpServletRequestBuilder requestBuilder) throws Exception {
    MvcResult mvcResult = mockMvc.perform(requestBuilder)
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andReturn();

    JsonFormat.parser().merge(mvcResult.getResponse().getContentAsString(), builder);
    return (E) builder.build();
}
 
Example 4
Source File: ClientRpcStore.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
private JsonNode getJSONFromMethod(Method m,Message msg,String fieldname) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, JsonParseException, IOException
{
	Message.Builder o2 = (Message.Builder) m.invoke(null);
	TypeRegistry registry = TypeRegistry.newBuilder().add(o2.getDescriptorForType()).build();
	
	JsonFormat.Printer jPrinter = JsonFormat.printer();
	String result = jPrinter.usingTypeRegistry(registry).print(msg);
	ObjectMapper mapper = new ObjectMapper();
	JsonFactory factory = mapper.getFactory();
	JsonParser parser = factory.createParser(result);
	JsonNode jNode = mapper.readTree(parser);
	if (jNode.has(fieldname) && jNode.get(fieldname).has("@type"))
		((ObjectNode) jNode.get(fieldname)).remove("@type");
	return jNode;
}
 
Example 5
Source File: ProtoFuzzer.java    From bundletool with Apache License 2.0 5 votes vote down vote up
private static void swapRepeatedFieldValues(
    Message.Builder mutableMsg, FieldDescriptor field, int idx1, int idx2) {
  Object value1 = mutableMsg.getRepeatedField(field, idx1);
  Object value2 = mutableMsg.getRepeatedField(field, idx2);
  mutableMsg.setRepeatedField(field, idx1, value2);
  mutableMsg.setRepeatedField(field, idx2, value1);
}
 
Example 6
Source File: XmlFormat.java    From jigsaw-payment with Apache License 2.0 5 votes vote down vote up
/**
 * Parse a text-format message from {@code input} and merge the contents into {@code builder}.
 * Extensions will be recognized if they are registered in {@code extensionRegistry}.
 */
public void merge(CharSequence input,
                         ExtensionRegistry extensionRegistry,
                         Message.Builder builder) throws ParseException {
    Tokenizer tokenizer = new Tokenizer(input);

    // Need to first consume the outer object name element
    consumeOpeningElement(tokenizer);

    while (!tokenizer.tryConsume("</")) { // Continue till the object is done
        mergeField(tokenizer, extensionRegistry, builder);
    }

    consumeClosingElement(tokenizer);
}
 
Example 7
Source File: ProtobufDatumFactory.java    From tajo with Apache License 2.0 5 votes vote down vote up
public static ProtobufDatum createDatum(String className, byte [] bytes, int offset, int length)
    throws InvalidProtocolBufferException {
  ProtobufDatumFactory factory = get(className);
  Message.Builder builder = factory.newBuilder();
  builder.mergeFrom(bytes, offset, length);
  return createDatum(builder);
}
 
Example 8
Source File: FirestoreProtoClient.java    From startup-os with Apache License 2.0 5 votes vote down vote up
public static Message parseProto(DocumentSnapshot document, Message.Builder builder)
    throws InvalidProtocolBufferException {
  return builder
      .build()
      .getParserForType()
      .parseFrom(Base64.getDecoder().decode(document.getString(PROTO_FIELD)));
}
 
Example 9
Source File: ConfigSource.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
private Builder(
    Message message,
    Message.Builder messageBuilder,
    Map<MessageKey, ImmutableMap<LocationKey, Location>> locations) {
  this.configMessage = message;
  this.configBuilder = messageBuilder;
  this.locations = locations;
}
 
Example 10
Source File: HeronClient.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param s the NIOLooper bind with this socket client
 * @param host the host of remote endpoint to communicate with
 * @param port the port of remote endpoint to communicate with
 */
public HeronClient(NIOLooper s, String host, int port, HeronSocketOptions options) {
  nioLooper = s;
  endpoint = new InetSocketAddress(host, port);
  socketOptions = options;

  isConnected = false;
  contextMap = new ConcurrentHashMap<REQID, Object>();
  responseMessageMap = new ConcurrentHashMap<REQID, Message.Builder>();
  messageMap = new ConcurrentHashMap<String, Message.Builder>();
}
 
Example 11
Source File: IncomingPacket.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
public void unpackMessage(Message.Builder builder) {
  int size = data.getInt();
  byte[] bytes = new byte[size];
  data.get(bytes);
  try {
    builder.mergeFrom(bytes);
  } catch (InvalidProtocolBufferException e) {
    LOG.log(Level.SEVERE, "InvalidProtocolBufferException: ", e);
  }
}
 
Example 12
Source File: ProtobufFormatter.java    From tajo with Apache License 2.0 4 votes vote down vote up
public void merge(final InputStream input,
		ExtensionRegistry extensionRegistry,
		final Message.Builder builder) throws IOException {
	merge(input, defaultCharset, extensionRegistry, builder);
}
 
Example 13
Source File: WellKnownTypeMarshaller.java    From curiostack with MIT License 4 votes vote down vote up
@Override
protected final void doMerge(JsonParser parser, int unused, Message.Builder messageBuilder)
    throws IOException {
  BytesValue.Builder b = (BytesValue.Builder) messageBuilder;
  b.setValue(ParseSupport.parseBytes(parser));
}
 
Example 14
Source File: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Optional<Message.Builder> getBuilder(Argument<T> type) {
    Class<? extends Message> clazz = (Class<? extends Message>) type.getType();
    return getMessageBuilder(clazz);
}
 
Example 15
Source File: HttpRpcProtocol.java    From brpc-java with Apache License 2.0 4 votes vote down vote up
public Object[] parseRequestParam(int protocolType, Object body, RpcMethodInfo rpcMethodInfo) {
        if (body == null) {
            return null;
        }

        Object[] args = new Object[rpcMethodInfo.getInputClasses().length];
        if (protocolType == Options.ProtocolType.PROTOCOL_HTTP_JSON_VALUE) {
            try {
                if (rpcMethodInfo instanceof ProtobufRpcMethodInfo) {
                    ProtobufRpcMethodInfo protobufRpcMethodInfo = (ProtobufRpcMethodInfo) rpcMethodInfo;
                    Message.Builder argBuilder = protobufRpcMethodInfo.getInputInstance().newBuilderForType();
//                    jsonPbConverter.merge((String) body, ExtensionRegistry.getEmptyRegistry(), argBuilder);
                    Pb2JsonUtils.json2Pb((String) body, argBuilder);
                    args[0] = argBuilder.build();
                } else {
                    if (rpcMethodInfo.getInputClasses().length == 1) {
                        args[0] = gson.fromJson((String) body, rpcMethodInfo.getInputClasses()[0]);
                    } else {
                        JsonArray jsonArray = (JsonArray) jsonParser.parse((String) body);
                        int jsonSize = jsonArray.size();
                        if (jsonSize != rpcMethodInfo.getInputClasses().length) {
                            LOG.warn("bad params num");
                            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, "bad params num");
                        }
                        for (int i = 0; i < jsonSize; i++) {
                            args[i] = gson.fromJson(jsonArray.get(i), rpcMethodInfo.getInputClasses()[i]);
                        }
                    }
                }
            } catch (Exception e) {
                LOG.error("decodeBody failed", e);
                throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, "decode body failed", e);
            }
        } else if (protocolType == Options.ProtocolType.PROTOCOL_HTTP_PROTOBUF_VALUE) {
            Object requestMessage = null;
            try {
                requestMessage = rpcMethodInfo.inputDecode((byte[]) body);
            } catch (Exception ex) {
                LOG.error("invoke protobuf method error, ex : ", ex);
                return null;
            }
            args[0] = requestMessage;
        } else {
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, "unknown protocol");
        }

        return args;

    }
 
Example 16
Source File: RRServer.java    From twister2 with Apache License 2.0 4 votes vote down vote up
public void registerRequestHandler(Message.Builder builder, MessageHandler handler) {
  requestHandlers.put(builder.getDescriptorForType().getFullName(), handler);
  messageBuilders.put(builder.getDescriptorForType().getFullName(), builder);
}
 
Example 17
Source File: ProtobufferCodec.java    From micronaut-grpc with Apache License 2.0 4 votes vote down vote up
private Optional<Message.Builder> createBuilder(Class<? extends Message> clazz) throws Exception {
    return Optional.of ((Message.Builder) getMethod(clazz).invoke(clazz));
}
 
Example 18
Source File: TrevniScanner.java    From incubator-tajo with Apache License 2.0 4 votes vote down vote up
@Override
public Tuple next() throws IOException {
  Tuple tuple = new VTuple(schema.size());

  if (!columns[0].hasNext()) {
    return null;
  }

  int tid; // column id of the original input schema
  for (int i = 0; i < projectionMap.length; i++) {
    tid = projectionMap[i];
    columns[i].startRow();
    DataType dataType = schema.getColumn(tid).getDataType();
    switch (dataType.getType()) {
      case BOOLEAN:
        tuple.put(tid,
            DatumFactory.createBool(((Integer)columns[i].nextValue()).byteValue()));
        break;
      case BIT:
        tuple.put(tid,
            DatumFactory.createBit(((Integer) columns[i].nextValue()).byteValue()));
        break;
      case CHAR:
        String str = (String) columns[i].nextValue();
        tuple.put(tid,
            DatumFactory.createChar(str));
        break;

      case INT2:
        tuple.put(tid,
            DatumFactory.createInt2(((Integer) columns[i].nextValue()).shortValue()));
        break;
      case INT4:
        tuple.put(tid,
            DatumFactory.createInt4((Integer) columns[i].nextValue()));
        break;

      case INT8:
        tuple.put(tid,
            DatumFactory.createInt8((Long) columns[i].nextValue()));
        break;

      case FLOAT4:
        tuple.put(tid,
            DatumFactory.createFloat4((Float) columns[i].nextValue()));
        break;

      case FLOAT8:
        tuple.put(tid,
            DatumFactory.createFloat8((Double) columns[i].nextValue()));
        break;

      case INET4:
        tuple.put(tid,
            DatumFactory.createInet4(((ByteBuffer) columns[i].nextValue()).array()));
        break;

      case TEXT:
        tuple.put(tid,
            DatumFactory.createText((String) columns[i].nextValue()));
        break;

      case PROTOBUF: {
        ProtobufDatumFactory factory = ProtobufDatumFactory.get(dataType.getCode());
        Message.Builder builder = factory.newBuilder();
        builder.mergeFrom(((ByteBuffer)columns[i].nextValue()).array());
        tuple.put(tid, factory.createDatum(builder));
        break;
      }

      case BLOB:
        tuple.put(tid,
            new BlobDatum(((ByteBuffer) columns[i].nextValue())));
        break;

      case NULL_TYPE:
        tuple.put(tid, NullDatum.get());
        break;

      default:
        throw new IOException("Unsupport data type");
    }
  }

  return tuple;
}
 
Example 19
Source File: Mapper.java    From protobuf-converter with MIT License 2 votes vote down vote up
/**
 * Maps data from domain field to Protobuf field.
 *
 * @param fieldResolver   Field resolver for which mapping is performed.
 * @param domain          Domain object that holds data.
 * @param protobufBuilder Builder for Protobuf dto that waiting for data mapping.
 * @param <T>             Type of Protobuf dto.
 * @return Result of the data mapping from domain object to Protobuf dto.
 * @throws MappingException throws when domain object field data access problems is occurred.
 */
<T extends Message.Builder> MappingResult mapToProtobufField(final FieldResolver fieldResolver,
		final Object domain, final T protobufBuilder) throws MappingException;
 
Example 20
Source File: ProtobufFormatter.java    From tajo with Apache License 2.0 2 votes vote down vote up
/**
 * Parse a text-format message from {@code input} and merge the contents
 * into {@code builder}.
 */
abstract public void merge(final InputStream input, Charset cs,
		ExtensionRegistry extensionRegistry,
		final Message.Builder builder) throws IOException;