Java 类com.google.protobuf.Descriptors.FieldDescriptor.JavaType 实例源码

项目:curiostack    文件:ProtoFieldInfo.java   
/**
 * Returns the method to get the value for the field within its message. The message must already
 * be on the execution stack. For map fields, this will be the method that returns a {@link
 * java.util.Map} and for repeated fields it will be the method that returns a {@link List}.
 */
Method getValueMethod() {
  StringBuilder methodName = new StringBuilder().append("get").append(camelCaseName);
  if (valueJavaType() == JavaType.ENUM) {
    methodName.append("Value");
  }
  if (isMapField()) {
    methodName.append("Map");
  } else if (field.isRepeated()) {
    methodName.append("List");
  }
  try {
    return containingPrototype.getClass().getDeclaredMethod(methodName.toString());
  } catch (NoSuchMethodException e) {
    throw new IllegalStateException("Could not find generated getter method.", e);
  }
}
项目:protobuf-el    文件:BuilderELResolver.java   
@Override
public Object getValue(final ELContext context, final Object base, final Object property) {
  if (context == null) {
    throw new NullPointerException();
  }

  if ((property != null) && resolveType(base)) {
    context.setPropertyResolved(base, property);
    final Message.Builder builder = (Message.Builder) base;
    final FieldDescriptor field = getPropertyFieldDescriptor(builder, property);

    if (field.isRepeated()) {
      return getBuilderForRepeatedField(builder, field);
    } else {
      if (field.getJavaType() == JavaType.MESSAGE) {
        return builder.getFieldBuilder(field);
      } else {
        return builder.getField(field);
      }
    }
  }

  return null;
}
项目:protobuf-el    文件:ProtoLists.java   
@SuppressWarnings("unchecked")
public static final IRepeatedFieldMessageBuilder getBuilderForRepeatedChild(
    final Message.Builder builder, final FieldDescriptor field) {
  if (!field.isRepeated()) {
    throw new IllegalArgumentException("the field must be repeated");
  } else if (field.getJavaType() != JavaType.MESSAGE) {
    throw new IllegalArgumentException("the field must be of Message type");
  } else if (builder.getDescriptorForType() != field.getContainingType()) {
    throw new IllegalArgumentException("the field doen't belong to this type");
  }

  if (builder instanceof GeneratedMessage.Builder) {
    final GeneratedMessage.Builder<?> generatedBuilder = (GeneratedMessage.Builder<?>) builder;
    return getGeneratedRepeatedFieldBuilder(generatedBuilder, field, generatedBuilder.getClass());
  } else if (builder instanceof IBuilder2) {
    return new DynamicRepeatedFieldMessageBuilder((IBuilder2) builder, field);
  } else {
    throw new IllegalArgumentException("builder is not of a supported Builder type");
  }
}
项目:protobuf-el    文件:Misc.java   
@SuppressWarnings({"null", "unchecked"})
private void addField(final Message.Builder builder, final FieldDescriptor field,
    final Object value, final Replacer replacer,
    final LinkedList<Entry<FieldDescriptor, MessageOrBuilder>> path) {

  if (field.getJavaType() == JavaType.MESSAGE) {
    if (field.isRepeated()) {
      for (final Message message : (List<Message>) value) {
        builder.addRepeatedField(field, getMessage(field, message, replacer, path));
      }
    } else {
      builder.setField(field, getMessage(field, (Message) value, replacer, path));
    }
  } else {
    builder.setField(field, getValue(field, value, replacer, path));
  }
}
项目:protobuf-el    文件:AbstractMessageUtils.java   
@SuppressWarnings({"null", "unchecked"})
private boolean addField(final Message.Builder protoBuilder, final FieldDescriptor field,
    final Object value, final Iterable<Pattern> skipPatterns) {
  if (isSkip(field.getFullName(), skipPatterns)) {
    return false;
  }

  if (field.getJavaType() == JavaType.MESSAGE) {
    if (field.isRepeated()) {
      for (final Message message : (List<Message>) value) {
        protoBuilder.addRepeatedField(field, getMessage(message, skipPatterns));
      }
    } else {
      protoBuilder.setField(field, getMessage((Message) value, skipPatterns));
    }
  } else {
    protoBuilder.setField(field, value);
  }

  return true;
}
项目:protobuf-el    文件:MockDescriptorCache.java   
public FieldDescriptor putField(String descriptorShortName, String fieldShortName,
    int index, boolean isRepeated, JavaType type, String fieldMessageTypeName) {
  String descriptorFullName = getFullName(descriptorShortName);
  MockDescriptorEntry fieldMap = descriptorMap.get(descriptorFullName);
  FieldDescriptor field = null;

  if (fieldMap == null) {
    fieldMap = new MockDescriptorEntry(createMockDescriptor(descriptorShortName));
    descriptorMap.put(descriptorFullName, fieldMap);
  } else {
    field = fieldMap.getField(fieldShortName);
  }

  if (field == null) {
    field = createMockField(fieldShortName, index, isRepeated, type, 
        fieldMap.getDescriptor(), fieldMessageTypeName);
    fieldMap.putField(fieldShortName, field);
  }

  return field;
}
项目:parquet-mr    文件:ProtoSchemaConverter.java   
private <T> Builder<? extends Builder<?, GroupBuilder<T>>, GroupBuilder<T>> addField(Descriptors.FieldDescriptor descriptor, GroupBuilder<T> builder) {
  Type.Repetition repetition = getRepetition(descriptor);
  JavaType javaType = descriptor.getJavaType();
  switch (javaType) {
    case BOOLEAN: return builder.primitive(BOOLEAN, repetition);
    case INT: return builder.primitive(INT32, repetition);
    case LONG: return builder.primitive(INT64, repetition);
    case FLOAT: return builder.primitive(FLOAT, repetition);
    case DOUBLE: return builder.primitive(DOUBLE, repetition);
    case BYTE_STRING: return builder.primitive(BINARY, repetition);
    case STRING: return builder.primitive(BINARY, repetition).as(UTF8);
    case MESSAGE: {
      GroupBuilder<GroupBuilder<T>> group = builder.group(repetition);
      convertFields(group, descriptor.getMessageType().getFields());
      return group;
    }
    case ENUM: return builder.primitive(BINARY, repetition).as(ENUM);
    default:
      throw new UnsupportedOperationException("Cannot convert Protocol Buffer: unknown type " + javaType);
  }
}
项目:BIMserver    文件:ProtocolBuffersConverter.java   
protected Class<?> getJavaType(FieldDescriptor fieldDescriptor) {
    if (fieldDescriptor.getJavaType() == JavaType.BOOLEAN) {
        return Boolean.class;
    } else if (fieldDescriptor.getJavaType() == JavaType.BYTE_STRING) {
        return DataHandler.class;
    } else if (fieldDescriptor.getJavaType() == JavaType.DOUBLE) {
        return Double.class;
    } else if (fieldDescriptor.getJavaType() == JavaType.FLOAT) {
        return Float.class;
    } else if (fieldDescriptor.getJavaType() == JavaType.INT) {
        return Integer.class;
    } else if (fieldDescriptor.getJavaType() == JavaType.LONG) {
        return Long.class;
    } else if (fieldDescriptor.getJavaType() == JavaType.STRING) {
        return String.class;
    } else if (fieldDescriptor.getJavaType() == JavaType.ENUM) {
        try {
            return Class.forName("org.bimserver.interfaces.objects." + fieldDescriptor.getEnumType().getName());
        } catch (ClassNotFoundException e) {
            LOGGER.error("", e);
        }
    }
    return null;
}
项目:BIMserver    文件:ProtocolBuffersConverter.java   
protected Class<?> getJavaPrimitiveType(FieldDescriptor fieldDescriptor) {
    if (fieldDescriptor.getJavaType() == JavaType.BOOLEAN) {
        return boolean.class;
    } else if (fieldDescriptor.getJavaType() == JavaType.BYTE_STRING) {
        return DataHandler.class;
    } else if (fieldDescriptor.getJavaType() == JavaType.DOUBLE) {
        return double.class;
    } else if (fieldDescriptor.getJavaType() == JavaType.FLOAT) {
        return float.class;
    } else if (fieldDescriptor.getJavaType() == JavaType.INT) {
        return int.class;
    } else if (fieldDescriptor.getJavaType() == JavaType.LONG) {
        return long.class;
    } else if (fieldDescriptor.getJavaType() == JavaType.STRING) {
        return String.class;
    } else if (fieldDescriptor.getJavaType() == JavaType.ENUM) {
        try {
            return Class.forName("org.bimserver.interfaces.objects." + fieldDescriptor.getEnumType().getName());
        } catch (ClassNotFoundException e) {
            LOGGER.error("", e);
        }
    }
    return null;
}
项目:shapeshifter    文件:NamedSchema.java   
/**
 * Populates a JSON schema for a repeated primitive proto field.
 * 
 * @param field the field being considered
 * @param property the JSON schema being built
 */
