Example usage for com.rabbitmq.client ConnectionFactory ConnectionFactory

List of usage examples for com.rabbitmq.client ConnectionFactory ConnectionFactory

Introduction

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

Prototype

ConnectionFactory

Source Link

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);/*w ww.  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);//from   ww  w.j  a v a2  s .  c om
    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.magikbyte.smalldoode.meeting.Manager.java

public void init() {
    try {//from  w w  w .jav a 2 s.c  om
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                dispatchMessage(message);
            }
        };
        channel.basicConsume(QUEUE_NAME, true, consumer);
    } catch (IOException | TimeoutException e) {
    }
}

From source file:com.magikbyte.smalldoode.meeting.model.Agent.java

public void init() {
    try {/*from  ww  w  . j  av a  2s .  c o m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(Manager.QUEUE_NAME, "fanout");
        String message = "msg," + this.name + " est connect au groupe";
        sendMsgToTopic(message);
    } catch (IOException | TimeoutException e) {
    }
}

From source file:com.magikbyte.smalldoode.meeting.model.Groupe.java

public void init() {
    try {//ww w  . j  av a 2s  .  com
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(this.name, "topic");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, this.name, this.name);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                String[] msg;
                String message = new String(body, "UTF-8");
                if (message.startsWith("msg,")) {
                    messages.add(message);

                } else if (message.startsWith("dateAdmin")) {

                    if (dateProposeParAdmin.size() < maxChoixPossiblePourUneReunion) {
                        message = message.replace("dateAdmin,", "");
                        dateProposeParAdmin.add(message.split(",")[1]);
                    }

                } else if (message.startsWith("dateUser")) {
                    message = message.replace("dateUser,", "");
                    msg = message.split(",");
                    List<String> mesMessages = dateProposeParLesAgents.get(msg[0].trim());
                    if (mesMessages == null) {
                        mesMessages = new ArrayList<>();
                    }
                    mesMessages.add(msg[1]);
                    dateProposeParLesAgents.put(msg[0].trim(), mesMessages);
                }

                setChanged();
                notifyObservers();
                System.out.println(" [x] Received " + message);
            }
        };
        channel.basicConsume(queueName, true, consumer);
    } catch (IOException | TimeoutException e) {
        e.printStackTrace();
    }

}

From source file:com.magikbyte.smalldoode.meeting.views.ManagerView.java

public void init() {
    try {/*from  w w  w .jav  a 2s . c  om*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(Manager.QUEUE_NAME, false, false, false, null);
    } catch (IOException ex) {
        Logger.getLogger(ManagerView.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TimeoutException ex) {
        Logger.getLogger(ManagerView.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.modeln.batam.connector.Connector.java

License:Open Source License

/**
 * Begin a connection using parameters. If some or all parameters are null, the connector will use values loaded either from property files or System properties.
 * //www. ja  v  a 2 s. c o  m
 * If no system property have been defined using {@see System#setProperty(String, String) setProperty}, This method will use configuration located in the batam.properties file by default.
 * Non null parameters will override default property file values.
 * 
 * To use external property file properties, call {@see com.modeln.batam.connector.Connector#loadProperties(String) loadProperties} function specifying the external property file location before to call this method with null parameters. 
 * 
 * If System properties are defined, they will override values defined in property files (default or external). Non null parameters will also override System properties.
 * 
 * @param host : message broker host configuration.
 * @param username : message broker user name configuration.
 * @param password : message broker password configuration. 
 * @param port : message broker port configuration.
 * @param vhost : message broker VHost configuration.
 * @param queue : message broker queue the connector publish data to.
 * @param publisher : when set to 'off', it prints messages in your console (stdout) instead of publishing them to the message broker. 
 * 
 * @throws IOException
 */
@RetryOnFailure(attempts = RETRY_ON_FAILURE_ATTEMPTS, delay = RETRY_ON_FAILURE_DELAY, unit = TimeUnit.SECONDS)
public void beginConnection(String host, String username, String password, Integer port, String vhost,
        String queue, String publisher) throws IOException {
    ConfigHelper.loadProperties(null);

    if (host == null && this.host == null) {
        this.host = ConfigHelper.HOST;
    } else if (host != null) {
        this.host = host;
    }

    if (username == null && this.username == null) {
        this.username = ConfigHelper.USER;
    } else if (username != null) {
        this.username = username;
    }

    if (password == null && this.password == null) {
        this.password = ConfigHelper.PASSWORD;
    } else if (password != null) {
        this.password = password;
    }

    if (port == null && this.port == null) {
        this.port = ConfigHelper.PORT;
    } else if (port != null) {
        this.port = port;
    }

    if (vhost == null && this.vhost == null) {
        this.vhost = ConfigHelper.VHOST;
    } else if (vhost != null) {
        this.vhost = vhost;
    }

    if (queue == null && this.queue == null) {
        this.queue = ConfigHelper.QUEUE;
    } else if (queue != null) {
        this.queue = queue;
    }

    if (publisher == null) {
        publisher = ConfigHelper.PUBLISHER;
    }
    if ("on".equals(publisher) || "true".equals(publisher)) {
        this.publish = true;
    } else {
        this.publish = false;
        return;
    }

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(this.host);
    factory.setPort(this.port);
    factory.setUsername(this.username);
    factory.setPassword(this.password);
    factory.setVirtualHost(this.vhost);
    this.connection = factory.newConnection();
    this.channel = this.connection.createChannel();
    this.channel.queueDeclare(this.queue, false, false, false, null);
}

From source file:com.mycompany.aggregator.Aggregator.java

public void subscribe() throws Exception, TimeoutException, IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setUsername(USERNAME);//from  w  ww  .j  a v a  2s.  co m
    factory.setPassword(PASSWORD);

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

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

    Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String response = new String(body, "UTF-8");

            System.out.println("Received message!!");

            synchronized (responseQueueBuffer) {
                if (responseQueueBuffer.get(properties.getCorrelationId()) == null) {
                    responseQueueBuffer.put(properties.getCorrelationId(), new ResponseBuffer());
                }
                if (response != null) {
                    responseQueueBuffer.get(properties.getCorrelationId())
                            .addResponse(new JSONObject(response));
                }
            }
        }
    };

    channel.basicConsume(QUEUE_NAME, true, consumer);

    Thread task = new Thread() {
        @Override
        public void run() {
            while (true) {
                syncQueues();
                for (Map.Entry<String, ResponseBuffer> pair : responseQueue.entrySet()) {
                    if (responseQueue.get(pair.getKey()).getCreatedAt() + TIMEOUT < System
                            .currentTimeMillis()) {
                        JSONObject bestResponse = responseQueue.get(pair.getKey()).getBestResponse();
                        try {
                            forwardToSockets(bestResponse, (String) pair.getKey());
                            System.out.println("Should return " + bestResponse);
                            responseQueue.get(pair.getKey()).setFinished();
                        } catch (IOException ex) {
                            Logger.getLogger(Aggregator.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (TimeoutException ex) {
                            Logger.getLogger(Aggregator.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    }
                }
            }
        }

    };
    task.start();
}

From source file:com.mycompany.aggregator.Aggregator.java

public void initializeResponseQueue() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5672);/*from  w w  w. ja  v a 2s  .c o m*/
    factory.setUsername("test");
    factory.setPassword("test");

    responseConnection = factory.newConnection();
    responseChannel = responseConnection.createChannel();
    responseChannel.queueDeclare(QUEUE_BEST_NAME, false, false, false, null);
}

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 ww w . java  2s  .  c om
        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);

}