Example usage for com.rabbitmq.client Channel basicPublish

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

Introduction

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

Prototype

void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException;

Source Link

Document

Publish a message.

Usage

From source file:com.jbrisbin.vcloud.session.CloudStore.java

License:Apache License

/**
 * Basically an "update" event.//  w ww  . j av  a  2 s  .  c o  m
 *
 * @param session
 * @throws IOException
 */
public void replicateSession(Session session) throws IOException {
    AMQP.BasicProperties props = new AMQP.BasicProperties();
    props.setContentType("application/octet-stream");
    props.setReplyTo(sourceEventsQueue);
    props.setType("replicate");
    Map<String, Object> headers = new LinkedHashMap<String, Object>();
    headers.put("id", session.getId());

    SessionSerializer serializer = new InternalSessionSerializer();
    serializer.setSession(session);
    byte[] bytes = serializer.serialize();

    Channel channel = getMqChannel();
    synchronized (channel) {
        channel.basicPublish(replicationEventsExchange, replicationEventsRoutingKey, props, bytes);
        channel.basicPublish(sessionEventsExchange, String.format(sessionEventsQueuePattern, session.getId()),
                props, bytes);
    }
}

From source file:com.jbrisbin.vcloud.session.CloudStore.java

License:Apache License

public void replicateAttribute(CloudSession session, String attr) throws IOException {
    AMQP.BasicProperties props = new AMQP.BasicProperties();
    props.setContentType("application/octet-stream");
    props.setReplyTo(sourceEventsQueue);
    props.setType("setattr");
    Map<String, Object> headers = new LinkedHashMap<String, Object>();
    headers.put("id", session.getId());
    headers.put("attribute", attr);
    props.setHeaders(headers);//from  w  ww .jav  a 2 s.  com

    AttributeSerializer ser = new InternalAttributeSerializer();
    ser.setObject(session.getAttribute(attr));
    byte[] bytes = ser.serialize();

    Channel channel = getMqChannel();
    synchronized (channel) {
        channel.basicPublish(replicationEventsExchange, replicationEventsRoutingKey, props, bytes);
        channel.basicPublish(sessionEventsExchange, String.format(sessionEventsQueuePattern, session.getId()),
                props, bytes);
    }
}

From source file:com.jbrisbin.vcloud.session.CloudStore.java

License:Apache License

public void removeAttribute(CloudSession session, String attr) throws IOException {
    AMQP.BasicProperties props = new AMQP.BasicProperties();
    props.setContentType("application/octet-stream");
    props.setReplyTo(sourceEventsQueue);
    props.setType("delattr");
    Map<String, Object> headers = new LinkedHashMap<String, Object>();
    headers.put("id", session.getId());
    props.setHeaders(headers);//from  ww  w.  j a  va2s. co m

    Channel channel = getMqChannel();
    synchronized (channel) {
        channel.basicPublish(replicationEventsExchange, replicationEventsRoutingKey, props, attr.getBytes());
        channel.basicPublish(sessionEventsExchange, String.format(sessionEventsQueuePattern, session.getId()),
                props, attr.getBytes());
    }
}

From source file:com.loanbroker.old.JSONSendTest.java

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

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

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
    String queueName = "Kender du hende der Arne";
    channel.queueDeclare(queueName, false, false, false, null);

    channel.queueBind(queueName, EXCHANGE_NAME, "");
    String messageOut = "{\"ssn\":1605789787,\"creditScore\":699,\"loanAmount\":10.0,\"loanDuration\":360}";
    BasicProperties.Builder props = new BasicProperties().builder();
    props.replyTo("");
    BasicProperties bp = props.build();/*ww w  . j  a va2  s  .c  om*/
    channel.basicPublish(EXCHANGE_NAME, "", bp, messageOut.getBytes());
    System.out.println(" [x] Sent by JSONtester: '" + messageOut + "'");

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

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

License:Apache License

/**
 * Authenticates to IMAP with parameters passed in on the commandline.
 */// w ww.j a v a 2  s .  c om
