@Override protected void encode(ChannelHandlerContext ctx, MessageOrBuilder in, List<Object> out) throws Exception { Message msg = in instanceof Message ? (Message) in : ((Message.Builder) in).build(); int typeId = register.getTypeId(msg.getClass()); if (typeId == Integer.MIN_VALUE) { throw new IllegalArgumentException("Unrecognisable message type, maybe not registered! "); } byte[] messageData = msg.toByteArray(); if (messageData.length <= 0) { out.add(ByteBufAllocator.DEFAULT.heapBuffer().writeInt(typeId) .writeInt(0)); return; } ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPOutputStream def = new GZIPOutputStream(bos); def.write(messageData); def.flush(); def.close(); byte[] compressedData = bos.toByteArray(); out.add(ByteBufAllocator.DEFAULT.heapBuffer().writeInt(typeId).writeInt(compressedData.length) .writeBytes(compressedData)); }
void print(MessageOrBuilder message) throws IOException { if (typeConverters.containsKey(message.getDescriptorForType().getFullName())) { String msg = typeConverters.get(message.getDescriptorForType().getFullName()).convert(message); generator.print(msg); return; } WellKnownTypePrinter specialPrinter = wellKnownTypePrinters.get(message.getDescriptorForType().getFullName()); if (specialPrinter != null) { specialPrinter.print(this, message); return; } print(message, null); }
/** Prints google.protobuf.Value */ private void printValue(MessageOrBuilder message) throws IOException { // For a Value message, only the value of the field is formatted. Map<FieldDescriptor, Object> fields = message.getAllFields(); if (fields.isEmpty()) { // No value set. generator.print("null"); return; } // A Value message can only have at most one field set (it only contains // an oneof). if (fields.size() != 1) { throw new InvalidProtocolBufferException("Invalid Value type."); } for (Map.Entry<FieldDescriptor, Object> entry : fields.entrySet()) { printSingleFieldValue(entry.getKey(), entry.getValue()); } }
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())); } } }
private void writeAllFields(MessageOrBuilder pb) { //returns changed fields with values. Map is ordered by id. Map<Descriptors.FieldDescriptor, Object> changedPbFields = pb.getAllFields(); for (Map.Entry<Descriptors.FieldDescriptor, Object> entry : changedPbFields.entrySet()) { Descriptors.FieldDescriptor fieldDescriptor = entry.getKey(); if(fieldDescriptor.isExtension()) { // Field index of an extension field might overlap with a base field. throw new UnsupportedOperationException( "Cannot convert Protobuf message with extension field(s)"); } int fieldIndex = fieldDescriptor.getIndex(); fieldWriters[fieldIndex].writeField(entry.getValue()); } }
/** * 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; }
/** * Write the message to file in JSON text format. * <p> * If this fails then an error message is written to the ImageJ log * * @param message * the message * @param file * the file * @param flags * the flags * @return True if written */ public static boolean toJSON(MessageOrBuilder message, File file, int flags) { PrintStream fs = null; try { fs = new PrintStream(file); return toJSON(message, fs, flags); } catch (FileNotFoundException e) { if (BitFlags.anyNotSet(flags, FLAG_SILENT)) IJ.log("Unable to write message: " + e.getMessage()); } finally { if (fs != null) { fs.close(); } } return false; }
protected FieldDescriptor getPropertyFieldDescriptor(final MessageOrBuilder mob, final Object property) { final Descriptor descriptor = mob.getDescriptorForType(); FieldDescriptor field = null; if (property instanceof String) { field = descriptor.findFieldByName(property.toString()); } else if (property instanceof FieldDescriptor) { field = FieldDescriptor.class.cast(property); if (field.getContainingType() != descriptor) { field = null; } } if (field == null) { throw new PropertyNotFoundException(); } return field; }
@Override @Nullable public <T extends Message> T replaceMessage(@Nullable final FieldDescriptor field, final T message, final List<? extends Entry<FieldDescriptor, ? extends MessageOrBuilder>> path) { if (replacers.isEmpty()) { return null; } for (final Replacer replacer : replacers) { final T result = replacer.replaceMessage(field, message, path); if (result != null) { return result; } } return null; }
@Override @Nullable public Object replaceValue(final FieldDescriptor field, final Object value, final List<? extends Entry<FieldDescriptor, ? extends MessageOrBuilder>> path) { if (replacers.isEmpty()) { return null; } for (final Replacer replacer : replacers) { final Object result = replacer.replaceValue(field, value, path); if (result != null) { return result; } } return null; }
@SuppressWarnings("null") private Message getMessage(@Nullable final FieldDescriptor field, final Message message, final Replacer replacer, final LinkedList<Entry<FieldDescriptor, MessageOrBuilder>> path) { final Message result = replacer.replaceMessage(field, message, path); if (result != null) { return result; } path.addFirst(new SimpleImmutableEntry<FieldDescriptor, MessageOrBuilder>(field, message)); final Message.Builder builder = message.newBuilderForType(); for (final Entry<FieldDescriptor, Object> entry : message.getAllFields().entrySet()) { addField(builder, entry.getKey(), entry.getValue(), replacer, path); } path.removeFirst(); return builder.buildPartial(); }
@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)); } }
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; }
@Override public Builder addAllRepeatedField(final Builder builder, final FieldDescriptor field, final Iterable<?> values) { final RepeatedFieldBuilder<Message, Builder, MessageOrBuilder> fieldBuilder = builder.getRepeatedFieldBuilder(field, false); if (fieldBuilder == null) { super.addAllRepeatedField(builder, field, values); } else { @SuppressWarnings("unchecked") final Iterable<? extends Message> verifiedValues = (Iterable<? extends Message>) getVerifiedValue(field, values, null); fieldBuilder.addAllMessages(verifiedValues); } return builder; }
@Override public Builder clearField(final Builder builder, final FieldDescriptor field) { final SingleFieldBuilder<Message, Builder, MessageOrBuilder> fieldBuilder = builder.getSingleFieldBuilder(field, false); if (fieldBuilder == null) { super.clearField(builder, field); } else { final OneofDescriptor oneofDescriptor = field.getContainingOneof(); if (oneofDescriptor != null) { // TODO update the oneof if the original ProtoBuf does so! builder.builders.dispose(field); builder.builder.clearField(field); // or call super.clearField(builder, field); } else { fieldBuilder.clear(); } } return builder; }
private static Object getVerifiedValue(final FieldDescriptor field, final Object value, final Class<? extends MessageOrBuilder> type) { if (field.isRepeated()) { if (value == null) { throw new NullPointerException(); } final Iterable<?> values = Iterable.class.cast(value); final Class<? extends MessageOrBuilder> elementType = type == null ? Message.class : type; final List<Object> result = new ArrayList<Object>(); for (final Object element : values) { result.add(getVerifiedSingleValue(field, element, elementType)); } return result; } else { return getVerifiedSingleValue(field, value, type); } }
private RepeatedFieldBuilder<Message, Builder, MessageOrBuilder> getRepeatedFieldBuilder( final FieldDescriptor field, final boolean newIfNull) { @SuppressWarnings("unchecked") RepeatedFieldBuilder<Message, Builder, MessageOrBuilder> fieldBuilder = (RepeatedFieldBuilder<Message, Builder, MessageOrBuilder>) builders.get(field); if (newIfNull && fieldBuilder == null) { final List<Message> messages = this.<Message>getRepeatedFieldValues(field, false); fieldBuilder = new DynamicRepeatedFieldBuilder(messages, isListMutable(messages), getParentForChildren(), isClean()); builders.put(field, fieldBuilder); builder.clearField(field); } return fieldBuilder; }
private SingleFieldBuilder<Message, Builder, MessageOrBuilder> getSingleFieldBuilder( final FieldDescriptor field, final boolean newIfNull) { @SuppressWarnings("unchecked") SingleFieldBuilder<Message, Builder, MessageOrBuilder> fieldBuilder = (SingleFieldBuilder<Message, Builder, MessageOrBuilder>) builders.get(field); if (newIfNull && fieldBuilder == null) { fieldBuilder = new DynamicSingleFieldBuilder((Message) getSingleFieldValue(field), getParentForChildren(), isClean()); builders.put(field, fieldBuilder); if (field.getContainingOneof() == null) { builder.clearField(field); } else { builder.setField(field, DynamicMessage.getDefaultInstance(field.getMessageType())); } } return fieldBuilder; }
/** * 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); } } } } } }
private boolean collectSingleResult(final List<Message> results, final Descriptor type, final int index, final Object result, final List<? extends Message> originalList) { if (result == null) { return true; } else if (!(result instanceof MessageOrBuilder)) { throw new IllegalArgumentException(String.format( "result of original record #%s is not a MessageOrBuilder", index)); } else if (!validationListener.validate(type, originalList.get(index), (MessageOrBuilder) result)) { throw new IllegalArgumentException(String.format( "result of original record #%s is of the wrong message type", index)); } if (result instanceof Message.Builder) { results.add(((Message.Builder) result).build()); } else if (result instanceof Message) { results.add((Message) result); } return notifyResultAdded(index); }
public static String protoToJson(MessageOrBuilder message) { try { return PRINTER.print(message); } catch (InvalidProtocolBufferException ex) { LOG.warn("get exception: ", ex); return ""; } }
private ByteString toByteString(MessageOrBuilder message) { if (message instanceof Message) { return ((Message) message).toByteString(); } else { return ((Message.Builder) message).build().toByteString(); } }
@Override public String convert(MessageOrBuilder message) throws IOException { IntOrString is = IntOrString.parseFrom(toByteString(message)); if (is.hasStrVal()) return "\"" + is.getStrVal() + "\""; else return ""+is.getIntVal(); }
/** * Converts a protobuf message to JSON format. * * @throws InvalidProtocolBufferException if the message contains Any types * that can't be resolved. * @throws IOException if writing to the output fails. */ public void appendTo(MessageOrBuilder message, Appendable output) throws IOException { // TODO(xiaofeng): Investigate the allocation overhead and optimize for // mobile. new PrinterImpl( registry, includingDefaultValueFields, preservingProtoFieldNames, output, omittingInsignificantWhitespace, customTypeConverters) .print(message); }
/** Prints wrapper types (e.g., google.protobuf.Int32Value) */ private void printWrapper(MessageOrBuilder message) throws IOException { Descriptor descriptor = message.getDescriptorForType(); FieldDescriptor valueField = descriptor.findFieldByName("value"); if (valueField == null) { throw new InvalidProtocolBufferException("Invalid Wrapper type."); } // When formatting wrapper types, we just print its value field instead of // the whole message. printSingleFieldValue(valueField, message.getField(valueField)); }
/** Prints google.protobuf.Struct */ private void printStruct(MessageOrBuilder message) throws IOException { Descriptor descriptor = message.getDescriptorForType(); FieldDescriptor field = descriptor.findFieldByName("fields"); if (field == null) { throw new InvalidProtocolBufferException("Invalid Struct type."); } // Struct is formatted as a map object. printMapFieldValue(field, message.getField(field)); }
/** Prints google.protobuf.ListValue */ private void printListValue(MessageOrBuilder message) throws IOException { Descriptor descriptor = message.getDescriptorForType(); FieldDescriptor field = descriptor.findFieldByName("values"); if (field == null) { throw new InvalidProtocolBufferException("Invalid ListValue type."); } printRepeatedFieldValue(field, message.getField(field)); }