private void populateRepeatedPrimitiveSchema(FieldDescriptor field,
        JsonSchema.Builder property) {
    property.setType(JsonType.ARRAY);
    JsonSchema.Builder itemsSchema = JsonSchema.newBuilder();

    if (treatLongsAsStrings && field.getJavaType().equals(JavaType.LONG)
            && !transforms.containsKey(field.getName())) {
        itemsSchema.setType(JsonType.STRING);
        if (field.getType().equals(Type.UINT64) || field.getType().equals(Type.FIXED64)) {
            itemsSchema.setFormat(UINT64_STRING_FORMAT);
        } else {
            itemsSchema.setFormat(INT64_STRING_FORMAT);
        }
    } else {
        itemsSchema.setType(getReifiedFieldType(field));
    }
    property.setItems(itemsSchema);

    if (field.getType().equals(Type.ENUM)) {
        for (EnumValueDescriptor enumValue : field.getEnumType().getValues()) {
            property.addEnum(PROTO_ENUM_CASE_FORMAT.to(
                    enumCaseFormat, enumValue.getName()));
        }
    }
}
项目:curiostack    文件:ProtoFieldInfo.java   
/**
 * Return the Java {@link Class} that corresponds to the value of this field. Generally used for
 * method resolution and casting generics.
 */