public static void main(String args[]) throws Exception {

    String mysqlhost = "localhost";
    String mysqlport = "3306";
    String mysqluser = "lumlate";
    String mysqlpassword = "lumlate$";
    String database = "lumlate";
    MySQLAccess myaccess = new MySQLAccess(mysqlhost, mysqlport, mysqluser, mysqlpassword, database);

    String email = "sharmavipul@gmail.com";
    String oauthToken = "1/co5CyT8QrJXyJagK5wzWNGZk2RTA0FU_dF9IhwPvlBs";
    String oauthTokenSecret = "aK5LCYOFrUweFPfMcPYNXWzg";
    String TASK_QUEUE_NAME = "gmail_oauth";
    String rmqserver = "rmq01.deallr.com";

    initialize();
    IMAPSSLStore imapSslStore = connectToImap("imap.googlemail.com", 993, email, oauthToken, oauthTokenSecret,
            getDeallrConsumer(), true);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(rmqserver);
    factory.setUsername("lumlate");
    factory.setPassword("lumlate$");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

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

    Folder folder = imapSslStore.getFolder("INBOX");//get inbox
    folder.open(Folder.READ_WRITE);//open folder only to read
    SearchTerm flagterm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);

    RetailersDAO retaildao = new RetailersDAO();
    retaildao.setStmt(myaccess.getConn().createStatement());
    LinkedList<String> retaildomains = retaildao.getallRetailerDomains();
    LinkedList<SearchTerm> searchterms = new LinkedList<SearchTerm>();
    for (String retaildomain : retaildomains) {
        SearchTerm retailsearchterm = new FromStringTerm(retaildomain);
        searchterms.add(retailsearchterm);
    }
    SearchTerm[] starray = new SearchTerm[searchterms.size()];
    searchterms.toArray(starray);
    SearchTerm st = new OrTerm(starray); //TODO add date to this as well so that fetch is since last time
    SearchTerm searchterm = new AndTerm(st, flagterm);

    Message message[] = folder.search(searchterm);
    for (int i = 0; i < message.length; i++) {
        Message msg = message[i];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        msg.writeTo(bos);
        byte[] buf = bos.toByteArray();
        channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, buf);
    }
    myaccess.Dissconnect();
    channel.close();
    connection.close();
}

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  w w w  .  j  a v  a  2  s.  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);

    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);/*  w  w  w . ja  v 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.Main.Aggregator.java

public static void sendFinalReply(ReplyObject replyObject) throws IOException {
    RabbitMQUtil rabbitMQUtil = new RabbitMQUtil();
    Channel channel = rabbitMQUtil.createQueue(QUEUE_NAME_SEND);

    channel.basicPublish("", QUEUE_NAME_SEND, null, StringByteHelper.fromObjectToByteArray(replyObject));
    System.out.println("Object sent");

}

From source file:com.mycompany.bankjsontranslator.Translator.java

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

    ConnectionFactory listeningFactory = new ConnectionFactory();
    listeningFactory.setHost("datdb.cphbusiness.dk");
    listeningFactory.setUsername("Dreamteam");
    listeningFactory.setPassword("bastian");

    ConnectionFactory sendingFactory = new ConnectionFactory();
    sendingFactory.setHost("datdb.cphbusiness.dk");
    sendingFactory.setUsername("Dreamteam");
    sendingFactory.setPassword("bastian");

    Connection listeningConnection = listeningFactory.newConnection();
    Connection sendingConnection = sendingFactory.newConnection();

    final Channel listeningChannel = listeningConnection.createChannel();
    final Channel sendingChannel = sendingConnection.createChannel();

    final BasicProperties props = new BasicProperties.Builder().replyTo(REPLY_TO_HEADER).build();

    listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null);
    listeningChannel.queueBind(LISTENING_QUEUE_NAME, EXCHANGE_NAME, "CphBusinessJSON");

    listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(listeningChannel) {
        @Override//from www  .  j a  va2s  .c o m
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");

            String[] arr = message.split(",");

            int dashRemoved = Integer.parseInt(arr[0].replace("-", ""));

            Result res = new Result(dashRemoved, Integer.parseInt(arr[1]), Double.parseDouble(arr[2]),
                    Integer.parseInt(arr[3]));

            String result = gson.toJson(res);
            System.out.println(result);

            sendingChannel.exchangeDeclare(SENDING_QUEUE_NAME, "fanout");
            String test = sendingChannel.queueDeclare().getQueue();
            sendingChannel.queueBind(test, SENDING_QUEUE_NAME, "");
            sendingChannel.basicPublish(SENDING_QUEUE_NAME, "", props, result.getBytes());

        }
    };
    listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer);

}

From source file:com.mycompany.bankxmltranslator.Translator.java

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

    ConnectionFactory listeningFactory = new ConnectionFactory();
    listeningFactory.setHost("datdb.cphbusiness.dk");
    listeningFactory.setUsername("Dreamteam");
    listeningFactory.setPassword("bastian");

    ConnectionFactory sendingFactory = new ConnectionFactory();
    sendingFactory.setHost("datdb.cphbusiness.dk");
    sendingFactory.setUsername("Dreamteam");
    sendingFactory.setPassword("bastian");

    Connection listeningConnection = listeningFactory.newConnection();
    Connection sendingConnection = sendingFactory.newConnection();

    final Channel listeningChannel = listeningConnection.createChannel();
    final Channel sendingChannel = sendingConnection.createChannel();

    listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null);
    listeningChannel.queueBind(LISTENING_QUEUE_NAME, EXCHANGE_NAME, "CphBusinessXML");

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(listeningChannel) {
        @Override/*  ww w  .j  a  v  a  2 s  . c om*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            try {
                message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'");

                String[] arr = message.split(",");

                //                    String ssnFix = arr[0].substring(2);
                String dashRemoved = arr[0].replace("-", "");

                Result res = new Result(dashRemoved, Integer.parseInt(arr[1]), Double.parseDouble(arr[2]),
                        theDateAdder(Integer.parseInt(arr[3])));

                JAXBContext jaxbContext = JAXBContext.newInstance(Result.class);
                Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

                StringWriter sw = new StringWriter();
                jaxbMarshaller.marshal(res, sw);
                String xmlString = sw.toString();

                xmlString = xmlString.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>",
                        "");

                System.out.println(xmlString);
                // HANDLE MESSAGE HERE

                sendingChannel.exchangeDeclare(SENDING_QUEUE_NAME, "fanout");
                String test = sendingChannel.queueDeclare().getQueue();
                sendingChannel.queueBind(test, SENDING_QUEUE_NAME, "");
                sendingChannel.basicPublish("", SENDING_QUEUE_NAME, props, xmlString.getBytes());

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

        }
    };
    listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer);

}