io.vertx.ext.stomp.StompClientConnection Java Examples

The following examples show how to use io.vertx.ext.stomp.StompClientConnection. 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: ReceiverStompClient.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Promise<Void> future) throws Exception {
  StompClient.create(vertx).connect(ar -> {
    if (ar.failed()) {
      future.fail(ar.cause());
      return;
    }
    final StompClientConnection connection = ar.result();
    connection
        .receivedFrameHandler(frame -> System.out.println("Client receiving:\n" + frame))
        .writingFrameHandler(frame -> System.out.println("Client sending:\n" + frame))
        .subscribe("/queue", FRAMES::add, frame -> {
          future.tryComplete();
    });
  });

}
 
Example #2
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized StompClientConnection unsubscribe(String destination, Map<String, String> headers, Handler<AsyncResult<Frame>>
  receiptHandler) {
  Objects.requireNonNull(destination);
  if (headers == null) {
    headers = Headers.create();
  }
  String id = headers.containsKey(Frame.ID) ? headers.get(Frame.ID) : destination;
  headers.put(Frame.ID, id);

  final Optional<Subscription> maybeSubscription = subscriptions.stream()
    .filter(s -> s.id.equals(id)).findFirst();

  if (maybeSubscription.isPresent()) {
    final Subscription subscription = maybeSubscription.get();
    subscriptions.remove(subscription);
    send(new Frame(Frame.Command.UNSUBSCRIBE, headers, null), receiptHandler);
    return this;
  } else {
    throw new IllegalArgumentException("No subscription with id " + id);
  }
}
 
Example #3
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
@Override
public StompClientConnection send(String destination, Map<String, String> headers, Buffer body,
                                  Handler<AsyncResult<Frame>> receiptHandler) {
  // No need for synchronization, no field access, except client (final)
  if (headers == null) {
    headers = new Headers();
  }
  if (destination != null) {
    headers.put(Frame.DESTINATION, destination);
  }
  // At that point, the 'destination' header must be set.
  if (headers.get(Frame.DESTINATION) == null) {
    throw new IllegalArgumentException("The 'destination' header is mandatory : " + headers);
  }

  if (body != null
    && client.options().isAutoComputeContentLength()
    && !headers.containsKey(Frame.CONTENT_LENGTH)) {
    headers.put(Frame.CONTENT_LENGTH, Integer.toString(body.length()));
  }

  Frame frame = new Frame(Frame.Command.SEND, headers, body);
  return send(frame, receiptHandler);
}
 
Example #4
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link StompClientConnectionImpl} instance
 *
 * @param vertx         the vert.x instance
 * @param socket        the underlying TCP socket
 * @param client        the stomp client managing this connection
 * @param resultHandler the result handler to invoke then the connection has been established
 */
public StompClientConnectionImpl(Vertx vertx, NetSocket socket, StompClient client,
                                 Handler<AsyncResult<StompClientConnection>> resultHandler) {
  this.socket = socket;
  this.client = client;
  this.resultHandler = resultHandler;
  this.context = vertx.getOrCreateContext();

  FrameParser parser = new FrameParser();
  parser.handler(this);
  socket.handler(buffer -> {
    lastServerActivity = System.nanoTime();
    parser.handle(buffer);
  })
    .closeHandler(v -> {
      if (!closed && !client.isClosed()) {
        close();
        if (droppedHandler != null) {
          droppedHandler.handle(this);
        }
      }
    });
}
 
Example #5
Source File: InboundEndpointTest.java    From vertx-camel-bridge with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithStomp(TestContext context) throws Exception {
  StompServerHandler serverHandler = StompServerHandler.create(vertx);
  StompServer.create(vertx).handler(serverHandler).listen(context.asyncAssertSuccess(s -> {
    stomp = s;
  }));
  await().atMost(DEFAULT_TIMEOUT).until(() -> stomp != null);

  Async async = context.async();

  Endpoint endpoint = camel.getEndpoint("stomp:queue");

  bridge = CamelBridge.create(vertx, new CamelBridgeOptions(camel)
      .addInboundMapping(fromCamel(endpoint).toVertx("test")));

  vertx.eventBus().consumer("test", message -> {
    // We get a buffer.
    context.assertEquals("hello", message.body().toString());
    async.complete();
  });

  camel.start();
  Async a = context.async();
  bridge.start(context.asyncAssertSuccess(v -> a.complete()));
  a.awaitSuccess(20000);

  AtomicReference<StompClientConnection> clientRef = new AtomicReference<>();
  StompClient.create(vertx).connect(context.asyncAssertSuccess(client -> {
    clientRef.set(client);
    client.send("queue", Buffer.buffer("hello"), context.asyncAssertSuccess(receipt -> {
    }));
  }));

  try {
    async.awaitSuccess(20000);
  } finally {
    clientRef.get().close();
  }
}
 