Class<?> javaClass() {
  if (isMapField() && valueJavaType() == JavaType.MESSAGE) {
    Message mapEntry = containingPrototype.newBuilderForType().newBuilderForField(field).build();
    return mapEntry.getField(mapEntry.getDescriptorForType().findFieldByName("value")).getClass();
  }
  switch (valueJavaType()) {
    case INT:
      return int.class;
    case LONG:
      return long.class;
    case FLOAT:
      return float.class;
    case DOUBLE:
      return double.class;
    case BOOLEAN:
      return boolean.class;
    case STRING:
      return String.class;
    case BYTE_STRING:
      return ByteString.class;
    case ENUM:
      return int.class;
    case MESSAGE:
      return containingPrototype
          .newBuilderForType()
          .newBuilderForField(valueField().descriptor())
          .build()
          .getClass();
    default:
      throw new IllegalArgumentException("Unknown field type: " + valueJavaType());
  }
}
项目:curiostack    文件:DoParse.java   
/**
 * Returns the {@link StackManipulation} for setting the value of a field. This will be all the
 * elements for a repeated field.
 *
 * @param info description of the field to set.
 * @param beforeReadField jump target for before reading a field, used once this field is
 *     completed being set.
 * @param locals the method local variables
 * @param fieldsByName the instance fields
 */
private StackManipulation setFieldValue(
    ProtoFieldInfo info,
    Label beforeReadField,
    LocalVariables<LocalVariable> locals,
    Map<String, FieldDescription> fieldsByName) {
  if (info.isMapField()) {
    return setMapFieldValue(info, beforeReadField, locals, fieldsByName);
  } else {
    final StackManipulation setConcreteValue = invoke(info.setValueMethod());
    final StackManipulation setSingleValue;
    if (info.valueJavaType() == JavaType.MESSAGE) {
      setSingleValue =
          new StackManipulation.Compound(
              TypeCasting.to(new ForLoadedType(info.javaClass())), setConcreteValue);
    } else {
      setSingleValue = setConcreteValue;
    }
    if (info.descriptor().isRepeated()) {
      return setRepeatedFieldValue(info, beforeReadField, locals, fieldsByName, setSingleValue);
    } else {
      // Set a singular value, e.g.,
      // builder.setFoo(readValue());
      return new StackManipulation.Compound(
          locals.load(LocalVariable.builder),
          locals.load(LocalVariable.parser),
          readValue(info, fieldsByName, locals),
          setSingleValue,
          Removal.SINGLE,
          new Goto(beforeReadField));
    }
  }
}
项目:curiostack    文件:DoParse.java   
/**
 * Returns the {@link StackManipulation} for setting the value of a map field.
 *
 * <p>Roughly equivalent to:
 *
 * <pre>{@code
 * ParseSupport.parseObjectStart(parser);
 * while (!ParseSupport.checkObjectEnd(parser.currentToken())) {
 *   builder.putFoo(readKey(), readValue());
 * }
 * }</pre>
 */
