Example usage for com.rabbitmq.client ShutdownSignalException getReason

List of usage examples for com.rabbitmq.client ShutdownSignalException getReason

Introduction

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

Prototype

public Method getReason() 

Source Link

Usage

From source file:com.coderdojo.libretalk.MainActivity.java

License:Apache License

@Override
public void onPause() {
    super.onPause(); // Always call the superclass method first
    datasource.close();/*from ww  w  .  j ava2 s .co m*/
    //XXX NETWORKING CODE BEGIN

    if (this.connection.getStatus() == LibretalkConnection.ConnectionStatus.CONNECTED) {
        try {
            this.connection.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ShutdownSignalException sig) {
            Log.w("libretalk::LibretalkConnection", "Caught shutdownSignal while attempting to close Channel:");
            Log.w("libretalk::LibretalkConnection", "\t[== " + sig.getMessage() + "==]");
            Log.w("libretalk::LibretalkConnection", "\tHard Error : " + sig.isHardError());
            Log.w("libretalk::LibretalkConnection", "\tReason     : " + sig.getReason());
        }
    }

    //XXX NETWORKING CODE END
}

From source file:com.netcore.hsmart.dlrconsumers.DlrConsumer1000.java

/**
 * @param args the command line arguments
 * @throws java.lang.Exception//from   w ww.  j  a v  a2 s .  co m
 */
public static void main(String[] args) throws Exception {

    /**
     * Set properties at runtime
     */
    System.setProperty("dlrconsumer_logfile", "557_dlr_consumer.log");
    AppConstants.loadAppConfig();

    final String queueName = AppConstants.getDlrReceiverQueuePrefix() + GATEWAY_ID;
    final String exchangeName = AppConstants.getDlrReceiverExchangeName();
    final String routingKey = GATEWAY_ID;

    Logger logger = LoggerFactory.getLogger(DlrConsumer1000.class);

    try {

        Connection connection = AppConstants.getRabbitMqObject().newConnection();

        connection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                //throw new UnsupportedOperationException("Not supported yet.");
                if (cause.isHardError()) {
                    Connection conn;
                    conn = (Connection) cause.getReference();
                    if (!cause.isInitiatedByApplication()) {
                        Method reason = cause.getReason();
                        logger.info("REASON:" + reason.toString());
                    }

                } else {
                    Channel ch = (Channel) cause.getReference();
                    logger.info("NO HARDSHUTDOWN");
                }
            }
        });

        Channel channel = connection.createChannel();

        channel.exchangeDeclare(exchangeName, "direct");
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
        channel.basicQos(1000);
        //channel.addShutdownListener(listener);
        logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C");

        Consumer consumer;

        consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {

                Map<String, String> dataToPost = new HashMap<>();
                String payload = new String(body, "UTF-8");

                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++");
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload);

                String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator());

                for (String payloadPart : payloadParts) {
                    String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator());

                    //check if any parameter is empty
                    if (s.length == 2) {
                        dataToPost.put(s[0], s[1]);
                    } else {
                        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|EMPTY_PARAM:" + s[0]);
                        dataToPost.put(s[0], null);
                    }
                }

                long deliveryTag = envelope.getDeliveryTag();

                if (invokeApiCall(dataToPost)) {
                    channel.basicAck(deliveryTag, false);

                } else {
                    channel.basicNack(deliveryTag, false, true);
                }

                /**
                 * release memory
                 */
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------");
                dataToPost.clear();
                payloadParts = null;

            }
        };

        String cTag = channel.basicConsume(queueName, false, consumer);
        logger.info("CONSUMER TAG : " + cTag);

    } catch (IOException | TimeoutException e) {
        logger.error("RMQ_ERROR:" + e.getMessage());
    }
}

From source file:com.netcore.hsmart.smsconsumers.SmsConsumer1000.java

/**
 * @param args the command line arguments
 * @throws java.lang.Exception/*from w  w  w .j  ava  2s.c  om*/
 */