Example #6
Source File: TxSenderStompClient.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws Exception {
  StompClient.create(vertx).connect(ar -> {
    final StompClientConnection connection = ar.result();
    connection.errorHandler(frame -> System.err.println("Tx Sender has received an ERROR frame : \n" + frame));
    connection.beginTX("my-transaction");
    connection.send("/queue", Headers.create(Frame.TRANSACTION, "my-transaction"), Buffer.buffer("Hello"));
    connection.send("/queue", Headers.create(Frame.TRANSACTION, "my-transaction"), Buffer.buffer("My"));
    connection.send("/queue", Headers.create(Frame.TRANSACTION, "my-transaction"), Buffer.buffer("Name"));
    connection.send("/queue", Headers.create(Frame.TRANSACTION, "my-transaction"), Buffer.buffer("Is"));
    connection.send("/queue", Headers.create(Frame.TRANSACTION, "my-transaction"), Buffer.buffer("Vert.x"));
    connection.commit("my-transaction");
    connection.disconnect();
  });
}
 
Example #7
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
@Override
public StompClientConnection nack(String id, String txId, Handler<AsyncResult<Frame>> receiptHandler) {
  Objects.requireNonNull(id, "A NACK frame must contain the ACK id");
  Objects.requireNonNull(txId);

  Frame toSend = new Frame(Frame.Command.NACK, Headers.create(Frame.ID, id, Frame.TRANSACTION, txId), null);
  send(toSend, receiptHandler);
  return this;
}
 
Example #8
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
@Override
public StompClientConnection ack(String id, String txId, Handler<AsyncResult<Frame>> receiptHandler) {
  Objects.requireNonNull(id, "A ACK frame must contain the ACK id");
  Objects.requireNonNull(txId);

  send(new Frame(Frame.Command.ACK, Headers.create(Frame.ID, id, Frame.TRANSACTION, txId), null), receiptHandler);

  return this;
}
 
Example #9
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
@Override
public StompClientConnection disconnect(Frame frame, Handler<AsyncResult<Frame>> receiptHandler) {
  Objects.requireNonNull(frame);
  send(frame, f -> {
    if (receiptHandler != null) {
      receiptHandler.handle(f);
    }
    // Close once the receipt have been received.
    if (!closed) {
      close();
    }
  });
  return this;
}
 
Example #10
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
@Override
public StompClientConnection beginTX(String id, Map<String, String> headers, Handler<AsyncResult<Frame>> receiptHandler) {
  Objects.requireNonNull(id);
  Objects.requireNonNull(headers);

  return send(new Frame().setCommand(Frame.Command.BEGIN).setTransaction(id), receiptHandler);
}
 
Example #11
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized StompClientConnection subscribe(String destination, Map<String, String> headers, Handler<Frame> handler, Handler<AsyncResult<String>> receiptHandler) {
  Objects.requireNonNull(destination);
  Objects.requireNonNull(handler);

  if (headers == null) {
    headers = Headers.create();
  }

  String id = headers.getOrDefault(Frame.ID, destination);

  final Optional<Subscription> maybeSubscription = subscriptions.stream()
    .filter(s -> s.id.equals(id)).findFirst();

  if (maybeSubscription.isPresent()) {
    throw new IllegalArgumentException("The client is already registered  to " + destination);
  }

  subscriptions.add(new Subscription(destination, id, handler));

  headers.put(Frame.DESTINATION, destination);

  if (!headers.containsKey(Frame.ID)) {
    headers.put(Frame.ID, id);
  }

  Frame frame = new Frame(Frame.Command.SUBSCRIBE, headers, null);
  send(frame, ar -> {
    if (receiptHandler != null) {
      receiptHandler.handle(ar.map(id));
    }
  });

  return this;
}
 
Example #12
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized StompClientConnection send(Frame frame, Handler<AsyncResult<Frame>> receiptHandler) {
  if (receiptHandler != null) {
    String receiptId = UUID.randomUUID().toString();
    frame.addHeader(Frame.RECEIPT, receiptId);
    Promise<Void> promise = Promise.promise();
    promise.future().onComplete(f -> receiptHandler.handle(f.map(frame)));
    pendingReceipts.put(receiptId, promise);
  }
  if (writingHandler != null) {
    writingHandler.handle(frame);
  }
  socket.write(frame.toBuffer(client.options().isTrailingLine()));
  return this;
}
 