private StackManipulation setMapFieldValue(
    ProtoFieldInfo info,
    Label beforeReadField,
    LocalVariables<LocalVariable> locals,
    Map<String, FieldDescription> fieldsByName) {
  final StackManipulation setConcreteValue = invoke(info.setValueMethod());
  final StackManipulation setMapEntry;
  if (info.valueJavaType() == JavaType.MESSAGE) {
    setMapEntry =
        new StackManipulation.Compound(
            TypeCasting.to(new ForLoadedType(info.javaClass())), setConcreteValue);
  } else {
    setMapEntry = setConcreteValue;
  }
  Label mapStart = new Label();
  return new StackManipulation.Compound(
      locals.load(LocalVariable.parser),
      ParseSupport_parseObjectStart,
      new SetJumpTargetLabel(mapStart),
      locals.load(LocalVariable.parser),
      Parser_currentToken,
      ParseSupport_checkObjectEnd,
      new IfTrue(beforeReadField),
      locals.load(LocalVariable.builder),
      locals.load(LocalVariable.parser),
      readValue(info.mapKeyField(), fieldsByName, locals),
      locals.load(LocalVariable.parser),
      Parser_nextToken,
      Removal.SINGLE,
      locals.load(LocalVariable.parser),
      readValue(info, fieldsByName, locals),
      setMapEntry,
      Removal.SINGLE,
      locals.load(LocalVariable.parser),
      Parser_nextToken,
      Removal.SINGLE,
      new Goto(mapStart));
}
项目:curiostack    文件:DoParse.java   
/**
 * Determines whether we skip processing of the field if it is null. We usually skip null values
 * in the JSON to treat them as default, but must actually process the null for {@link Value} and
 * {@link NullValue} because it means their value must be set.
 */
private boolean mustSkipNull(FieldDescriptor field) {
  if (field.isRepeated()) {
    return true;
  }
  if (field.getJavaType() == JavaType.MESSAGE
      && field.getMessageType() == Value.getDescriptor()) {
    return false;
  }
  if (field.getJavaType() == JavaType.ENUM && field.getEnumType() == NullValue.getDescriptor()) {
    return false;
  }
  return true;
}
项目:Wiab.pro    文件:Message.java   
/**
 * Collects messages referred to by a message and its nested messages.
 *
 * @return {@code referenced}
 */
private static Collection<Descriptor> collectMessages(
    Descriptor message, Collection<Descriptor> referenced) {
  for (FieldDescriptor fd : message.getFields()) {
    if (fd.getJavaType() == JavaType.MESSAGE) {
      referenced.add(fd.getMessageType());
    }
  }
  for (Descriptor nd : message.getNestedTypes()) {
    collectMessages(nd, referenced);
  }
  return referenced;
}
项目:Wiab.pro    文件:Message.java   
/**
 * Collects enums referred to by a message and its nested messages.
 *
 * @return {@code referenced}
 */
private static Collection<EnumDescriptor> collectEnums(
    Descriptor d, Collection<EnumDescriptor> referenced) {
  for (FieldDescriptor fd : d.getFields()) {
    if (fd.getJavaType() == JavaType.ENUM) {
      referenced.add(fd.getEnumType());
    }
  }
  for (Descriptor nd : d.getNestedTypes()) {
    collectEnums(nd, referenced);
  }
  return referenced;
}
项目:core-java    文件:Sample.java   
/**
 * Generates a non-default value for the given message field.
 *
 * <p>All the protobuf types are supported including nested {@link Message}s and
 * the {@code enum}s.
 *
 * @param field {@link FieldDescriptor} to take the type info from
 * @return a non-default generated value of type of the given field
 */
@SuppressWarnings("OverlyComplexMethod")
private static Object valueFor(FieldDescriptor field) {
    final Type type = field.getType();
    final JavaType javaType = type.getJavaType();
    final Random random = new SecureRandom();
    switch (javaType) {
        case INT:
            return random.nextInt();
        case LONG:
            return random.nextLong();
        case FLOAT:
            return random.nextFloat();
        case DOUBLE:
            return random.nextDouble();
        case BOOLEAN:
            return random.nextBoolean();
        case STRING:
            final byte[] bytes = new byte[8];
            random.nextBytes(bytes);
            return new String(bytes);
        case BYTE_STRING:
            final byte[] bytesPrimitive = new byte[8];
            random.nextBytes(bytesPrimitive);
            return ByteString.copyFrom(bytesPrimitive);
        case ENUM:
            return enumValueFor(field, random);
        case MESSAGE:
            return messageValueFor(field);
        default:
            throw new IllegalArgumentException(format("Field type %s is not supported.", type));
    }
}
项目:louie    文件:PBUtils.java   
/**
 * Checks that all possible fields for this message are set.
 * If a field is of String type, it will also ensure it is != ""
 *
 * This method will throw an exception if a field is missing, else does nothing.
 *
 * @param message the message object to check
 * @param errorHeader an optional prefix to the exception string
 * @param excludes a list of excluded field names
 * @throws Exception
 */
