Example usage for com.rabbitmq.client Channel queueDeclare

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

Introduction

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

Prototype

Queue.DeclareOk queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete,
        Map<String, Object> arguments) throws IOException;

Source Link

Document

Declare a queue

Usage

From source file:grnet.validation.XMLValidation.java

License:Open Source License

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method ssstub

    Enviroment enviroment = new Enviroment(args[0]);

    if (enviroment.envCreation) {
        String schemaUrl = enviroment.getArguments().getSchemaURL();
        Core core = new Core(schemaUrl);

        XMLSource source = new XMLSource(args[0]);

        File sourceFile = source.getSource();

        if (sourceFile.exists()) {

            Collection<File> xmls = source.getXMLs();

            System.out.println("Validating repository:" + sourceFile.getName());

            System.out.println("Number of files to validate:" + xmls.size());

            Iterator<File> iterator = xmls.iterator();

            System.out.println("Validating against schema:" + schemaUrl + "...");

            ValidationReport report = null;
            if (enviroment.getArguments().createReport().equalsIgnoreCase("true")) {

                report = new ValidationReport(enviroment.getArguments().getDestFolderLocation(),
                        enviroment.getDataProviderValid().getName());

            }//from   ww w  . j  ava  2s  .  c o  m

            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(enviroment.getArguments().getQueueHost());
            factory.setUsername(enviroment.getArguments().getQueueUserName());
            factory.setPassword(enviroment.getArguments().getQueuePassword());

            while (iterator.hasNext()) {

                StringBuffer logString = new StringBuffer();
                logString.append(sourceFile.getName());
                logString.append(" " + schemaUrl);

                File xmlFile = iterator.next();
                String name = xmlFile.getName();
                name = name.substring(0, name.indexOf(".xml"));

                logString.append(" " + name);

                boolean xmlIsValid = core.validateXMLSchema(xmlFile);

                if (xmlIsValid) {
                    logString.append(" " + "Valid");
                    slf4jLogger.info(logString.toString());

                    Connection connection = factory.newConnection();
                    Channel channel = connection.createChannel();
                    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();
                    try {
                        if (report != null) {

                            report.raiseValidFilesNum();
                        }

                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderValid());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    logString.append(" " + "Invalid");
                    slf4jLogger.info(logString.toString());

                    Connection connection = factory.newConnection();
                    Channel channel = connection.createChannel();
                    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();

                    try {
                        if (report != null) {

                            if (enviroment.getArguments().extendedReport().equalsIgnoreCase("true"))
                                report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.invalidData,
                                        core.getReason());

                            report.raiseInvalidFilesNum();
                        }
                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderInValid());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            if (report != null) {
                report.writeErrorBank(core.getErrorBank());
                report.appendGeneralInfo();
            }
            System.out.println("Validation is done.");

        }

    }
}

From source file:hu.sztaki.stratosphere.workshop.RMQ.BasicRMQSender.java

License:Apache License

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

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String message;//from  w w w  .j  a v  a 2 s .c o m

    while (true) {
        System.out.println("Enter next message (q to quit):");
        message = br.readLine();
        if (message.equals("q")) {
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            break;
        }
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
    }
    channel.close();
    connection.close();
}

From source file:hu.sztaki.stratosphere.workshop.RMQ.RMQALSSender.java

License:Apache License

public static void main(String[] argv) throws java.io.IOException, InterruptedException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    Random rnd = new Random();
    for (int i = 0; i < 1000; i++) {
        Thread.sleep(10);/*from ww  w.  j a  v a 2 s .co  m*/
        channel.basicPublish("", QUEUE_NAME, null, Integer.toString(rnd.nextInt(250)).getBytes());
    }
    channel.close();
    connection.close();
}

From source file:hudson.plugins.collabnet.orchestrate.AmqpOrchestrateClient.java

License:Apache License

