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

The following examples show how to use com.google.protobuf.Message.Builder#build() . 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: MessageToMessage.java    From krpc with Apache License 2.0 6 votes vote down vote up
static public Message toMessage(Builder b,  Message src) {
    try {
        for (Descriptors.FieldDescriptor field : b.getDescriptorForType().getFields()) {
            String name = field.getName();
            Object value = getValue(src, name);
            if (value == null) continue;
            if (field.isMapField()) {
                objToMap(b, field, value);
            } else if (field.isRepeated()) {
                objToMessageObjRepeated(b, value, field);
            } else {
                objToMessageObj(b, value, field);
            }
        }

        return b.build();
    } catch(Exception e) {
        log.error("toMessage exception, e="+e.getMessage());
        return null;
    }
}
 
Example 2
Source File: MapToMessage.java    From krpc with Apache License 2.0 6 votes vote down vote up
static public Message toMessage(Builder b, Map<String, Object> params, Map<String, Object> ctx) {
    for (FieldDescriptor field : b.getDescriptorForType().getFields()) {
        String name = field.getName();
        Object value = getValue(params, ctx, name);
        if (value == null) continue;
        if (field.isMapField()) {
            objToMap(b, field, value);
        } else if (field.isRepeated()) {
            objToMessageObjRepeated(b, value, field);
        } else {
            if (value instanceof List) {
                value = ((List) value).get(0);
                if (value == null) continue;
            }
            objToMessageObj(b, value, field);
        }
    }

    return b.build();
}
 
Example 3
Source File: BeanToMessage.java    From krpc with Apache License 2.0 6 votes vote down vote up
static public Message toMessage(Builder b,  Object bean) {
    try {
        for (Descriptors.FieldDescriptor field : b.getDescriptorForType().getFields()) {
            String name = field.getName();
            Object value = getValue(bean, name);
            if (value == null) continue;
            if (field.isMapField()) {
                objToMap(b, field, value);
            } else if (field.isRepeated()) {
                objToMessageObjRepeated(b, value, field);
            } else {
                objToMessageObj(b, value, field);
            }
        }

        return b.build();
    } catch(Exception e) {
        log.error("toMessage exception, e="+e.getMessage());
        return null;
    }
}
 
Example 4
Source File: QueryResponseToProto.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Object buildMessage(Builder builder, Map<String, Object> fields) {
  if (fields == null) {
    return builder.build();
  }
  Descriptor descriptor = builder.getDescriptorForType();
  for (Map.Entry<String, Object> entry : fields.entrySet()) {
    if (entry.getValue() == null) {
      continue;
    }
    FieldDescriptor field = getField(descriptor, entry.getKey());
    if (entry.getValue() instanceof List<?>) {
      List<Object> values = (List<Object>) entry.getValue();
      for (Object value : values) {
        builder.addRepeatedField(field, buildValue(builder, field, value));
      }

    } else {
      builder.setField(field, buildValue(builder, field, entry.getValue()));
    }
  }
  return builder.build();
}
 
Example 5
Source File: VendorExtensionProtoConverter.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T extends Message> T convertJsonToProto(T prototype, String json, String extensionName) {
  try {
    Builder builder = prototype.newBuilderForType();
    JsonFormat.parser().merge(json, builder);
    return (T) builder.build();
  } catch (InvalidProtocolBufferException ex) {
    diagCollector.addDiag(
        Diag.error(
            new SimpleLocation(extensionName),
            "Extension %s cannot be converted into proto type %s. Details: %s",
            extensionName,
            prototype.getDescriptorForType().getFullName(),
            ex.getMessage()));
    return prototype;
  }
}
 
Example 6
Source File: JsonToMessage.java    From krpc with Apache License 2.0 5 votes vote down vote up
static public Message toMessage(Builder b,  String json) {
    try {
        JsonFormat.parser().merge(json, b);
        return b.build();
    } catch(Exception e) {
        log.error("toMessage exception, e="+e.getMessage());
        return null;
    }
}
 
Example 7
Source File: Server.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Decode the a protobuf from the given input stream 
 * @param builder - Builder of the protobuf to decode
 * @param dis - DataInputStream to read the protobuf
 * @return Message - decoded protobuf
 * @throws WrappedRpcServerException - deserialization failed
 */
@SuppressWarnings("unchecked")
private <T extends Message> T decodeProtobufFromStream(Builder builder,
    DataInputStream dis) throws WrappedRpcServerException {
  try {
    builder.mergeDelimitedFrom(dis);
    return (T)builder.build();
  } catch (Exception ioe) {
    Class<?> protoClass = builder.getDefaultInstanceForType().getClass();
    throw new WrappedRpcServerException(
        RpcErrorCodeProto.FATAL_DESERIALIZING_REQUEST,
        "Error decoding " + protoClass.getSimpleName() + ": "+ ioe);
  }
}
 
Example 8
Source File: Server.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Decode the a protobuf from the given input stream 
 * @param builder - Builder of the protobuf to decode
 * @param dis - DataInputStream to read the protobuf
 * @return Message - decoded protobuf
 * @throws WrappedRpcServerException - deserialization failed
 */