static public void ensureAllFields(MessageOrBuilder message, String errorHeader, Set<String> excludes) throws Exception {
    for (FieldDescriptor f : message.getDescriptorForType().getFields()) {
        if ((!message.hasField(f) || 
                (f.getJavaType().equals(JavaType.STRING) && message.getField(f).equals("")) ) 
            && !excludes.contains(f.getName()) ) {
                if (errorHeader!=null && !errorHeader.equals("")) {
                    errorHeader+=" ";
                }
                throw new Exception(errorHeader+"Missing field: "+f.getName());
        }
    }
}
项目:protobuf-el    文件:ProtoLists.java   
public static final IRepeatedFieldValueBuilder<?> getBuilderForRepeatedField(
    final Message.Builder builder, final FieldDescriptor field) {
  if (field.getJavaType() == JavaType.MESSAGE) {
    return getBuilderForRepeatedChild(builder, field);
  } else {
    return getBuilderForRepeatedAttribute(builder, field);
  }
}
项目:protobuf-el    文件:ProtoLists.java   
public static final IRepeatedFieldValueBuilder<Object> getBuilderForRepeatedAttribute(
    final Message.Builder builder, final FieldDescriptor field) {
  if (!field.isRepeated()) {
    throw new IllegalArgumentException("the field must be repeated");
  } else if (builder.getDescriptorForType() != field.getContainingType()) {
    throw new IllegalArgumentException("the field doen't belong to this type");
  }
  if (field.getJavaType() == JavaType.MESSAGE) {
    throw new IllegalArgumentException("the field must be of a non-Message type");
  }

  return new RepeatedFieldValueBuilder<Message.Builder, Object>(builder, field);
}
项目:protobuf-el    文件:ExtensionRegistries.java   
/**
 * Adds extension to the registry, making a default DynamicMessage if its type is a Message.
 */
public static ExtensionRegistry addToRegistry(final FieldDescriptor extension,
    final ExtensionRegistry registry) {
  if (extension.getJavaType() == JavaType.MESSAGE) {
    registry.add(extension, DynamicMessage.getDefaultInstance(extension.getMessageType()));
  } else {
    registry.add(extension);
  }

  return registry;
}
项目:protobuf-el    文件:DynamicMessage.java   
private void maybeForceBuilderInitialization() {
  if (alwaysUseFieldBuilders) {
    for (final FieldDescriptor field : builder.getDescriptorForType().getFields()) {
      if (field.getJavaType() == JavaType.MESSAGE) {
        if (field.isRepeated()) {
          getRepeatedFieldBuilder(field, true);
        } else {
          getSingleFieldBuilder(field, true);
        }
      }
    }
  }
}
项目:protobuf-el    文件:DynamicMessage.java   
@Override
public Builder newBuilderForField(final FieldDescriptor field) {
  verifyContainingType(field);

  if (field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) {
    throw new IllegalArgumentException(
        "newBuilderForField is only valid for fields with message type.");
  }

  return create(field.getMessageType());
}
项目:protobuf-el    文件:DynamicMessage.java   
@SuppressWarnings("unchecked")
private <T> T getSingleFieldValue(final FieldDescriptor field) {
  if (builder.hasField(field)) {
    return (T) builder.getField(field);
  }

  if (field.getJavaType() == JavaType.MESSAGE) {
    return (T) DynamicMessage.getDefaultInstance(field.getMessageType());
  } else {
    return (T) field.getDefaultValue();
  }
}
项目:protobuf-el    文件:DynamicMessage.java   
private Object getFieldOrDefault(final FieldDescriptor field) {
  if (field.isRepeated()) {
    if (builder.getRepeatedFieldCount(field) == 0) {
      return Collections.emptyList();
    }
  } else if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE
      && !builder.hasField(field)) {
    return getDefaultInstance(field.getMessageType());
  }

  return builder.getField(field);
}
项目:protobuf-el    文件:MessageAdapter.java   
public static <T> EnumValueDescriptor getEnumValue(final FieldDescriptor key, final T value) {
  MessageAdapter.verifyArgument(key.getJavaType() == JavaType.ENUM, "Not enum type!");

  if (value instanceof EnumValueDescriptor) {
    return getEnumValue(key, (EnumValueDescriptor) value);
  } else if (value instanceof ProtocolMessageEnum) {
    return getEnumValue(key, (ProtocolMessageEnum) value);
  } else if (value instanceof String) {
    return getEnumValue(key, (String) value);
  } else if (value instanceof Integer) {
    return getEnumValue(key, (Integer) value);
  } else {
    throw new IllegalArgumentException("value is not of the allowed type");
  }
}
项目:protobuf-el    文件:ProtoMatchersTest.java   
private Message createMockMessage(final boolean isMapImmutable, final int depth,
    final Collection<?> testCollection, final boolean... deepRepeatedPattern) {
  final Message mocked = mock(Message.class);
  final SortedMap<FieldDescriptor, Object> map = new TreeMap<FieldDescriptor, Object>(new Comparator<FieldDescriptor>() {
    @Override
    public int compare(FieldDescriptor o1, FieldDescriptor o2) {
      return Integer.compare(o1.getNumber(), o2.getNumber());
    }
  });
  map.put(getMockFieldDescriptor(1, false, JavaType.STRING), "immutable string");
  map.put(getMockFieldDescriptor(2, true, JavaType.STRING),
      Collections.unmodifiableList(Arrays.asList("one", "two")));

  if (depth == 0) {
    map.put(getMockFieldDescriptor(3, true, JavaType.INT), testCollection);
  } else {
    final Message child = createMockMessage(true, depth - 1, testCollection, 
        deepRepeatedPattern);
    boolean isRepeated = deepRepeatedPattern.length < depth 
        ? false 
            : deepRepeatedPattern[deepRepeatedPattern.length - depth];
    map.put(getMockFieldDescriptor(3, isRepeated, JavaType.MESSAGE),
        (isRepeated ? Collections.singletonList(child) : child));
  }

  given(mocked.getAllFields())
      .willReturn(isMapImmutable ? Collections.unmodifiableSortedMap(map) : map);
  return mocked;
}
项目:closure-templates    文件:ProtoUtils.java   
/**
 * Returns whether or not we should check for presence to emulate jspb nullability semantics in
 * server side soy.
 */
