Example usage for com.rabbitmq.client Channel queueUnbind

List of usage examples for com.rabbitmq.client Channel queueUnbind

Introduction

In this page you can find the example usage for com.rabbitmq.client Channel queueUnbind.

Prototype

Queue.UnbindOk queueUnbind(String queue, String exchange, String routingKey) throws IOException;

Source Link

Document

Unbinds a queue from an exchange, with no extra arguments.

Usage

From source file:mobisocial.musubi.service.AMQPService.java

License:Apache License

void attachToQueues() throws IOException {
    Log.i(TAG, "Setting up identity exchange and device queue");

    DefaultConsumer consumer = new DefaultConsumer(mIncomingChannel) {
        @Override//www .j a  v  a2  s . c  om
        public void handleDelivery(final String consumerTag, final Envelope envelope,
                final BasicProperties properties, final byte[] body) throws IOException {
            if (DBG)
                Log.i(TAG, "recevied message: " + envelope.getExchange());
            assert (body != null);
            //TODO: throttle if we have too many incoming?
            //TODO: check blacklist up front?
            //TODO: check hash up front?
            MEncodedMessage encoded = new MEncodedMessage();
            encoded.encoded_ = body;
            mEncodedMessageManager.insertEncoded(encoded);
            getContentResolver().notifyChange(MusubiService.ENCODED_RECEIVED, null);

            //we have to do this in our AMQP thread, or add synchronization logic
            //for all of the AMQP related fields.
            mAMQPHandler.post(new Runnable() {
                public void run() {
                    if (mIncomingChannel == null) {
                        //it can close in this time window
                        return;
                    }
                    try {
                        mIncomingChannel.basicAck(envelope.getDeliveryTag(), false);
                        if (mFailedOperation == FailedOperationType.FailedReceive) {
                            mFailureDelay = MIN_DELAY;
                            mFailedOperation = FailedOperationType.FailedNone;
                        }
                    } catch (Throwable e) {
                        Log.e(TAG, "failed to ack message on AMQP", e);
                        //next connection that receives a packet wins
                        closeConnection(FailedOperationType.FailedReceive);
                    }

                }
            });
        }
    };
    byte[] device_name = new byte[8];
    ByteBuffer.wrap(device_name).putLong(mDeviceManager.getLocalDeviceName());
    String device_queue_name = encodeAMQPname("ibedevice-", device_name);
    //leaving these since they mark the beginning of the connection and shouldn't be too frequent (once per drop)
    Log.v(TAG, "queueDeclare " + device_queue_name);
    mIncomingChannel.queueDeclare(device_queue_name, true, false, false, null);
    //TODO: device_queue_name needs to involve the identities some how? or be a larger byte array
    List<MIdentity> mine = mIdentitiesManager.getOwnedIdentities();
    for (MIdentity me : mine) {
        IBHashedIdentity id = IdentitiesManager.toIBHashedIdentity(me, 0);
        String identity_exchange_name = encodeAMQPname("ibeidentity-", id.identity_);
        Log.v(TAG, "exchangeDeclare " + identity_exchange_name);
        mIncomingChannel.exchangeDeclare(identity_exchange_name, "fanout", true);
        Log.v(TAG, "queueBind " + device_queue_name + " " + identity_exchange_name);
        mIncomingChannel.queueBind(device_queue_name, identity_exchange_name, "");
        try {
            Log.v(TAG, "queueDeclarePassive " + "initial-" + identity_exchange_name);
            Channel incoming_initial = mConnection.createChannel();
            incoming_initial.queueDeclarePassive("initial-" + identity_exchange_name);
            try {
                Log.v(TAG, "queueUnbind " + "initial-" + identity_exchange_name + " " + identity_exchange_name);
                //   we now have claimed our identity, unbind this queue
                incoming_initial.queueUnbind("initial-" + identity_exchange_name, identity_exchange_name, "");
                //but also drain it
            } catch (IOException e) {
            }
            Log.v(TAG, "basicConsume " + "initial-" + identity_exchange_name);
            mIncomingChannel.basicConsume("initial-" + identity_exchange_name, consumer);
        } catch (IOException e) {
            //no one sent up messages before we joined
            //IF we deleted it: we already claimed our identity, so we ate this queue up
        }
    }

    Log.v(TAG, "basicConsume " + device_queue_name);
    mIncomingChannel.basicConsume(device_queue_name, false, "", true, true, null, consumer);
}

