Example usage for com.rabbitmq.client Connection close

List of usage examples for com.rabbitmq.client Connection close

Introduction

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

Prototype

@Override
void close() throws IOException;

Source Link

Document

Close this connection and all its channels with the com.rabbitmq.client.AMQP#REPLY_SUCCESS close code and message 'OK'.

Usage

From source file:com.wakkir.rabbitmq.basic.Sender.java

public static void main(String[] argv) throws Exception {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    String message = "Hello World!";
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();/*from  w  ww  .j av  a 2 s .c  om*/
    connection.close();
}

From source file:com.zuehlke.carrera.javapilot.show.ConfirmDontLoseMessages.java

License:Mozilla Public License

public static void main1(String[] args) throws IOException, InterruptedException, TimeoutException {

    connectionFactory = new ConnectionFactory();
    String POWER_QUEUE = "/app/pilots/power";
    String json = new JacksonSerializer().serialize(new PowerControl(200, "team", "access", 0L));
    Connection conn = connectionFactory.newConnection();
    Channel ch = conn.createChannel();
    //ch.queueDeclare(POWER_QUEUE, true, false, false, null);
    AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().expiration("0").build();
    ch.basicPublish("", POWER_QUEUE, props, json.getBytes());

    String SENSOR_QUEUE = "/topic/pilots/starterkit/sensor";
    SensorEvent sensorEvent = SensorEvent.createEmptyCarSensor().withRaceTrackId("simulator");
    json = new JacksonSerializer().serialize(sensorEvent);

    //ch.queueDeclare(SENSOR_QUEUE, true, false, false, null);
    ch.basicPublish("", SENSOR_QUEUE, props, json.getBytes());

    ch.close();/*  w  w  w. j  a  va  2  s  .  c o  m*/
    conn.close();
}

From source file:controllers.TargetController.java

License:Open Source License

/**
 * This method pushes a message onto a RabbitMQ queue for given target
 * using global settings from project configuration file.
 *
 * @param target The field URL of the target
 * @return//from  ww w  .ja v  a2s.  co  m
 */
public static Result archive(Long id) {

    Target target = Target.findById(id);
    Logger.debug("archiveTarget() " + target);
    if (target != null) {
        if (!target.isInScopeAllOrInheritedWithoutLicense()) {
            return ok(infomessage.render("On-demand archiving is only supported for NPLD targets."));
        }

        // Send the message:
        try {
            String queueHost = Play.application().configuration().getString(Const.QUEUE_HOST);
            String queuePort = Play.application().configuration().getString(Const.QUEUE_PORT);
            String queueName = Play.application().configuration().getString(Const.QUEUE_NAME);
            String routingKey = Play.application().configuration().getString(Const.ROUTING_KEY);
            String exchangeName = Play.application().configuration().getString(Const.EXCHANGE_NAME);

            Logger.debug("archiveTarget() queue host: " + queueHost);
            Logger.debug("archiveTarget() queue port: " + queuePort);
            Logger.debug("archiveTarget() queue name: " + queueName);
            Logger.debug("archiveTarget() routing key: " + routingKey);
            Logger.debug("archiveTarget() exchange name: " + exchangeName);

            JsonNode jsonData = Json.toJson(target);
            String message = jsonData.toString();
            Logger.debug("Crawl Now message: " + message);

            ConnectionFactory factory = new ConnectionFactory();
            if (queueHost != null) {
                factory.setHost(queueHost);
            }
            if (queuePort != null) {
                factory.setPort(Integer.parseInt(queuePort));
            }
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            channel.exchangeDeclare(exchangeName, "direct", true);
            channel.queueDeclare(queueName, true, false, false, null);
            channel.queueBind(queueName, exchangeName, routingKey);

            BasicProperties.Builder propsBuilder = new BasicProperties.Builder();
            propsBuilder.deliveryMode(2);
            channel.basicPublish(exchangeName, routingKey, propsBuilder.build(), message.getBytes());

            channel.close();
            connection.close();

        } catch (IOException e) {
            String msg = "There was a problem queuing this crawl instruction. Please refer to the system administrator.";
            User currentUser = User.findByEmail(request().username());
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String msgFullTrace = sw.toString();
            Logger.error(msgFullTrace);
            if (currentUser.hasRole("sys_admin")) {
                msg = msgFullTrace;
            }
            return ok(infomessage.render(msg));
        } catch (Exception e) {
            String msg = "There was a problem queuing this crawl instruction. Please refer to the system administrator.";
            User currentUser = User.findByEmail(request().username());
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String msgFullTrace = sw.toString();
            Logger.error(msgFullTrace);
            if (currentUser.hasRole("sys_admin")) {
                msg = msgFullTrace;
            }
            return ok(infomessage.render(msg));
        }
    } else {
        Logger.debug("There was a problem sending the message. Target field for archiving is empty");
        return ok(infomessage
                .render("There was a problem sending the message. Target field for archiving is empty"));
    }
    return ok(ukwalicenceresult.render());
}

