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:com.lumlate.midas.email.InboxReader.java

License:Apache License

public Boolean readInbox(Properties props, String protocol, String hostname, String username, String password,
        Date lastfetch, String TASK_QUEUE_NAME) throws Exception {
    String rmqserver = props.getProperty("com.lumlate.midas.rmq.server");
    String rmqusername = props.getProperty("com.lumlate.midas.rmq.username");
    String rmqpassword = props.getProperty("com.lumlate.midas.rmq.password");

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(rmqusername);//from www. j  a  v  a2  s. co m
    factory.setPassword(rmqpassword);
    factory.setHost(rmqserver);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

    Session session = Session.getDefaultInstance(props, null);
    // session.setDebug(true);
    // session.setDebugOut(System.out);
    Store store = session.getStore(protocol);
    store.connect(hostname, username, password);
    // Folder folder = store.getFolder("Inbox");// get inbox
    Folder folder = store.getDefaultFolder();
    folder.open(Folder.READ_WRITE);
    Folder deallrfolder = store.getFolder("Deallr");
    // if (!deallrfolder.exists()) {
    try {
        deallrfolder.create(Folder.HOLDS_MESSAGES);
    } catch (Exception err) {
        System.out.println("Cannot create Folder");
        err.printStackTrace();
    }
    // }

    // SearchTerm flagterm = new FlagTerm(new Flags(Flags.Flag.SEEN),
    // false);

    SearchTerm[] starray = new SearchTerm[searchterms.size()];
    searchterms.toArray(starray);
    SearchTerm st = new OrTerm(starray); // TODO add date to this as
    SearchTerm newerThen; // well so
    // that fetch is since last time
    if (lastfetch != null) {
        newerThen = new ReceivedDateTerm(ComparisonTerm.GT, lastfetch);
        // st = new AndTerm(st, flagterm);
        st = new AndTerm(st, newerThen);
    } else {
        newerThen = new ReceivedDateTerm(ComparisonTerm.GT, fetchsince);
        // st = new AndTerm(st, flagterm);
        st = new AndTerm(st, newerThen);
    }
    try {
        Message message[] = folder.search(st);
        for (int i = 0; i < message.length; i++) {
            Message msg = message[i];
            folder.copyMessages(new Message[] { msg }, deallrfolder);
            msg.setFlag(Flag.SEEN, true);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            msg.writeTo(bos);
            byte[] buf = bos.toByteArray();
            channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, buf);
        }
    } catch (Exception err) {
        err.printStackTrace();
        throw new Exception(err.getMessage());
    }

    folder.close(true);
    store.close();
    channel.close();
    connection.close();
    return true;
}

From source file:com.lumlate.midas.email.InboxReader.java

License:Apache License

