Example usage for com.rabbitmq.client ShutdownListener ShutdownListener

List of usage examples for com.rabbitmq.client ShutdownListener ShutdownListener

Introduction

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

Prototype

ShutdownListener

Source Link

Usage

From source file:com.vmware.vhadoop.vhm.rabbit.RabbitConnection.java

License:Open Source License

private Channel getChannel() throws IOException {
    synchronized (_channelLock) {
        if (_channel == null || !_channel.isOpen()) {
            _log.fine("Creating new channel");
            _channel = null;/*from ww w .jav a 2s.c  om*/
            Connection connection = getConnection();
            _channel = connection.createChannel();
            _channel.addShutdownListener(new ShutdownListener() {
                @Override
                public void shutdownCompleted(ShutdownSignalException cause) {
                    _log.info("Channel shut down");
                    _log.log(Level.FINE, "{0}", cause.getReason());
                    synchronized (_channelLock) {
                        _channel = null;
                        _queueName = null;
                    }
                    _started = false;
                }
            });
        }

        return _channel;
    }
}

From source file:de.tuberlin.cit.livescale.messaging.endpoints.AMQPEndpoint.java

License:Apache License

/**
 * Sets up a consumer that passes received messages to the
 * {@link MessageEndpointListener}s.//  w  w  w.ja v a 2s .  c om
 */
private void setUpConsumer() throws IOException {
    DefaultConsumer consumer = new DefaultConsumer(this.channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties,
                byte[] body) throws IOException {
            long deliveryTag = envelope.getDeliveryTag();
            super.getChannel().basicAck(deliveryTag, false);
            if (!properties.getAppId().equals(AMQPEndpoint.this.uuid.toString())) {
                MessageManifest mm = MessageFactory.decode(body);
                try {
                    URI responseURI = new URIBuilder().routingKey(properties.getReplyTo())
                            .instanceName(getName()).build();
                    mm.setResponseURI(responseURI);
                } catch (URISyntaxException e) { // this should never happen!
                    LOG.warn("Unable to create response URI for incoming message", e);
                }
                notifyMessageEndpointListeners(mm);
            }
        }
    };
    if (this.listenForTasks) {
        String queueName = QUEUE_NAME_TASKS + this.routingKey;
        this.channel.basicConsume(queueName, false, consumer);
    }
    this.channel.basicConsume(this.exclusiveQueueName, false, consumer);

    // listening to the remote shutdown
    ShutdownListener shutdownListener = new ShutdownListener() {
        @Override
        public void shutdownCompleted(ShutdownSignalException cause) {
            shutdown();
        }
    };
    this.channel.addShutdownListener(shutdownListener);
    //      if (this.channel.isOpen()) {
    //         handler.handleConnectionEvent(true);
    //      }
}

From source file:edu.iu.messaging.service.core.impl.RabbitMQPublisher.java

License:Apache License

private void connect() {
    try {/* w  w w. j  a va2  s .c  om*/
        logger.info("connect() -> Connecting to server");
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(properties.getBrokerUrl());
        connectionFactory.setAutomaticRecoveryEnabled(properties.isAutoRecoveryEnable());
        connection = connectionFactory.newConnection();
        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
            }
        });

        channel = connection.createChannel();

        /*
        Not required for work queue implementation
         */
        //channel.basicQos(properties.getPrefetchCount());
        //channel.exchangeDeclare(properties.getExchangeName(), properties.getExchangeType(), true);

    } catch (Exception e) {
        logger.error("connect() -> Error connecting to server.", e);
    }

}

From source file:edu.iu.messaging.service.core.impl.RabbitMQSubscriber.java

License:Apache License

private void addShutdownListener() {
    connection.addShutdownListener(new ShutdownListener() {
        public void shutdownCompleted(ShutdownSignalException cause) {
        }//from  w w w.  j  a  v  a 2s  .  c  om
    });
}

From source file:io.druid.firehose.rabbitmq.RabbitMQFirehoseFactory.java

License:Apache License

