com.google.protobuf.MessageOrBuilder Java Examples
The following examples show how to use
com.google.protobuf.MessageOrBuilder.
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: FieldWithComparison.java From fdb-record-layer with Apache License 2.0 | 6 votes |
@Override @Nullable public <M extends Message> Boolean evalMessage(@Nonnull FDBRecordStoreBase<M> store, @Nonnull EvaluationContext context, @Nullable FDBRecord<M> record, @Nullable Message message) { if (message == null) { getComparison().eval(store, context, null); } final Object value = getFieldValue(message); if (value == null) { return getComparison().eval(store, context, null); } else if (value instanceof MessageOrBuilder && !allowWholeMessage()) { throw new Query.InvalidExpressionException("Expression requiring primitive found a message value"); } else { return getComparison().eval(store, context, value); } }
Example #2
Source File: ProtobufDecompiler.java From sql-layer with GNU Affero General Public License v3.0 | 6 votes |
protected void decompileOptions(MessageOrBuilder options) throws IOException { for (Map.Entry<FieldDescriptor,Object> entry : options.getAllFields().entrySet()) { FieldDescriptor field = entry.getKey(); Object value = entry.getValue(); String fieldName = field.getName(); if (field.isExtension()) { fieldName = "(" + fieldName + ")"; } if (field.getType() == FieldDescriptor.Type.MESSAGE) { for (Map.Entry<FieldDescriptor,Object> subentry : ((MessageOrBuilder)value).getAllFields().entrySet()) { FieldDescriptor subfield = subentry.getKey(); Object subvalue = subentry.getValue(); indentedFormat("option %s.%s = %s;", fieldName, subfield.getName(), literal(subvalue, subfield.getType())); } } else { indentedFormat("option %s = %s;", fieldName, literal(value, field.getType())); } } }
Example #3
Source File: TestUtils.java From parquet-mr with Apache License 2.0 | 6 votes |
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 #4
Source File: MessageToBean.java From krpc with Apache License 2.0 | 6 votes |
static public Map<Descriptors.FieldDescriptor, Object> getFields(MessageOrBuilder message, boolean withDefaultValue) { if (!withDefaultValue) { return message.getAllFields(); } Map<Descriptors.FieldDescriptor, Object> fieldsToPrint = new LinkedHashMap<>(); for (Descriptors.FieldDescriptor field : message.getDescriptorForType().getFields()) { if (field.isOptional()) { if (field.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE && !message.hasField(field)) { continue; } // if (field.getJavaType() == Descriptors.FieldDescriptor.JavaType.STRING && !message.hasField(field)) { // continue; // } } fieldsToPrint.put(field, message.getField(field)); } return fieldsToPrint; }
Example #5
Source File: JsonEncoder.java From xrpc with Apache License 2.0 | 6 votes |
/** * Encode a response object to JSON format for the HttpResponse. * * @param buf target byte buffer for encoding * @param acceptCharset Accept-Charset header * @param object object to encode * @return ByteBuf representing JSON formatted String */ @Override public ByteBuf encode(ByteBuf buf, CharSequence acceptCharset, Object object) throws IOException { try (OutputStreamWriter writer = new OutputStreamWriter(new ByteBufOutputStream(buf), charset(acceptCharset))) { if (object instanceof MessageOrBuilder) { // Encode proto using its defined serialization. String json = printer.print((MessageOrBuilder) object); writer.write(json); } else { // Encode POJO using Jackson. mapper.writeValue(writer, object); } return buf; } }
Example #6
Source File: TestUtils.java From parquet-mr with Apache License 2.0 | 6 votes |
/** * Fails if some instance of builder is two times in list. */ private static void checkSameBuilderInstance(MessageOrBuilder[] messages) { for (int i = 0; i < messages.length; i++) { MessageOrBuilder firstMessage = messages[i]; boolean isBuilder = firstMessage instanceof Message.Builder; if (isBuilder) { for (int j = 0; j < messages.length; j++) { MessageOrBuilder secondMessage = messages[j]; if (i != j) { boolean isSame = secondMessage == firstMessage; if (isSame) { fail("Data contains two references to same instance." + secondMessage); } } } } } }
Example #7
Source File: MessageValue.java From fdb-record-layer with Apache License 2.0 | 6 votes |
/** * Get the value of the field with the given field name on the given message. * If the field is repeated, the repeated values are combined into a list. If the field has a message type, * the value is returned as a {@link Message} of that type. Otherwise, the field is returned as a primitive. * @param message a message or builder to extract the field from * @param fieldName the field to extract * @return the value of the field as described above */ @Nullable public static Object getFieldOnMessage(@Nonnull MessageOrBuilder message, @Nonnull String fieldName) { final Descriptors.FieldDescriptor field = findFieldDescriptorOnMessage(message, fieldName); if (field.isRepeated()) { int count = message.getRepeatedFieldCount(field); List<Object> list = new ArrayList<>(count); for (int i = 0; i < count; i++) { list.add(message.getRepeatedField(field, i)); } return list; } if (field.hasDefaultValue() || message.hasField(field)) { if (field.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE && TupleFieldsHelper.isTupleField(field.getMessageType())) { return TupleFieldsHelper.fromProto((Message)message.getField(field), field.getMessageType()); } else { return message.getField(field); } } else { return null; } }
Example #8
Source File: MessageValue.java From fdb-record-layer with Apache License 2.0 | 6 votes |
/** * Get the value of the (nested) field on the path from the message defined by {@code fieldNames}. * The given field names define a path through the nested structure of the given message; this method traverses * that path and returns the value at the leaf, using the return semantics of {@link #getFieldOnMessage(MessageOrBuilder, String)}. * @param message a message * @param fieldNames a list of field names defining a path starting at {@code message} * @return the value at the end of hte path */ @Nullable public static Object getFieldValue(@Nonnull MessageOrBuilder message, @Nonnull List<String> fieldNames) { if (fieldNames.isEmpty()) { throw new RecordCoreException("empty list of field names"); } MessageOrBuilder current = message; int fieldNamesIndex; // Notice that up to fieldNames.size() - 2 are calling getFieldMessageOnMessage, and fieldNames.size() - 1 is calling getFieldOnMessage for (fieldNamesIndex = 0; fieldNamesIndex < fieldNames.size() - 1; fieldNamesIndex++) { current = getFieldMessageOnMessage(current, fieldNames.get(fieldNamesIndex)); if (current == null) { return null; } } return getFieldOnMessage(current, fieldNames.get(fieldNames.size() - 1)); }
Example #9
Source File: TestUtils.java From parquet-mr with Apache License 2.0 | 6 votes |
/** * Reads messages from given file. The file could/should be created by method writeMessages */ public static <T extends MessageOrBuilder> List<T> readMessages(Path file) throws IOException { ProtoParquetReader<T> reader = new ProtoParquetReader<T>(file); List<T> result = new ArrayList<T>(); boolean hasNext = true; while (hasNext) { T item = reader.read(); if (item == null) { hasNext = false; } else { assertNotNull(item); // It makes sense to return message but production code wont work with messages result.add((T) asMessage(item).toBuilder()); } } reader.close(); return result; }
Example #10
Source File: ProtobufGCNotificationsTest.java From garmadon with Apache License 2.0 | 6 votes |
@Test public void getGCNotificationWithInfos() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); ProtobufGCNotifications notif = new ProtobufGCNotifications(); notif.subscribe((timestamp, stats) -> { JsonFormat.Printer printer = JsonFormat.printer() .includingDefaultValueFields() .preservingProtoFieldNames(); try { String s = printer.print((MessageOrBuilder) stats); MatcherAssert.assertThat(s, MatchesPattern.matchesPattern(GC_PATTERN)); latch.countDown(); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); } }); System.gc(); Assert.assertTrue(latch.await(1000, TimeUnit.MILLISECONDS)); }
Example #11
Source File: TestUtils.java From parquet-mr with Apache License 2.0 | 5 votes |
/** * Writes messages to file, reads messages from file and checks if everything is OK. */ public static <T extends MessageOrBuilder> List<T> testData(T... messages) throws IOException { checkSameBuilderInstance(messages); List<MessageOrBuilder> output = (List<MessageOrBuilder>) writeAndRead(messages); List<Message> outputAsMessages = asMessages(output); Descriptors.Descriptor messageDescriptor = Protobufs.getMessageDescriptor(asMessage(messages[0]).getClass()); Descriptors.FileDescriptor.Syntax syntax = messageDescriptor.getFile().getSyntax(); for (int i = 0 ; i < messages.length ; i++) { if (Descriptors.FileDescriptor.Syntax.PROTO2.equals(syntax)) { com.google.common.truth.extensions.proto.ProtoTruth.assertThat(outputAsMessages.get(i)) .ignoringRepeatedFieldOrder() .reportingMismatchesOnly() .isEqualTo(asMessage(messages[i])); } else if (Descriptors.FileDescriptor.Syntax.PROTO3.equals(syntax)) { // proto3 will return default values for absent fields which is what is returned in output // this is why we can ignore absent fields here com.google.common.truth.extensions.proto.ProtoTruth.assertThat(outputAsMessages.get(i)) .ignoringRepeatedFieldOrder() .ignoringFieldAbsence() .reportingMismatchesOnly() .isEqualTo(asMessage(messages[i])); } } return (List<T>) outputAsMessages; }
Example #12
Source File: ProtoHelpers.java From api-compiler with Apache License 2.0 | 5 votes |
public static boolean getFieldBoolean( MessageOrBuilder mob, String fieldName, boolean defaultValue) { boolean value = defaultValue; FieldDescriptor fieldDesc = mob.getDescriptorForType().findFieldByName(fieldName); if (null != fieldDesc) { if (mob.hasField(fieldDesc)) { Object fieldValue = mob.getField(fieldDesc); if (fieldValue instanceof Boolean) { value = (Boolean) fieldValue; } } } return value; }
Example #13
Source File: ProtoHelpers.java From api-compiler with Apache License 2.0 | 5 votes |
@Nullable public static <Type> Type getFieldIfPresent( MessageOrBuilder mob, FieldDescriptor fieldDesc, Class<Type> clazz) { if (mob.hasField(fieldDesc)) { Object fieldValue = null; try { fieldValue = mob.getField(fieldDesc); if (null == fieldValue) { return null; } if (fieldValue instanceof EnumValueDescriptor && clazz.isEnum()) { // Do some sanity checks and convert the EnumValueDescriptor into the (Type) class (which // has to be an enum) EnumValueDescriptor fieldEnumValue = (EnumValueDescriptor) fieldValue; if (clazz.getSimpleName().equals(fieldEnumValue.getType().getName())) { Type[] enumValues = clazz.getEnumConstants(); if (fieldEnumValue.getIndex() >= 0 && fieldEnumValue.getIndex() < enumValues.length) { Type value = enumValues[fieldEnumValue.getIndex()]; return value; } } throw new RuntimeException( String.format("Couldn't convert '%s' to class '%s'", fieldValue, clazz.getName())); } return clazz.cast(fieldValue); } catch (ClassCastException ex) { throw new RuntimeException( String.format( "Expected (%s) type, not (%s), for field '%s' of (%s)%s", clazz, fieldValue.getClass(), fieldDesc.getName(), mob.getClass(), getName(mob)), ex); } } return null; }
Example #14
Source File: ProtoHelpers.java From api-compiler with Apache License 2.0 | 5 votes |
/** Returns the name that this object would contribute to a fully qualified name of a type. */ public static String getContextName(MessageOrBuilder mob) { if (mob instanceof FileDescriptorProtoOrBuilder) { return ((FileDescriptorProtoOrBuilder) mob).getPackage(); } return getName(mob); }
Example #15
Source File: TextFormatForTest.java From api-compiler with Apache License 2.0 | 5 votes |
/** * Converts a message into a string. */ public String printToString(MessageOrBuilder message) { StringBuilder result = new StringBuilder(); for (FieldDescriptor field : getFieldsInNumberOrder(message.getDescriptorForType())) { // Skip empty fields. if ((field.isRepeated() && message.getRepeatedFieldCount(field) == 0) || (!field.isRepeated() && !message.hasField(field))) { continue; } // Normalize repeated and singleton fields. Object rawValue = message.getField(field); @SuppressWarnings("unchecked") List<Object> values = field.isMapField() ? sortMapEntries(field, rawValue) : field.isRepeated() ? (List<Object>) rawValue : ImmutableList.of(rawValue); // Print field values. for (Object value : values) { result.append(printFieldToString(field, value)); } } return result.toString(); }
Example #16
Source File: BaseField.java From fdb-record-layer with Apache License 2.0 | 5 votes |
@Nullable protected Object getFieldValue(@Nullable MessageOrBuilder message) { if (message == null) { return null; } return MessageValue.getFieldOnMessage(message, fieldName); }
Example #17
Source File: MessageValue.java From fdb-record-layer with Apache License 2.0 | 5 votes |
@Nullable private static Message getFieldMessageOnMessage(@Nonnull MessageOrBuilder message, @Nonnull String fieldName) { final Descriptors.FieldDescriptor field = findFieldDescriptorOnMessage(message, fieldName); if (!field.isRepeated() && (field.hasDefaultValue() || message.hasField(field)) && field.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { return (Message)message.getField(field); } return null; }
Example #18
Source File: ConfigBaselineTestCase.java From api-compiler with Apache License 2.0 | 5 votes |
/** Fetches content from various values for a content source (File, Doc, etc.) */ private String displayValue(Object value) throws IOException { if (value instanceof Doc) { return ((Doc) value).prettyPrint(100); } else if (value instanceof File) { return Files.asCharSource((File) value, StandardCharsets.UTF_8).read(); } else if (value instanceof MessageOrBuilder) { // Convert proto to text format, considering any instances. return formatter.printToString((MessageOrBuilder) value); } else { return value.toString(); } }
Example #19
Source File: BaseRepeatedField.java From fdb-record-layer with Apache License 2.0 | 5 votes |
@Nullable @SuppressWarnings("unchecked") protected List<Object> getValues(@Nonnull MessageOrBuilder message) { final Descriptors.FieldDescriptor field = findFieldDescriptor(message); if (emptyMode == Field.OneOfThemEmptyMode.EMPTY_UNKNOWN && message.getRepeatedFieldCount(field) == 0) { return null; } else { return (List<Object>) message.getField(field); } }
Example #20
Source File: GrpcDocServicePlugin.java From armeria with Apache License 2.0 | 5 votes |
@Override public String serializeExampleRequest(String serviceName, String methodName, Object exampleRequest) { try { return defaultExamplePrinter.print((MessageOrBuilder) exampleRequest); } catch (InvalidProtocolBufferException e) { throw new UncheckedIOException( "Invalid example request protobuf. Is it missing required fields?", e); } }
Example #21
Source File: ProtoHelpers.java From api-compiler with Apache License 2.0 | 5 votes |
@Nullable public static <Type> Type getFieldIfPresent( MessageOrBuilder mob, String fieldName, Class<Type> clazz) { FieldDescriptor fieldDesc = mob.getDescriptorForType().findFieldByName(fieldName); if (null == fieldDesc) { return null; } return getFieldIfPresent(mob, fieldDesc, clazz); }
Example #22
Source File: TestUtils.java From parquet-mr with Apache License 2.0 | 5 votes |
private static List<MessageOrBuilder> cloneList(MessageOrBuilder[] messages) { List<MessageOrBuilder> result = new ArrayList<MessageOrBuilder>(); for (MessageOrBuilder mob : messages) { result.add(asMessage(mob)); } return result; }
Example #23
Source File: TestUtils.java From parquet-mr with Apache License 2.0 | 5 votes |
public static List<Message> asMessages(List<MessageOrBuilder> mobs) { List<Message> result = new ArrayList<Message>(); for (MessageOrBuilder messageOrBuilder : mobs) { result.add(asMessage(messageOrBuilder)); } return result; }
Example #24
Source File: TestUtils.java From parquet-mr with Apache License 2.0 | 5 votes |
public static Path writeMessages(Class<? extends Message> cls, MessageOrBuilder... records) throws IOException { Path file = someTemporaryFilePath(); ProtoParquetWriter<MessageOrBuilder> writer = new ProtoParquetWriter<MessageOrBuilder>(file, cls); for (MessageOrBuilder record : records) { writer.write(record); } writer.close(); return file; }
Example #25
Source File: DetailedExitCode.java From bazel with Apache License 2.0 | 5 votes |
/** Returns the numeric exit code associated with a {@link FailureDetail} message. */ private static int getNumericExitCode(FailureDetail failureDetail) { MessageOrBuilder categoryMsg = getCategorySubmessage(failureDetail); EnumValueDescriptor subcategoryDescriptor = getSubcategoryDescriptor(failureDetail, categoryMsg); return getNumericExitCode(subcategoryDescriptor); }
Example #26
Source File: DetailedExitCode.java From bazel with Apache License 2.0 | 5 votes |
/** * Returns the enum value descriptor for the enum field with field number 1 in the {@link * FailureDetail}'s category submessage. */ private static EnumValueDescriptor getSubcategoryDescriptor( FailureDetail failureDetail, MessageOrBuilder categoryMsg) { FieldDescriptor fieldNumberOne = categoryMsg.getDescriptorForType().findFieldByNumber(1); checkNotNull( fieldNumberOne, "FailureDetail category submessage has no field #1: %s", failureDetail); Object fieldNumberOneVal = categoryMsg.getField(fieldNumberOne); checkArgument( fieldNumberOneVal instanceof EnumValueDescriptor, "FailureDetail category submessage has non-enum field #1: %s", failureDetail); return (EnumValueDescriptor) fieldNumberOneVal; }
Example #27
Source File: XdsClientImpl.java From grpc-java with Apache License 2.0 | 5 votes |
@VisibleForTesting String print(MessageOrBuilder message) { String res; try { res = printer.print(message); } catch (InvalidProtocolBufferException e) { res = message + " (failed to pretty-print: " + e + ")"; } return res; }
Example #28
Source File: WrappedPrimitiveSerializer.java From jackson-datatype-protobuf with Apache License 2.0 | 5 votes |
@Override public void serialize( MessageOrBuilder message, JsonGenerator generator, SerializerProvider serializerProvider ) throws IOException { FieldDescriptor field = message.getDescriptorForType().findFieldByName("value"); Object value = message.getField(field); writeValue(field, value, generator, serializerProvider); }
Example #29
Source File: ObjectMapperHelper.java From jackson-datatype-protobuf with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public static <T extends MessageOrBuilder> T writeAndReadBack(ObjectMapper mapper, T value) { TreeNode tree = toTree(mapper, value); try { return (T) mapper.treeToValue(tree, value.getClass()); } catch (JsonProcessingException e) { throw new RuntimeException(e); } }
Example #30
Source File: ObjectMapperHelper.java From jackson-datatype-protobuf with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public static <T extends MessageOrBuilder> List<T> writeAndReadBack(ObjectMapper mapper, List<T> values) { if (values.isEmpty()) { return Collections.emptyList(); } Class<T> messageType = (Class<T>) values.get(0).getClass(); JsonParser parser = mapper.treeAsTokens(toTree(mapper, values)); try { return Lists.newArrayList(mapper.readValues(parser, messageType)); } catch (IOException e) { throw new RuntimeException(e); } }