public Boolean readOauthInbox(Properties props, String scope, String email, String oauthToken,
        String oauthTokenSecret, Date lastfetch, String TASK_QUEUE_NAME, String fetchtype) throws Exception {
    String rmqserver = props.getProperty("com.lumlate.midas.rmq.server");
    String rmqusername = props.getProperty("com.lumlate.midas.rmq.username");
    String rmqpassword = props.getProperty("com.lumlate.midas.rmq.password");

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(rmqusername);/*from   w w  w.  j  av  a  2s. c  o  m*/
    factory.setPassword(rmqpassword);
    factory.setHost(rmqserver);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

    Store imapSslStore = XoauthAuthenticator.connectToImap("imap.googlemail.com", 993, email, oauthToken,
            oauthTokenSecret, XoauthAuthenticator.getDeallrConsumer(), true);

    SearchTerm[] starray = new SearchTerm[searchterms.size()];
    searchterms.toArray(starray);
    SearchTerm st = new OrTerm(starray); // TODO add date to this as
    SearchTerm newerThen;
    // that fetch is since last time
    if (lastfetch != null) {
        newerThen = new ReceivedDateTerm(ComparisonTerm.GT, lastfetch);
        st = new AndTerm(st, newerThen);
    } else {
        newerThen = new ReceivedDateTerm(ComparisonTerm.GT, fetchsince);
        st = new AndTerm(st, newerThen);
    }

    Folder folder = imapSslStore.getFolder("[Gmail]/All Mail");// get inbox
    folder.open(Folder.READ_WRITE);
    //Folder deallrfolder=null;
    //if(fetchtype.equalsIgnoreCase("scheduler")){
    //deallrfolder = imapSslStore.getFolder("Deallr");
    //if (!deallrfolder.exists())
    //   deallrfolder.create(Folder.HOLDS_MESSAGES);         
    //}
    try {
        Message message[] = folder.search(st);
        for (int i = 0; i < message.length; i++) {
            Message msg = message[i];
            msg.setFlag(Flag.SEEN, true);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            msg.writeTo(bos);
            byte[] buf = bos.toByteArray();
            channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, buf);
            //if(deallrfolder!=null){
            //   folder.copyMessages(new Message[] { msg }, deallrfolder);
            //}
        }
    } catch (Exception err) {
        err.printStackTrace();
        throw new Exception(err.getMessage());
    }

    folder.close(true);
    //deallrfolder.close(true);
    imapSslStore.close();
    channel.close();
    connection.close();
    return true;
}

From source file:com.mycompany.dreamteamxml.DreamTeamXML.java

public void sender(double interestRate, String ssn) throws IOException {

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

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

    String message = "<LoanResponse>" + "<interestRate>" + interestRate + "</interestRate>" + "<ssn>" + ssn
            + "</ssn>" + "</LoanResponse>";

    System.out.println("Message created as soap");

    channel.basicPublish("", SENDING_QUEUE_NAME, null, message.getBytes());

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

    channel.close();
    connection.close();//from   ww  w.  ja v  a2s  .  co m

}

From source file:com.mycompany.javateste.queues.pubsub.EmitLog.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.exchangeDeclare(EXCHANGE_NAME, "fanout");

    String message = getMessage(argv);

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

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

From source file:com.mycompany.javateste.queues.routing.EmitLogDirect.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.exchangeDeclare(EXCHANGE_NAME, "direct");

    String severity = getSeverity(argv);
    String message = getMessage(argv);

    channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes("UTF-8"));
    System.out.println(" [x] Sent '" + severity + "':'" + message + "'");

    channel.close();
    connection.close();/*from   w w  w. j ava 2s.co  m*/
}

From source file:com.mycompany.javateste.queues.Send.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();
    connection.close();/*from  w w w.  jav  a  2s. c  om*/
}

From source file:com.mycompany.javateste.queues.worktasks.NewTask.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(TASK_QUEUE_NAME, true, false, false, null);

    String message = getMessage(argv);

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

    channel.close();
    connection.close();//from  w ww. j  ava  2 s  . co m
}

From source file:com.mycompany.loanbroker.requestLoan.java

/**
 * Web service operation//from  www .ja  va2s . c om
 */
@WebMethod(operationName = "request")
public String request(@WebParam(name = "ssn") String ssn, @WebParam(name = "loanAmount") double loanAmount,
        @WebParam(name = "loanDuration") int loanDuration) throws IOException, InterruptedException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("Dreamteam");
    factory.setPassword("bastian");
    Connection connection = factory.newConnection();
    Channel sendingchannel = connection.createChannel();
    Channel listeningChannel = connection.createChannel();

    listeningChannel.exchangeDeclare(EXCHANGE, "direct");
    listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null);
    listeningChannel.queueBind(LISTENING_QUEUE_NAME, EXCHANGE, ssn.replace("-", ""));

    sendingchannel.queueDeclare(SENDING_QUEUE_NAME, false, false, false, null);

    message = ssn + "," + loanAmount + "," + loanDuration;

    sendingchannel.basicPublish("", SENDING_QUEUE_NAME, null, message.getBytes());

    sendingchannel.close();

    Consumer consumer = new DefaultConsumer(listeningChannel) {
        @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] The LoanBroker Has Received '" + message + "'");
            result = message;
        }
    };

    listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer);
    //connection.close();

    return result;
}