@Override
public Firehose connect(StringInputRowParser firehoseParser) throws IOException {
    final StringInputRowParser stringParser = firehoseParser;

    ConnectionOptions lyraOptions = new ConnectionOptions(this.connectionFactory);
    Config lyraConfig = new Config().withRecoveryPolicy(new RetryPolicy().withMaxRetries(config.getMaxRetries())
            .withRetryInterval(Duration.seconds(config.getRetryIntervalSeconds()))
            .withMaxDuration(Duration.seconds(config.getMaxDurationSeconds())));

    String queue = config.getQueue();
    String exchange = config.getExchange();
    String routingKey = config.getRoutingKey();

    boolean durable = config.isDurable();
    boolean exclusive = config.isExclusive();
    boolean autoDelete = config.isAutoDelete();

    final Connection connection = Connections.create(lyraOptions, lyraConfig);

    connection.addShutdownListener(new ShutdownListener() {
        @Override//from www . j  a va  2  s .c om
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Connection closed!");
        }
    });

    final Channel channel = connection.createChannel();
    channel.queueDeclare(queue, durable, exclusive, autoDelete, null);
    channel.queueBind(queue, exchange, routingKey);
    channel.addShutdownListener(new ShutdownListener() {
        @Override
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Channel closed!");
        }
    });

    // We create a QueueingConsumer that will not auto-acknowledge messages since that
    // happens on commit().
    final QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);

    return new Firehose() {
        /**
         * Storing the latest delivery as a member variable should be safe since this will only be run
         * by a single thread.
         */
        private Delivery delivery;

        /**
         * Store the latest delivery tag to be able to commit (acknowledge) the message delivery up to
         * and including this tag. See commit() for more detail.
         */
        private long lastDeliveryTag;

        @Override
        public boolean hasMore() {
            delivery = null;
            try {
                // Wait for the next delivery. This will block until something is available.
                delivery = consumer.nextDelivery();
                if (delivery != null) {
                    lastDeliveryTag = delivery.getEnvelope().getDeliveryTag();
                    // If delivery is non-null, we report that there is something more to process.
                    return true;
                }
            } catch (InterruptedException e) {
                // A little unclear on how we should handle this.

                // At any rate, we're in an unknown state now so let's log something and return false.
                log.wtf(e, "Got interrupted while waiting for next delivery. Doubt this should ever happen.");
            }

            // This means that delivery is null or we caught the exception above so we report that we have
            // nothing more to process.
            return false;
        }

        @Override
        public InputRow nextRow() {
            if (delivery == null) {
                //Just making sure.
                log.wtf("I have nothing in delivery. Method hasMore() should have returned false.");
                return null;
            }

            return stringParser.parse(StringUtils.fromUtf8(delivery.getBody()));
        }

        @Override
        public Runnable commit() {
            // This method will be called from the same thread that calls the other methods of
            // this Firehose. However, the returned Runnable will be called by a different thread.
            //
            // It should be (thread) safe to copy the lastDeliveryTag like we do below and then
            // acknowledge values up to and including that value.
            return new Runnable() {
                // Store (copy) the last delivery tag to "become" thread safe.
                final long deliveryTag = lastDeliveryTag;

                @Override
                public void run() {
                    try {
                        log.info("Acknowledging delivery of messages up to tag: " + deliveryTag);

                        // Acknowledge all messages up to and including the stored delivery tag.
                        channel.basicAck(deliveryTag, true);
                    } catch (IOException e) {
                        log.error(e, "Unable to acknowledge message reception to message queue.");
                    }
                }
            };
        }

        @Override
        public void close() throws IOException {
            log.info("Closing connection to RabbitMQ");
            channel.close();
            connection.close();
        }
    };
}

From source file:io.druid.segment.realtime.firehose.RabbitMQFirehoseFactory.java

License:Open Source License