@SuppressWarnings("unchecked")
private <T extends Message> T decodeProtobufFromStream(Builder builder,
    DataInputStream dis) throws WrappedRpcServerException {
  try {
    builder.mergeDelimitedFrom(dis);
    return (T)builder.build();
  } catch (Exception ioe) {
    Class<?> protoClass = builder.getDefaultInstanceForType().getClass();
    throw new WrappedRpcServerException(
        RpcErrorCodeProto.FATAL_DESERIALIZING_REQUEST,
        "Error decoding " + protoClass.getSimpleName() + ": "+ ioe);
  }
}
 
Example 9
Source File: RandomProtobufGenerator.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a random protocol buffer, filling in all required fields but
 * with a p chance of not setting an optional field and p chance of having
 * an empty repeated field.
 */
@SuppressWarnings("unchecked")
public E generate(double p) {
  Builder builder = instance.newBuilderForType();
  Descriptor descriptor = instance.getDescriptorForType();
  for (FieldDescriptor field : descriptor.getFields()) {
    if (!field.isRequired() && random.nextDouble() < p) {
      continue;
    }
    builder.setField(field, getRandomValue(field, p));
  }
  return (E) builder.build();
}
 
Example 10
Source File: ProtobufCreator.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T extends Message> T create(Class<T> messageType, ExtensionRegistryWrapper extensionRegistry) {
  Builder builder = newBuilder(messageType);
  partiallyBuilt.put(messageType, builder);
  populate(builder, extensionRegistry);
  return (T) builder.build();
}
 
Example 11
Source File: RandomProtobufGenerator.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a random protocol buffer, filling in all required fields but
 * with a p chance of not setting an optional field and p chance of having
 * an empty repeated field.
 */
@SuppressWarnings("unchecked")
public E generate(double p) {
  Builder builder = instance.newBuilderForType();
  Descriptor descriptor = instance.getDescriptorForType();
  for (FieldDescriptor field : descriptor.getFields()) {
    if (!field.isRequired() && random.nextDouble() < p) {
      continue;
    }
    builder.setField(field, getRandomValue(field, p));
  }
  return (E) builder.build();
}
 
Example 12
Source File: MessageToMessage.java    From krpc with Apache License 2.0 4 votes vote down vote up
static Object objToMessageObjInner(Builder b, Object value, Descriptors.FieldDescriptor field, boolean isRepeated) {

        switch (field.getType()) {
            case INT32:
            case SINT32:
            case SFIXED32:
                return TypeSafe.anyToInt(value);

            case INT64:
            case SINT64:
            case SFIXED64:
                if( value instanceof Date)
                    return ((Date)value).getTime();
                return TypeSafe.anyToLong(value);

            case BOOL:
                return TypeSafe.anyToBool(value);

            case FLOAT:
                return TypeSafe.anyToFloat(value);

            case DOUBLE:
                return TypeSafe.anyToDouble(value);

            case UINT32:
            case FIXED32:
                return (int) (TypeSafe.anyToLong(value) & 0x00000000FFFFFFFFL);

            case UINT64:
            case FIXED64:
                BigInteger bi = new BigInteger(value.toString());
                return bi.longValue();

            case STRING:
                if( value instanceof Date)
                    return formatDate((Date)value);
                return TypeSafe.anyToString(value);

            case BYTES: {
                if (value instanceof ByteString) {
                    return value;
                }
                if (value instanceof String) {
                    byte[] bb = getBytes((String) value);
                    if (bb == null) return null;
                    return ByteString.copyFrom(bb);
                }
                if (value instanceof byte[]) {
                    return ByteString.copyFrom((byte[]) value);
                }
            }

            return null;

            case ENUM:
                Descriptors.EnumDescriptor ed = field.getEnumType();
                Descriptors.EnumValueDescriptor evd = ed.findValueByName(value.toString());
                if (evd == null) {
                    evd = ed.findValueByNumber(TypeSafe.anyToInt(value));
                }
                if (evd == null) return null;
                return evd;

            case MESSAGE:

                Message src = (Message)value;

                Builder b2 = isRepeated ?
                        getRepeatedFieldBuilder(b, field.getName()) :
                        getFieldBuilder(b, field);

                for (Descriptors.FieldDescriptor subfield : b2.getDescriptorForType().getFields()) {
                    String subName = subfield.getName();
                    Object subValue = getValue(src, subName);
                    if (subValue == null) continue;
                    if (subfield.isRepeated()) {
                        objToMessageObjRepeated(b2, subValue, subfield);
                    } else {
                        objToMessageObj(b2, subValue, subfield);
                    }
                }

                return isRepeated ? null : b2.build();

            default:
                return null;
        }
    }
 
