Example usage for com.rabbitmq.client ConnectionFactory setPassword

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

Introduction

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

Prototype

public void setPassword(String password) 

Source Link

Document

Set the password.

Usage

From source file:TestUfms.java

public static void main(String[] args) throws Exception {
    // AMQP/* ww  w . j  av  a 2s.  co 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:biospectra.classify.server.RabbitMQInputClient.java

License:Apache License

public synchronized void connect() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    String hostname = this.conf.getRabbitMQHostnames().get(this.hostId);
    factory.setHost(hostname);//from  w w w.  jav  a 2s .c  o m
    factory.setPort(this.conf.getRabbitMQPort());
    factory.setUsername(this.conf.getRabbitMQUserId());
    factory.setPassword(this.conf.getRabbitMQUserPwd());

    factory.setRequestedHeartbeat(60);

    factory.setAutomaticRecoveryEnabled(true);

    this.connection = factory.newConnection();
    this.shutdownListener = new ShutdownListener() {

        @Override
        public void shutdownCompleted(ShutdownSignalException sse) {
            LOG.error("connection shutdown", sse);
        }
    };

    this.connection.addShutdownListener(this.shutdownListener);

    this.requestChannel = this.connection.createChannel();
    this.responseChannel = this.connection.createChannel();

    LOG.info("reader connected - " + hostname + ":" + this.conf.getRabbitMQPort());

    this.responseChannel.basicQos(10);
    this.queueName = this.responseChannel.queueDeclare().getQueue();

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

            this.getChannel().basicAck(envelope.getDeliveryTag(), false);

            LOG.info("> " + message);

            ClassificationResponseMessage res = ClassificationResponseMessage.createInstance(message);
            ClassificationRequest ereq = null;
            synchronized (requestMap) {
                ereq = requestMap.get(res.getReqId());
                if (ereq != null) {
                    requestMap.remove(res.getReqId());
                }
            }

            if (ereq == null) {
                LOG.error("cannot find matching request");
            } else {
                ClassificationResponse eres = new ClassificationResponse(ereq, res);

                boolean responded = false;
                synchronized (ereq) {
                    ClassificationRequest.RequestStatus status = ereq.getStatus();
                    if (status.equals(ClassificationRequest.RequestStatus.STATUS_UNKNOWN)) {
                        ereq.setStatus(ClassificationRequest.RequestStatus.STATUS_RESPONDED);
                        responded = true;
                    }

                    requestQueue.remove(ereq);
                }

                if (responded) {
                    LOG.info("res : " + ereq.getReqId());
                    if (handler != null) {
                        handler.onSuccess(eres.getReqId(), eres.getHeader(), eres.getSequence(),
                                eres.getResult(), eres.getType(), eres.getTaxonRank(), eres.getTaxonName());
                    }

                    synchronized (requestQueue) {
                        requestQueue.notifyAll();
                    }
                }
            }
        }
    };

    this.workerThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                responseChannel.basicConsume(queueName, consumer);
                LOG.info("Waiting for messages");
            } catch (IOException ex) {
                LOG.error("Exception occurred while consuming a message", ex);
            }
        }
    });
    this.workerThread.start();
    this.reachable = true;

    this.timeoutThread = new Thread(new Runnable() {

        @Override
        public void run() {
            while (true) {
                boolean cont = false;
                if (requestQueue.size() > 0) {
                    ClassificationRequest ereq = requestQueue.peek();
                    Date cur = new Date();
                    if (ereq != null && cur.getTime() - ereq.getSentTime() >= QUERY_TIMEOUT) {
                        LOG.info("found timeout request");
                        //timeout
                        boolean timeout = false;
                        synchronized (ereq) {
                            ClassificationRequest.RequestStatus status = ereq.getStatus();
                            if (status.equals(ClassificationRequest.RequestStatus.STATUS_UNKNOWN)) {
                                ereq.setStatus(ClassificationRequest.RequestStatus.STATUS_TIMEOUT);
                                timeout = true;
                            }

                            requestQueue.remove(ereq);
                        }

                        synchronized (requestMap) {
                            requestMap.remove(ereq.getReqId());
                        }

                        if (timeout) {
                            LOG.info("timeout : " + ereq.getReqId());
                            handler.onTimeout(ereq.getReqId(), ereq.getHeader(), ereq.getSequence());

                            synchronized (requestQueue) {
                                requestQueue.notifyAll();
                            }
                        }
                        cont = true;
                    }
                }

                if (!cont) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        break;
                    }
                }
            }
        }
    });
    this.timeoutThread.start();
}

From source file:biospectra.classify.server.RabbitMQInputServer.java

License:Apache License