From source file:com.navercorp.pinpoint.plugin.jdk7.rabbitmq.RabbitMQTestRunner.java

License:Apache License

void runPushTest() throws Exception {

    final String message = "hello rabbit mq";

    // producer side
    final Connection producerConnection = connectionFactory.newConnection();
    final Channel producerChannel = producerConnection.createChannel();

    producerChannel.exchangeDeclare(RabbitMQTestConstants.EXCHANGE, "direct", false);
    producerChannel.queueDeclare(RabbitMQTestConstants.QUEUE_PUSH, false, false, false, null);
    producerChannel.queueBind(RabbitMQTestConstants.QUEUE_PUSH, RabbitMQTestConstants.EXCHANGE,
            RabbitMQTestConstants.ROUTING_KEY_PUSH);

    AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
    producerChannel.basicPublish(RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PUSH, false,
            false, builder.appId("test").build(), message.getBytes());

    producerChannel.close();
    producerConnection.close();/*from  ww  w. j a v a2s . c  om*/

    //comsumer side
    final Connection consumerConnection = connectionFactory.newConnection();
    final Channel consumerChannel = consumerConnection.createChannel();
    final String remoteAddress = consumerConnection.getAddress().getHostAddress() + ":"
            + consumerConnection.getPort();

    consumerChannel.queueDeclare(RabbitMQTestConstants.QUEUE_PUSH, false, false, false, null);

    TestConsumer<String> consumer = new TestConsumer<String>(consumerChannel, MessageConverter.FOR_TEST);
    consumerChannel.basicConsume(RabbitMQTestConstants.QUEUE_PUSH, true, consumer);

    // wait consumer
    Assert.assertEquals(message, consumer.getMessage(10, TimeUnit.SECONDS));

    consumerChannel.close();
    consumerConnection.close();

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    // Wait till all traces are recorded (consumer traces are recorded from another thread)
    awaitAndVerifyTraceCount(verifier, 6, 5000L);

    verifier.printCache();
    Class<?> producerChannelClass = producerChannel.getClass();
    Method channelBasicPublish = producerChannelClass.getDeclaredMethod("basicPublish", String.class,
            String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
    ExpectedTrace channelBasicPublishTrace = Expectations.event(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
            channelBasicPublish, // method
            null, // rpc
            remoteAddress, // endPoint
            "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
            Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
            Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PUSH));
    ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
            "RabbitMQ Consumer Invocation", // method
            "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
            null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
            remoteAddress, // remoteAddress
            Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PUSH));
    Class<?> consumerDispatchClass = Class.forName("com.rabbitmq.client.impl.ConsumerDispatcher");
    Method consumerDispatchHandleDelivery = consumerDispatchClass.getDeclaredMethod("handleDelivery",
            Consumer.class, String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
    ExpectedTrace consumerDispatcherHandleDeliveryTrace = Expectations
            .event(RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, consumerDispatchHandleDelivery); // method
    ExpectedTrace asynchronousInvocationTrace = Expectations.event(ServiceType.ASYNC.getName(),
            "Asynchronous Invocation");
    Class<?> consumerClass = consumer.getClass();
    Method consumerHandleDelivery = consumerClass.getDeclaredMethod("handleDelivery", String.class,
            Envelope.class, AMQP.BasicProperties.class, byte[].class);
    ExpectedTrace consumerHandleDeliveryTrace = Expectations
            .event(RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, consumerHandleDelivery);
    Class<?> propagationMarkerClass = PropagationMarker.class;
    Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
    ExpectedTrace markTrace = Expectations.event(ServiceType.INTERNAL_METHOD.getName(), propagationMarkerMark);
    verifier.verifyTrace(channelBasicPublishTrace, rabbitMqConsumerInvocationTrace,
            consumerDispatcherHandleDeliveryTrace, asynchronousInvocationTrace, consumerHandleDeliveryTrace,
            markTrace);
    verifier.verifyTraceCount(0);
}

