Example usage for com.rabbitmq.client Connection createChannel

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

Introduction

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

Prototype

Channel createChannel() throws IOException;

Source Link

Document

Create a new channel, using an internally allocated channel number.

Usage

From source file:sd_aula06.Send.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("reindeer.rmq.cloudamqp.com");
    factory.setUsername("jmodzuaw");
    factory.setPassword("Kwuy7kd81ED1fIj9gxEti1J4FTPBj2Jz");
    factory.setVirtualHost("jmodzuaw");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

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

    String message = "RafaelReis: VSF!";
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
    System.out.println(" [x] Sent '" + message + "'");

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

From source file:se.kodiak.logging.appenders.amqp.AmqpFactory.java

License:Open Source License

@Override
public Channel channelFor(String url, String exchange)
        throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException {

    Connection con = this.connections.get(url);

    if (con == null || !con.isOpen()) {
        log.debug("No known connections for URI ({}), creating new.", url);
        f.setUri(url);/*from w ww.  ja  v a 2s  .  c  o m*/

        con = f.newConnection();
    }

    Channel channel = con.createChannel();
    setupChannel(channel, exchange);

    return channel;
}

From source file:se.kodiak.logging.appenders.util.MQListener.java

License:Open Source License

public MQListener() {
    try {//  w w w .  ja  v a  2  s .c  om
        ConnectionFactory factory = new ConnectionFactory();
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.basicQos(1);
        channel.exchangeDeclare("test", "topic");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, "test", "log.*");
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:server.Worker.java

License:Open Source License

/**
 * @param args//from www. j a v  a  2  s  .  com
 * @throws IOException
 * @throws TimeoutException
 */
public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection requestConnection = factory.newConnection();
    Channel requestChannel = requestConnection.createChannel();
    requestChannel.queueDeclare(REQUEST_QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Connection responseConnection = factory.newConnection();
    final Channel responseChannel = responseConnection.createChannel();
    responseChannel.queueDeclare(RESPONSE_QUEUE_NAME, false, false, false, null);

    Consumer consumer = new DefaultConsumer(requestChannel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            PriorityRequest request = (PriorityRequest) SerializationUtils.deserialize(body);
            System.out.println(" [x] Received");
            System.out.println(request.request.toString());
            System.out.println("*************************************");

            System.out.println(request.request.getMethod());
            HttpResponse response = PluginManager.getInstance().process(request.request, request.rootDir);
            if (response == null) {
                response = HttpResponseFactory.create400BadRequest(Protocol.CLOSE);
            }
            try {
                System.out.println(request.id);
            } catch (Exception e) {
                e.printStackTrace();
            }

            response.id = request.id;

            byte[] data = SerializationUtils.serialize(response);
            responseChannel.basicPublish("", RESPONSE_QUEUE_NAME, null, data);
        }
    };
    requestChannel.basicConsume(REQUEST_QUEUE_NAME, true, consumer);
}

From source file:server.WorkerServer.java

License:Open Source License

private void doWork(HttpRequest request) throws Exception {
    // Parse the request
    try {/*ww  w.  jav a  2  s.  c  o  m*/
        String[] uri = request.getUri().split("/");
        String requestTypeString = request.getMethod();
        String pluginString = uri[1];
        String servletString = uri[2];

        HashMap<String, IPlugin> plugins = server.getPlugins();
        IPlugin currPlugin = plugins.get(pluginString);

        if (currPlugin == null) {
            throw new ProtocolException(Protocol.NOT_FOUND_CODE, "This plugin doesn't exist");
        }

        IServlet servlet = currPlugin.getServlet(requestTypeString + ":/" + servletString);

        if (servlet == null) {
            System.out.println("servlet is null");
            throw new ProtocolException(Protocol.NOT_FOUND_CODE, "This servlet doesn't exist");
        }
        System.out.println("requestTypeString: " + requestTypeString);
        HttpResponse response = servlet.processRequest(request, null);

        // publish response to response queue
        Connection connection2 = factory.newConnection();
        Channel channel2 = connection2.createChannel();
        boolean durable = true;
        //System.out.println("response: " + response.getBytes(request.getKey()));
        channel2.queueDeclare(Protocol.RESPONSE_QUEUE, durable, false, false, null);
        channel2.basicPublish("", Protocol.RESPONSE_QUEUE, MessageProperties.PERSISTENT_TEXT_PLAIN,
                response.getBytes(request.getKey()));
    } catch (ProtocolException e) {
        e.printStackTrace();
    }
}