static boolean shouldCheckFieldPresenceToEmulateJspbNullability(FieldDescriptor desc) {
  boolean hasBrokenSemantics = false;
  if (desc.hasDefaultValue() || desc.isRepeated()) {
    return false;
  } else if (desc.getFile().getSyntax() == Syntax.PROTO3 || !hasBrokenSemantics) {
    // in proto3 or proto2 with non-broken semantics we only need to check for presence for
    // message typed fields.
    return desc.getJavaType() == JavaType.MESSAGE;
  } else {
    return true;
  }
}
项目:incubator-wave    文件:Message.java   
/**
 * Collects messages referred to by a message and its nested messages.
 *
 * @return {@code referenced}
 */
private static Collection<Descriptor> collectMessages(
    Descriptor message, Collection<Descriptor> referenced) {
  for (FieldDescriptor fd : message.getFields()) {
    if (fd.getJavaType() == JavaType.MESSAGE) {
      referenced.add(fd.getMessageType());
    }
  }
  for (Descriptor nd : message.getNestedTypes()) {
    collectMessages(nd, referenced);
  }
  return referenced;
}
项目:incubator-wave    文件:Message.java   
/**
 * Collects enums referred to by a message and its nested messages.
 *
 * @return {@code referenced}
 */
private static Collection<EnumDescriptor> collectEnums(
    Descriptor d, Collection<EnumDescriptor> referenced) {
  for (FieldDescriptor fd : d.getFields()) {
    if (fd.getJavaType() == JavaType.ENUM) {
      referenced.add(fd.getEnumType());
    }
  }
  for (Descriptor nd : d.getNestedTypes()) {
    collectEnums(nd, referenced);
  }
  return referenced;
}
项目:protobuf-transformer    文件:Transformer.java   
protected Object javaValueToMessageValue(Object value, Descriptors.FieldDescriptor fieldDescriptor){
    JavaType type=fieldDescriptor.getJavaType();
    if(type.equals(JavaType.BOOLEAN)){
        return value;
    }else if(type.equals(JavaType.INT) ||type.equals(JavaType.LONG)){
        if(value instanceof BigInteger){
            if(type.equals(JavaType.INT)){
                return ((BigInteger) value).intValue();
            }else{
                return ((BigInteger) value).longValue();
            }
        }
        return value;
    }else if(type.equals(JavaType.FLOAT) || type.equals(JavaType.DOUBLE)){
        if(value instanceof BigDecimal){
            if(type.equals(JavaType.FLOAT)){
                return ((BigDecimal) value).floatValue();
            }else{
                return ((BigDecimal) value).doubleValue();
            }
        }
        return value;
    }else if(type.equals(JavaType.STRING)){
        if(value instanceof LocalDateTime){
            return ((LocalDateTime) value).format(dateTimeFormatter);
        } else {
            return value.toString();
        }

    }else if(type.equals(JavaType.ENUM)){
        try {
            if (value instanceof String) {
                return fieldDescriptor.getEnumType().findValueByName((String) value);
            } else if (value.getClass().isEnum()) {
                return fieldDescriptor.getEnumType().findValueByName(((Enum) value).name());
            }
        }catch (Exception e){}
    }else if(type.equals(JavaType.BYTE_STRING)){
        return ByteString.copyFrom(((byte[]) value));
    }
    return null;
}
项目:protobuf-transformer    文件:CoreValueCoerce.java   
public static Object toMessageValue(Object value, Descriptors.FieldDescriptor fieldDescriptor){
    if(value!=null){
        if(value instanceof Enum){
            value=((Enum) value).name();
        }
        JavaType type=fieldDescriptor.getJavaType();
        Class clz=MESSAGE_TYPE_TO_WRAPPERS.get(type);
        if(clz!=null){
            if(value instanceof Number){
                if(Integer.class.equals(clz)){
                    return ((Number) value).intValue();
                }else if(Long.class.equals(clz)){
                    return ((Number) value).longValue();
                }else if(Float.class.equals(clz)){
                    return ((Number) value).floatValue();
                }else if(Double.class.equals(clz)){
                    return ((Number) value).doubleValue();
                }
            }
        }else if(type.equals(JavaType.BOOLEAN)){
            return Boolean.TRUE.equals(value);
        }else if(type.equals(JavaType.STRING)){
            if(value instanceof LocalDateTime){
                return ((LocalDateTime) value).format(dateTimeFormatter);
            } else {
                return value.toString();
            }

        }else if(type.equals(JavaType.ENUM)){
            try {
                if (value instanceof String) {
                    return fieldDescriptor.getEnumType().findValueByName((String) value);
                } else if (value.getClass().isEnum()) {
                    return fieldDescriptor.getEnumType().findValueByName(((Enum) value).name());
                }
            }catch (Exception e){

            }
        }else if(type.equals(JavaType.BYTE_STRING) && value instanceof byte[]){
            return ByteString.copyFrom(((byte[]) value));
        }
    }
    return null;
}
项目:protobuf-el    文件:ProtoLists.java   
@Override
public JavaType getType() {
  return field.getJavaType();
}
项目:protobuf-el    文件:FileDescriptors.java   
private void makeCanonicalField(final FieldDescriptorProto.Builder field,
    final FieldDescriptor fieldDescriptor) {
  if (field.hasExtendee() && !field.getExtendee().startsWith(".")) {
    field.setExtendee(ensureLeadingDot(fieldDescriptor.getContainingType().getFullName()));
  }

  if (field.hasTypeName() && !field.getTypeName().startsWith(".")) {
    if (fieldDescriptor.getJavaType() == JavaType.ENUM) {
      field.setTypeName(ensureLeadingDot(fieldDescriptor.getEnumType().getFullName()));
      field.setType(Type.TYPE_ENUM);
    } else {
      // this must be a Message/Group field
      field.setTypeName(ensureLeadingDot(fieldDescriptor.getMessageType().getFullName()));

      if (!field.hasType()) {
        switch (fieldDescriptor.getType()) {
          case MESSAGE:
            field.setType(Type.TYPE_MESSAGE);
            break;
          case GROUP:
            field.setType(Type.TYPE_GROUP);
            break;
          default:
            field.setType(Type.valueOf("TYPE_" + fieldDescriptor.getType().name()));
        }
      }
    }
  }

  // reparsing of the default value if present - protoc does this contrary to the spec!
  if (protocCompatible) {
    if (field.hasDefaultValue()) {
      try {
        final String defaultValue =
            getSimpleFieldValue(fieldDescriptor, fieldDescriptor.getDefaultValue());
        field.setDefaultValue(defaultValue);
      } catch (final IOException e) {
        // this should not happen!
        throw new RuntimeException(e);
      }
    }
  }
}
项目:protobuf-el    文件:LocationBuilder.java   
public Descriptor getElementType(final int fieldNumber) {
  final FieldDescriptor field = protoDescriptor.findFieldByNumber(fieldNumber);
  return field.getJavaType() == JavaType.MESSAGE ? field.getMessageType() : null;
}
项目:protobuf-el    文件:FileDescriptorEx.java   
private void makeCanonicalField(final FieldDescriptorProto.Builder field,
    final FieldDescriptor fieldDescriptor) {
  if (field.hasExtendee() && !field.getExtendee().startsWith(".")) {
    field.setExtendee(ensureLeadingDot(fieldDescriptor.getContainingType().getFullName()));
  }

  if (field.hasTypeName() && !field.getTypeName().startsWith(".")) {
    if (fieldDescriptor.getJavaType() == JavaType.ENUM) {
      field.setTypeName(ensureLeadingDot(fieldDescriptor.getEnumType().getFullName()));
      field.setType(Type.TYPE_ENUM);
    } else {
      // this must be a Message/Group field
      field.setTypeName(ensureLeadingDot(fieldDescriptor.getMessageType().getFullName()));

      if (!field.hasType()) {
        switch (fieldDescriptor.getType()) {
          case MESSAGE:
            field.setType(Type.TYPE_MESSAGE);
            break;
          case GROUP:
            field.setType(Type.TYPE_GROUP);
            break;
          default:
            field.setType(Type.valueOf("TYPE_" + fieldDescriptor.getType().name()));
        }
      }
    }
  }

  // reparsing of the default value if present - protoc does this contrary to the spec!
  if (protocCompatible) {
    if (field.hasDefaultValue()) {
      final StringBuilder sb = new StringBuilder();

      try {
        // TextFormat.printFieldValue(fieldDescriptor, fieldDescriptor.getDefaultValue(), sb);
        // field.setDefaultValue(sb.toString());
        final String defaultValue =
            getSimpleFieldValue(fieldDescriptor, fieldDescriptor.getDefaultValue());
        field.setDefaultValue(defaultValue);
      } catch (final IOException e) {
        // this should not happen!
        throw new RuntimeException(e);
      }
    }
  }
}
项目:protobuf-el    文件:AbstractMessageUtils.java   
@SuppressWarnings("null")
@Override
public Result isEqual(final FieldDescriptor field, final Object value1, final Object value2) {
  if (skipFields.contains(field.getFullName())) {
    return Result.EQUAL;
  }

  if (field == RANGE_END_FIELD) {
    if (Objects.equals(min(ProtoFileParser.MAX_FIELD_NUMBER + 1, (Integer) value1),
        min(ProtoFileParser.MAX_FIELD_NUMBER + 1, (Integer) value2))) {
      return Result.EQUAL;
    } else {
      return Result.NOT_EQUAL;
    }
  }

  if (field.getJavaType() != JavaType.MESSAGE) {
    return Result.NOT_FILTERED;
  }

  if (field.getMessageType() == FieldDescriptorProto.getDescriptor()) {
    if (field.isRepeated()) {
      @SuppressWarnings("unchecked")
      final List<Message> list1 = (List<Message>) value1;
      final List<?> list2 = (List<?>) value1;

      if (list1.size() != list2.size()) {
        return Result.NOT_EQUAL;
      }

      for (int i = 0; i < list1.size(); i++) {
        if (!isSingleFieldProtoEqual(list1.get(i), list2.get(i))) {
          return Result.NOT_EQUAL;
        }
      }
    } else if (!isSingleFieldProtoEqual(value1, value2)) {
      return Result.NOT_EQUAL;
    }

    return Result.EQUAL;
  }

  return Result.NOT_FILTERED;
}
项目:protobuf-el    文件:DynamicMessage.java   
/**
 * Merges other DynamicMessage into this.
 *
 * @see #mergeFrom(Message)
 */