From source file:org.apache.airavata.gfac.monitor.impl.push.amqp.AMQPMonitor.java

License:Apache License

@Subscribe
public boolean unRegisterListener(MonitorID monitorID) throws AiravataMonitorException {
    Iterator<MonitorID> iterator = finishQueue.iterator();
    MonitorID next = null;//from  www . j av a 2s .  c  o  m
    while (iterator.hasNext()) {
        next = iterator.next();
        if (next.getJobID().endsWith(monitorID.getJobID())) {
            break;
        }
    }
    if (next == null) {
        logger.error("Job has removed from the queue, old obsolete message recieved");
        return false;
    }
    String channelID = CommonUtils.getChannelID(next);
    if (JobState.FAILED.equals(monitorID.getStatus()) || JobState.COMPLETE.equals(monitorID.getStatus())) {
        finishQueue.remove(next);

        // if this is the last job in the queue at this point with the same username and same host we
        // close the channel and close the connection and remove it from availableChannels
        if (CommonUtils.isTheLastJobInQueue(finishQueue, next)) {
            logger.info("There are no jobs to monitor for common ChannelID:" + channelID
                    + " , so we unsubscribe it" + ", incase new job created we do subscribe again");
            Channel channel = availableChannels.get(channelID);
            if (channel == null) {
                logger.error("Already Unregistered the listener");
                throw new AiravataMonitorException("Already Unregistered the listener");
            } else {
                try {
                    channel.queueUnbind(channel.queueDeclare().getQueue(), "glue2.computing_activity",
                            CommonUtils.getRoutingKey(next));
                    channel.close();
                    channel.getConnection().close();
                    availableChannels.remove(channelID);
                } catch (IOException e) {
                    logger.error("Error unregistering the listener");
                    throw new AiravataMonitorException("Error unregistering the listener");
                }
            }
        }
    }
    next.setStatus(monitorID.getStatus());
    JobIdentifier jobIdentity = new JobIdentifier(next.getJobID(), next.getTaskID(), next.getWorkflowNodeID(),
            next.getExperimentID(), next.getJobExecutionContext().getGatewayID());
    publisher.publish(new JobStatusChangeEvent(next.getStatus(), jobIdentity));
    return true;
}

From source file:org.apache.airavata.gfac.monitor.impl.push.amqp.UnRegisterWorker.java

License:Apache License

@Subscribe
private boolean unRegisterListener(JobStatusChangeEvent jobStatus, MonitorID monitorID)
        throws AiravataMonitorException {
    String channelID = CommonUtils.getChannelID(monitorID);
    if (JobState.FAILED.equals(jobStatus.getState()) || JobState.COMPLETE.equals(jobStatus.getState())) {
        Channel channel = availableChannels.get(channelID);
        if (channel == null) {
            logger.error("Already Unregistered the listener");
            throw new AiravataMonitorException("Already Unregistered the listener");
        } else {//  w w  w. java 2  s . co  m
            try {
                channel.queueUnbind(channel.queueDeclare().getQueue(), "glue2.computing_activity",
                        CommonUtils.getRoutingKey(monitorID));
                channel.close();
                channel.getConnection().close();
                availableChannels.remove(channelID);
            } catch (IOException e) {
                logger.error("Error unregistering the listener");
                throw new AiravataMonitorException("Error unregistering the listener");
            }
        }
    }
    return true;
}

From source file:org.smartdeveloperhub.harvesters.it.notification.CollectorControllerTest.java

License:Apache License