public static void main(String[] args) throws Exception {

    /**
     * Set properties at runtime
     */
    System.setProperty("smsconsumer_logfile", GATEWAY_ID + "_sms_consumer.log");
    AppConstants.loadAppConfig();

    final String queueName = AppConstants.getSmsReceiverQueuePrefix() + GATEWAY_ID;
    final String exchangeName = AppConstants.getSmsReceiverExchangeName();
    final String routingKey = GATEWAY_ID;

    Logger logger = LoggerFactory.getLogger(SmsConsumer1000.class);

    try {

        Connection connection = AppConstants.getRabbitMqObject().newConnection();

        connection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                //throw new UnsupportedOperationException("Not supported yet.");
                if (cause.isHardError()) {
                    Connection conn;
                    conn = (Connection) cause.getReference();
                    if (!cause.isInitiatedByApplication()) {
                        Method reason = cause.getReason();
                        logger.info("REASON:" + reason.toString());
                    }

                } else {
                    Channel ch = (Channel) cause.getReference();
                    logger.info("NO HARDSHUTDOWN");
                }
            }
        });

        Channel channel = connection.createChannel();

        channel.exchangeDeclare(exchangeName, "direct");
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
        channel.basicQos(1000);
        //channel.addShutdownListener(listener);
        logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C");

        Consumer consumer;

        consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {

                Map<String, String> dataToPost = new HashMap<>();
                String payload = new String(body, "UTF-8");

                String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator());

                for (String payloadPart : payloadParts) {
                    String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator());
                    dataToPost.put(s[0], s[1]);
                }
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++");
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload);

                long deliveryTag = envelope.getDeliveryTag();

                if (invokeApiCall(dataToPost)) {
                    if (saveRequestData()) {

                        channel.basicAck(deliveryTag, false);
                    } else {
                        channel.basicNack(deliveryTag, false, true);
                    }

                } else {
                    channel.basicNack(deliveryTag, false, true);
                }

                /**
                 * release memory
                 */
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------");
                API_CALL_STATS.clear();
                dataToPost.clear();
                payloadParts = null;

            }
        };

        String cTag = channel.basicConsume(queueName, false, consumer);
        logger.info("CONSUMER TAG : " + cTag);

    } catch (IOException | TimeoutException e) {
        logger.error("RMQ_ERROR:" + e.getMessage());
    }
}

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

License:Open Source License

private Connection getConnection() throws IOException {
    synchronized (_connectionLock) {
        if (_connection == null || !_connection.isOpen()) {
            _connection = null;// w ww  . ja v a2  s .co m
            _connection = _connectionFactory.newConnection();
            _connection.addShutdownListener(new ShutdownListener() {
                @Override
                public void shutdownCompleted(ShutdownSignalException cause) {
                    _log.info("Connection shut down");
                    _log.log(Level.FINE, "{0}", cause.getReason());
                    synchronized (_connectionLock) {
                        _connection = null;
                        _channel = null;
                        _queueName = null;
                    }
                    _started = false;
                }
            });
            _started = true;
            _log.fine("Created new connection");
        }

        return _connection;
    }
}

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;/* ww  w  .  j a v  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:com.vmware.vhadoop.vhm.rabbit.RabbitConnection.java

License:Open Source License

QueueingConsumer getConsumer() throws CannotConnectException {
    synchronized (_consumerLock) {
        if (_consumer == null) {
            _log.fine("Creating new consumer");
            try {
                Channel channel = getChannel();
                _consumer = new QueueingConsumer(channel) {
                    @Override//from  w w w  . j a va  2s  .  c  o m
                    public void handleShutdownSignal(java.lang.String consumerTag,
                            ShutdownSignalException sig) {
                        super.handleShutdownSignal(consumerTag, sig);
                        _log.info("Consumer received shutdown notification");
                        _log.log(Level.FINE, "{0}", sig.getReason());

                        synchronized (_consumerLock) {
                            _consumer = null;
                        }
                    }
                };
                channel.basicConsume(getQueueName(), true, _consumer);
            } catch (Exception e) {
                throw new CannotConnectException("Unable to get message consumer", e);
            }
        }

        return _consumer;
    }
}

From source file:de.htwk_leipzig.bis.connection.handshake.clientRewrite.Copyright.java

License:Mozilla Public License

/**
 * Start up the connection, including the MainLoop thread. Sends the
 * protocol version negotiation header, and runs through
 * Connection.Start/.StartOk, Connection.Tune/.TuneOk, and then calls
 * Connection.Open and waits for the OpenOk. Sets heart-beat and frame max
 * values after tuning has taken place./*w  w  w  . java  2 s . c o  m*/
 * 
 * @throws IOException
 *             if an error is encountered either before, or during, protocol
 *             negotiation; sub-classes
 *             {@link ProtocolVersionMismatchException} and
 *             {@link PossibleAuthenticationFailureException} will be thrown
 *             in the corresponding circumstances.
 *             {@link AuthenticationFailureException} will be thrown if the
 *             broker closes the connection with ACCESS_REFUSED. If an
 *             exception is thrown, connection resources allocated can all
 *             be garbage collected when the connection object is no longer
 *             referenced.
 */