From source file:cs.rsa.ts14dist.appserver.RabbitMQDaemon.java

License:Apache License

@Override
public void run() {

    Connection connection = null;
    Channel channel = null;/* w  ww .j  a  va 2  s . c o  m*/
    try {
        ConnectionFactory factory = new ConnectionFactory();
        logger.info("Starting RabbitMQDaemon, MQ IP = " + hostname);
        factory.setHost(hostname);

        connection = factory.newConnection();
        channel = connection.createChannel();

        channel.queueDeclare(rpcQueueName, false, false, false, null);

        channel.basicQos(1);

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(rpcQueueName, false, consumer);

        while (true) {
            String response = null;

            // Block and fetch next msg from queue
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();

            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();

            try {
                String message = new String(delivery.getBody(), "UTF-8");
                logger.trace("Received msg: " + message);

                // Convert the message to a JSON request object
                JSONObject request = (JSONObject) JSONValue.parse(message);

                // Delegate to the server request handler for handling the
                // request and computing an answer
                JSONObject reply = serverRequestHandler.handleRequest(request);

                // Convert the answer back into a string for replying to
                // client
                response = reply.toJSONString();
            } catch (Exception e) {
                logger.error(" Exception in MQDAemon run()/while true] " + e.toString());
                response = "wrong";
            } finally {
                logger.trace("Returning answer: " + response);
                channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8"));
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                logger.trace("Answer acknowledged.");
            }
        }
    } catch (Exception e) {
        logger.error("Exception in daemon's outer loop: nested exception" + e.getMessage());
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:de.dhbw.mannheim.erpsim.ErpSimulator.java

License:Open Source License

/**
 *
 *
 * @param args command line parameter//from  w  ww  .jav  a 2 s .c  o  m
 *             args[0] number of customer orders that should be created
 *             args[1] hostname of rabbitMQ
 * @throws IOException
 */
public static void main(String[] args) throws IOException {

    int numOfCustomerOrder = 10;
    String rabbitMqHostName = "localhost";
    String rabbitMqUserName = null;
    String rabbitMqPassword = null;

    if (args.length >= 1) {
        try {
            numOfCustomerOrder = Integer.parseInt(args[0]);
            System.out.println("Number of customer orders: " + numOfCustomerOrder);
        } catch (Exception e) {
            System.err.println("Could not parse number of customer orders " + args[0]);
        }
    }

    if (args.length >= 2 && args[1] != null) {
        rabbitMqHostName = args[1];
        System.out.println("Host of rabbitMq: " + rabbitMqHostName);
    }
    if (args.length >= 4 && args[2] != null && args[3] != null) {
        rabbitMqUserName = args[2];
        rabbitMqPassword = args[3];
        System.out.println("Username of rabbitMq: " + rabbitMqUserName);
    }

    CustomerOrder[] customerOrders = new CustomerOrder[numOfCustomerOrder];

    for (int i = 0; i < customerOrders.length; i++) {
        customerOrders[i] = CustomerOrderGenerator.getCustomOrder();
    }

    XStream xstream = new XStream();
    xstream.registerConverter(new Converter() {
        @Override
        public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) {
            MachineOrder mo = (MachineOrder) o;
            writer.startNode("id");
            writer.setValue(mo.getId());
            writer.endNode();
        }

        @Override
        public Object unmarshal(HierarchicalStreamReader hierarchicalStreamReader,
                UnmarshallingContext unmarshallingContext) {
            return null;
        }

        @Override
        public boolean canConvert(Class aClass) {
            return aClass == MachineOrder.class;
        }
    });

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(rabbitMqHostName);
    if (rabbitMqPassword != null && rabbitMqUserName != null) {
        factory.setUsername(rabbitMqUserName);
        factory.setPassword(rabbitMqPassword);
    }
    Connection connection = factory.newConnection();
    Channel channelCO = connection.createChannel();
    channelCO.exchangeDeclare(CUSTOMER_ORDER_EXCHANGE_NAME, "fanout");
    for (CustomerOrder co : customerOrders) {
        String message = xstream.toXML(co);

        channelCO.basicPublish(CUSTOMER_ORDER_EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println("Send customer order");
    }
    channelCO.close();

    Channel channelMO = connection.createChannel();
    channelMO.exchangeDeclare(MACHINE_ORDER_EXCHANGE_NAME, "fanout");
    MachineOrder mo = MachineOrderGenerator.getRandomMachineOrder();

    xstream = new XStream(); // reconstruct XStream to parse the full machine order, not just only the id
    while (mo != null) {
        int i = System.in.read();
        String message = xstream.toXML(mo);
        channelMO.basicPublish(MACHINE_ORDER_EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println("Send Machine order");
        mo = MachineOrderGenerator.getRandomMachineOrder();
    }

    channelMO.close();
    connection.close();
}

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.//from  ww w.jav a  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:de.htwk_leipzig.bis.connection.handshake.clientRewrite.Copyright.java

License:Mozilla Public License

/**
 * Handles incoming control commands on channel zero.
 * //from w ww.  j  a v  a2  s.co  m
 * @see ChannelN#processAsync
 */
@SuppressWarnings("unused")
public boolean processControlCommand(Command c) throws IOException {
    // Similar trick to ChannelN.processAsync used here, except
    // we're interested in whole-connection quiescing.

    // See the detailed comments in ChannelN.processAsync.

    Method method = c.getMethod();

    if (isOpen()) {
        if (method instanceof AMQP.Connection.Close) {
            handleConnectionClose(c);
            return true;
        } else if (method instanceof AMQP.Connection.Blocked) {
            AMQP.Connection.Blocked blocked = (AMQP.Connection.Blocked) method;
            try {
                for (BlockedListener l : this.blockedListeners) {
                    l.handleBlocked(blocked.getReason());
                }
            } catch (Throwable ex) {
                getExceptionHandler().handleBlockedListenerException(this, ex);
            }
            return true;
        } else if (method instanceof AMQP.Connection.Unblocked) {
            try {
                for (BlockedListener l : this.blockedListeners) {
                    l.handleUnblocked();
                }
            } catch (Throwable ex) {
                getExceptionHandler().handleBlockedListenerException(this, ex);
            }
            return true;
        } else {
            return false;
        }
    } else {
        if (method instanceof AMQP.Connection.Close) {
            // Already shutting down, so just send back a CloseOk.
            try {
                _channel0.quiescingTransmit(new AMQP.Connection.CloseOk.Builder().build());
            } catch (IOException _e) {
            } // ignore
            return true;
        } else if (method instanceof AMQP.Connection.CloseOk) {
            // It's our final "RPC". Time to shut down.
            _running = false;
            // If Close was sent from within the MainLoop we
            // will not have a continuation to return to, so
            // we treat this as processed in that case.
            return !_channel0.isOutstandingRpc();
        } else { // Ignore all others.
            return true;
        }
    }
}

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

License:Mozilla Public License

/**
 * Protected API - Close this connection with the given code, message,
 * source and timeout value for all the close operations to complete.
 * Specifies if any encountered exceptions should be ignored.
 *//*from  ww w. j  a  v a2s . com*/
public void close(int closeCode, String closeMessage, boolean initiatedByApplication, Throwable cause,
        int timeout, boolean abort) throws IOException {
    boolean sync = !(Thread.currentThread() == mainLoopThread);

    try {
        AMQP.Connection.Close reason = new AMQP.Connection.Close.Builder().replyCode(closeCode)
                .replyText(closeMessage).build();

        final ShutdownSignalException sse = startShutdown(reason, initiatedByApplication, cause, true);
        if (sync) {

            /*
             * Do custom action
             */
            mHandshakeAction.doAction();

            BlockingRpcContinuation<AMQCommand> k = new BlockingRpcContinuation<AMQCommand>() {

                @Override
                public AMQCommand transformReply(AMQCommand command) {
                    AMQConnection.this.finishShutdown(sse);
                    return command;
                }
            };

            _channel0.quiescingRpc(reason, k);

            /*
             * Do custom action
             */
            mHandshakeAction.doAction();

            k.getReply(timeout);

        } else {
            _channel0.quiescingTransmit(reason);
        }
    } catch (TimeoutException tte) {
        if (!abort) {
            ShutdownSignalException sse = new ShutdownSignalException(true, true, null, this);
            sse.initCause(cause);
            throw sse;
        }
    } catch (ShutdownSignalException sse) {
        if (!abort)
            throw sse;
    } catch (IOException ioe) {
        if (!abort)
            throw ioe;
    } finally {
        if (sync)
            _frameHandler.close();
    }
}

From source file:dfki.sb.rabbitmqjava.RabbitMQServer.java

License:Open Source License

public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;/*from www.  j  av  a 2  s . c o  m*/
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        System.out.println("Starting server waiting for client requests:");
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();
            DataInputStream dis = new DataInputStream(
                    new BufferedInputStream(new ByteArrayInputStream(delivery.getBody())));
            try {
                int type = dis.readInt();
                byte[] response;
                if (type == 2) {
                    response = handleMarketRequest(dis);
                } else {
                    response = handleQuoteRequest(dis);
                }
                channel.basicPublish("", props.getReplyTo(), replyProps, response);
                dis.close();
            } catch (IOException | ClassNotFoundException e) {
                System.out.println(" [.] " + e.toString());
            } finally {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (IOException | InterruptedException | ShutdownSignalException | ConsumerCancelledException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:dk.bankjsonrabbit.messaging.Send.java

public static void sendMessage(String message, BasicProperties props) throws IOException, TimeoutException {
    String taskQueueName = props.getReplyTo();

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("student");
    factory.setPassword("cph");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(taskQueueName, true, false, false, null);

    channel.basicPublish("", taskQueueName, props, message.getBytes());

    channel.close();//w w  w .  j a v a 2  s  .  com
    connection.close();
}