@SuppressWarnings("unchecked")
@Test/*from   w  w  w.  j a v  a  2s .co m*/
public void testDisconnect$ignoreCleanerFailures(@Mocked final Channel channel,
        @Mocked final Queue.DeclareOk ok) throws Exception {
    new MockUp<ConnectionManager>() {
        private boolean connected = false;

        @Mock(invocations = 1)
        void connect() {
            this.connected = true;
        }

        @Mock(invocations = 1)
        void disconnect() {
        }

        @Mock
        boolean isConnected() {
            return this.connected;
        }

        @Mock
        Channel channel() {
            return channel;
        }
    };
    final CollectorConfiguration defaultCollector = defaultCollector();
    final CollectorController sut = collectorController(defaultCollector);
    new Expectations() {
        {
            channel.queueDeclare((String) this.any, true, true, true, (Map<String, Object>) this.any);
            this.result = ok;
            ok.getQueue();
            this.result = "actualQueueName";
            channel.basicConsume("actualQueueName", false, (Consumer) this.any);
            channel.queueUnbind("actualQueueName", defaultCollector.getExchangeName(), (String) this.any);
            this.result = new IOException("failure");
        }
    };
    sut.connect();
    sut.disconnect();
}

From source file:org.smartdeveloperhub.harvesters.scm.backend.notification.CollectorControllerTest.java

License:Apache License

@SuppressWarnings("unchecked")
@Test/*w  w w .j  a v  a 2  s . c o  m*/
public void testDisconnect$ignoreCleanerFailures(@Mocked final Channel channel,
        @Mocked final Queue.DeclareOk ok) throws Exception {
    new MockUp<ConnectionManager>() {
        private boolean connected = false;

        @Mock(invocations = 1)
        void connect() {
            this.connected = true;
        }

        @Mock(invocations = 1)
        void disconnect() {
        }

        @Mock
        boolean isConnected() {
            return this.connected;
        }

        @Mock
        Channel channel() {
            return channel;
        }
    };
    final Collector defaultCollector = defaultCollector();
    final CollectorController sut = collectorController(defaultCollector);
    new Expectations() {
        {
            channel.queueDeclare((String) this.any, true, true, true, (Map<String, Object>) this.any);
            this.result = ok;
            ok.getQueue();
            this.result = "actualQueueName";
            channel.basicConsume("actualQueueName", false, (Consumer) this.any);
            channel.queueUnbind("actualQueueName", defaultCollector.getExchangeName(), (String) this.any);
            this.result = new IOException("failure");
        }
    };
    sut.connect();
    sut.disconnect();
}

From source file:rabbitirc.RabbitIRC.java

public static void main(String[] argv) throws java.io.IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Random rnd = new Random();
    int indeks = rnd.nextInt(usernamelist.length);
    String Randusername = usernamelist[indeks] + rnd.nextInt(100);

    user = Randusername;/*from www .j  a  va 2  s  .c  o m*/
    channellist.add("lounge");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    String queueName = channel.queueDeclare().getQueue();
    channel.exchangeDeclare(EXCHANGE_NAME, "direct");

    Scanner sc = new Scanner(System.in);

    channel.queueBind(queueName, EXCHANGE_NAME, "lounge");
    channellist.add("lounge");
    Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received :'" + message + "'");
        }
    };
    System.out.println(" Welcome " + user + " to Channel lounge");
    System.out.println(" Queries: ");
    System.out.println(" 1. /NICK <Username>            : Change username ");
    System.out.println(" 2. /JOIN <Channel Name>        : Join Channel");
    System.out.println(" 3. @<Channel Name> <Message>   : Send message to Spesific Channel");
    System.out.println(" 4. /LEAVE <Channel Name>       : Leave Channel");
    System.out.println(" 5. <Random text>               : BroadCast");
    System.out.println(" 6. /EXIT                       : Exit App");
    while (true) {
        channel.basicConsume(queueName, true, consumer);
        String input = sc.nextLine();
        String[] query;
        if ((query = CommandRegexes.NICK.match(input)) != null) {
            String Nickname = query[0];
            user = Nickname;
            System.out.println(" [x] Your Nickname '" + Nickname + "'");

        } else if ((query = CommandRegexes.JOIN.match(input)) != null) {
            String channel_name = query[0];
            channel.queueBind(queueName, EXCHANGE_NAME, channel_name);
            channellist.add(channel_name);
            System.out.println(" [x] you had Join '" + channel_name + "'");

        } else if ((query = CommandRegexes.LEAVE.match(input)) != null) {
            String channel_name = query[0];
            if (channellist.contains(channel_name)) {
                channellist.remove(channellist.indexOf(channel_name));
                channel.queueUnbind(queueName, EXCHANGE_NAME, channel_name);
                System.out.println(" [x] you had leave '" + channel_name);
            } else {
                System.out.println(" [x] you're not in the channel " + channel_name);
            }
            System.out.println(" [x] you had leave '" + channel_name + "'");

        } else if (CommandRegexes.EXIT.match(input) != null) {
            channel.close();
            connection.close();
            break;

        } else if ((query = CommandRegexes.MESSAGE_CHANNEL.match(input)) != null) {
            String channel_name = query[0];
            if (channellist.contains(channel_name)) {
                String message = "[" + channel_name + "] (" + user + ") " + query[1];
                channel.basicPublish(EXCHANGE_NAME, channel_name, null, message.getBytes());
                System.out.println(" [x] Sent '" + message + "'");
                System.out.println(" : to '" + channel_name + "'");
            } else {
                System.out.println(" [x] No Channel " + channel_name + " on your list");
            }
        } else {
            System.out.println(" [x] Broadcasting '" + input + "'");
            for (String channellist1 : channellist) {
                String messages = "[" + channellist1 + "] (" + user + ") " + input;
                channel.basicPublish(EXCHANGE_NAME, channellist1, null, messages.getBytes());
            }
            System.out.println(" [x] OK ;D");
        }
    }

}