Example 13
Source File: MapToMessage.java    From krpc with Apache License 2.0 4 votes vote down vote up
static Object objToMessageObjInner(Builder b, Object value, FieldDescriptor field, boolean isRepeated) {

        switch (field.getType()) {
            case INT32:
            case SINT32:
            case SFIXED32:
                return TypeSafe.anyToInt(value);

            case INT64:
            case SINT64:
            case SFIXED64:
                if( value instanceof Date)
                    return ((Date)value).getTime();
                return TypeSafe.anyToLong(value);

            case BOOL:
                return TypeSafe.anyToBool(value);

            case FLOAT:
                return TypeSafe.anyToFloat(value);

            case DOUBLE:
                return TypeSafe.anyToDouble(value);

            case UINT32:
            case FIXED32:
                return (int) (TypeSafe.anyToLong(value) & 0x00000000FFFFFFFFL);

            case UINT64:
            case FIXED64:
                BigInteger bi = new BigInteger(value.toString());
                return bi.longValue();

            case STRING:
                if( value instanceof Date)
                    return formatDate((Date)value);
                return TypeSafe.anyToString(value);

            case BYTES: {
                    if (value instanceof ByteString) {
                        return value;
                    }
                    if (value instanceof String) {
                        byte[] bb = getBytes((String) value);
                        if (bb == null) return null;
                        return ByteString.copyFrom(bb);
                    }
                    if (value instanceof byte[]) {
                        return ByteString.copyFrom((byte[]) value);
                    }

                    return null;
                }

            case ENUM: {
                    EnumDescriptor ed = field.getEnumType();
                    EnumValueDescriptor evd = ed.findValueByName(value.toString());
                    if (evd == null) {
                        evd = ed.findValueByNumber(TypeSafe.anyToInt(value));
                    }
                    if (evd == null) return null;
                    return evd;
                }

            case MESSAGE:

                Map<String, Object> map = TypeSafe.anyToMap(value);
                if (map == null) {
                    if( value instanceof MapConvertable) {
                        map = ((MapConvertable)value).toMap();
                    }
                    if( map == null ) {
                        return null;
                    }
                }

                Builder b2 = isRepeated ?
                        getRepeatedFieldBuilder(b, field.getName()) :
                                getFieldBuilder(b, field);

                for (FieldDescriptor subfield : b2.getDescriptorForType().getFields()) {
                    String subName = subfield.getName();
                    Object subValue = getValue(map, null, subName);
                    if (subValue == null) continue;
                    if (subfield.isRepeated()) {
                        objToMessageObjRepeated(b2, subValue, subfield);
                    } else {
                        objToMessageObj(b2, subValue, subfield);
                    }
                }

                return isRepeated ? null : b2.build();

            default:
                return null;
        }
    }
 
Example 14
Source File: BeanToMessage.java    From krpc with Apache License 2.0 4 votes vote down vote up
static Object objToMessageObjInner(Builder b, Object value, Descriptors.FieldDescriptor field, boolean isRepeated) {

        switch (field.getType()) {
            case INT32:
            case SINT32:
            case SFIXED32:
                return TypeSafe.anyToInt(value);

            case INT64:
            case SINT64:
            case SFIXED64:
                if( value instanceof Date)
                    return ((Date)value).getTime();
                return TypeSafe.anyToLong(value);

            case BOOL:
                return TypeSafe.anyToBool(value);

            case FLOAT:
                return TypeSafe.anyToFloat(value);

            case DOUBLE:
                return TypeSafe.anyToDouble(value);

            case UINT32:
            case FIXED32:
                return (int) (TypeSafe.anyToLong(value) & 0x00000000FFFFFFFFL);

            case UINT64:
            case FIXED64:
                BigInteger bi = new BigInteger(value.toString());
                return bi.longValue();

            case STRING:
                if( value instanceof Date)
                    return formatDate((Date)value);
                return TypeSafe.anyToString(value);

            case BYTES: {
                if (value instanceof ByteString) {
                    return value;
                }
                if (value instanceof String) {
                    byte[] bb = getBytes((String) value);
                    if (bb == null) return null;
                    return ByteString.copyFrom(bb);
                }
                if (value instanceof byte[]) {
                    return ByteString.copyFrom((byte[]) value);
                }
            }

            return null;

            case ENUM:
                Descriptors.EnumDescriptor ed = field.getEnumType();
                Descriptors.EnumValueDescriptor evd = ed.findValueByName(value.toString());
                if (evd == null) {
                    evd = ed.findValueByNumber(TypeSafe.anyToInt(value));
                }
                if (evd == null) return null;
                return evd;

            case MESSAGE:

                Object bean = value;

                Builder b2 = isRepeated ?
                        getRepeatedFieldBuilder(b, field.getName()) :
                        getFieldBuilder(b, field);

                for (Descriptors.FieldDescriptor subfield : b2.getDescriptorForType().getFields()) {
                    String subName = subfield.getName();
                    Object subValue = getValue(bean, subName);
                    if (subValue == null) continue;
                    if (subfield.isRepeated()) {
                        objToMessageObjRepeated(b2, subValue, subfield);
                    } else {
                        objToMessageObj(b2, subValue, subfield);
                    }
                }

                return isRepeated ? null : b2.build();

            default:
                return null;
        }
    }