From source file:src.main.java.server.MsgReceiveServer.java

public MsgReceiveServer(int SERVER_PORT, String logDirname, String zipDirname, String dbUser, String dbPwd,
        boolean withLog) throws IOException, TimeoutException, JSONException {

    super(SERVER_PORT);

    this.withLog = withLog;
    this.logDir = logDirname;
    this.zipDir = zipDirname;

    dataSource = new DataSource(dbUser, dbPwd);

    HashMap<String, Message> user2msg;
    allMsg = new HashMap<String, HashMap<String, Message>>();
    ArrayList<Pair<String, String>> res = dataSource.getGroupUser();
    for (Pair<String, String> p : res) {
        msg = new Message("{}", p.getR());
        msg.init(p.getR(), "localhost");
        msg.bindTo(p.getL(), p.getR());/*from  w  ww.ja v  a 2 s  . com*/
        if (allMsg.containsKey(p.getL())) {
            allMsg.get(p.getL()).put(p.getR(), msg);
        } else {
            user2msg = new HashMap<String, Message>();
            user2msg.put(p.getR(), msg);
            allMsg.put(p.getL(), user2msg);
        }
    }

    loginMsg = new Message("{}", "");
    loginMsg.init("login_request", "localhost");
    loginMsg.bindTo("login_auth", "login_request");

    normalMsg = new Message("{}", "");
    normalMsg.init("normal_msg", "localhost");
    normalMsg.bindTo("msg_send", "normal_msg");

    logoutMsg = new Message("{}", "");
    logoutMsg.init("logout_msg", "localhost");
    logoutMsg.bindTo("msg_send", "logout_msg");

    reloginMsg = new Message("{}", "");
    reloginMsg.init("relogin_msg", "localhost");
    reloginMsg.bindTo("msg_send", "relogin_msg");

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel loginSuccessChannel = connection.createChannel();
    loginSuccessChannel.queueDeclare("login_success", true, false, false, null);
    loginSuccessConsumer = new DefaultConsumer(loginSuccessChannel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String sLoginSuccessMsg = new String(body, "UTF-8");
            try {
                Message loginSuccessMsg = new Message("{}", "");
                loginSuccessMsg.reset(sLoginSuccessMsg);
                String loginSuccessUsername = loginSuccessMsg.getValue("username");
                if (user_list.contains(loginSuccessUsername) == false) {
                    user_list.add(loginSuccessUsername);
                }
                System.out.println(user_list.size());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    loginSuccessChannel.basicConsume("login_success", true, loginSuccessConsumer);

}

From source file:SubsrciberStuff.BrokerSubscriber.java

public void turnOnTopicMonitoring() {

    try {/*from   ww  w  .  ja va2 s.  c  om*/
        Connection connection = factory.newConnection();
        topicChannel = connection.createChannel();
        topicChannel.exchangeDeclare(SENSOR_EXCHANGE, "topic");
        String topChName = topicChannel.queueDeclare().getQueue();
        topicChannel.queueBind(topChName, SENSOR_EXCHANGE, BIND_KEY_ALL_SENSOR);
        topicChannel.basicConsume(topChName, true, topicConsumer);
        System.out.println("Topic Monitoring ---ON---");

    } catch (IOException ex) {
        Logger.getLogger(BrokerSubscriber.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:taucalcmanager.TaucalcManager.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException/*ww  w.j  a v  a2s  .  c o m*/
 * @throws java.util.concurrent.TimeoutException
 */
public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(WORKQUEUENAME, false, false, false, null);
    channel.queueDeclare(RESULTQUEUENAME, false, false, false, null);
    channel.basicQos(1);

    int calcs = Integer.parseInt(args[0]);
    int triesPerCalc = Integer.parseInt(args[1]);
    int[] results = new int[calcs];
    byte[] task = { (byte) (triesPerCalc >> 24), (byte) (triesPerCalc >> 16), (byte) (triesPerCalc >> 8),
            (byte) (triesPerCalc) };

    System.out.println("Start Publishing");
    for (int i = 0; i < calcs; i++) {
        channel.basicPublish("", WORKQUEUENAME, null, task);
    }
    System.out.println("Done Publishing");
    GetResponse response;
    System.out.println("Start Gathering results");
    for (int i = 0; i < calcs; i++) {
        System.out.println("Waiting for next result: ( " + i + " )");
        do {
            response = channel.basicGet(RESULTQUEUENAME, true);
        } while (response == null);

        results[i] = ByteBuffer.wrap(response.getBody()).getInt();
        System.out.println("Received result: " + results[i]);
    }
    System.out.println("Done gathering results");
    System.out.println("Calculating tau");
    BigDecimal result = sumToTau(sum(results), calcs, triesPerCalc);
    System.out.println("Tau = " + result);
    BigDecimal two = new BigDecimal(2);
    System.out.println("pi = tau/2 = " + result.divide(two, RoundingMode.HALF_UP));
    channel.close();
    connection.close();
}

From source file:taucalcworker.TaucalcWorker.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException//from ww  w.jav a 2s.c  o  m
 * @throws java.util.concurrent.TimeoutException
 */
public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(WORKQUEUENAME, false, false, false, null);
    channel.queueDeclare(RESULTQUEUENAME, false, false, false, null);
    channel.basicQos(1);

    byte[] inputbyte = { 0, 0, 0, 0 };
    String input = "";

    do {
        if (System.in.available() > 0) {
            System.in.read(inputbyte);
            input = new String(inputbyte);
        }
        GetResponse response = channel.basicGet(WORKQUEUENAME, false);
        if (response != null) {
            long deliverytag = response.getEnvelope().getDeliveryTag();
            byte[] body = response.getBody();
            int tries = ByteBuffer.wrap(body).getInt();
            System.out.println("Task received: " + tries);
            int success = 0;
            for (int i = 0; i < tries; i++) {
                double x = Math.random();
                double y = Math.random();
                if (x * x + y * y <= 1) {
                    success++;
                }
            }
            System.out.println("success: " + success + " out of " + tries);
            double tau = ((double) success / tries) * 8;
            System.out.println("Tau = " + tau);
            byte[] resultbytes = new byte[8];
            ByteBuffer.wrap(resultbytes).putDouble(tau);
            channel.basicPublish("", RESULTQUEUENAME, null, resultbytes);
            channel.basicAck(deliverytag, false);
        }
    } while (!input.equals("stop"));
    channel.close();
    connection.close();
    System.out.println("You stopped the program.");
}

From source file:translators.ToOurXmlBank.java

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

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

    channel.exchangeDeclare(exchangeName, "direct");
    String queueName = channel.queueDeclare().getQueue();

    channel.queueBind(queueName, exchangeName, "ourBankSoapXML");

    //get banks from queue. "Get banks" component
    QueueingConsumer consumer = new QueueingConsumer(channel) {
        @Override//from www .j  ava  2 s.c  om
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            Message messageFromJson = getFromJson(message);
            connectToWebService(messageFromJson, properties.getCorrelationId(), EXCHANGE_NAME_SCHOOL,
                    replyQueueName);

        }
    };
    channel.basicConsume(queueName, true, consumer);

}