From source file:com.navercorp.pinpoint.plugin.jdk7.rabbitmq.RabbitMQTestRunner.java

License:Apache License

void runPullTest() throws Exception {

    final String message = "hello rabbit mq";

    // producer side
    final Connection producerConnection = connectionFactory.newConnection();
    final Channel producerChannel = producerConnection.createChannel();

    producerChannel.exchangeDeclare(RabbitMQTestConstants.EXCHANGE, "direct", false);
    producerChannel.queueDeclare(RabbitMQTestConstants.QUEUE_PULL, false, false, false, null);
    producerChannel.queueBind(RabbitMQTestConstants.QUEUE_PULL, RabbitMQTestConstants.EXCHANGE,
            RabbitMQTestConstants.ROUTING_KEY_PULL);

    AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
    producerChannel.basicPublish(RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PULL, false,
            false, builder.appId("test").build(), message.getBytes());

    producerChannel.close();
    producerConnection.close();//  w  w  w .ja  va  2s .  co m

    //comsumer side
    final Connection consumerConnection = connectionFactory.newConnection();
    final Channel consumerChannel = consumerConnection.createChannel();
    final String remoteAddress = consumerConnection.getAddress().getHostAddress() + ":"
            + consumerConnection.getPort();

    TestMessagePuller messagePuller = new TestMessagePuller(consumerChannel);
    Assert.assertEquals(message,
            messagePuller.pullMessage(MessageConverter.FOR_TEST, RabbitMQTestConstants.QUEUE_PULL, true));

    consumerChannel.close();
    consumerConnection.close();

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    // Wait till all traces are recorded (consumer traces are recorded from another thread)
    awaitAndVerifyTraceCount(verifier, 5, 5000L);

    verifier.printCache();
    // verify producer traces
    Class<?> producerChannelClass = producerChannel.getClass();
    Method channelBasicPublish = producerChannelClass.getDeclaredMethod("basicPublish", String.class,
            String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
    ExpectedTrace channelBasicPublishTrace = Expectations.event(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
            channelBasicPublish, // method
            null, // rpc
            remoteAddress, // endPoint
            "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
            Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
            Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
    ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
            "RabbitMQ Consumer Invocation", // method
            "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
            null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
            remoteAddress, // remoteAddress
            Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
    Class<?> amqChannelClass = Class.forName("com.rabbitmq.client.impl.AMQChannel");
    Method handleCompleteInboundCommand = amqChannelClass.getDeclaredMethod("handleCompleteInboundCommand",
            AMQCommand.class);
    ExpectedTrace handleCompleteInboundCommandTrace = Expectations.event(
            RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
            handleCompleteInboundCommand); // method
    verifier.verifyDiscreteTrace(channelBasicPublishTrace, rabbitMqConsumerInvocationTrace,
            handleCompleteInboundCommandTrace);

    // verify consumer traces
    Class<?> consumerChannelClass = consumerChannel.getClass();
    Method channelBasicGet = consumerChannelClass.getDeclaredMethod("basicGet", String.class, boolean.class);
    ExpectedTrace channelBasicGetTrace = Expectations.event(RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL,
            channelBasicGet);
    Class<?> propagationMarkerClass = PropagationMarker.class;
    Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
    ExpectedTrace markTrace = Expectations.event(ServiceType.INTERNAL_METHOD.getName(), propagationMarkerMark);
    verifier.verifyDiscreteTrace(channelBasicGetTrace, markTrace);
    verifier.verifyTraceCount(0);
}