Java Code Examples for io.nats.client.Dispatcher#unsubscribe()

The following examples show how to use io.nats.client.Dispatcher#unsubscribe() . 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: DispatcherTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test(expected=IllegalStateException.class)
public void testThrowOnUnsubscribeWhenClosed() throws IOException, InterruptedException, TimeoutException {
    try (NatsTestServer ts = new NatsTestServer(false);
                Connection nc = Nats.connect(ts.getURI())) {
        Dispatcher d = nc.createDispatcher((msg) -> {});
        d.subscribe("foo");
        nc.closeDispatcher(d);
        d.unsubscribe("foo");
        assertFalse(true);
    }
}
 
Example 2
Source File: DispatcherTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test(expected=IllegalArgumentException.class)
public void testThrowOnEmptySubjectInUnsub() throws IOException, InterruptedException, TimeoutException {
    try (NatsTestServer ts = new NatsTestServer(false);
                Connection nc = Nats.connect(ts.getURI())) {
        Dispatcher d = nc.createDispatcher((msg) -> {});
        d.unsubscribe("");
        assertFalse(true);
    }
}
 
Example 3
Source File: DispatcherTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test(expected=IllegalStateException.class)
public void testThrowOnUnsubWhenClosed() throws IOException, InterruptedException, TimeoutException {
    try (NatsTestServer ts = new NatsTestServer(false);
                Connection nc = Nats.connect(ts.getURI())) {
        Dispatcher d = nc.createDispatcher((msg) -> {});
        Subscription sub = d.subscribe("subject", (msg) -> {});
        nc.closeDispatcher(d);
        d.unsubscribe(sub);
        assertFalse(true);
    }
}
 
Example 4
Source File: DispatcherTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test(expected=IllegalStateException.class)
public void testThrowOnWrongSubscription() throws IOException, InterruptedException, TimeoutException {
    try (NatsTestServer ts = new NatsTestServer(false);
                Connection nc = Nats.connect(ts.getURI())) {
        Dispatcher d = nc.createDispatcher((msg) -> {});
        Subscription sub2 = nc.subscribe("test");
        d.unsubscribe(sub2);
        assertFalse(true);
    }
}
 
Example 5
Source File: SubscriptionImpl.java    From stan.java with Apache License 2.0 4 votes vote down vote up
@Override
public void close(boolean unsubscribe) throws IOException {
    StreamingConnectionImpl sc;
    String reqSubject;
    Connection nc;
    wLock();
    try {
        sc = this.sc;
        if (sc == null) {
            throw new IllegalStateException(NatsStreaming.ERR_BAD_SUBSCRIPTION);
        }

        Dispatcher d = sc.getDispatcherByName(this.getOptions().getDispatcherName());
        d.unsubscribe(this.inbox);

        this.sc = null;

    } finally {
        wUnlock();
    }

    sc.lock();
    try {
        // Snapshot connection to avoid data race, since the connection may be
        // closing while we try to send the request
        nc = sc.getNatsConnection();
        if (nc == null) {
            throw new IllegalStateException(NatsStreaming.ERR_CONNECTION_CLOSED);
        }

        sc.subMap.remove(this.inbox);
        reqSubject = sc.subCloseRequests;
        if (unsubscribe) {
            reqSubject = sc.unsubRequests;
        }
        if (reqSubject.isEmpty()) {
            throw new IllegalStateException(ERR_NO_SERVER_SUPPORT);
        }
    } finally {
        sc.unlock();
    }

    byte[] bytes;

    UnsubscribeRequest usr = UnsubscribeRequest.newBuilder()
            .setClientID(sc.getClientId()).setSubject(subject).setInbox(ackInbox).build();
    bytes = usr.toByteArray();

    io.nats.client.Message reply;

    try {
        Future<io.nats.client.Message> incoming = nc.request(reqSubject, bytes);
        reply = incoming.get(sc.opts.getConnectTimeout().toMillis(), TimeUnit.MILLISECONDS);
        if (reply == null) {
            if (unsubscribe) {
                throw new IOException(ERR_UNSUB_REQ_TIMEOUT);
            }
            throw new IOException(ERR_CLOSE_REQ_TIMEOUT);
        }
    } catch (TimeoutException|ExecutionException|InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IOException(e);
    }

    SubscriptionResponse response = SubscriptionResponse.parseFrom(reply.getData());
    if (!response.getError().isEmpty()) {
        throw new IOException(PFX + response.getError());
    }
}
 