public void start() throws IOException {
    initializeConsumerWorkService();
    initializeHeartbeatSender();
    this._running = true;
    // Make sure that the first thing we do is to send the header,
    // which should cause any socket errors to show up for us, rather
    // than risking them pop out in the MainLoop
    AMQChannel.SimpleBlockingRpcContinuation connStartBlocker = new AMQChannel.SimpleBlockingRpcContinuation();
    // We enqueue an RPC continuation here without sending an RPC
    // request, since the protocol specifies that after sending
    // the version negotiation header, the client (connection
    // initiator) is to wait for a connection.start method to
    // arrive.
    _channel0.enqueueRpc(connStartBlocker);
    try {
        // The following two lines are akin to AMQChannel's
        // transmit() method for this pseudo-RPC.
        _frameHandler.setTimeout(HANDSHAKE_TIMEOUT);
        _frameHandler.sendHeader();
    } catch (IOException ioe) {
        _frameHandler.close();
        throw ioe;
    }

    /*
     * Custom action during handshake
     */
    mHandshakeAction.doAction();

    // start the main loop going
    MainLoop loop = new MainLoop();
    final String name = "AMQP Connection " + getHostAddress() + ":" + getPort();
    mainLoopThread = Environment.newThread(threadFactory, loop, name);
    mainLoopThread.start();
    // after this point clear-up of MainLoop is triggered by closing the
    // frameHandler.

    AMQP.Connection.Start connStart = null;
    AMQP.Connection.Tune connTune = null;
    try {
        connStart = (AMQP.Connection.Start) connStartBlocker.getReply().getMethod();

        /*
         * Custom action during handshake
         */
        mHandshakeAction.doAction();

        _serverProperties = Collections.unmodifiableMap(connStart.getServerProperties());

        Version serverVersion = new Version(connStart.getVersionMajor(), connStart.getVersionMinor());

        if (!Version.checkVersion(clientVersion, serverVersion)) {
            throw new ProtocolVersionMismatchException(clientVersion, serverVersion);
        }

        String[] mechanisms = connStart.getMechanisms().toString().split(" ");
        SaslMechanism sm = this.saslConfig.getSaslMechanism(mechanisms);
        if (sm == null) {
            throw new IOException("No compatible authentication mechanism found - " + "server offered ["
                    + connStart.getMechanisms() + "]");
        }

        LongString challenge = null;
        LongString response = sm.handleChallenge(null, this.username, this.password);

        /*
         * Custom action during handshake
         */
        mHandshakeAction.doAction();

        do {
            Method method = (challenge == null)
                    ? new AMQP.Connection.StartOk.Builder().clientProperties(_clientProperties)
                            .mechanism(sm.getName()).response(response).build()
                    : new AMQP.Connection.SecureOk.Builder().response(response).build();

            /*
             * Custom action during handshake
             */
            mHandshakeAction.doAction();

            try {
                Method serverResponse = _channel0.rpc(method).getMethod();

                /*
                 * Custom action during handshake
                 */
                mHandshakeAction.doAction();

                if (serverResponse instanceof AMQP.Connection.Tune) {
                    connTune = (AMQP.Connection.Tune) serverResponse;
                } else {
                    challenge = ((AMQP.Connection.Secure) serverResponse).getChallenge();
                    response = sm.handleChallenge(challenge, this.username, this.password);
                }
            } catch (ShutdownSignalException e) {
                Method shutdownMethod = e.getReason();
                if (shutdownMethod instanceof AMQP.Connection.Close) {
                    AMQP.Connection.Close shutdownClose = (AMQP.Connection.Close) shutdownMethod;
                    if (shutdownClose.getReplyCode() == AMQP.ACCESS_REFUSED) {
                        throw new AuthenticationFailureException(shutdownClose.getReplyText());
                    }
                }
                throw new PossibleAuthenticationFailureException(e);
            }
        } while (connTune == null);
    } catch (ShutdownSignalException sse) {
        _frameHandler.close();
        throw AMQChannel.wrap(sse);
    } catch (IOException ioe) {
        _frameHandler.close();
        throw ioe;
    }

    try {
        int channelMax = negotiateChannelMax(this.requestedChannelMax, connTune.getChannelMax());
        _channelManager = instantiateChannelManager(channelMax, threadFactory);

        int frameMax = negotiatedMaxValue(this.requestedFrameMax, connTune.getFrameMax());
        this._frameMax = frameMax;

        int heartbeat = negotiatedMaxValue(this.requestedHeartbeat, connTune.getHeartbeat());

        setHeartbeat(heartbeat);

        /*
         * Custom action during handshake
         */
        mHandshakeAction.doAction();

        _channel0.transmit(new AMQP.Connection.TuneOk.Builder().channelMax(channelMax).frameMax(frameMax)
                .heartbeat(heartbeat).build());

        /*
         * Custom action during handshake
         */
        mHandshakeAction.doAction();

        _channel0.exnWrappingRpc(new AMQP.Connection.Open.Builder().virtualHost(_virtualHost).build());
    } catch (IOException ioe) {
        _heartbeatSender.shutdown();
        _frameHandler.close();
        throw ioe;
    } catch (ShutdownSignalException sse) {
        _heartbeatSender.shutdown();
        _frameHandler.close();
        throw AMQChannel.wrap(sse);
    }

    // We can now respond to errors having finished tailoring the connection
    this._inConnectionNegotiation = false;

    return;
}

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

