Java Code Examples for io.nats.client.Connection#close()

The following examples show how to use io.nats.client.Connection#close() . 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: TLSConnectTests.java    From nats.java with Apache License 2.0 6 votes vote down vote up
@Test(expected=IOException.class)
public void testClientSecureServerNotMismatch() throws Exception {
    Connection nc = null;
    try (NatsTestServer ts = new NatsTestServer()) {
        SSLContext ctx = TestSSLUtils.createTestSSLContext();
        Options options = new Options.Builder().
                            server(ts.getURI()).
                            maxReconnects(0).
                            sslContext(ctx).
                            build();
        try {
            nc = Nats.connect(options);
        } finally {
            if (nc != null) {
                nc.close();
                assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
            }
        }
    }
}
 
Example 2
Source File: TLSConnectTests.java    From nats.java with Apache License 2.0 6 votes vote down vote up
@Test
public void testURISchemeTLSConnection() throws Exception {
    try (NatsTestServer ts = new NatsTestServer("src/test/resources/tlsverify.conf", false)) {
        Options options = new Options.Builder().
                            server("tls://localhost:"+ts.getPort()).
                            sslContext(TestSSLUtils.createTestSSLContext()). // override the custom one
                            maxReconnects(0).
                            build();
        Connection nc = Nats.connect(options);
        try {
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
    }
}
 
Example 3
Source File: TLSConnectTests.java    From nats.java with Apache License 2.0 6 votes vote down vote up
@Test
public void testOpenTLSConnection() throws Exception {
    try (NatsTestServer ts = new NatsTestServer("src/test/resources/tls.conf", false)) {
        Options options = new Options.Builder().
                            server(ts.getURI()).
                            maxReconnects(0).
                            opentls().
                            build();
        Connection nc = Nats.connect(options);
        try {
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
    }
}
 
Example 4
Source File: PubBenchmark.java    From nats.java with Apache License 2.0 6 votes vote down vote up
public void execute(Options connectOptions) throws InterruptedException {
    byte[] payload = createPayload();
    String subject = getSubject();

    try {
        Connection nc = Nats.connect(connectOptions);
        try {
            this.startTiming();
            for(int i = 0; i < this.getMessageCount(); i++) {
                nc.publish(subject, payload);
            }
            try {nc.flush(Duration.ofSeconds(5));}catch(Exception e){}
            this.endTiming();
        } finally {
            nc.close();
        }
    } catch (IOException ex) {
        this.setException(ex);
    }
}
 
Example 5
Source File: TLSConnectTests.java    From nats.java with Apache License 2.0 6 votes vote down vote up
@Test(expected=IOException.class)
public void testDisconnectOnUpgrade() throws Exception {
    Connection nc = null;
    try (NatsTestServer ts = new NatsTestServer("src/test/resources/tlsverify.conf", false)) {
        SSLContext ctx = TestSSLUtils.createTestSSLContext();
        Options options = new Options.Builder().
                            server(ts.getURI()).
                            maxReconnects(0).
                            dataPortType(CloseOnUpgradeAttempt.class.getCanonicalName()).
                            sslContext(ctx).
                            build();
        try {
            nc = Nats.connect(options);
        } finally {
            if (nc != null) {
                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: ReconnectTests.java    From nats.java with Apache License 2.0 6 votes vote down vote up
@Test
public void testURISchemeNoIPTLSConnection() throws Exception {
    //System.setProperty("javax.net.debug", "all");
    TestSSLUtils.setKeystoreSystemParameters();
    try (NatsTestServer ts = new NatsTestServer("src/test/resources/tls_noip.conf", false)) {
        Options options = new Options.Builder().
                            server("tls://localhost:"+ts.getPort()).
                            maxReconnects(0).
                            build();
        Connection nc = Nats.connect(options);
        try {
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
    }
}
 
Example 8
Source File: ConnectionListenerTests.java    From nats.java with Apache License 2.0 6 votes vote down vote up
@Test
public void testExceptionInConnectionListener() throws Exception {
    try (NatsTestServer ts = new NatsTestServer(false)) {
        BadHandler handler = new BadHandler();
        Options options = new Options.Builder().
                            server(ts.getURI()).
                            connectionListener(handler).
                            build();
        Connection nc = Nats.connect(options);
        try {
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
        assertTrue(((NatsConnection)nc).getNatsStatistics().getExceptions() > 0);
    }
}
 
Example 9
Source File: TLSConnectTests.java    From nats.java with Apache License 2.0 6 votes vote down vote up
@Test
public void testVerifiedTLSConnection() throws Exception {
    try (NatsTestServer ts = new NatsTestServer("src/test/resources/tlsverify.conf", false)) {
        SSLContext ctx = TestSSLUtils.createTestSSLContext();
        Options options = new Options.Builder().
                            server(ts.getURI()).
                            maxReconnects(0).
                            sslContext(ctx).
                            build();
        Connection nc = Nats.connect(options);
        try {
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
    }
}
 
Example 10
Source File: TLSConnectTests.java    From nats.java with Apache License 2.0 6 votes vote down vote up
@Test(expected=IOException.class)
public void testClientServerCertMismatch() throws Exception {
    Connection nc = null;
    try (NatsTestServer ts = new NatsTestServer("src/test/resources/tlsverify.conf", false)) {
        SSLContext ctx = TestSSLUtils.createEmptySSLContext();
        Options options = new Options.Builder().
                            server(ts.getURI()).
                            maxReconnects(0).
                            sslContext(ctx).
                            build();
        try {
            nc = Nats.connect(options);
        } finally {
            if (nc != null) {
                nc.close();
                assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
            }
        }
    }
}
 
Example 11
Source File: AuthAndConnectTests.java    From nats.java with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsAuthError() throws IOException, InterruptedException {
    try (NatsTestServer ts = new NatsTestServer(false)) {
        Connection nc = Nats.connect(ts.getURI());
        try {
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());

            NatsConnection nats = (NatsConnection)nc;

            assertTrue(nats.isAuthenticationError("user authentication expired"));
            assertTrue(nats.isAuthenticationError("authorization violation"));
            assertTrue(nats.isAuthenticationError("Authorization Violation"));
            assertFalse(nats.isAuthenticationError("test"));
            assertFalse(nats.isAuthenticationError(""));
            assertFalse(nats.isAuthenticationError(null));
            
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
    }
}
 
Example 12
Source File: ConnectionListenerTests.java    From nats.java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseCount() throws Exception {
    try (NatsTestServer ts = new NatsTestServer(false)) {
        TestHandler handler = new TestHandler();
        Options options = new Options.Builder().
                            server(ts.getURI()).
                            connectionListener(handler).
                            build();
        Connection nc = Nats.connect(options);
        try {
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
            assertEquals(ts.getURI(), nc.getConnectedUrl());
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
            assertNull(nc.getConnectedUrl());
        }
        assertEquals(1, handler.getEventCount(Events.CLOSED));
    }
}
 
Example 13
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 14
Source File: TLSConnectTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testTLSOnReconnect() throws InterruptedException, Exception {
    Connection nc = null;
    TestHandler handler = new TestHandler();
    int port = NatsTestServer.nextPort();
    int newPort = NatsTestServer.nextPort();

    // Use two server ports to avoid port release timing issues
    try {
        try (NatsTestServer ts = new NatsTestServer("src/test/resources/tlsverify.conf", port, false)) {
            SSLContext ctx = TestSSLUtils.createTestSSLContext();
            Options options = new Options.Builder().
                                server(ts.getURI()).
                                server(NatsTestServer.getURIForPort(newPort)).
                                maxReconnects(-1).
                                sslContext(ctx).
                                connectionListener(handler).
                                reconnectWait(Duration.ofMillis(10)).
                                build();
            nc = Nats.connect(options);
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
            assertTrue("Correct data port class", ((NatsConnection)nc).getDataPort() instanceof SocketDataPort);
            handler.prepForStatusChange(Events.DISCONNECTED);
        }

        ReconnectTests.flushAndWait(nc, handler);
        handler.prepForStatusChange(Events.RESUBSCRIBED);

        try (NatsTestServer ts = new NatsTestServer("src/test/resources/tlsverify.conf", newPort, false)) {
            handler.waitForStatusChange(10, TimeUnit.SECONDS);
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
        }
    } finally {
        if (nc != null) {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
    }
}
 
Example 15
Source File: NatsMessageTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test(expected=IllegalArgumentException.class)
public void testCustomMaxControlLine() throws Exception {
    byte[] body = new byte[10];
    String subject = "subject";
    String replyTo = "reply";
    int maxControlLine = 1024;

    while (subject.length() <= maxControlLine) {
        subject = subject + subject;
    }

    try (NatsTestServer ts = new NatsTestServer()) {
        Options options = new Options.Builder().
                    server(ts.getURI()).
                    maxReconnects(0).
                    maxControlLine(maxControlLine).
                    build();
        Connection nc = Nats.connect(options);
        try {
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
            nc.publish(subject, replyTo, body);
            assertFalse(true);
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
    }
}
 
Example 16
Source File: PingTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandlingPing() throws IOException, InterruptedException,ExecutionException {
    CompletableFuture<Boolean> gotPong = new CompletableFuture<>();

    NatsServerProtocolMock.Customizer pingPongCustomizer = (ts, r,w) -> {
        
        System.out.println("*** Mock Server @" + ts.getPort() + " sending PING ...");
        w.write("PING\r\n");
        w.flush();

        String pong = "";
        
        System.out.println("*** Mock Server @" + ts.getPort() + " waiting for PONG ...");
        try {
            pong = r.readLine();
        } catch(Exception e) {
            gotPong.cancel(true);
            return;
        }

        if (pong.startsWith("PONG")) {
            System.out.println("*** Mock Server @" + ts.getPort() + " got PONG ...");
            gotPong.complete(Boolean.TRUE);
        } else {
            System.out.println("*** Mock Server @" + ts.getPort() + " got something else... " + pong);
            gotPong.complete(Boolean.FALSE);
        }
    };

    try (NatsServerProtocolMock ts = new NatsServerProtocolMock(pingPongCustomizer)) {
        Connection  nc = Nats.connect(ts.getURI());
        try {
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
            assertTrue("Got pong.", gotPong.get().booleanValue());
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
    }
}
 
Example 17
Source File: NatsPub.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));

        System.out.println();
        System.out.printf("Sending %s on %s, server is %s\n", message, subject, server);
        System.out.println();
        nc.publish(subject, message.getBytes(StandardCharsets.UTF_8));
        nc.flush(Duration.ofSeconds(5));
        nc.close();

    } catch (Exception exp) {
        exp.printStackTrace();
    }
}
 
Example 18
Source File: Stan.java    From nats.java with Apache License 2.0 4 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 {
        SecureRandom random = new SecureRandom();
        CompletableFuture<Void> latch = new CompletableFuture<>();
        Options options = new Options.Builder().server(server).noReconnect().build();
        Connection nc = Nats.connect(options);

        Dispatcher d = nc.createDispatcher((msg) -> {

            String reply = "";
            boolean exit = false;

            switch (msg.getSubject()) {
            case "stan.time":
                reply = LocalTime.now().toString();
                break;
            case "stan.random":
                reply = String.valueOf(random.nextInt());
                break;
            case "stan.exit":
                if ("confirm".equals(new String(msg.getData(), StandardCharsets.UTF_8))) {
                    reply = "exiting";
                    exit = true;
                } else {
                    reply = "you have to confirm the exit";
                }
                break;
            }

            nc.publish(msg.getReplyTo(), reply.getBytes(StandardCharsets.UTF_8));

            if (exit) {
                try {
                    nc.flush(Duration.ZERO);
                    latch.complete(null);
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
        });
        d.subscribe("stan.time");
        d.subscribe("stan.random");
        d.subscribe("stan.exit");

        nc.flush(Duration.ZERO);

        System.out.println("Stan is listening...");
        latch.get();
        System.out.println("Stan is exiting ...");

        nc.close();

    } catch (Exception exp) {
        exp.printStackTrace();
    }
}
 
Example 19
Source File: NatsDispatch.java    From nats.java with Apache License 2.0 4 votes vote down vote up
public static void main(String args[]) {
    String subject;
    int msgCount;
    String server;

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

    try {
        System.out.println();
        System.out.printf("Trying to connect to %s, and listen to %s for %d messages.\n", server, subject, msgCount);
        System.out.println();

        Connection nc = Nats.connect(ExampleUtils.createExampleOptions(server, true));
        CountDownLatch latch = new CountDownLatch(msgCount); // dispatcher runs callback in another thread
        
        Dispatcher d = nc.createDispatcher((msg) -> {
            System.out.printf("Received message \"%s\" on subject \"%s\"\n", 
                                    new String(msg.getData(), StandardCharsets.UTF_8), 
                                    msg.getSubject());
            latch.countDown();
        });
        d.subscribe(subject);

        nc.flush(Duration.ZERO);

        latch.await();
        nc.close();
        
    } catch (Exception exp) {
        exp.printStackTrace();
    }
}
 
Example 20
Source File: NatsSub.java    From nats.java with Apache License 2.0 4 votes vote down vote up
public static void main(String args[]) {
    String subject;
    int msgCount;
    String server;

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

    try {
        System.out.println();
        System.out.printf("Trying to connect to %s, and listen to %s for %d messages.\n", server, subject, msgCount);
        System.out.println();

        Connection nc = Nats.connect(ExampleUtils.createExampleOptions(server, true));
        Subscription sub = nc.subscribe(subject);
        nc.flush(Duration.ofSeconds(5));

        for(int i=0;i<msgCount;i++) {
            Message msg = sub.nextMessage(Duration.ofHours(1));

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

        nc.close();
        
    } catch (Exception exp) {
        exp.printStackTrace();
    }
}