io.nats.client.Message Java Examples

The following examples show how to use io.nats.client.Message. 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: NatsSubscription.java    From nats.java with Apache License 2.0 6 votes vote down vote up
public Message nextMessage(Duration timeout) throws InterruptedException, IllegalStateException {
    if (this.dispatcher != null) {
        throw new IllegalStateException(
                "Subscriptions that belong to a dispatcher cannot respond to nextMessage directly.");
    } else if (this.incoming == null) {
        throw new IllegalStateException("This subscription is inactive.");
    }

    NatsMessage msg = incoming.pop(timeout);

    if (this.incoming == null || !this.incoming.isRunning()) { // We were unsubscribed while waiting
        throw new IllegalStateException("This subscription became inactive.");
    }

    this.incrementDeliveredCount();

    if (this.reachedUnsubLimit()) {
        this.connection.invalidate(this);
    }

    return msg;
}
 
Example #2
Source File: StreamingConnectionImpl.java    From stan.java with Apache License 2.0 6 votes vote down vote up
/**
 * Receives PING responses from the server.
 * If the response contains an error message, the connection is closed
 * and the connection error callback is invoked (if one is specified).
 * If no error, the number of ping out is reset to 0. There is no
 * decrement by one since for a given PING, the client may received
 * many responses when servers are running in channel partitioning mode.
 * Regardless, any positive response from the server ought to signal
 * that the connection is ok.
 */
void processPing(Message msg) {
    // No data means OK (we don't have to call Unmarshal)
    if (msg.getData() != null && msg.getData().length > 0) {
        try {
            PingResponse pingResp = PingResponse.parseFrom(msg.getData());
            String error = pingResp.getError();
            if (error != null && !error.isEmpty()) {
                closeDueToPing(error);
                return;
            }
        } catch (Exception e) {
            return; // exception here stops us from reseting pings out
        }
    }
    // Do not attempt to decrement, simply reset to 0.
    this.lock();
    this.pingsOut = 0;
    this.unlock();
}
 