Example 6
Source File: StreamingConnectionImpl.java    From stan.java with Apache License 2.0 4 votes vote down vote up
@Override
public Subscription subscribe(String subject, String queue, io.nats.streaming.MessageHandler cb,
                              SubscriptionOptions opts) throws IOException,
        InterruptedException, TimeoutException {
    SubscriptionImpl sub;
    io.nats.client.Connection nc;

    if (opts == null) {
        opts = new SubscriptionOptions.Builder().build();
    }
    
    this.lock();
    try {
        if (getNatsConnection() == null) {
            throw new IllegalStateException(NatsStreaming.ERR_CONNECTION_CLOSED);
        }
        sub = createSubscription(subject, queue, cb, this, opts);

        // Register subscription.
        subMap.put(sub.inbox, sub);
        nc = getNatsConnection();
    } finally {
        this.unlock();
    }

    // Hold lock throughout.
    sub.wLock();
    try {
        Dispatcher d = this.getDispatcherByName(opts.getDispatcherName());

        // Listen for actual messages
        d.subscribe(sub.inbox);

        // Create a subscription request
        // FIXME(dlc) add others.
        SubscriptionRequest sr = createSubscriptionRequest(sub);

        Message reply = nc.request(subRequests, sr.toByteArray(), opts.getSubscriptionTimeout());
        
        if (reply == null) {
            d.unsubscribe(sub.inbox);
            throw new IOException(ERR_SUB_REQ_TIMEOUT);
        }

        SubscriptionResponse response;
        try {
            response = SubscriptionResponse.parseFrom(reply.getData());
        } catch (InvalidProtocolBufferException e) {
            d.unsubscribe(sub.inbox);
            throw e;
        }
        if (!response.getError().isEmpty()) {
            d.unsubscribe(sub.inbox);
            throw new IOException(response.getError());
        }
        sub.setAckInbox(response.getAckInbox());
    } finally {
        sub.wUnlock();
    }
    return sub;
}
 
Example 7
Source File: DispatcherTests.java    From nats.java with Apache License 2.0 4 votes vote down vote up
@Test
public void testUnsub() throws IOException, InterruptedException, ExecutionException, TimeoutException {
    try (NatsTestServer ts = new NatsTestServer(false);
            Connection nc = Nats.connect(ts.getURI())) {
        final CompletableFuture<Boolean> phase1 = new CompletableFuture<>();
        final CompletableFuture<Boolean> phase2 = new CompletableFuture<>();
        int msgCount = 10;
        assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());

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

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

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

        phase1.get(5000, TimeUnit.MILLISECONDS);

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

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

        phase2.get(1000, TimeUnit.MILLISECONDS); // make sure we got them

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

        final AtomicInteger count = new AtomicInteger(0);
        Dispatcher d = nc.createDispatcher((msg) -> {});
        Subscription s1 = d.subscribe("subject", (msg) -> { count.incrementAndGet(); });
        Subscription doneSub = d.subscribe("done", (msg) -> { done1.complete(Boolean.TRUE); });
        d.subscribe("subject", (msg) -> { count.incrementAndGet(); });

        nc.flush(Duration.ofSeconds(5)); // wait for the subs 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 the messages to go through

        done1.get(5, TimeUnit.SECONDS);

        assertEquals(msgCount * 2, count.get()); // We should get 2x the messages because we subscribed 2 times.

        count.set(0);
        d.unsubscribe(s1);
        d.unsubscribe(doneSub);
        d.subscribe("done", (msg) -> { done2.complete(Boolean.TRUE); });
        nc.flush(Duration.ofSeconds(5)); // wait for the unsub 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 the messages to go through

        done2.get(5, TimeUnit.SECONDS);

        assertEquals(msgCount, count.get()); // We only have 1 active subscription, so we should only get msgCount.
    }
}