From source file:user.Client.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("rabbitmq.akhfa.me");
    factory.setUsername(username);//from  w  w w . j  a va2s  .  c o  m
    factory.setPassword(password);
    factory.setVirtualHost("pat");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    ArrayList<String> daftarNick = getAllQueues();

    String nick = "";

    while (true) {
        Scanner in = new Scanner(System.in);

        System.out.print("Please enter your command: ");
        String command = in.nextLine();

        String[] com = command.split(" ", 2);
        try {
            switch (com[0]) {
            case "/NICK":
                if (!nick.equals("")) {
                    System.out.println("You have registered with nickname: " + nick);
                } else {
                    if (!daftarNick.contains(com[1])) {
                        channel.queueDeclare(com[1], false, false, true, null);
                        nick = com[1];
                        System.out.println("Your nickname is " + nick);

                        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

                        Consumer consumer = new DefaultConsumer(channel) {
                            @Override
                            public void handleDelivery(String consumerTag, Envelope envelope,
                                    AMQP.BasicProperties properties, byte[] body) throws IOException {
                                String message = new String(body, "UTF-8");
                                filterChannel(message);
                            }
                        };
                        channel.basicConsume(nick, true, consumer);
                    } else {
                        System.out.println("Nickname exists.");
                    }
                }
                break;
            case "/JOIN":
                channel.exchangeDeclare(com[1], "fanout", false, false, false, null);
                channel.queueBind(nick, com[1], "");
                System.out.println("You have successfully join " + com[1]);
                break;
            case "/LEAVE":
                channel.queueUnbind(nick, com[1], "");
                System.out.println("Leave " + com[1]);
                break;
            case "/EXIT":
                System.out.println("bye bye...  :D");
                System.exit(0);
            default:
                String message = nick + ' ' + command;
                channel.basicPublish(com[0].substring(1), "", null, message.getBytes("UTF-8"));
                break;
            }
        } catch (Exception e) {
            if (command.compareTo("/NICK") == 0) {
                //random nick
                String random;

                if (!nick.equals("")) {
                    System.out.println("You have registered with nickname: " + nick);
                } else {
                    do {
                        random = randomNick();
                    } while (daftarNick.contains(random));

                    nick = random;

                    channel.queueDeclare(random, false, false, true, null);
                    System.out.println("Your nickname is " + random);

                    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

                    Consumer consumer = new DefaultConsumer(channel) {
                        @Override
                        public void handleDelivery(String consumerTag, Envelope envelope,
                                AMQP.BasicProperties properties, byte[] body) throws IOException {
                            String message = new String(body, "UTF-8");
                            filterChannel(message);
                        }
                    };
                    channel.basicConsume(nick, true, consumer);
                }

            } else if ((command.compareTo("/JOIN") == 0) || (command.compareTo("/LEAVE") == 0)) {
                //error
                System.out.println("Please enter channel name!");
            } else if (command.charAt(0) == '@') {
                System.out.println("Please enter your command for the channel.");
            } else {
                System.out.println("Invalid command.");
            }
        }
    }
}