/** * A metadata marshaller that encodes objects as protobuf according to their proto IDL specification. * * @param clazz the type to serialize * @param <T> */ public static <T extends GeneratedMessageV3> Metadata.BinaryMarshaller<T> PROTOBUF_MARSHALLER(Class<T> clazz) { try { Method defaultInstance = clazz.getMethod("getDefaultInstance"); GeneratedMessageV3 instance = (GeneratedMessageV3) defaultInstance.invoke(null); return new Metadata.BinaryMarshaller<T>() { @Override public byte[] toBytes(T value) { return value.toByteArray(); } @SuppressWarnings("unchecked") @Override public T parseBytes(byte[] serialized) { try { return (T) instance.getParserForType().parseFrom(serialized); } catch (InvalidProtocolBufferException ipbe) { throw new IllegalArgumentException(ipbe); } } }; } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) { throw new IllegalStateException(ex); } }
private static ImmutableList<GeneratedMessageV3> generateEvents() { final ProjectId ALPHA = projectId("alpha"); final Task task1 = newTask(ALPHA, "Annotate internal API", "Use @Internal annotation."); final TaskId taskId1 = task1.getId(); return ImmutableList.of( ProjectCreated.newBuilder().setProject(newProject(ALPHA.getCode(), "Alpha", "Initial public release.")).build(), TaskCreated.newBuilder().setTask(task1).build(), TaskAssigned.newBuilder() .setTaskId(taskId1) .setAssignee(randomSelectUser()).build(), TaskCreated.newBuilder().setTask(newTask(ALPHA, "Check code coverage", "")).build(), TaskCreated.newBuilder().setTask(newTask(ALPHA, "Verify JavaDocs", "")).build(), TaskDone.newBuilder().setTaskId(taskId1).build(), TaskCreated.newBuilder().setTask(newTask(ALPHA, "Blog post", "Announce the release at the blog.")).build() ); }
public static void main(String[] args) throws InterruptedException, IOException { final EventPublisher publisher = new EventPublisher(PORT); try { for (GeneratedMessageV3 message : events) { // Simulate event id generation. final EventId eventId = Events.generateId(); // Simulate `EventContext` creation. Normally version, and aggregate ID will be set by // the framework code when new instance of `EventContext` is generated. final EventContext context = EventContext.newBuilder() .setEventId(eventId) .build(); final Event record = Events.createEvent(message, context); publisher.publish(record); } } finally { publisher.awaitTermination(); } }
public DiozeroProtos.Response sendMessage(String topic, String correlationId, GeneratedMessageV3 message) throws MqttException { Condition condition = lock.newCondition(); conditions.put(correlationId, condition); lock.lock(); try { mqttClient.publish(topic, message.toByteArray(), MqttProviderConstants.DEFAULT_QOS, MqttProviderConstants.DEFAULT_RETAINED); Logger.info("Waiting for response..."); condition.await(TIMEOUT_MS, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Logger.error(e, "Interrupted: {}", e); } finally { lock.unlock(); } DiozeroProtos.Response response = responses.remove(correlationId); if (response == null) { throw new RuntimeIOException("Cannot find response message for " + correlationId); } return response; }
public List<String> getGeneratedProtoClasses(String serviceName) { FastClasspathScanner cpScanner = new FastClasspathScanner(); ScanResult scanResult = cpScanner.scan(); List<String> oldProtobuf = scanResult.getNamesOfSubclassesOf(GeneratedMessage.class); List<String> newProtobuf = scanResult.getNamesOfSubclassesOf(GeneratedMessageV3.class); List<String> retval = Stream.concat(oldProtobuf.stream(), newProtobuf.stream()).collect(Collectors.toList()); String[] packageTokens = serviceName.split("\\."); return retval.stream().filter(s -> protoFilePackageMatches(s, packageTokens)).collect(Collectors.toList()); }
public static final Class<? extends GeneratedMessageV3> getProtobufClassFromPojoAnno( Class<?> clazz) { final ProtobufEntity annotation = getProtobufEntity(clazz); final Class<? extends GeneratedMessageV3> gpbClazz = (Class<? extends GeneratedMessageV3>) annotation.value(); if (gpbClazz == null) { return null; } return gpbClazz; }
public static void write(GeneratedMessageV3 msg, OutputStream out, byte[] hlen) throws IOException { final int tam = msg.getSerializedSize(); hlen[0] = (byte)((tam & 0xff00) >> 8); hlen[1] = (byte)(tam & 0xff); out.write(hlen); msg.writeTo(out); out.flush(); }
@Override protected void sendMessage(String url, GeneratedMessageV3 message) throws IOException { DiozeroProtos.MessageWrapper message_wrapper = DiozeroProtos.MessageWrapper.newBuilder() .setType(message.getClass().getSimpleName()).setMessage(ByteString.copyFrom(message.toByteArray())) .build(); session.getRemote().sendBytes(ByteBuffer.wrap(message_wrapper.toByteArray())); }
private InvalidEntityStateException(String messageText, Message entityState, Error error) { super(messageText); this.entityState = entityState instanceof GeneratedMessageV3 ? (GeneratedMessageV3) entityState : AnyPacker.pack(entityState); this.error = error; }
public UnsupportedExternalMessageException(Message externalMessage) { super(); if (externalMessage instanceof GeneratedMessageV3) { this.externalMessage = (GeneratedMessageV3) externalMessage; } else { // This is strange. However, let's preserve the value by packing it. this.externalMessage = AnyPacker.pack(externalMessage); } }
/** * Creates new instance. * * @param target the object which method failed * @param dispatchedMessage the message passed to the method which failed * @param messageContext the context of the message * @param cause the exception thrown by the method */ public HandlerMethodFailedException(Object target, Message dispatchedMessage, Message messageContext, Exception cause) { super(checkNotNull(cause)); this.target = target.toString(); /** All messages we handle are generated, so the cast below is safe. We do not want to accept `GeneratedMessageV3` to avoid the cast in the calling code which uses `Message` as {@linkplain GeneratedMessageV3 advised} by Protobuf authors. */ this.dispatchedMessage = (GeneratedMessageV3) checkNotNull(dispatchedMessage); this.messageContext = (GeneratedMessageV3) checkNotNull(messageContext); }
/** * Creates a new instance. * * @param messageText an error message text * @param eventMessage a related event message * @param error an error occurred */ protected EventException(String messageText, Message eventMessage, Error error) { super(messageText); if (eventMessage instanceof GeneratedMessageV3) { this.eventMessage = (GeneratedMessageV3) eventMessage; } else { // In an unlikely case on encountering a message, which is not `GeneratedMessageV3`, // wrap it into `Any`. this.eventMessage = AnyPacker.pack(eventMessage); } this.error = error; }
@Test public void find_closest_superclass_column_type() { final ColumnTypeRegistry<?> registry = ColumnTypeRegistry.newBuilder() .put(GeneratedMessageV3.class, new GeneratedMessageType()) .put(AbstractMessage.class, new AbstractMessageType()) .build(); final EntityColumn column = mockProperty(Any.class); final ColumnType type = registry.get(column); assertNotNull(type); assertThat(type, instanceOf(GeneratedMessageType.class)); }
@Override public byte[] convertToProtoMessage(Event<?, ?> event) { LinkEvent linkEvent = (LinkEvent) event; if (!linkEventTypeSupported(linkEvent)) { log.error("Unsupported Onos Event {}. There is no matching " + "proto Event type", linkEvent.type().toString()); return null; } return ((GeneratedMessageV3) buildDeviceProtoMessage(linkEvent)).toByteArray(); }
@Override public byte[] convertToProtoMessage(Event<?, ?> event) { DeviceEvent deviceEvent = (DeviceEvent) event; if (!deviceEventTypeSupported(deviceEvent)) { log.error("Unsupported Onos Device Event {}. There is no matching" + "proto Device Event type", deviceEvent.type().toString()); return null; } return ((GeneratedMessageV3) buildDeviceProtoMessage(deviceEvent)).toByteArray(); }
/** * @see com.quancheng.saluki.serializer.IProtobufSerializer#toProtobuf(java.lang.Object) */ @Override @SuppressWarnings({"unchecked", "rawtypes", "unused"}) public Message toProtobuf(Object pojo) throws ProtobufException { try { final Class<?> fromClazz = (Class<?>) pojo.getClass(); final Class<? extends GeneratedMessageV3> protoClazz = ProtobufSerializerUtils.getProtobufClassFromPojoAnno(fromClazz); if (protoClazz == null) { throw new ProtobufAnnotationException( "Doesn't seem like " + fromClazz + " is ProtobufEntity"); } final Map<Field, ProtobufAttribute> protoBufFields = ProtobufSerializerUtils.getAllProtbufFields(fromClazz); if (protoBufFields.isEmpty()) { return null; } final Method newBuilderMethod = protoClazz.getMethod("newBuilder"); final Builder protoObjBuilder = (Builder) newBuilderMethod.invoke(null); for (Entry<Field, ProtobufAttribute> entry : protoBufFields.entrySet()) { final Field field = entry.getKey(); final ProtobufAttribute gpbAnnotation = entry.getValue(); final String fieldName = field.getName(); // 1. Determine validity of value Object value = Pojo2ProtobufHelp.getPojoFieldValue(pojo, gpbAnnotation, field); // If value is null and it is not required, skip, as the default for Protobuf values is null if (value == null) { continue; } // 2. Call recursively if this is a ProtobufEntity value = Pojo2ProtobufHelp.serializeToProtobufEntity(value); // 3. Special recursively if this is a ProtobufEntity if (value instanceof Collection) { value = Pojo2ProtobufHelp.convertCollectionToProtobufs((Collection<Object>) value); if (((Collection) value).isEmpty()) { continue; } } if (value instanceof Map) { value = Pojo2ProtobufHelp.convertMapToProtobufs((Map) value); if (((Map) value).isEmpty()) { continue; } } String setter = ProtobufSerializerUtils.getProtobufSetter(gpbAnnotation, field, value); if (value instanceof Enum) { value = JReflectionUtils.runMethod(value, "getNumber"); setter = setter + "Value"; } Pojo2ProtobufHelp.setProtobufFieldValue(gpbAnnotation, protoObjBuilder, setter, value); } return protoObjBuilder.build(); } catch (Exception e) { throw new ProtobufException( "Could not generate Protobuf object for " + pojo.getClass() + ": " + e, e); } }
@Override protected void sendMessage(String topic, GeneratedMessageV3 message) throws MqttException { mqttClient.publish(topic, message.toByteArray(), MqttProviderConstants.DEFAULT_QOS, MqttProviderConstants.DEFAULT_RETAINED); }
public CassandraMutationError(GeneratedMessageV3 request, Throwable throwable) { this.request = request; this.throwable = throwable; }
private static void checkClass(Class<? extends Message> clazz) { checkNotNull(clazz); // Support only generated protobuf messages checkArgument(GeneratedMessageV3.class.isAssignableFrom(clazz), "Only generated protobuf messages are allowed."); }
@Override public String convertColumnValue(GeneratedMessageV3 fieldValue) { return fieldValue.toString(); }
private TestThrowableMessage(GeneratedMessageV3 message) { super(message); }
public SuccessResponseHandler(Class<? extends GeneratedMessageV3> expectedMessageClass) { this(expectedMessageClass, null); }
public SuccessResponseHandler(Class<? extends GeneratedMessageV3> expectedMessageClass, TestResponseHandler delegate) { this.expectedMessageClass = expectedMessageClass; this.delegate = delegate; }
/** * Creates a new instance. * * @param messageText an error message text * @param request a related actor request * @param error an error occurred */ InvalidRequestException(String messageText, GeneratedMessageV3 request, Error error) { super(messageText); this.request = request; this.error = error; }
protected abstract void sendMessage(String url, GeneratedMessageV3 message) throws Exception;