Example #3
Source File: NATSTestPlugin.java    From nats-connector-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void onNATSMessage(io.nats.client.Message msg) {

    logger.info("Received message: " + msg.toString());

    msg.setSubject("baz");

    byte[] reply = "reply".getBytes();

    msg.setData(reply, 0, (int) reply.length);

    connector.publish(msg);

    try {
        connector.flush();
        logger.info("Flushed.");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #4
Source File: NatsClientLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenMessageExchange_MessagesReceived() throws Exception {

    NatsClient client = connectClient();

    SyncSubscription fooSubscription = client.subscribeSync("foo.bar");
    SyncSubscription barSubscription = client.subscribeSync("bar.foo");
    client.publishMessage("foo.bar", "bar.foo", "hello there");

    Message message = fooSubscription.nextMessage(200);
    assertNotNull("No message!", message);
    assertEquals("hello there", new String(message.getData()));

    client.publishMessage(message.getReplyTo(), message.getSubject(), "hello back");

    message = barSubscription.nextMessage(200);
    assertNotNull("No message!", message);
    assertEquals("hello back", new String(message.getData()));
}
 
Example #5
Source File: RequestTests.java    From nats.java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequireCleanupOnCancel() throws IOException, ExecutionException, TimeoutException, InterruptedException {
    try (NatsTestServer ts = new NatsTestServer(false)) {
        Options options = new Options.Builder().server(ts.getURI()).requestCleanupInterval(Duration.ofHours(1)).build();
        Connection nc = Nats.connect(options);
        try {
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
            
            Future<Message> incoming = nc.request("subject", null);
            incoming.cancel(true);

            assertEquals(1, ((NatsStatistics)nc.getStatistics()).getOutstandingRequests());
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
    }
}
 
Example #6
Source File: RequestTests.java    From nats.java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequireCleanupOnTimeout() throws IOException, ExecutionException, InterruptedException {
    try (NatsTestServer ts = new NatsTestServer(false)) {
        Options options = new Options.Builder().server(ts.getURI()).requestCleanupInterval(Duration.ofHours(1)).build();
        Connection nc = Nats.connect(options);
        try {
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
            
            Future<Message> incoming = nc.request("subject", null);
            Message msg = null;
            
            try {
                msg = incoming.get(100, TimeUnit.MILLISECONDS);
                assertFalse(true);
            } catch(TimeoutException e) {
                assertTrue(true);
            }

            assertNull(msg);
            assertEquals(1, ((NatsStatistics)nc.getStatistics()).getOutstandingRequests());
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
    }
}
 
Example #7
Source File: NATSTestPlugin.java    From nats-connector-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void onNATSMessage(io.nats.client.Message msg) {

    logger.info("Received message: " + msg.toString());

    msg.setSubject("baz");

    byte[] reply = "reply".getBytes();

    msg.setData(reply, 0, (int) reply.length);

    connector.publish(msg);

    try {
        connector.flush();
        logger.info("Flushed.");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #8
Source File: DrainTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleSubDrain() throws Exception {
    try (NatsTestServer ts = new NatsTestServer(false);
            Connection subCon = Nats.connect(new Options.Builder().server(ts.getURI()).maxReconnects(0).build());
            Connection pubCon = Nats.connect(new Options.Builder().server(ts.getURI()).maxReconnects(0).build())) {
        assertTrue("Connected Status", Connection.Status.CONNECTED == subCon.getStatus());
        assertTrue("Connected Status", Connection.Status.CONNECTED == pubCon.getStatus());

        Subscription sub = subCon.subscribe("draintest");
        subCon.flush(Duration.ofSeconds(1)); // Get the sub to the server

        pubCon.publish("draintest", null);
        pubCon.publish("draintest", null); // publish 2
        pubCon.flush(Duration.ofSeconds(1));

        Message msg = sub.nextMessage(Duration.ofSeconds(1)); // read 1
        assertNotNull(msg);

        subCon.flush(Duration.ofSeconds(1));
        CompletableFuture<Boolean> tracker = sub.drain(Duration.ofSeconds(1));

        msg = sub.nextMessage(Duration.ofSeconds(1)); // read the second one, should be there because we drained
        assertNotNull(msg);

        assertTrue(tracker.get(1, TimeUnit.SECONDS));
        assertFalse(sub.isActive());
        assertEquals(((NatsConnection) subCon).getConsumerCount(), 0);
    }
}
 
Example #9
Source File: StanRandom.java    From nats.java with Apache License 2.0 5 votes vote down vote up
public static void main(String args[]) {
    String server = "help";

    if (args.length == 1) {
        server = args[0];
    } else if (args.length == 0) {
        server = Options.DEFAULT_URL;
    }

    if (server.equals("help")) {
        usage();
        return;
    }

    try {
        
        Options options = new Options.Builder().server(server).noReconnect().build();
        Connection nc = Nats.connect(options);
        Future<Message> replyFuture = nc.request("stan.random", null);
        Message reply = replyFuture.get();

        System.out.printf("The next stan-random number is %s\n", 
                                new String(reply.getData(), StandardCharsets.UTF_8));

        nc.close();

    } catch (Exception exp) {
        exp.printStackTrace();
    }
}
 
Example #10
Source File: StanTime.java    From nats.java with Apache License 2.0 5 votes vote down vote up
public static void main(String args[]) {
    String server = "help";

    if (args.length == 1) {
        server = args[0];
    } else if (args.length == 0) {
        server = Options.DEFAULT_URL;
    }

    if (server.equals("help")) {
        usage();
        return;
    }

    try {
        
        Options options = new Options.Builder().server(server).noReconnect().build();
        Connection nc = Nats.connect(options);
        Future<Message> replyFuture = nc.request("stan.time", null);
        Message reply = replyFuture.get();

        System.out.printf("The time where stan is, is \"%s\"\n", 
                                new String(reply.getData(), StandardCharsets.UTF_8));

        nc.close();

    } catch (Exception exp) {
        exp.printStackTrace();
    }
}
 
Example #11
Source File: NatsConnection.java    From nats.java with Apache License 2.0 5 votes vote down vote up
public Message request(String subject, byte[] body, Duration timeout) throws InterruptedException {
    Message reply = null;
    Future<Message> incoming = this.request(subject, body);
    try {
        reply = incoming.get(timeout.toNanos(), TimeUnit.NANOSECONDS);
    } catch (ExecutionException | TimeoutException e) {
        reply = null;
    }

    return reply;
}
 
Example #12
Source File: DispatcherTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDispatchHandlesExceptionInHandler() throws IOException, InterruptedException, ExecutionException, TimeoutException {
    try (NatsTestServer ts = new NatsTestServer(false);
            Connection nc = Nats.connect(ts.getURI())) {
        final CompletableFuture<Boolean> done = new CompletableFuture<>();
        int msgCount = 100;
        assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());

        final ConcurrentLinkedQueue<Message> q = new ConcurrentLinkedQueue<>();
        Dispatcher d = nc.createDispatcher((msg) -> {
            if (msg.getSubject().equals("done")) {
                done.complete(Boolean.TRUE);
            } else {
                q.add(msg);
                throw new NumberFormatException();
            }
        });

        d.subscribe("subject");
        d.subscribe("done");
        nc.flush(Duration.ofMillis(500));// Get them all to the server

        for (int i = 0; i < msgCount; i++) {
            nc.publish("subject", new byte[16]);
        }
        nc.publish("done", new byte[16]);

        nc.flush(Duration.ofMillis(1000)); // wait for them to go through
        done.get(200, TimeUnit.MILLISECONDS);

        assertEquals(msgCount, q.size());
    }
}
 
Example #13
Source File: NatsConnection.java    From nats.java with Apache License 2.0 5 votes vote down vote up
void deliverReply(Message msg) {
    String subject = msg.getSubject();
    String token = getResponseToken(subject);
    CompletableFuture<Message> f = null;

    f = responses.remove(token);

    if (f != null) {
        statistics.decrementOutstandingRequests();
        f.complete(msg);
        statistics.incrementRepliesReceived();
    }
}
 
Example #14
Source File: SlowConsumerTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultPendingLimits() throws Exception {
    try (NatsTestServer ts = new NatsTestServer(false);
            NatsConnection nc = (NatsConnection) Nats.connect(ts.getURI())) {
        
        Subscription sub = nc.subscribe("subject");
        Dispatcher d = nc.createDispatcher((Message m) -> {});

        assertEquals(sub.getPendingMessageLimit(), Consumer.DEFAULT_MAX_MESSAGES);
        assertEquals(sub.getPendingByteLimit(), Consumer.DEFAULT_MAX_BYTES);

        assertEquals(d.getPendingMessageLimit(), Consumer.DEFAULT_MAX_MESSAGES);
        assertEquals(d.getPendingByteLimit(), Consumer.DEFAULT_MAX_BYTES);
    }
}
 
Example #15
Source File: NatsReq.java    From nats.java with Apache License 2.0 5 votes vote down vote up
public static void main(String args[]) {
    String subject;
    String message;
    String server;

    if (args.length == 3) {
        server = args[0];
        subject = args[1];
        message = args[2];
    } else if (args.length == 2) {
        server = Options.DEFAULT_URL;
        subject = args[0];
        message = args[1];
    } else {
        usage();
        return;
    }

    try {
        Connection nc = Nats.connect(ExampleUtils.createExampleOptions(server, false));
        Future<Message> replyFuture = nc.request(subject, message.getBytes(StandardCharsets.UTF_8));
        Message reply = replyFuture.get(5, TimeUnit.SECONDS);

        System.out.println();
        System.out.printf("Received reply \"%s\" on subject \"%s\"\n", 
                                new String(reply.getData(), StandardCharsets.UTF_8), 
                                reply.getSubject());
        System.out.println();

        nc.close();

    } catch (Exception exp) {
        exp.printStackTrace();
    }
}
 
Example #16
Source File: DrainTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDrainWithZeroTimeout() throws Exception {
    try (NatsTestServer ts = new NatsTestServer(false);
            Connection subCon = Nats.connect(new Options.Builder().server(ts.getURI()).maxReconnects(0).build());
            Connection pubCon = Nats.connect(new Options.Builder().server(ts.getURI()).maxReconnects(0).build())) {
        assertTrue("Connected Status", Connection.Status.CONNECTED == subCon.getStatus());
        assertTrue("Connected Status", Connection.Status.CONNECTED == pubCon.getStatus());

        Subscription sub = subCon.subscribe("draintest");
        subCon.flush(Duration.ofSeconds(1)); // Get the sub to the server

        pubCon.publish("draintest", null);
        pubCon.publish("draintest", null); // publish 2
        pubCon.flush(Duration.ofSeconds(1));

        Message msg = sub.nextMessage(Duration.ofSeconds(1)); // read 1
        assertNotNull(msg);

        subCon.flush(Duration.ofSeconds(1));
        CompletableFuture<Boolean> tracker = sub.drain(Duration.ZERO);

        msg = sub.nextMessage(Duration.ofSeconds(1)); // read the second one, should be there because we drained
        assertNotNull(msg);

        assertTrue(tracker.get(1, TimeUnit.SECONDS));
        assertFalse(sub.isActive());
    }
}
 
Example #17
Source File: RequestTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testCleanupTimerWorks() throws IOException, ExecutionException, TimeoutException, InterruptedException {
    try (NatsTestServer ts = new NatsTestServer(false)) {
        long cleanupInterval = 50;
        Options options = new Options.Builder().server(ts.getURI()).requestCleanupInterval(Duration.ofMillis(cleanupInterval)).build();
        Connection nc = Nats.connect(options);
        try {
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
            
            Future<Message> incoming = nc.request("subject", null);
            incoming.cancel(true);
            incoming = nc.request("subject", null);
            incoming.cancel(true);
            incoming = nc.request("subject", null);
            incoming.cancel(true);

            Thread.sleep(2 * cleanupInterval);
            assertEquals(0, ((NatsStatistics)nc.getStatistics()).getOutstandingRequests());

            // Make sure it is still running
            incoming = nc.request("subject", null);
            incoming.cancel(true);
            incoming = nc.request("subject", null);
            incoming.cancel(true);
            incoming = nc.request("subject", null);
            incoming.cancel(true);

            Thread.sleep(2 * cleanupInterval);
            assertEquals(0, ((NatsStatistics)nc.getStatistics()).getOutstandingRequests());
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
    }
}
 
Example #18
Source File: DispatcherTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiMessage() throws IOException, InterruptedException, ExecutionException, TimeoutException {
    try (NatsTestServer ts = new NatsTestServer(false);
            Connection nc = Nats.connect(ts.getURI())) {
        final CompletableFuture<Boolean> done = new CompletableFuture<>();
        int msgCount = 100;
        assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());

        final ConcurrentLinkedQueue<Message> q = new ConcurrentLinkedQueue<>();
        Dispatcher d = nc.createDispatcher((msg) -> {
            if (msg.getSubject().equals("done")) {
                done.complete(Boolean.TRUE);
            } else {
                q.add(msg);
            }
        });

        d.subscribe("subject");
        d.subscribe("done");
        nc.flush(Duration.ofMillis(1000)); // wait for them to go through

        for (int i = 0; i < msgCount; i++) {
            nc.publish("subject", new byte[16]);
        }
        nc.publish("done", new byte[16]);
        nc.flush(Duration.ofMillis(1000)); // wait for them to go through

        done.get(500, TimeUnit.MILLISECONDS);

        assertEquals(msgCount, q.size());
    }
}
 
Example #19
Source File: DispatcherTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAutoUnsubFromCallback()
        throws IOException, InterruptedException, ExecutionException, TimeoutException {
    try (NatsTestServer ts = new NatsTestServer(false);
            Connection nc = Nats.connect(ts.getURI())) {
        final CompletableFuture<Boolean> done = new CompletableFuture<>();
        assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());

        final AtomicReference<Dispatcher> dispatcher = new AtomicReference<>();
        final ConcurrentLinkedQueue<Message> q = new ConcurrentLinkedQueue<>();
        final Dispatcher d = nc.createDispatcher((msg) -> {
            if (msg.getSubject().equals("done")) {
                done.complete(Boolean.TRUE);
            } else {
                q.add(msg);
                dispatcher.get().unsubscribe("subject", 2); // get 1 more, for a total of 2
            }
        });

        dispatcher.set(d);

        d.subscribe("subject");
        d.subscribe("done");
        nc.flush(Duration.ofMillis(1000));// Get them all to the server

        nc.publish("subject", new byte[16]);
        nc.publish("subject", new byte[16]);
        nc.publish("subject", new byte[16]);
        nc.publish("done", new byte[16]); // when we get this we know the others are dispatched
        nc.flush(Duration.ofMillis(1000)); // Wait for the publish

        done.get(200, TimeUnit.MILLISECONDS); // make sure we got them

        assertEquals(2, q.size());
    }
}
 
Example #20
Source File: DispatcherTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsubFromCallback() throws IOException, InterruptedException, ExecutionException, TimeoutException {
    try (NatsTestServer ts = new NatsTestServer(false);
            Connection nc = Nats.connect(ts.getURI())) {
        final CompletableFuture<Boolean> done = new CompletableFuture<>();
        assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());

        final AtomicReference<Dispatcher> dispatcher = new AtomicReference<>();
        final ConcurrentLinkedQueue<Message> q = new ConcurrentLinkedQueue<>();
        final Dispatcher d = nc.createDispatcher((msg) -> {
            if (msg.getSubject().equals("done")) {
                done.complete(Boolean.TRUE);
            } else {
                q.add(msg);
                dispatcher.get().unsubscribe("subject");
            }
        });

        dispatcher.set(d);

        d.subscribe("subject");
        d.subscribe("done");
        nc.flush(Duration.ofMillis(500));// Get them all to the server

        nc.publish("subject", new byte[16]);
        nc.publish("subject", new byte[16]);
        nc.publish("done", new byte[16]); // when we get this we know the others are dispatched
        nc.flush(Duration.ofMillis(1000)); // Wait for the publish, or we will get multiples for sure
        done.get(200, TimeUnit.MILLISECONDS); // make sure we got them

        assertEquals(1, q.size());
    }
}
 
Example #21
Source File: StanExit.java    From nats.java with Apache License 2.0 5 votes vote down vote up
public static void main(String args[]) {
    String server = "help";

    if (args.length == 1) {
        server = args[0];
    } else if (args.length == 0) {
        server = Options.DEFAULT_URL;
    }

    if (server.equals("help")) {
        usage();
        return;
    }

    try {
        
        Options options = new Options.Builder().server(server).noReconnect().build();
        Connection nc = Nats.connect(options);
        Future<Message> replyFuture = nc.request("stan.exit", null);
        Message reply = replyFuture.get();

        System.out.printf("I asked stan to exit without confirmation, he replied \"%s\"\n", 
                                new String(reply.getData(), StandardCharsets.UTF_8));

        replyFuture = nc.request("stan.exit", "confirm".getBytes(StandardCharsets.UTF_8));
        reply = replyFuture.get();

        System.out.printf("I asked stan to exit with confirmation, he replied \"%s\"\n", 
                                new String(reply.getData(), StandardCharsets.UTF_8));

        nc.close();

    } catch (Exception exp) {
        exp.printStackTrace();
    }
}
 
Example #22
Source File: DispatcherTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoubleSubscribe() throws IOException, InterruptedException, ExecutionException, TimeoutException {
    try (NatsTestServer ts = new NatsTestServer(false);
                Connection nc = Nats.connect(ts.getURI())) {
        final CompletableFuture<Boolean> done = new CompletableFuture<>();
        int msgCount = 100;
        assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());

        final ConcurrentLinkedQueue<Message> q = new ConcurrentLinkedQueue<>();
        Dispatcher d = nc.createDispatcher((msg) -> {
            if (msg.getSubject().equals("done")) {
                done.complete(Boolean.TRUE);
            } else {
                q.add(msg);
            }
        });

        d.subscribe("subject").subscribe("subject").subscribe("subject").subscribe("done");
        nc.flush(Duration.ofSeconds(5)); // wait for them to go through

        for (int i = 0; i < msgCount; i++) {
            nc.publish("subject", new byte[16]);
        }
        nc.publish("done", new byte[16]);
        nc.flush(Duration.ofSeconds(5)); // wait for them to go through

        done.get(5, TimeUnit.SECONDS);

        assertEquals(msgCount, q.size()); // Shoudl only get one since all the extra subs do nothing??
    }
}
 
Example #23
Source File: ErrorListenerTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDiscardedMessageFastProducer() throws Exception {
    int maxMessages = 10;
    TestHandler handler = new TestHandler();
    try (NatsTestServer ts = new NatsTestServer()) {
        Options options = new Options.Builder().
                server(ts.getURI()).
                maxMessagesInOutgoingQueue(maxMessages).
                discardMessagesWhenOutgoingQueueFull().
                errorListener(handler).
                pingInterval(Duration.ofSeconds(100)). // make this long so we don't ping during test
                build();
        NatsConnection nc = (NatsConnection) Nats.connect(options);

        try {
            nc.flush(Duration.ofSeconds(2));

            nc.getWriter().stop().get(2, TimeUnit.SECONDS);
            for (int i = 0; i < maxMessages + 1; i++) {
                nc.publish("subject" + i, ("message" + i).getBytes());
            }
            nc.getWriter().start(nc.getDataPortFuture());

            nc.flush(Duration.ofSeconds(2));
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
    }

    List<Message> discardedMessages = handler.getDiscardedMessages();
    assertEquals(1, discardedMessages.size());
    assertEquals("subject10", discardedMessages.get(0).getSubject());
    assertEquals("message10", new String(discardedMessages.get(0).getData()));
}
 
Example #24
Source File: NATSTestPlugin.java    From nats-connector-framework with Apache License 2.0 5 votes vote down vote up
private void testConnectorAPIs() throws Exception {
    MessageHandler mh = new MessageHandler() {
        @Override
        public void onMessage(Message message) {
            ;;
        }
    };

    // test various combinatitions of subscribes and unsubscribes.
    connector.subscribe("foo1");
    connector.subscribe("foo1");

    connector.subscribe("foo2", mh);
    connector.subscribe("foo2", mh);

    connector.subscribe("foo3", "qg1");
    connector.subscribe("foo3", "qg1");

    connector.subscribe("foo4", "qg1", mh);
    connector.unsubscribe("foo1");
    connector.unsubscribe("foo2");
    connector.unsubscribe("foo3");

    connector.unsubscribe("foo4");
    connector.unsubscribe("foo4");

    connector.unsubscribe("unknown");
    connector.unsubscribe(null);

    connector.flush();

    Connection c = connector.getConnection();
    if (c == null)
        throw new Exception("Expected a valid connection.");

    ConnectionFactory cf = connector.getConnectionFactory();
    if (cf == null)
        throw new Exception("Expected a valid connection.");
}
 
Example #25
Source File: ErrorListenerTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDiscardedMessageServerClosed() throws Exception {
    int maxMessages = 10;
    TestHandler handler = new TestHandler();
    try (NatsTestServer ts = new NatsTestServer(false)) {
        Options options = new Options.Builder().
                server(ts.getURI()).
                maxMessagesInOutgoingQueue(maxMessages).
                discardMessagesWhenOutgoingQueueFull().
                pingInterval(Duration.ofSeconds(100)). // make this long so we don't ping during test
                connectionListener(handler).
                errorListener(handler).
                build();
        Connection nc = Nats.connect(options);
        assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
        try {
            nc.flush(Duration.ofSeconds(1)); // Get the sub to the server

            handler.prepForStatusChange(Events.DISCONNECTED);
            ts.close();
            handler.waitForStatusChange(2, TimeUnit.SECONDS); // make sure the connection is down

            for (int i = 0; i < maxMessages + 1; i++) {
                nc.publish("subject" + i, ("message" + i).getBytes());
            }
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
    }

    List<Message> discardedMessages = handler.getDiscardedMessages();
    assertTrue("At least one message discarded", discardedMessages.size() >= 1);
    assertTrue("Message subject", discardedMessages.get(0).getSubject().startsWith("subject"));
    assertTrue("Message data", new String(discardedMessages.get(0).getData()).startsWith("message"));
}
 
Example #26
Source File: DataFlowHandler.java    From nats-connector-framework with Apache License 2.0 5 votes vote down vote up
public void publish(Message msg) {
    if (isRunning.get() == false)
        return;

    try {
        connection.publish(msg);
    } catch (Exception ex) {
        logger.error("Exception publishing: " + ex.getMessage());
        logger.debug("Exception: " + ex);
    }

}
 
Example #27
Source File: DataFlowHandler.java    From nats-connector-framework with Apache License 2.0 5 votes vote down vote up
public void onMessage(Message m) {
    try {
        plugin.onNATSMessage(m);
    } catch (Exception e) {
        logger.error("Runtime exception thrown by plugin (onMessage): ", e);
    }
}
 
Example #28
Source File: NATSTestPlugin.java    From nats-connector-framework with Apache License 2.0 5 votes vote down vote up
private void testConnectorAPIs() throws Exception {
    MessageHandler mh = new MessageHandler() {
        @Override
        public void onMessage(Message message) {
            ;;
        }
    };

    // test various combinatitions of subscribes and unsubscribes.
    connector.subscribe("foo1");
    connector.subscribe("foo1");

    connector.subscribe("foo2", mh);
    connector.subscribe("foo2", mh);

    connector.subscribe("foo3", "qg1");
    connector.subscribe("foo3", "qg1");

    connector.subscribe("foo4", "qg1", mh);
    connector.unsubscribe("foo1");
    connector.unsubscribe("foo2");
    connector.unsubscribe("foo3");

    connector.unsubscribe("foo4");
    connector.unsubscribe("foo4");

    connector.unsubscribe("unknown");
    connector.unsubscribe(null);

    connector.flush();

    Connection c = connector.getConnection();
    if (c == null)
        throw new Exception("Expected a valid connection.");

    ConnectionFactory cf = connector.getConnectionFactory();
    if (cf == null)
        throw new Exception("Expected a valid connection.");
}
 
Example #29
Source File: NatsClient.java    From tutorials with MIT License 5 votes vote down vote up
Message makeRequest(String topic, String request) {
    try {
        return natsConnection.request(topic, request.getBytes(), 100);
    } catch (IOException | InterruptedException ioe) {
        log.error("Error making request {} to {} ", topic, request, ioe);
        return null;
    }
}
 
Example #30
Source File: DataFlowHandler.java    From nats-connector-framework with Apache License 2.0 5 votes vote down vote up
public void publish(Message msg) {
    if (isRunning.get() == false)
        return;

    try {
        connection.publish(msg);
    } catch (Exception ex) {
        logger.error("Exception publishing: " + ex.getMessage());
        logger.debug("Exception: " + ex);
    }

}