Example usage for com.rabbitmq.client Channel close

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

Introduction

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

Prototype

@Override
void close() throws IOException, TimeoutException;

Source Link

Document

Close this channel with the com.rabbitmq.client.AMQP#REPLY_SUCCESS close code and message 'OK'.

Usage

From source file:SendMessage.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 = "Message 004!";

    channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();
    connection.close();//from   w  ww.j a v a2 s.c om
}

From source file:TestUfms.java

public static void main(String[] args) throws Exception {
    // AMQP/*from ww  w.  j a v  a2  s  . c o  m*/

    //      UfmsProto.RegCompany.Builder builderRegCompany = UfmsProto.RegCompany.newBuilder();
    //      builderRegCompany.setAddress("11-chaulong");
    //      builderRegCompany.setCompany("CPR_0101885631");
    //      builderRegCompany.setName("cadpro");
    //      builderRegCompany.setTel("0437152984");      
    //      UfmsProto.RegCompany rc = builderRegCompany.build();
    //      UfmsProto.BaseMessage rcMsg = UfmsProto.BaseMessage.newBuilder().setMsgType(UfmsProto.BaseMessage.MsgType.RegCompany).setExtension(UfmsProto.RegCompany.msg, rc).build();      
    //      byte[] rcData = rcMsg.toByteArray();
    //      System.out.println(rcMsg.toString());
    //      
    //      
    //      UfmsProto.RegDriver.Builder builderRegDriver = UfmsProto.RegDriver.newBuilder();
    //      builderRegDriver.setDatetimeExpire(1981979234);
    //      builderRegDriver.setDatetimeIssue(1095379200);
    //      builderRegDriver.setDriver("CPR_010099045659");
    //      builderRegDriver.setLicense("B2");
    //      builderRegDriver.setName("Dao Duy Hung");
    //      builderRegDriver.setRegPlace("Ha Noi");
    //      UfmsProto.RegDriver rd = builderRegDriver.build();
    //      UfmsProto.BaseMessage rdMsg = UfmsProto.BaseMessage.newBuilder().setMsgType(UfmsProto.BaseMessage.MsgType.RegDriver).setExtension(UfmsProto.RegDriver.msg, rd).build();      
    //      byte[] rdData = rdMsg.toByteArray();
    //      System.out.println(rdMsg.toString());
    //      
    //      UfmsProto.RegVehicle.Builder builderRegVehicle = UfmsProto.RegVehicle.newBuilder();
    //      builderRegVehicle.setCompany("CPR_0101885631");
    //      builderRegVehicle.setDatetime(1481979234);
    //      builderRegVehicle.setDeviceId("CPR_01");
    //      builderRegVehicle.setDeviceModel("CPR_Model_1");
    //      builderRegVehicle.setDeviceModelNo(1);
    //      builderRegVehicle.setDriver("CPR_010099045659");
    //      builderRegVehicle.setSim("0966871864");
    //      builderRegVehicle.setVehicle("29A1511");
    //      builderRegVehicle.setVehicleType(VehicleType.HopDong);
    //      builderRegVehicle.setVin("01");
    //      UfmsProto.RegVehicle rv = builderRegVehicle.build();
    //      UfmsProto.BaseMessage rvMsg = UfmsProto.BaseMessage.newBuilder().setMsgType(UfmsProto.BaseMessage.MsgType.RegVehicle).setExtension(UfmsProto.RegVehicle.msg, rv).build();      
    //      byte[] rvData = rvMsg.toByteArray();
    //      System.out.println(rvMsg.toString());

    ConnectionFactory factory = new ConnectionFactory();

    factory.setHost("27.118.27.118");
    factory.setUsername("ctchaulong");
    factory.setPassword("EHjt81_FI");
    factory.setPort(5673);

    factory.setConnectionTimeout(600);

    Connection connection = factory.newConnection();
    System.out.println("creat connection done!");
    Channel channel = connection.createChannel();
    System.out.println("creat channel done!");

    int i = 0;
    // build WayPoint message 
    boolean a = true;
    while (a) {
        i++;

        UfmsProto.WayPoint.Builder builder = UfmsProto.WayPoint.newBuilder();
        int now = (int) (System.currentTimeMillis() / 1000);
        builder.setDatetime(now);
        builder.setDoor(true);
        builder.setDriver("010099045659");
        builder.setHeading(90);
        builder.setIgnition(true);
        builder.setSpeed(0); //<200
        //builder.setVehicle("29A1511");
        builder.setVehicle("29A1516");
        //builder.setVehicle("29K-8942");
        builder.setX(105.8445795); //> 0
        builder.setY(21.0306089); //>0
        //         builder.setX(021.0306089); //>0
        //         builder.setY(105.8445795); //> 0         
        builder.setZ(20); //>0            21.0306089,105.8445795,16z

        UfmsProto.WayPoint wp = builder.build();
        UfmsProto.BaseMessage msg = UfmsProto.BaseMessage.newBuilder()
                .setMsgType(UfmsProto.BaseMessage.MsgType.WayPoint).setExtension(UfmsProto.WayPoint.msg, wp)
                .build();
        byte[] data = msg.toByteArray();
        System.out.println(msg.toString());

        // send to server
        //channel.basicPublish("ufms.all", "", null, data);
        //      channel.basicPublish("tracking.ctpmdktest", "track1", null, rcData);
        //      channel.basicPublish("tracking.ctpmdktest", "track1", null, rdData);
        //      channel.basicPublish("tracking.ctpmdktest", "track1", null, rvData);   

        channel.basicPublish("tracking.ctchaulong", "track1", null, data);
        try {
            System.out.println("Send [" + i + "] time(s)! sleep in 1s...");
            Thread.sleep(1000); //1000 milliseconds is one second.
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }

    }
    // clean up
    channel.close();
    connection.close();
    //      System.out.println("send done! ");
}