public synchronized void connect() throws IOException, TimeoutException {
    LOG.info("Connecting to - " + this.conf.getRabbitMQHostname() + ":" + this.conf.getRabbitMQPort());

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(this.conf.getRabbitMQHostname());
    factory.setPort(this.conf.getRabbitMQPort());
    factory.setUsername(this.conf.getRabbitMQUserId());
    factory.setPassword(this.conf.getRabbitMQUserPwd());

    factory.setRequestedHeartbeat(60);//from w w  w .ja  va2  s  . com

    factory.setAutomaticRecoveryEnabled(true);

    this.connection = factory.newConnection();
    this.connection.addShutdownListener(new ShutdownListener() {

        @Override
        public void shutdownCompleted(ShutdownSignalException sse) {
            LOG.error("connection shutdown", sse);
        }
    });

    this.requestChannel = this.connection.createChannel();
    this.responseChannel = this.connection.createChannel();

    LOG.info("connected.");

    this.requestChannel.basicQos(1);
    this.requestChannel.queueDeclare("request", false, false, true, null);

    this.responseChannel.addReturnListener(new ReturnListener() {

        @Override
        public void handleReturn(int replyCode, String replyText, String exchange, String routingKey,
                AMQP.BasicProperties properties, byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            LOG.info("message not delivered to " + routingKey);
            LOG.info(message);
        }
    });

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

            this.getChannel().basicAck(envelope.getDeliveryTag(), false);

            if (handler != null) {
                ClassificationRequestMessage req = ClassificationRequestMessage.createInstance(message);
                handler.handleMessage(req, properties.getReplyTo());
            }
        }
    };

    this.workerThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                requestChannel.basicConsume("request", consumer);
                LOG.info("Waiting for messages");
            } catch (IOException ex) {
                LOG.error("Exception occurred while consuming a message", ex);
            }
        }
    });
    this.workerThread.start();
}

From source file:blocker.Blocker.java

/**
 * @param argv//from  ww  w  .j ava  2  s  .c o  m
 */
public static void main(String[] argv) throws Exception {
    seconds = Integer.parseInt(argv[7]);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(argv[0]);
    factory.setUsername(argv[2]);
    factory.setPassword(argv[3]);
    factory.setVirtualHost(argv[1]);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(argv[4], "direct", true);
    String queueName = channel.queueDeclare(argv[5], true, false, false, null).getQueue();

    //                          exchange  key
    channel.queueBind(queueName, argv[4], argv[6]);

    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 message = new String(body, "UTF-8");
            JSONParser parser = new JSONParser();

            Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread th, Throwable ex) {
                    System.out.println("Uncaught exception: " + ex);
                }
            };

            try {
                Object obj = parser.parse(message);
                JSONObject jobj = (JSONObject) obj;
                String IP = (String) jobj.get("clientip");
                Thread t = new Thread(new BlockerThread(IP));
                t.setUncaughtExceptionHandler(h);
                t.start();
            } catch (ParseException ex) {
                Logger.getLogger(Blocker.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    };
    channel.basicConsume(argv[5], true, consumer);
}

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

License:Apache License

public void connect() throws ConnectionException {
    if (connection == null || !connection.isOpen()) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(this.host);

        if (this.user != null && this.pass != null) {
            factory.setUsername(this.user);
            factory.setPassword(this.pass);
        }/*from   w ww.  j  a va  2  s  . c  om*/

        try {
            connection = factory.newConnection();

        } catch (Exception ex) {//IOException
            close();
            this.checkHostOrDie(host);
            throw new ConnectionException("Could not connect to RabbitMQ", ex);
        }
    } else {
        throw new ConnectionException("Already connected to RabbitMQ");
    }
}

From source file:ch.icclab.cyclops.consume.RabbitMQListener.java

License:Open Source License

/**
 * Will return channel for RabbitMQ connection
 * @return channel reference or null/*  w w  w . j ava2 s.c o m*/
 */
private Channel getChannel() {
    // connect to the RabbitMQ based on settings from Load
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(credentials.getConsumerUsername());
    factory.setPassword(credentials.getConsumerPassword());
    factory.setHost(credentials.getConsumerHost());
    factory.setPort(credentials.getConsumerPort());
    factory.setVirtualHost(credentials.getConsumerVirtualHost());
    factory.setAutomaticRecoveryEnabled(true);

    Channel chan;

    try {
        // create new connection
        connection = factory.newConnection();

        // create/connect to the channel
        chan = connection.createChannel();

        logger.trace(String.format("RabbitMQ Consumer connected to %s:%d", credentials.getConsumerHost(),
                credentials.getConsumerPort()));

    } catch (Exception e) {
        logger.error(String.format("RabbitMQ Consumer couldn't be created: %s", e.getMessage()));
        connection = null;
        chan = null;
    }

    // return channel reference, or null
    return chan;
}