Example #13
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Override
public StompClientConnection abort(String id, Map<String, String> headers, Handler<AsyncResult<Frame>> receiptHandler) {
  Objects.requireNonNull(id);
  Objects.requireNonNull(headers);
  return send(new Frame().setCommand(Frame.Command.ABORT).setTransaction(id), receiptHandler);
}
 
Example #14
Source File: StompEventChannel.java    From jstarcraft-core with Apache License 2.0 4 votes vote down vote up
public StompEventChannel(EventMode mode, String name, StompClientConnection session, ContentCodec codec) {
    super(mode, name);
    this.session = session;
    this.codec = codec;
}
 
Example #15
Source File: StompClientImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Override
public StompClient connect(int port, String host, Handler<AsyncResult<StompClientConnection>> resultHandler) {
  return connect(port, host, vertx.createNetClient(options), resultHandler);
}
 
Example #16
Source File: AbstractClientIT.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
/**
 * Same test as the previous one, but using SSL.
 */
@Test
public void testSSLConnection() {
  if (getOptionsWithSSL() == null) {
    // SSL test disabled.
    return;
  }
  AtomicReference<StompClientConnection> receiver = new AtomicReference<>();
  AtomicReference<StompClientConnection> sender = new AtomicReference<>();

  AtomicReference<Frame> frame = new AtomicReference<>();

  // Step 1.
  StompClient client1 = StompClient.create(vertx, getOptionsWithSSL())
      .connect(connection -> {
        if (connection.failed()) {
          connection.cause().printStackTrace();
        } else {
          receiver.set(connection.result());
          connection.result().subscribe(getDestination(), frame::set);
        }
      });
  clients.add(client1);

  await().atMost(10, TimeUnit.SECONDS).until(() -> receiver.get() != null);

  // Step 2.
  StompClient client2 = StompClient.create(vertx, getOptionsWithSSL())
      .connect(connection -> {
        if (connection.failed()) {
          connection.cause().printStackTrace();
        } else {
          sender.set(connection.result());
          connection.result().send(getDestination(), Buffer.buffer("hello from vert.x"));
        }
      });
  clients.add(client2);
  await().atMost(10, TimeUnit.SECONDS).until(() -> sender.get() != null);

  // Step 3.
  await().atMost(10, TimeUnit.SECONDS).until(() -> frame.get() != null);
  assertThat(frame.get().getCommand()).isEqualTo(Frame.Command.MESSAGE);
  assertThat(frame.get().getHeaders())
      .contains(entry("content-length", "17"))
      .containsKeys("destination", "message-id", "subscription");
  assertThat(frame.get().getBodyAsString()).isEqualToIgnoringCase("hello from vert.x");
}
 
Example #17
Source File: AbstractClientIT.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
/**
 * The test is the following:
 * 1. Create a client subscribing to the "box" destination
 * 2. Create another client sending messages to the "box" destination
 * 3. Ensure the the client 1 receives the message.
 */
@Test
public void testRegularConnection() {
  AtomicReference<StompClientConnection> receiver = new AtomicReference<>();
  AtomicReference<StompClientConnection> sender = new AtomicReference<>();

  AtomicReference<Frame> frame = new AtomicReference<>();

  // Step 1.
  StompClient client1 = StompClient.create(vertx, getOptions())
      .connect(connection -> {
        if (connection.failed()) {
          connection.cause().printStackTrace();
        } else {
          receiver.set(connection.result());
          connection.result().subscribe(getDestination(), frame::set);
        }
      });
  clients.add(client1);

  await().atMost(10, TimeUnit.SECONDS).until(() -> receiver.get() != null);

  // Step 2.
  StompClient client2 = StompClient.create(vertx, getOptions())
      .connect(connection -> {
        if (connection.failed()) {
          connection.cause().printStackTrace();
        } else {
          sender.set(connection.result());
          connection.result().send(getDestination(), Buffer.buffer("hello from vert.x"));
        }
      });
  clients.add(client2);
  await().atMost(10, TimeUnit.SECONDS).until(() -> sender.get() != null);

  // Step 3.
  await().atMost(10, TimeUnit.SECONDS).until(() -> frame.get() != null);
  assertThat(frame.get().getCommand()).isEqualTo(Frame.Command.MESSAGE);
  assertThat(frame.get().getHeaders())
      .contains(entry("content-length", "17"))
      .containsKeys("destination", "message-id", "subscription");
  Assertions.assertThat(frame.get().getBodyAsString()).isEqualToIgnoringCase("hello from vert.x");
}
 
