io.vertx.ext.stomp.StompClient Java Examples

The following examples show how to use io.vertx.ext.stomp.StompClient. 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: StompPublisher.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
  System.out.println("Starting publisher");
  client = StompClient.create(vertx, new StompClientOptions(config()));
  client.connect(ar -> {
    if (ar.failed()) {
      System.err.println("Cannot connect to STOMP server");
      ar.cause().printStackTrace();
      return;
    }

    vertx.setPeriodic(5000, l -> ar.result().send("/queue/event", Buffer.buffer("Hello"), frame -> {
      System.out.println("Receipt received");
    }));
  });
}
 
Example #3
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 #4
Source File: StompClientExamples.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
public void example14(Vertx vertx) {
  StompClient.create(vertx)
    .connect()
    .onSuccess(connection -> {

      connection.connectionDroppedHandler(con -> {
        // The connection has been lost
        // You can reconnect or switch to another server.
      });

      connection.send("/queue", Buffer.buffer("Hello"))
        .onSuccess(frame -> System.out.println("Message processed by the server")
        );
    })
    .onFailure(err ->
      System.out.println(
        "Failed to connect to the STOMP server: " + err.toString()));
}
 
Example #5
Source File: StompClientExamples.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
public void example12(Vertx vertx) {
  StompClient.create(vertx)
    .connect()
    .onSuccess(connection -> {
      Map<String, String> headers = new HashMap<>();
      headers.put("transaction", "my-transaction");
      connection.beginTX("my-transaction");
      connection.send("/queue", headers, Buffer.buffer("Hello"));
      connection.send("/queue", headers, Buffer.buffer("World"));
      connection.send("/queue", headers, Buffer.buffer("!!!"));
      connection.commit("my-transaction");
      // OR
      connection.abort("my-transaction");
    })
    .onFailure(err ->
      System.out.println(
        "Failed to connect to the STOMP server: " + err.toString()));
}
 
Example #6
Source File: StompClientExamples.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
public void example9(Vertx vertx) {
  StompClient.create(vertx)
    .connect()
    .onSuccess(connection -> {
      // use the connection
      connection.subscribe("/queue", frame ->
        System.out.println("Just received a frame from /queue : " + frame));

      // ....

      connection.unsubscribe("/queue");
    })
    .onFailure(err ->
      System.out.println(
        "Failed to connect to the STOMP server: " + err.toString()));
}
 
Example #7
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 #8
Source File: TestSendFailure.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleAck(TestContext ctx) {
  Handler<AsyncResult<Frame>> receiptHandler = ctx.asyncAssertFailure();
  client = StompClient.create(vertx);
  client.connect(ctx.asyncAssertSuccess(conn -> {
    conn.send("/queue", Buffer.buffer("Hello"), receiptHandler);
  }));
}
 
Example #9
Source File: SecuredServerConnectionTest.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailedAuthenticationWithClient(TestContext context) {
  Async async = context.async();
  StompClient client = StompClient.create(vertx, new StompClientOptions()
      .setPort(server.actualPort()).setHost("0.0.0.0").setLogin("admin").setPasscode("nope"))
      .errorFrameHandler(frame -> {
        async.complete();
      });
  client.connect(connection -> {
    context.fail("Authentication issue expected");
  });
}
 
Example #10
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 #11
Source File: AbstractClientIT.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() {
  clients.forEach(StompClient::close);
  AsyncLock<Void> lock = new AsyncLock<>();
  vertx.close(lock.handler());
  lock.waitForSuccess();
}
 
Example #12
Source File: StompConsumer.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws Exception {
  System.out.println("Starting client");
  client = StompClient.create(vertx, new StompClientOptions(config()));
  client.connect(ar -> {
    if (ar.failed()) {
      System.err.println("Cannot connect to STOMP server");
      ar.cause().printStackTrace();
      return;
    }
    ar.result().subscribe("/queue/event", frame -> System.out.println("Frame received : " + frame.getBodyAsString()));
  });
}
 
