下面列出了com.google.protobuf.UInt64Value#com.google.protobuf.Descriptors.FieldDescriptor 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public Object getField(final FieldDescriptor field) {
if (field.isExtension()) {
verifyContainingType(field);
final Object value = extensions.getField(field);
if (value == null) {
if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
// Lacking an ExtensionRegistry, we have no way to determine the
// extension's real type, so we return a DynamicMessage.
return DynamicMessage.getDefaultInstance(field.getMessageType());
} else {
return field.getDefaultValue();
}
} else {
return value;
}
} else {
return super.getField(field);
}
}
private static void testAddRepeatedFieldsWithDescriptors() {
List<FieldDescriptor> fields = getRepeatedFieldDescriptors();
List<Object> values = new ArrayList<Object>();
values.add(Integer.valueOf(1));
values.add(Long.valueOf(2));
values.add(Integer.valueOf(3));
values.add(Long.valueOf(4));
values.add(Boolean.TRUE);
values.add(Float.valueOf(5.6f));
values.add(Double.valueOf(7.8));
values.add("foo");
values.add(ByteString.copyFrom("bar".getBytes()));
values.add(TypicalData.EnumType.VALUE1.getValueDescriptor());
for (int i = 0; i < 150; i++) {
TypicalData.Builder builder = TypicalData.newBuilder();
for (int j = 0; j < 25; j++) {
for (int k = 0; k < 10; k++) {
builder.addRepeatedField(fields.get(k), values.get(k));
}
}
}
}
/** Get the value of an extension. */
@Override
@SuppressWarnings("unchecked")
public final <Type> Type getExtension(final ExtensionLite<MessageType, Type> extensionLite) {
Extension<MessageType, Type> extension = checkNotLite(extensionLite);
verifyExtensionContainingType(extension);
FieldDescriptor descriptor = extension.getDescriptor();
final Object value = extensions.getField(descriptor);
if (value == null) {
if (descriptor.isRepeated()) {
return (Type) Collections.emptyList();
} else if (descriptor.getJavaType() ==
FieldDescriptor.JavaType.MESSAGE) {
return (Type) extension.getMessageDefaultInstance();
} else {
return (Type) extension.fromReflectionType(
descriptor.getDefaultValue());
}
} else {
return (Type) extension.fromReflectionType(value);
}
}
private void add(final ExtensionInfo extension) {
if (!extension.descriptor.isExtension()) {
throw new IllegalArgumentException(
"ExtensionRegistry.add() was given a FieldDescriptor for a regular " +
"(non-extension) field.");
}
extensionsByName.put(extension.descriptor.getFullName(), extension);
extensionsByNumber.put(
new DescriptorIntPair(extension.descriptor.getContainingType(),
extension.descriptor.getNumber()),
extension);
final FieldDescriptor field = extension.descriptor;
if (field.getContainingType().getOptions().getMessageSetWireFormat() &&
field.getType() == FieldDescriptor.Type.MESSAGE &&
field.isOptional() &&
field.getExtensionScope() == field.getMessageType()) {
// This is an extension of a MessageSet type defined within the extension
// type's own scope. For backwards-compatibility, allow it to be looked
// up by type name.
extensionsByName.put(field.getMessageType().getFullName(), extension);
}
}
/** Internal helper which returns a mutable map. */
private Map<FieldDescriptor, Object> getAllFieldsMutable() {
final TreeMap<FieldDescriptor, Object> result =
new TreeMap<FieldDescriptor, Object>();
final Descriptor descriptor = internalGetFieldAccessorTable().descriptor;
for (final FieldDescriptor field : descriptor.getFields()) {
if (field.isRepeated()) {
final List value = (List) getField(field);
if (!value.isEmpty()) {
result.put(field, value);
}
} else {
if (hasField(field)) {
result.put(field, getField(field));
}
}
}
return result;
}
public Builder treatAsMapWithMultipleFieldsAsKey(
FieldDescriptor field, List<FieldDescriptor> keyFields) {
Preconditions.checkArgument(
field.isRepeated(), "Field must be repeated " + field.getFullName());
Preconditions.checkArgument(
JavaType.MESSAGE.equals(field.getJavaType()),
"Field has to be message type. Field name is: " + field.getFullName());
for (int i = 0; i < keyFields.size(); ++i) {
FieldDescriptor key = keyFields.get(i);
Preconditions.checkArgument(
key.getContainingType().equals(field.getMessageType()),
key.getFullName()
+ " must be a direct subfield within the repeated field: "
+ field.getFullName());
}
Preconditions.checkArgument(
!setFields.contains(field),
"Cannot treat this repeated field as both Map and Set for comparison.");
MapKeyComparator keyComparator = new MultipleFieldsMapKeyComparator(keyFields);
mapKeyComparatorMap.put(field, keyComparator);
return this;
}
/** For use by generated code only. */
public static <ContainingType extends Message, Type>
GeneratedExtension<ContainingType, Type>
newMessageScopedGeneratedExtension(final Message scope,
final int descriptorIndex,
final Class singularType,
final Message defaultInstance) {
// For extensions scoped within a Message, we use the Message to resolve
// the outer class's descriptor, from which the extension descriptor is
// obtained.
return new GeneratedExtension<ContainingType, Type>(
new ExtensionDescriptorRetriever() {
//@Override (Java 1.6 override semantics, but we must support 1.5)
public FieldDescriptor getDescriptor() {
return scope.getDescriptorForType().getExtensions()
.get(descriptorIndex);
}
},
singularType,
defaultInstance);
}
@Override
public void geoServerAddWorkspaceCommand(
final org.locationtech.geowave.service.grpc.protobuf.GeoServerAddWorkspaceCommandParametersProtos request,
final StreamObserver<org.locationtech.geowave.service.grpc.protobuf.GeoWaveReturnTypesProtos.StringResponseProtos> responseObserver) {
final GeoServerAddWorkspaceCommand cmd = new GeoServerAddWorkspaceCommand();
final Map<FieldDescriptor, Object> m = request.getAllFields();
GeoWaveGrpcServiceCommandUtil.setGrpcToCommandFields(m, cmd);
final File configFile = GeoWaveGrpcServiceOptions.geowaveConfigFile;
final OperationParams params = new ManualOperationParams();
params.getContext().put(ConfigOptions.PROPERTIES_FILE_CONTEXT, configFile);
cmd.prepare(params);
LOGGER.info("Executing GeoServerAddWorkspaceCommand...");
try {
final String result = cmd.computeResults(params);
final StringResponseProtos resp =
StringResponseProtos.newBuilder().setResponseValue(result).build();
responseObserver.onNext(resp);
responseObserver.onCompleted();
} catch (final Exception e) {
LOGGER.error("Exception encountered executing command", e);
}
}
/** Get a hash code for given fields and values, using the given seed. */
@SuppressWarnings("unchecked")
protected int hashFields(int hash, Map<FieldDescriptor, Object> map) {
for (Map.Entry<FieldDescriptor, Object> entry : map.entrySet()) {
FieldDescriptor field = entry.getKey();
Object value = entry.getValue();
hash = (37 * hash) + field.getNumber();
if (field.getType() != FieldDescriptor.Type.ENUM){
hash = (53 * hash) + value.hashCode();
} else if (field.isRepeated()) {
List<? extends EnumLite> list = (List<? extends EnumLite>) value;
hash = (53 * hash) + hashEnumList(list);
} else {
hash = (53 * hash) + hashEnum((EnumLite) value);
}
}
return hash;
}
@Override
public Object parseGroup(
CodedInputStream input,
ExtensionRegistryLite registry,
Descriptors.FieldDescriptor field,
Message defaultInstance)
throws IOException {
Message.Builder subBuilder =
defaultInstance.newBuilderForType();
if (!field.isRepeated()) {
Message originalMessage = (Message) getField(field);
if (originalMessage != null) {
subBuilder.mergeFrom(originalMessage);
}
}
input.readGroup(field.getNumber(), subBuilder, registry);
return subBuilder.buildPartial();
}
/**
* Used in proto1 generated code only.
*
* After enabling bridge, we can define proto2 extensions (the extended type
* is a proto2 mutable message) in a proto1 .proto file. For these extensions
* we should generate proto2 GeneratedExtensions.
*/
public static <ContainingType extends Message, Type>
GeneratedExtension<ContainingType, Type>
newMessageScopedGeneratedExtension(
final Message scope, final String name,
final Class singularType, final Message defaultInstance) {
// For extensions scoped within a Message, we use the Message to resolve
// the outer class's descriptor, from which the extension descriptor is
// obtained.
return new GeneratedExtension<ContainingType, Type>(
new CachedDescriptorRetriever() {
@Override
protected FieldDescriptor loadDescriptor() {
return scope.getDescriptorForType().findFieldByName(name);
}
},
singularType,
defaultInstance,
Extension.ExtensionType.MUTABLE);
}
void printSingleField(FieldDescriptor field, Object value, Appender appender, Level level)
throws IOException {
if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
if (level.level + 1 > maxLevels) {
return;
}
}
if (!level.isFirst()) {
appender.appendSep(level.level);
}
level.setFirst(false);
if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
appender.appendKey(field.getName());
appender.appendSep9();
appender.appendMapStart();
printFieldValue(field, value, appender, level);
appender.appendMapEnd();
} else {
appender.appendKey(field.getName());
appender.appendSep9();
printFieldValue(field, value, appender, level);
}
}
/** Recursively crawls the proto message while clearing each field of type {@link Source}. */
@VisibleForTesting
static void stripSourceReferences(Message.Builder msg) {
for (FieldDescriptor fieldDesc : msg.getAllFields().keySet()) {
if (!fieldDesc.getJavaType().equals(JavaType.MESSAGE)) {
continue;
}
if (fieldDesc.getMessageType().getFullName().equals(Source.getDescriptor().getFullName())) {
msg.clearField(fieldDesc);
} else {
if (fieldDesc.isRepeated()) {
int repeatCount = msg.getRepeatedFieldCount(fieldDesc);
for (int i = 0; i < repeatCount; i++) {
stripSourceReferences(msg.getRepeatedFieldBuilder(fieldDesc, i));
}
} else {
stripSourceReferences(msg.getFieldBuilder(fieldDesc));
}
}
}
}
RepeatedEnumFieldAccessor(
final FieldDescriptor descriptor, final String camelCaseName,
final Class<? extends GeneratedMessage> messageClass,
final Class<? extends Builder> builderClass) {
super(descriptor, camelCaseName, messageClass, builderClass);
enumDescriptor = descriptor.getEnumType();
valueOfMethod = getMethodOrDie(type, "valueOf",
EnumValueDescriptor.class);
getValueDescriptorMethod =
getMethodOrDie(type, "getValueDescriptor");
supportUnknownEnumValue = descriptor.getFile().supportsUnknownEnumValue();
if (supportUnknownEnumValue) {
getRepeatedValueMethod =
getMethodOrDie(messageClass, "get" + camelCaseName + "Value", int.class);
getRepeatedValueMethodBuilder =
getMethodOrDie(builderClass, "get" + camelCaseName + "Value", int.class);
setRepeatedValueMethod =
getMethodOrDie(builderClass, "set" + camelCaseName + "Value", int.class, int.class);
addRepeatedValueMethod =
getMethodOrDie(builderClass, "add" + camelCaseName + "Value", int.class);
}
}
private static <T extends Message> Object fuzzField(FieldDescriptor field, T containingMessage) {
switch (field.getType().getJavaType()) {
case BOOLEAN:
return RAND.nextBoolean();
case BYTE_STRING:
return randomByteString();
case DOUBLE:
return RAND.nextDouble();
case ENUM:
return randomEnum(field.getEnumType());
case FLOAT:
return RAND.nextFloat();
case INT:
return RAND.nextInt();
case LONG:
return RAND.nextLong();
case STRING:
return randomString();
case MESSAGE:
return randomProtoMessage(
ProtoReflection.getJavaClassOfMessageField(containingMessage, field));
}
throw new RuntimeException("Unhandled field type: " + field.getType());
}
public Object getField(FieldDescriptor field) {
verifyContainingType(field);
Object result = fields.getField(field);
if (result == null) {
if (field.isRepeated()) {
result = Collections.emptyList();
} else if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
result = getDefaultInstance(field.getMessageType());
} else {
result = field.getDefaultValue();
}
}
return result;
}
private static HashMap<String, Object> convertMessageIntoInnerMap(Message msg, boolean expandEnum) {
HashMap<String, Object> ret = new HashMap<String, Object>();
if (msg == null) {
return ret;
}
for (Map.Entry<Descriptors.FieldDescriptor, Object> kv : msg.getAllFields().entrySet()) {
ret.put(kv.getKey().getName(), convertMessageFieldIntoObject(kv.getKey(), kv.getValue(), expandEnum));
}
return ret;
}
private static List<FieldDescriptor> getRepeatedFieldDescriptors() {
Descriptor descriptor = TypicalData.Builder.getDescriptor();
List<FieldDescriptor> fields = new ArrayList<FieldDescriptor>();
fields.add(descriptor.findFieldByNumber(4));
fields.add(descriptor.findFieldByNumber(19));
fields.add(descriptor.findFieldByNumber(20));
fields.add(descriptor.findFieldByNumber(21));
fields.add(descriptor.findFieldByNumber(5));
fields.add(descriptor.findFieldByNumber(6));
fields.add(descriptor.findFieldByNumber(7));
fields.add(descriptor.findFieldByNumber(8));
fields.add(descriptor.findFieldByNumber(9));
fields.add(descriptor.findFieldByNumber(10));
return fields;
}
@Override
public void geoServerListDatastoresCommand(
final org.locationtech.geowave.service.grpc.protobuf.GeoServerListDatastoresCommandParametersProtos request,
final StreamObserver<org.locationtech.geowave.service.grpc.protobuf.GeoWaveReturnTypesProtos.StringResponseProtos> responseObserver) {
final GeoServerListDatastoresCommand cmd = new GeoServerListDatastoresCommand();
final Map<FieldDescriptor, Object> m = request.getAllFields();
GeoWaveGrpcServiceCommandUtil.setGrpcToCommandFields(m, cmd);
final File configFile = GeoWaveGrpcServiceOptions.geowaveConfigFile;
final OperationParams params = new ManualOperationParams();
params.getContext().put(ConfigOptions.PROPERTIES_FILE_CONTEXT, configFile);
cmd.prepare(params);
LOGGER.info("Executing GeoServerListDatastoresCommand...");
try {
final String result = cmd.computeResults(params);
final StringResponseProtos resp =
StringResponseProtos.newBuilder().setResponseValue(result).build();
responseObserver.onNext(resp);
responseObserver.onCompleted();
} catch (final Exception e) {
LOGGER.error("Exception encountered executing command", e);
}
}
@Override
public BuilderType setRepeatedField(final FieldDescriptor field,
final int index, final Object value) {
if (field.isExtension()) {
verifyContainingType(field);
ensureExtensionsIsMutable();
extensions.setRepeatedField(field, index, value);
onChanged();
return (BuilderType) this;
} else {
return super.setRepeatedField(field, index, value);
}
}
public void writeUntil(final int end, final CodedOutputStream output)
throws IOException {
while (next != null && next.getKey().getNumber() < end) {
FieldDescriptor descriptor = next.getKey();
if (messageSetWireFormat && descriptor.getLiteJavaType() ==
WireFormat.JavaType.MESSAGE &&
!descriptor.isRepeated()) {
if (next instanceof LazyField.LazyEntry<?>) {
output.writeRawMessageSetExtension(descriptor.getNumber(),
((LazyField.LazyEntry<?>) next).getField().toByteString());
} else {
output.writeMessageSetExtension(descriptor.getNumber(),
(Message) next.getValue());
}
} else {
// TODO(xiangl): Taken care of following code, it may cause
// problem when we use LazyField for normal fields/extensions.
// Due to the optional field can be duplicated at the end of
// serialized bytes, which will make the serialized size change
// after lazy field parsed. So when we use LazyField globally,
// we need to change the following write method to write cached
// bytes directly rather than write the parsed message.
FieldSet.writeField(descriptor, next.getValue(), output);
}
if (iter.hasNext()) {
next = iter.next();
} else {
next = null;
}
}
}
/** helper method to handle {@code builder} and {@code extensions}. */
private static void addRepeatedField(
Message.Builder builder,
FieldSet<FieldDescriptor> extensions,
FieldDescriptor field,
Object value) {
if (builder != null) {
builder.addRepeatedField(field, value);
} else {
extensions.addRepeatedField(field, value);
}
}
/** Get one element of a repeated extension. */
//@Override (Java 1.6 override semantics, but we must support 1.5)
public final <Type> Type getExtension(
final GeneratedExtension<MessageType, List<Type>> extension,
final int index) {
verifyExtensionContainingType(extension);
FieldDescriptor descriptor = extension.getDescriptor();
return (Type) extension.singularFromReflectionType(
extensions.getRepeatedField(descriptor, index));
}
public void testEnumDescriptor() throws Exception {
Descriptor descriptor = TypicalData.Builder.getDescriptor();
FieldDescriptor fieldDescriptor = descriptor.findFieldByNumber(3);
assertEquals(Type.ENUM, fieldDescriptor.getType());
EnumDescriptor enumDescriptor = fieldDescriptor.getEnumType();
assertNotNull(enumDescriptor);
EnumValueDescriptor enumValueDescriptor = enumDescriptor.findValueByNumber(1);
assertEquals(1, enumValueDescriptor.getNumber());
assertEquals("VALUE1", enumValueDescriptor.getName());
}
@Override
Object getFromProtoMessage(Message message) {
FieldDescriptor fieldDescriptor = getFieldDescriptor(message);
if (message.hasField(fieldDescriptor)) {
Message wrapper = (Message) message.getField(fieldDescriptor);
return convertFromProtoValue(wrapper);
}
return null;
}
/** Verifies that the field is a field of this message. */
private void verifyContainingType(FieldDescriptor field) {
if (field.getContainingType() != type) {
throw new IllegalArgumentException(
"FieldDescriptor does not match message type.");
}
}
public Builder newBuilderForField(FieldDescriptor field) {
verifyContainingType(field);
if (field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) {
throw new IllegalArgumentException(
"newBuilderForField is only valid for fields with message type.");
}
return new Builder(field.getMessageType());
}
/** Verifies that the field is a field of this message. */
private void verifyContainingType(FieldDescriptor field) {
if (field.getContainingType() != type) {
throw new IllegalArgumentException(
"FieldDescriptor does not match message type.");
}
}
SingularEnumFieldAccessor(
final FieldDescriptor descriptor, final String camelCaseName,
final Class<? extends GeneratedMessage> messageClass,
final Class<? extends Builder> builderClass) {
super(descriptor, camelCaseName, messageClass, builderClass);
valueOfMethod = getMethodOrDie(type, "valueOf",
EnumValueDescriptor.class);
getValueDescriptorMethod =
getMethodOrDie(type, "getValueDescriptor");
}
/** Set the value of one element of a repeated extension. */
public final <Type> BuilderType setExtension(
final Extension<MessageType, List<Type>> extension,
final int index, final Type value) {
verifyExtensionContainingType(extension);
ensureExtensionsIsMutable();
final FieldDescriptor descriptor = extension.getDescriptor();
extensions.setRepeatedField(
descriptor, index,
extension.singularToReflectionType(value));
onChanged();
return (BuilderType) this;
}