From source file:ch.icclab.cyclops.publish.RabbitMQPublisher.java

License:Open Source License

/**
 * Initialise connection to RabbitMQ/*from   w  w w  .j  a v  a 2s.  c  o  m*/
 * @return status
 */
private Boolean initialiseConnection() {
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(credentials.getPublisherUsername());
        factory.setPassword(credentials.getPublisherPassword());
        factory.setHost(credentials.getPublisherHost());
        factory.setPort(credentials.getPublisherPort());
        factory.setVirtualHost(credentials.getPublisherVirtualHost());
        factory.setAutomaticRecoveryEnabled(true);

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

        // declare exchange to be used (we want it to be durable and based on routing key)
        channel.exchangeDeclare(credentials.getPublisherDispatchExchange(), "direct", true);
        channel.exchangeDeclare(credentials.getPublisherBroadcastExchange(), "fanout", true);

        logger.trace(String.format("RabbitMQ Publisher connected to %s:%d", credentials.getPublisherHost(),
                credentials.getPublisherPort()));
        logger.trace(String.format(
                "RabbitMQ Publisher will dispatch to \"%s\" and broadcast to \"%s\" exchanges",
                credentials.getPublisherDispatchExchange(), credentials.getPublisherBroadcastExchange()));

        return true;
    } catch (Exception e) {
        logger.error(String.format("RabbitMQ Publisher couldn't be created: %s", e.getMessage()));
        return false;
    }
}

From source file:ch.icclab.cyclops.rabbitmq.RabbitMQAbstract.java

License:Open Source License

/**
 * Will return channel for RabbitMQ connection
 * @return channel reference or null//from   w  w  w  .j  a  v a 2s  . co  m
 */
protected Channel getChannel() {
    // connect to the RabbitMQ based on settings from Load
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(credentials.getRabbitMQUsername());
    factory.setPassword(credentials.getRabbitMQPassword());
    factory.setHost(credentials.getRabbitMQHost());
    factory.setPort(credentials.getRabbitMQPort());
    factory.setVirtualHost(credentials.getRabbitMQVirtualHost());

    Channel chan;

    try {

        logger.trace("Creating connection to RabbitMQ for host: " + credentials.getRabbitMQHost()
                + " and port: " + credentials.getRabbitMQPort());

        // create new connection
        connection = factory.newConnection();

        logger.trace("Creating and connecting to RabbitMQ channel");

        // create/connect to the channel
        chan = connection.createChannel();

    } catch (Exception ex) {
        logger.error("Couldn't start Rabbit MQ: " + ex.getMessage());
        connection = null;
        chan = null;
    }

    // return channel reference, or null
    return chan;
}

From source file:ch.icclab.cyclops.usecases.mcn.rabbitMQClient.McnRabbitMQClient.java

License:Open Source License

/**
 * Will return channel for RabbitMQ connection
 *
 * @return channel reference or null//from  w w  w.  j  ava 2s . co m
 */
private Channel getChannel() {
    // connect to the RabbitMQ based on settings from Load
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(rabbitMQSettings.getRabbitMQUsername());
    factory.setPassword(rabbitMQSettings.getRabbitMQPassword());
    factory.setVirtualHost(rabbitMQSettings.getRabbitMQVirtualHost());
    factory.setHost(rabbitMQSettings.getRabbitMQHost());
    factory.setPort(rabbitMQSettings.getRabbitMQPort());
    try {
        // create new connection
        connection = factory.newConnection();

        // create/connect to the channel
        channel = connection.createChannel();
        channel.queueDeclare(queueName, true, false, false, null);
    } catch (Exception ex) {
        logger.error("Couldn't start Rabbit MQ: " + ex.getMessage());
        ex.printStackTrace();
    }

    // return channel reference, or null
    return channel;
}

From source file:Colas.Colas.java

private String reciver(String enviar) {
    try {/* ww w .  ja v a  2  s  .  com*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(IP);
        factory.setPort(5672);
        factory.setUsername("valencia");
        factory.setPassword("admin123");

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

        channel.queueDeclare("SC", false, false, false, null);

        channel.basicPublish("", "SC", null, enviar.getBytes());
        System.out.println(" [x] Sent '" + enviar + "'");
        channel.close();
        connection.close();
    } catch (Exception e) {
        System.out.println("Error enviando ");
        e.printStackTrace();
    }
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setUsername("guest");
        factory.setPassword("admin123");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("CF", false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume("CF", true, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            System.out.println(" [x] Received '" + message + "'");
            return message;

        }
    } catch (Exception e) {
        System.out.println("Error reciviendo ");
        e.printStackTrace();
    }
    return "Error";

}