@Override
public Firehose connect() throws IOException {
    String queue = config.getQueue();
    String exchange = config.getExchange();
    String routingKey = config.getRoutingKey();

    boolean durable = config.isDurable();
    boolean exclusive = config.isExclusive();
    boolean autoDelete = config.isAutoDelete();

    final Connection connection = connectionFactory.newConnection();
    connection.addShutdownListener(new ShutdownListener() {
        @Override/*  w w w  . ja v  a 2  s . com*/
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Connection closed!");
            //FUTURE: we could try to re-establish the connection here. Not done in this version though.
        }
    });

    final Channel channel = connection.createChannel();
    channel.queueDeclare(queue, durable, exclusive, autoDelete, null);
    channel.queueBind(queue, exchange, routingKey);
    channel.addShutdownListener(new ShutdownListener() {
        @Override
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Channel closed!");
            //FUTURE: we could try to re-establish the connection here. Not done in this version though.
        }
    });

    // We create a QueueingConsumer that will not auto-acknowledge messages since that
    // happens on commit().
    final QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);

    return new Firehose() {
        /**
         * Storing the latest delivery as a member variable should be safe since this will only be run
         * by a single thread.
         */
        private QueueingConsumer.Delivery delivery;

        /**
         * Store the latest delivery tag to be able to commit (acknowledge) the message delivery up to
         * and including this tag. See commit() for more detail.
         */
        private long lastDeliveryTag;

        @Override
        public boolean hasMore() {
            delivery = null;
            try {
                // Wait for the next delivery. This will block until something is available.
                delivery = consumer.nextDelivery();
                if (delivery != null) {
                    lastDeliveryTag = delivery.getEnvelope().getDeliveryTag();
                    // If delivery is non-null, we report that there is something more to process.
                    return true;
                }
            } catch (InterruptedException e) {
                // A little unclear on how we should handle this.

                // At any rate, we're in an unknown state now so let's log something and return false.
                log.wtf(e, "Got interrupted while waiting for next delivery. Doubt this should ever happen.");
            }

            // This means that delivery is null or we caught the exception above so we report that we have
            // nothing more to process.
            return false;
        }

        @Override
        public InputRow nextRow() {
            if (delivery == null) {
                //Just making sure.
                log.wtf("I have nothing in delivery. Method hasMore() should have returned false.");
                return null;
            }

            return parser.parse(new String(delivery.getBody()));
        }

        @Override
        public Runnable commit() {
            // This method will be called from the same thread that calls the other methods of
            // this Firehose. However, the returned Runnable will be called by a different thread.
            //
            // It should be (thread) safe to copy the lastDeliveryTag like we do below and then
            // acknowledge values up to and including that value.
            return new Runnable() {
                // Store (copy) the last delivery tag to "become" thread safe.
                final long deliveryTag = lastDeliveryTag;

                @Override
                public void run() {
                    try {
                        log.info("Acknowledging delivery of messages up to tag: " + deliveryTag);

                        // Acknowledge all messages up to and including the stored delivery tag.
                        channel.basicAck(deliveryTag, true);
                    } catch (IOException e) {
                        log.error(e, "Unable to acknowledge message reception to message queue.");
                    }
                }
            };
        }

        @Override
        public void close() throws IOException {
            log.info("Closing connection to RabbitMQ");
            channel.close();
            connection.close();
        }
    };
}

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

License:Apache License

void initiateConnection() {
    if (mConnection != null) {
        //just for information sake, this is a legitimate event
        Log.i(TAG, "Already connected when triggered to initiate connection");
        return;//from   w  w  w.j  av  a  2 s .  co m
    }
    Log.i(TAG, "Network is up connection is being attempted");
    try {
        mConnection = mConnectionFactory.newConnection();
        mConnection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                if (!cause.isInitiatedByApplication()) {
                    //start the connection
                    mAMQPHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            closeConnection(FailedOperationType.FailedConnect);
                        }
                    });
                }
            }
        });

        mDeclaredGroups = new HashSet<String>();
        mMessageWaitingForAck = new TLongHashSet();
        mMessageWaitingForAckByTag = new TLongLongHashMap();

        mIncomingChannel = mConnection.createChannel();
        mIncomingChannel.basicQos(10);
        attachToQueues();

        mOutgoingChannel = mConnection.createChannel();
        //TODO: these callbacks run in another thread, so this is not correct
        //we need some synchronized or a customized ExecutorService that
        //posts to the handler (though, that may not be possible if they demand
        //n threads to run on
        mOutgoingChannel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                //don't immediately try to resend, just flag it, it will be rescanned later
                //this probably only happens if the server is temporarily out of space
                long encoded_id = mMessageWaitingForAckByTag.get(deliveryTag);
                mMessageWaitingForAckByTag.remove(deliveryTag);
                mMessageWaitingForAck.remove(encoded_id);
            }

            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                //delivered!
                long encoded_id = mMessageWaitingForAckByTag.get(deliveryTag);

                //mark the db entry as processed
                MEncodedMessage encoded = mEncodedMessageManager.lookupMetadataById(encoded_id);
                assert (encoded.outbound_);
                encoded.processed_ = true;
                encoded.processedTime_ = new Date().getTime();
                mEncodedMessageManager.updateEncodedMetadata(encoded);

                mMessageWaitingForAckByTag.remove(deliveryTag);
                mMessageWaitingForAck.remove(encoded_id);

                long feedId = mEncodedMessageManager.getFeedIdForEncoded(encoded_id);
                if (feedId != -1) {
                    Uri feedUri = MusubiContentProvider.uriForItem(Provided.FEEDS_ID, feedId);
                    getContentResolver().notifyChange(feedUri, null);
                }
            }
        });
        mOutgoingChannel.confirmSelect();
        mConnectionReady = true;

        //once we have successfully done our work, we can
        //reset the failure delay, FYI, internal exceptions in the
        //message sender will cause backoff to MAX_DELAY
        if (mFailedOperation == FailedOperationType.FailedConnect) {
            mFailureDelay = MIN_DELAY;
            mFailedOperation = FailedOperationType.FailedNone;
        }
    } catch (Throwable e) {
        closeConnection(FailedOperationType.FailedConnect);
        Log.e(TAG, "Failed to connect to AMQP", e);
    }
    //slight downside here is that if publish a message causes the fault,
    //then we will always reconnect and disconnect
    sendMessages();
}