From source file:ThreadWorkers.java

private static String doWork(String task) throws InterruptedException, IOException {
    //for (char ch: task.toCharArray()) {
    //  if (ch == '.') Thread.sleep(1000);
    //}/*from w  ww.j a v  a 2  s .  com*/
    String result = "empty result";
    long threadId = Thread.currentThread().getId();
    System.out.println("in thread>>>>" + threadId);

    if (task.equalsIgnoreCase(""))
        return result;
    if (task == null)
        return result;
    //if(task.charAt(0)=='f' || task.charAt(0)=='1') return result;

    if (task.charAt(0) == 'f')
        result = "factorial of " + task.substring(1) + ">>" + factor(task.substring(1)).toString();
    else if (task.charAt(0) == 'p') {

        if (isPrime(task.substring(1).toString()))
            result = task.substring(1).toString() + " is prime";
        else
            result = task.substring(1).toString() + " is not prime";
    } else {
        result = "exponent " + task.substring(1) + ">>" + exp(task.substring(1)).toString();
    }
    // sending result
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(TASK_QUEUE_REPLY_NAME, true, false, false, null);
    //String[] msg= {"10","second",".........."};
    //String[] msg= {"1","second","."};
    //String message ="rvr";// getMessage(msg);

    channel.basicPublish("", TASK_QUEUE_REPLY_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, result.getBytes());
    System.out.println(" [x] Sent reply to client:: '" + result + "'");

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

    return result;
}

From source file:RabbitMQConnector.java

License:Open Source License

@Override
boolean sendMsg(String msg) {
    try {//from   w  ww  .  j ava 2  s .c o  m
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        AMQP.Queue.DeclareOk myQueue = channel.queueDeclare(queueName, true, false, false, null);
        String message = msg;
        channel.basicPublish("", queueName, null, message.getBytes());
        channel.close();
        connection.close();
    } catch (Exception ex) {
        return false;
    }
    return true;
}

From source file:SenderUtil.java

public void sendMessage(String msg) throws IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    //String[] msg= {"10","second",".........."};
    //String[] msg= {"1","second","."};
    String message = msg;//getMessage(msg);

    channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();
    connection.close();//w w  w.j  a v  a  2 s. co m

}

From source file:RabbitMQsender.java