Example #13
Source File: StompClientExamples.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
public void example13(Vertx vertx) {
  StompClient.create(vertx)
    .connect()
    .onSuccess(connection -> {
      connection
        .send("/queue", Buffer.buffer("Hello"))
        .onSuccess(frame ->
          System.out.println("Message processed by the server"));
    })
    .onFailure(err ->
      System.out.println(
        "Failed to connect to the STOMP server: " + err.toString()));
}
 
Example #14
Source File: StompClientExamples.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
public void example11(Vertx vertx) {
  StompClient.create(vertx)
    .connect()
    .onSuccess(connection -> {
      connection.subscribe("/queue", frame -> {
        connection.ack(frame.getAck());
        // OR
        connection.nack(frame.getAck());
      });
    })
    .onFailure(err ->
      System.out.println(
        "Failed to connect to the STOMP server: " + err.toString()));
}
 
Example #15
Source File: StompClientExamples.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
public void example8(Vertx vertx) {
  StompClient.create(vertx)
    .connect()
    .onSuccess(connection -> {
      // use the connection
      connection.subscribe("/queue", frame ->
        System.out.println("Just received a frame from /queue : " + frame));
    })
    .onFailure(err ->
      System.out.println(
        "Failed to connect to the STOMP server: " + err.toString()));
}
 
Example #16
Source File: StompEventChannelTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Before
public void start() throws Exception {
    vertx = Vertx.vertx();
    session = StompClient.create(vertx);
    CountDownLatch latch = new CountDownLatch(1);
    session.connect(61613, "localhost", (connect) -> {
        connection = connect.result();
        latch.countDown();
    });
    latch.await();
}
 
Example #17
Source File: InboundEndpointTest.java    From vertx-camel-bridge with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testWithStompAndJson(TestContext context) throws Exception {
  StompServerHandler serverHandler = StompServerHandler.create(vertx);
  StompServer.create(vertx).handler(serverHandler).listen(ar -> {
    stomp = ar.result();
  });
  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().<Buffer>consumer("test", message -> {
    // We get a buffer.
    JsonObject json = message.body().toJsonObject();
    context.assertEquals("bar", json.getString("foo"));
    async.complete();
  });

  camel.start();
  BridgeHelper.startBlocking(bridge);

  StompClient.create(vertx).connect(connection -> {
    connection.result().send("queue", Buffer.buffer(new JsonObject().put("foo", "bar").encode()));
    connection.result().close();
  });
}
 
Example #18
Source File: StompClientExamples.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
public void example1(Vertx vertx) {
  StompClient.create(vertx)
    .connect()
    .onSuccess(connection -> {
      // use the connection
    })
    .onFailure(err ->
      System.out.println(
        "Failed to connect to the STOMP server: " + err.toString()));
}
 
Example #19
Source File: StompClientExamples.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
public void example2(Vertx vertx) {
  StompClient.create(vertx)
    .connect(61613, "0.0.0.0")
    .onSuccess(connection -> {
      // use the connection
    })
    .onFailure(err ->
      System.out.println(
        "Failed to connect to the STOMP server: " + err.toString()));
}
 
Example #20
Source File: StompClientExamples.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
public void example21(Vertx vertx) {
  StompClient.create(vertx)
    .errorFrameHandler(frame -> {
      // Received the ERROR frame
    })
    .connect(61613, "0.0.0.0")
    .onSuccess(connection -> {
      // use the connection
    })
    .onFailure(err ->
      System.out.println(
        "Failed to connect to the STOMP server: " + err.toString()));
}
 
Example #21
Source File: StompClientExamples.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
public void example3(Vertx vertx) {
  StompClient
    .create(vertx, new StompClientOptions().setHost("localhost").setPort(1234))
    .connect()
    .onSuccess(connection -> {
      // use the connection
    })
    .onFailure(err ->
      System.out.println(
        "Failed to connect to the STOMP server: " + err.toString()));
}
 
Example #22
Source File: StompClientExamples.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
public void example4(Vertx vertx) {
  StompClient client = StompClient
    .create(vertx, new StompClientOptions().setHost("localhost").setPort(1234));

  client
    .connect()
    .onSuccess(connection -> {
      // use the connection
    })
    .onFailure(err ->
      System.out.println(
        "Failed to connect to the STOMP server: " + err.toString()));

  client.close();
}
 