public Builder mergeFrom(final DynamicMessage other) {
  verifyNotNull(other);

  if (other.getDescriptorForType() != getDescriptorForType()) {
    throw new IllegalArgumentException(
        "mergeFrom(Message) can only merge messages of the same type.");
  }

  if (other.isEmpty()) {
    return this;
  }

  for (final Entry<FieldDescriptor, Object> entry : other.getAllFields().entrySet()) {
    final FieldDescriptor field = entry.getKey();

    if (field.isRepeated()) {
      final List<?> otherValue = (List<?>) entry.getValue();

      if (!otherValue.isEmpty()) {
        if (field.getJavaType() == JavaType.MESSAGE) {
          final RepeatedFieldBuilder<Message, Builder, MessageOrBuilder> fieldBuilder =
              getRepeatedFieldBuilder(field, false);

          if (fieldBuilder != null) {
            @SuppressWarnings("unchecked")
            final Iterable<? extends Message> otherMessages =
            (Iterable<? extends Message>) otherValue;
            fieldBuilder.addAllMessages(otherMessages);
            continue;
          }
        }

        FieldHandlerType.REPEATED_PRIMITIVE.getFieldHandler().addAllRepeatedField(this, field,
            otherValue);
      }
    } else if (field.getJavaType() == JavaType.MESSAGE) {
      FieldHandlerType.SINGLE_MESSAGE.getFieldHandler().mergeField(this, field,
          (Message) entry.getValue());
    } else {
      builder.setField(field, entry.getValue());
      onChanged();
    }
  }

  mergeUnknownFields(other.getUnknownFields());
  return this;
}
项目:protobuf-el    文件:MessageAdapter.java   
@Override
public boolean isAttribute(final FieldDescriptor key) {
  return key.getJavaType() != JavaType.MESSAGE;
}
项目:protobuf-el    文件:MessageAdapter.java   
public static boolean isFieldAttribute(final FieldDescriptor key) {
  return key.getJavaType() != JavaType.MESSAGE;
}