License:Apache License

private boolean initConsumer() {
    Channel channel = null;/*from  w ww.j a  v  a2s  .com*/
    try {
        channel = amqp.declareChannel(factory, key);
        String queue = createQueue(amqp, channel, key);
        this.consumer = new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                ReconnectingConsumer.this.handleDelivery(consumerTag, envelope, properties, body);
            }

            @Override
            public void handleConsumeOk(String consumerTag) {
                ReconnectingConsumer.this.consumerTag = consumerTag;
            }

            @Override
            public void handleCancel(String consumerTag) throws IOException {
                logger.warn(tag + " handleCancel for consumer tag: " + consumerTag);
                try {
                    this.getChannel().basicCancel(ReconnectingConsumer.this.consumerTag);
                } catch (Exception ignore) {
                }
                this.getChannel().getConnection().abort(5000);
                reconnect();
            }

            @Override
            public void handleShutdownSignal(java.lang.String consumerTag, ShutdownSignalException sig) {
                try {
                    getChannel().basicCancel(ReconnectingConsumer.this.consumerTag);
                } catch (Exception ignore) {
                    ;
                }
                getChannel().getConnection().abort(5000);
                if (!sig.isInitiatedByApplication()) {
                    logger.warn(tag + " ShutdownSignal for tag: " + tag + "\n\t consumer tag: " + consumerTag
                            + "\n\t reason: " + sig.getReason() + "\n\t reference: " + sig.getReason()
                            + "\n\t ", sig);
                    reconnect();
                } else {
                    logger.debug(tag + " ShutdownSignal for tag: " + tag + "\n\t consumer tag: " + consumerTag
                            + "\n\t reason: " + sig.getReason() + "\n\t reference: " + sig.getReason()
                            + "\n\t ", sig);
                    consumer = null;
                }
            }
        };

        channel.basicConsume(queue, false, consumer);
        logger.info("Consumer " + tag + " initilized");
        return true;
    } catch (Throwable e) {
        logger.error("Exception initializing consumer " + tag + ": ", e);
        if (channel != null) {
            channel.getConnection().abort(5000);
        }
    }
    return false;
}

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

License:Apache License

private boolean initPublisher() {
    try {/* w  w w . ja  v  a  2  s . c om*/
        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.joshdevins.rabbitmq.client.ha.HaUtils.java

License:Apache License

/**
 * Determines if the {@link ShutdownSignalException} can be recovered from.
 * /*  w  w  w  .  j ava2  s  .c o m*/
 * Straight code copy from RabbitMQ messagepatterns library v0.1.3 {@code
 * ConnectorImpl}.
 * 
 * <p>
 * Changes:
 * <ul>
 * <li>added AlreadyClosedException as recoverable when isInitiatedByApplication == true</li>
 * </ul>
 * </p>
 */
public static boolean isShutdownRecoverable(final ShutdownSignalException s) {

    if (s != null) {
        int replyCode = 0;

        if (s.getReason() instanceof AMQImpl.Connection.Close) {
            replyCode = ((AMQImpl.Connection.Close) s.getReason()).getReplyCode();
        }

        if (s.isInitiatedByApplication()) {

            return replyCode == AMQP.CONNECTION_FORCED || replyCode == AMQP.INTERNAL_ERROR
                    || s.getCause() instanceof EOFException || s instanceof AlreadyClosedException;
        }
    }

    return false;
}