Example #23
Source File: StompClientExamples.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
public void example5(Vertx vertx) {
  StompClient
    .create(vertx, new StompClientOptions().setHost("localhost").setPort(1234))
    .connect()
    .onSuccess(connection -> {
      // use the connection
      connection.disconnect();
    })
    .onFailure(err ->
      System.out.println(
        "Failed to connect to the STOMP server: " + err.toString()));
}
 
Example #24
Source File: StompClientExamples.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
public void example6(Vertx vertx) {
  StompClient
    .create(vertx, new StompClientOptions().setHost("localhost").setPort(1234))
    .connect()
    .onSuccess(connection -> {
      // use the connection
      connection
        .errorHandler(frame ->
          System.out.println("ERROR frame received : " + frame));
    })
    .onFailure(err ->
      System.out.println(
        "Failed to connect to the STOMP server: " + err.toString()));
}
 
Example #25
Source File: StompClientExamples.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
public void example7(Vertx vertx, NetClient netClient) {
  StompClient.create(vertx)
    .connect(netClient)
    .onSuccess(connection -> {
      // use the connection
      connection
        .errorHandler(frame ->
          System.out.println("ERROR frame received : " + frame));
    })
    .onFailure(err ->
      System.out.println(
        "Failed to connect to the STOMP server: " + err.toString()));
}
 
Example #26
Source File: StompClientExamples.java    From vertx-stomp with Apache License 2.0 5 votes vote down vote up
public void example10(Vertx vertx) {
  StompClient.create(vertx)
    .connect()
    .onSuccess(connection -> {
      Map<String, String> headers = new HashMap<>();
      headers.put("header1", "value1");
      connection.send("/queue", headers, Buffer.buffer("Hello"));
      // No headers:
      connection.send("/queue", Buffer.buffer("World"));
    })
    .onFailure(err ->
      System.out.println(
        "Failed to connect to the STOMP server: " + err.toString()));
}
 
Example #27
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 #28
Source File: StompClientImpl.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized StompClient connect(int port, String host, NetClient net, Handler<AsyncResult<StompClientConnection>> resultHandler) {
  if (client != null) {
    client.close();
    client = null;
  }

  Handler<Frame> r = receivedFrameHandler;
  Handler<Frame> w = writingFrameHandler;
  Handler<Throwable> err = exceptionHandler;
  net.connect(port, host, ar -> {
    synchronized (StompClientImpl.this) {
      client = ar.failed() ? null : net;
      if (client != null) {
        ar.result().exceptionHandler(t -> {
          if (resultHandler != null) {
            resultHandler.handle(Future.failedFuture(t));
          } else {
            log.error("Unable to connect to the server", t);
          }
        });
      }
    }

    if (ar.failed()) {
      if (resultHandler != null) {
        resultHandler.handle(Future.failedFuture(ar.cause()));
      } else {
        log.error("Unable to connect to the server", ar.cause());
      }
    } else {
      // Create the connection, the connection attach a handler on the socket.
      StompClientConnection stompClientConnection = new StompClientConnectionImpl(vertx, ar.result(), this, resultHandler)
        .receivedFrameHandler(r)
        .writingFrameHandler(w)
        .exceptionHandler(err)
        .errorHandler(errorFrameHandler);
      // Socket connected - send "CONNECT" Frame
      Frame frame = getConnectFrame(host);

      // If we don't get the CONNECTED timeout in time, fail the connection.
      vertx.setTimer(options.getConnectTimeout(), l -> {
        if (!stompClientConnection.isConnected()) {
          resultHandler.handle(Future.failedFuture("CONNECTED frame not receive in time"));
          stompClientConnection.close();
        }
      });

      if (w != null) {
        w.handle(frame);
      }

      ar.result().write(frame.toBuffer(options.isTrailingLine()));
    }
  });
  return this;
}
 
Example #29
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 #30
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");
}