Example #18
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
private synchronized void handleConnected(Frame frame) {
  sessionId = frame.getHeader(Frame.SESSION);
  version = frame.getHeader(Frame.VERSION);
  server = frame.getHeader(Frame.SERVER);

  // Compute the heartbeat.
  // Stomp client acts as a client to call the computePingPeriod & computePongPeriod method
  long ping = Frame.Heartbeat.computePingPeriod(
    Frame.Heartbeat.create(client.options().getHeartbeat()),
    Frame.Heartbeat.parse(frame.getHeader(Frame.HEARTBEAT)));
  long pong = Frame.Heartbeat.computePongPeriod(
    Frame.Heartbeat.create(client.options().getHeartbeat()),
    Frame.Heartbeat.parse(frame.getHeader(Frame.HEARTBEAT)));

  if (ping > 0) {
    pinger = client.vertx().setPeriodic(ping, l -> pingHandler.handle(this));
  }
  if (pong > 0) {
    ponger = client.vertx().setPeriodic(pong, l -> {
      long delta = System.nanoTime() - lastServerActivity;
      final long deltaInMs = TimeUnit.MILLISECONDS.convert(delta, TimeUnit.NANOSECONDS);
      if (deltaInMs > pong * 2) {
        LOGGER.error("Disconnecting client " + client + " - no server activity detected in the last " + deltaInMs + " ms.");
        client.vertx().cancelTimer(ponger);

        // Do not send disconnect here, just close the connection.
        // The server will detect the disconnection using its own heartbeat.
        close();

        // Stack confinement, guarded by the parent class monitor lock.
        Handler<StompClientConnection> handler;
        synchronized (StompClientConnectionImpl.this) {
          handler = droppedHandler;
        }

        if (handler != null) {
          handler.handle(this);
        }
      }
    });
  }
  // Switch the exception handler.
  socket.exceptionHandler(this.exceptionHandler);
  connected = true;
  resultHandler.handle(Future.succeededFuture(this));
}
 
Example #19
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized StompClientConnection connectionDroppedHandler(Handler<StompClientConnection> handler) {
  this.droppedHandler = handler;
  return this;
}
 
Example #20
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized StompClientConnection writingFrameHandler(Handler<Frame> handler) {
  this.writingHandler = handler;
  return this;
}
 
Example #21
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized StompClientConnection receivedFrameHandler(Handler<Frame> handler) {
  this.receivedFrameHandler = handler;
  return this;
}
 
Example #22
Source File: StompClientImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Override
public StompClient connect(Handler<AsyncResult<StompClientConnection>> resultHandler) {
  return connect(options.getPort(), options.getHost(), vertx.createNetClient(options), resultHandler);
}
 
Example #23
Source File: StompClientImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Override
public Future<StompClientConnection> connect() {
  Promise<StompClientConnection> promise = Promise.promise();
  connect(promise);
  return promise.future();
}
 
Example #24
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Override
public StompClientConnection nack(String id, Handler<AsyncResult<Frame>> receiptHandler) {
  Objects.requireNonNull(id);
  send(new Frame(Frame.Command.NACK, Headers.create(Frame.ID, id), null), receiptHandler);
  return this;
}
 
Example #25
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Override
public StompClientConnection ack(String id, Handler<AsyncResult<Frame>> receiptHandler) {
  Objects.requireNonNull(id);
  send(new Frame(Frame.Command.ACK, Headers.create(Frame.ID, id), null), receiptHandler);
  return this;
}
 
Example #26
Source File: StompClientImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Override
public StompClient connect(NetClient netClient, Handler<AsyncResult<StompClientConnection>> resultHandler) {
  return connect(options.getPort(), options.getHost(), netClient, resultHandler);
}
 
Example #27
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Override
public StompClientConnection disconnect(Handler<AsyncResult<Frame>> receiptHandler) {
  return disconnect(new Frame().setCommand(Frame.Command.DISCONNECT), receiptHandler);
}
 
Example #28
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Override
public StompClientConnection send(String destination, Buffer body, Handler<AsyncResult<Frame>> receiptHandler) {
  return send(destination, null, body, receiptHandler);
}
 
Example #29
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Override
public StompClientConnection abort(String id, Handler<AsyncResult<Frame>> receiptHandler) {
  return abort(id, new Headers(), receiptHandler);
}
 
Example #30
Source File: StompClientConnectionImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Override
public StompClientConnection commit(String id, Map<String, String> headers, Handler<AsyncResult<Frame>> receiptHandler) {
  Objects.requireNonNull(id);
  Objects.requireNonNull(headers);
  return send(new Frame().setCommand(Frame.Command.COMMIT).setTransaction(id), receiptHandler);
}