From source file:mx.bigdata.utils.amqp.ReconnectingPublisher.java

License:Apache License

private boolean initPublisher() {
    try {//from www.  ja  v a  2  s. c  o m
        declaredExchanges.clear();
        String exchName = amqp.getExchangeName(key);
        if (exchName == null || amqp.getExchangeType(key) == null) {
            out = amqp.declareChannel(factory, key, false);
        } else {
            out = amqp.declareChannel(factory, key);
            declaredExchanges.add(exchName);
        }
        out.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException sig) {
                out.getConnection().abort(10000);
                if (!sig.isInitiatedByApplication()) {
                    logger.warn(tag + " ShutdownSignal for tag: " + tag + "\n\t reason: " + sig.getReason()
                            + "\n\t reference: " + sig.getReason() + "\n\t ", sig);
                    reconnect();
                } else {
                    logger.debug(tag + " ShutdownSignal for tag: " + tag + "\n\t reason: " + sig.getReason());
                    out = null;
                }
            }
        });
        logger.info("Publisher " + tag + " initialized");
        return true;
    } catch (Throwable e) {
        logger.error("Exception initializing publisher " + tag + ": ", e);
        if (out != null) {
            out.getConnection().abort(5000);
        }
    }
    return false;
}

From source file:net.lshift.accent.AccentChannel.java

License:Apache License

/**
 * Callback method from ConnectionListener that handles a connection becoming available.
 * @param connection the connection that is available.
 * @throws IOException if an exception occurs setting up the channel within the connection.
 *///from   www  .j  a  v  a2 s. c  o m
public void onConnected(final Connection connection) throws IOException {
    ShutdownListener shutdownListener = new ShutdownListener() {
        @Override
        public void shutdownCompleted(ShutdownSignalException cause) {
            synchronized (channelStateLock) {
                // Release the channel
                channel = null;

                // Inform all listeners that the channel is lost
                for (ChannelListener cb : setupListeners) {
                    cb.channelLost();
                }

                // Request that the connection thread rebuild us when it is ready
                AccentChannel.this.connection.rebuild(AccentChannel.this);
            }
        }
    };

    // Attach a shutdown listener to the connection so if it goes completely, we'll be able to tear down
    // our channel.
    connection.addShutdownListener(shutdownListener);

    synchronized (channelStateLock) {
        channel = connection.createChannel();
        channel.addShutdownListener(shutdownListener);

        // Invoke the setup listeners
        for (ChannelListener cb : setupListeners) {
            cb.channelCreated(channel);
        }

        channelStateLock.notifyAll();
    }
}

From source file:org.apache.airavata.datacat.agent.messageBroker.RabbitMQProducer.java

License:Apache License

private Connection createConnection() throws IOException {
    try {//from w  ww  .  j  a va  2  s .  com
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(url);
        Connection connection = factory.newConnection();

        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
            }
        });
        log.info("connected to rabbitmq: " + connection + " for " + exchangeName);
        return connection;
    } catch (Exception e) {
        log.info("connection failed to rabbitmq: " + connection + " for " + exchangeName);
        return null;
    }
}