/** {@inheritDoc} */
public void postBuild(String serverUrl, String serverUsername, String serverPassword, String buildInformation)
        throws IOException {

    Connection conn = null;/*from  w  w w .j  a  va  2 s  .c  om*/
    Channel channel = null;
    try {

        // verify serverUrl, and clear trailing slash if need be
        URI uri = new URI(serverUrl);
        if (serverUrl.endsWith("/")) {
            serverUrl = serverUrl.substring(0, serverUrl.lastIndexOf("/"));
        }

        factory.setUri(serverUrl);
        // add username / password credentials to request, if needed
        if (!StringUtils.isBlank(serverUsername)) {
            factory.setUsername(serverUsername);
            factory.setPassword(serverPassword);
        }
        conn = factory.newConnection();
        channel = conn.createChannel();
        channel.queueDeclare(routingKey, true, false, false, null);

        byte[] messageBodyBytes = buildInformation.getBytes("UTF-8");
        channel.basicPublish(exchangeName, routingKey, properties, messageBodyBytes);
    } catch (Exception e) {
        String errorMsg = "Unable to send build info to the message queue";
        throw new IOException(errorMsg, e);
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (TimeoutException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (conn != null) {
            conn.close();
        }
    }
}

From source file:hudson.plugins.collabnet.orchestrate.TestAmqpOrchestrateClient.java

License:Apache License

/** Tests that the MQ client attempts to use credentials when provided */
@Test//from  w  w  w.java 2 s  . c o m
public void postBuildUsesProvidedCredentials() throws Exception {
    // set up
    String serverUrl = "amqp://test.host";
    String serverUsername = "someuser";
    String serverPassword = "somepassword";
    String messageBody = "somemessage";

    Connection conn = mocks.createMock("mqConn", Connection.class);
    Channel channel = mocks.createNiceMock("mqChannel", Channel.class);
    AMQP.Queue.DeclareOk ok = mocks.createMock("mqOk", AMQP.Queue.DeclareOk.class);

    mqConnectionFactory.setUri(serverUrl);
    expectLastCall().once();
    mqConnectionFactory.setUsername(serverUsername);
    expectLastCall().once();
    mqConnectionFactory.setPassword(serverPassword);
    expectLastCall().once();

    expect(mqConnectionFactory.newConnection()).andReturn(conn);
    expect(conn.createChannel()).andReturn(channel);
    expect(channel.queueDeclare(orchestrateClient.getRoutingKey(), true, false, false, null)).andReturn(ok);

    channel.close();
    expectLastCall().once();

    conn.close();
    expectLastCall().once();

    mocks.replayAll();

    // exercise
    orchestrateClient.postBuild(serverUrl, serverUsername, serverPassword, messageBody);

    // verify
    mocks.verifyAll();
}

From source file:hudson.plugins.collabnet.orchestrate.TestAmqpOrchestrateClient.java

License:Apache License

/** Tests that the MQ client does not use credentials when not provided */
@Test//from  w  ww.  ja  v a 2 s. c  o  m
public void postBuildUsesNoCredentialsWhenNull() throws Exception {
    // set up
    String serverUrl = "amqp://test.host";
    String serverUsername = null;
    String serverPassword = null;
    String messageBody = "somemessage";

    Connection conn = mocks.createMock("mqConn", Connection.class);
    Channel channel = mocks.createNiceMock("mqChannel", Channel.class);
    AMQP.Queue.DeclareOk ok = mocks.createMock("mqOk", AMQP.Queue.DeclareOk.class);

    mqConnectionFactory.setUri(serverUrl);
    expectLastCall().once();

    expect(mqConnectionFactory.newConnection()).andReturn(conn);
    expect(conn.createChannel()).andReturn(channel);
    expect(channel.queueDeclare(orchestrateClient.getRoutingKey(), true, false, false, null)).andReturn(ok);

    channel.close();
    expectLastCall().once();

    conn.close();
    expectLastCall().once();

    mocks.replayAll();

    // exercise
    orchestrateClient.postBuild(serverUrl, serverUsername, serverPassword, messageBody);

    // verify
    mocks.verifyAll();
}

From source file:in.cs654.chariot.ashva.AshvaServer.java

License:Open Source License

public static void main(String[] args) {
    Connection connection = null;
    Channel channel;
    try {/*from  www. j  a  v a 2  s  . co  m*/
        final ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST_IP_ADDR);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);

        final QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        LOGGER.info("Ashva Server started. Waiting for requests...");

        AshvaHelper.joinOrStartChariotPool();
        AshvaHelper.startHeartbeat();

        while (true) {
            final QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicResponse response = new BasicResponse();
            BasicRequest request = new BasicRequest();
            final BasicProperties props = delivery.getProperties();
            final BasicProperties replyProps = new BasicProperties.Builder()
                    .correlationId(props.getCorrelationId()).build();
            try {
                final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>(
                        BasicRequest.class);
                decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder);
                request = avroReader.read(request, decoder);
                response = AshvaProcessor.process(request);

            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.severe("Error in handling request: " + e.getMessage());
                response = ResponseFactory.getErrorResponse(request);

            } finally {
                baos.reset();
                final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>(
                        BasicResponse.class);
                encoder = EncoderFactory.get().binaryEncoder(baos, encoder);
                avroWriter.write(response, encoder);
                encoder.flush();
                LOGGER.info("Responding to request id " + request.getRequestId() + " " + response.getStatus());
                channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray());
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.severe("Error in RPC server: " + e.getMessage());
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:in.cs654.chariot.prashti.PrashtiServer.java

License:Open Source License

public static void main(String[] args) {
    Connection connection = null;
    Channel channel;
    try {/*from  w w  w.ja  v a 2  s. c o  m*/
        final ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST_IP_ADDR);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);

        final QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        LOGGER.info("Prashti Server started. Waiting for requests...");

        final List<Prashti> prashtiList = D2Client.getOnlinePrashtiServers();
        final String ipAddr = CommonUtils.getIPAddress();
        prashtiList.add(new Prashti(ipAddr));
        LOGGER.info("Notifying D2 to set Prashti Server IP Address");
        D2Client.setPrashtiServers(prashtiList);

        while (true) {
            final QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicResponse response = new BasicResponse();
            BasicRequest request = new BasicRequest();
            final BasicProperties props = delivery.getProperties();
            final BasicProperties replyProps = new BasicProperties.Builder()
                    .correlationId(props.getCorrelationId()).build();
            try {
                final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>(
                        BasicRequest.class);
                decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder);
                request = avroReader.read(request, decoder);
                response = RequestProcessor.process(request);

            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.severe("Error in handling request: " + e.getMessage());
                response = ResponseFactory.getErrorResponse(request);

            } finally {
                baos.reset();
                final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>(
                        BasicResponse.class);
                encoder = EncoderFactory.get().binaryEncoder(baos, encoder);
                avroWriter.write(response, encoder);
                encoder.flush();
                LOGGER.info("Responding to request id " + request.getRequestId() + " " + response.getStatus());
                channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray());
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.severe("Error in RPC server: " + e.getMessage());
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:in.cs654.chariot.turagraksa.ZooKeeperServer.java

License:Open Source License

public static void main(String[] args) {
    Connection connection = null;
    Channel channel;
    try {//www . j a va2 s.  com
        final ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST_IP_ADDR);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);

        final QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        LOGGER.info("ZooKeeper Server started. Waiting for requests...");
        ZooKeeper.startPingEcho();

        while (true) {
            final QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicResponse response = new BasicResponse();
            BasicRequest request = new BasicRequest();
            final AMQP.BasicProperties props = delivery.getProperties();
            final AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder()
                    .correlationId(props.getCorrelationId()).build();
            try {
                final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>(
                        BasicRequest.class);
                decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder);
                request = avroReader.read(request, decoder);
                response = ZooKeeperProcessor.process(request);

            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.severe("Error in handling request: " + e.getMessage());
                response = ResponseFactory.getErrorResponse(request);

            } finally {
                baos.reset();
                final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>(
                        BasicResponse.class);
                encoder = EncoderFactory.get().binaryEncoder(baos, encoder);
                avroWriter.write(response, encoder);
                encoder.flush();
                channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray());
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.severe("Error in RPC server: " + e.getMessage());
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:info.pancancer.arch3.utils.Utilities.java

License:Open Source License

public static Channel setupQueue(HierarchicalINIConfiguration settings, String queue)
        throws IOException, TimeoutException {

    String server = settings.getString(Constants.RABBIT_HOST);
    String user = settings.getString(Constants.RABBIT_USERNAME);
    String pass = settings.getString(Constants.RABBIT_PASSWORD);

    Channel channel = null;

    try {/*from w  ww  .j a  v a  2s . c  o m*/

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(server);
        factory.setUsername(user);
        factory.setPassword(pass);
        factory.setAutomaticRecoveryEnabled(true);
        Connection connection = factory.newConnection();
        channel = connection.createChannel();
        channel.basicQos(1);
        channel.queueDeclare(queue, true, false, false, null);
        channel.confirmSelect();
        // channel.queueDeclarePassive(queue);

    } catch (IOException | TimeoutException ex) {
        // Logger.getLogger(Master.class.getName()).log(Level.SEVERE, null, ex);
        LOG.error("Error setting up queue connections to queue:" + queue + " on host: " + server
                + "; error is: " + ex.getMessage(), ex);
    }
    return channel;

}