public void send(String[] args) {

    if (args.length != 4) {
        logger.warn(/*from  ww w . j av a 2 s  . c  o m*/
                "Bad number of arguments, Sender needs String hostURL, String queueName, String fileName, int sleepTime");
        return;
    }

    String hostURL = args[0];
    String queueName = args[1];
    String fileName = args[2];
    int sleepTime = Integer.parseInt(args[3]);
    File myFile = new File(fileName);

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostURL);

    try {
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //send contents of file
        FileReader inputFile = new FileReader(myFile);
        BufferedReader bufferReader = new BufferedReader(inputFile);
        String line = bufferReader.readLine();

        logger.info("Sending file contents");

        do {
            if (sleepTime > 0) {
                Thread.sleep(sleepTime);
            }
            if (line != null) {
                String toSend = addTimestamp(line);
                this.publish(channel, queueName, toSend); //will be dropped till queue is declared (so, declare)
                if (logger.isDebugEnabled()) {
                    logger.debug("Sending '" + toSend + "' from file " + myFile.getAbsolutePath());
                }
                line = bufferReader.readLine();
            }
        } while (line != null);
        bufferReader.close();
        channel.close();
        connection.close();
    } catch (Exception ex) {
        logger.error("Error while reading file line by line: " + ex.getMessage());
        return;
    }
    logger.info("Everything sent without errors\n");
}

From source file:amqp.AmqpClient.java

License:Apache License

/**
 * Tries to close the channel ignoring any {@link java.io.IOException}s that may occur while doing so.
 *
 * @param channel channel to close//  w w  w  .  jav a  2s .c  o  m
 */
protected void closeChannelSilently(Channel channel) {
    if (channel != null) {
        try {
            channel.close();
        } catch (IOException e) {
            LOG.warn("Problem closing down channel", e);
        } catch (AlreadyClosedException e) {
            LOG.debug("Channel was already closed");
        } catch (ShutdownSignalException e) {
            // we can ignore this since we are shutting down
            LOG.debug("Got a shutdown signal while closing channel", e);
        }
        closeConnectionSilently(channel.getConnection());
    }
}

From source file:at.ac.tuwien.dsg.cloud.utilities.messaging.lightweight.rabbitMq.channel.SendingChannel.java

License:Apache License

public void sendMessage(String type, RabbitMqMessage msg) throws ChannelException {
    try {//  w w w .j  a  v  a  2 s.c  o m
        byte[] body = this.serializer.serialze(msg);
        Channel channel = this.getChannel();
        channel.basicPublish(ARabbitChannel.EXCHANGE_NAME, type, null, body);
        channel.close();
    } catch (IOException ex) {
        logger.error(String.format("Error while sending message with type %s!", type), ex);
    }
}

From source file:bank.OurRabbitBank.java

private static void sendToNormalizer(Message msg, AMQP.BasicProperties props) {
    try {//from   ww  w .  j  ava  2 s.  c  o m
        Gson g = new Gson();
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("datdb.cphbusiness.dk");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //channel.exchangeDeclare(ExchangeName.OUR_JSON_BANK_RESPONSE, "direct");

        int ssn = Integer.valueOf(msg.getSsn());
        double interestRate = calcRate();
        String bank = "OurRabbitBank";
        String correlationId = props.getCorrelationId();

        LoanResponse response = new LoanResponse(ssn, interestRate, bank, correlationId);

        String res = g.toJson(response);

        channel.basicPublish(ExchangeName.OUR_JSON_BANK_RESPONSE, "", props, res.getBytes());

        System.out.println(" [x] Sent '" + res + "'");

        channel.close();
        connection.close();
    } catch (Exception e) {
        System.out.println("Error in OutRabbitBank: " + e.getMessage());
    }
}

From source file:br.uff.labtempo.omcp.common.utils.RabbitComm.java

License:Apache License

public void checkQueueOrDie(String queueName) throws UnreachableModuleException {
    if (!connection.isOpen()) {
        throw new UnreachableModuleException("Not connected to broker!");
    }//from ww  w. j  ava 2 s .  c om
    try {
        Channel ch = connection.createChannel();
        AMQP.Queue.DeclareOk declare = ch.queueDeclarePassive(queueName);
        ch.close();
    } catch (Exception e) {
        throw new UnreachableModuleException("Queue not exists!");
    }
}