Example usage for com.rabbitmq.client MessageProperties PERSISTENT_TEXT_PLAIN

List of usage examples for com.rabbitmq.client MessageProperties PERSISTENT_TEXT_PLAIN

Introduction

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

Prototype

BasicProperties PERSISTENT_TEXT_PLAIN

To view the source code for com.rabbitmq.client MessageProperties PERSISTENT_TEXT_PLAIN.

Click Source Link

Document

Content-type "text/plain", deliveryMode 2 (persistent), priority zero

Usage

From source file:org.trpr.platform.integration.impl.messaging.RabbitMQMessagePublisherImpl.java

License:Apache License

/**
 * Publishes on a provided connection as per the connection configuration index. 
 * If the connection is null or if publishing fails it throws an Exception.
 * @param message/*  w w w  . ja v a 2  s . c  o  m*/
 * @param connectionIndex
 * @throws Exception
 */
protected void publishToConnection(Object message, int connectionIndex) throws Exception {
    RabbitMQConfiguration rabbitMQConfiguration = rabbitMQConfigurations.get(connectionIndex);

    if (this.rabbitConnectionHolders[connectionIndex] == null) {
        throw new MessagingException("Connection not initialized");
    }

    boolean isMessageOfTypeString = (message instanceof String);
    byte[] body = isMessageOfTypeString ? ((String) message).getBytes(ENCODING)
            : PlatformUtils.toBytes(message);
    AMQP.BasicProperties msgProps = rabbitMQConfiguration.isDurable()
            ? (isMessageOfTypeString ? MessageProperties.PERSISTENT_TEXT_PLAIN
                    : MessageProperties.PERSISTENT_BASIC)
            : (isMessageOfTypeString ? MessageProperties.TEXT_PLAIN : MessageProperties.BASIC);

    if (rabbitMQConfiguration.isDurable()) {
        synchronized (this.rabbitConnectionHolders[connectionIndex].getChannel()) {
            // synchronized on the channel to avoid the below RabbitMQ client exception, caused in multi-threaded execution using the same channel:
            // java.lang.IllegalStateException: cannot execute more than one synchronous AMQP command at a time
            this.rabbitConnectionHolders[connectionIndex].getChannel().basicPublish(
                    rabbitMQConfiguration.getExchangeName(), rabbitMQConfiguration.getRoutingKey(), msgProps,
                    body);
            // Commit the message if it is durable and the commit count is reached. 
            // The channel should and would be in txSelect mode when it was created using the RabbitMQConfiguration details
            // increment totNoOfMessagesQueued by 1 and check as it is post incremented after publishing the message
            if ((totNoOfMessagesQueued + 1) % rabbitMQConfiguration.getDurableMessageCommitCount() == 0) {
                if (rabbitMQConfiguration.isDisableTX()) {
                    // error out, as explicitly disabling TX will not make the message durable
                    LOGGER.error(
                            "Configuration conflict. TX disabled for message publishing on durable queue. Message will not be published.");
                    return;
                }
                this.rabbitConnectionHolders[connectionIndex].getChannel().txCommit();
            }
        }
    } else {
        this.rabbitConnectionHolders[connectionIndex].getChannel().basicPublish(
                rabbitMQConfiguration.getExchangeName(), rabbitMQConfiguration.getRoutingKey(), msgProps, body);
    }
}

From source file:org.voltdb.exportclient.RabbitMQExportClient.java

License:Open Source License

@Override
public void configure(Properties config) throws Exception {
    final String brokerHost = config.getProperty("broker.host");
    final String amqpUri = config.getProperty("amqp.uri");
    if (brokerHost == null && amqpUri == null) {
        throw new IllegalArgumentException("One of \"broker.host\" and \"amqp.uri\" must not be null");
    }/*from ww  w .  j av  a 2 s  .c om*/

    final int brokerPort = Integer
            .parseInt(config.getProperty("broker.port", String.valueOf(ConnectionFactory.DEFAULT_AMQP_PORT)));
    final String username = config.getProperty("username", ConnectionFactory.DEFAULT_USER);
    final String password = config.getProperty("password", ConnectionFactory.DEFAULT_PASS);
    final String vhost = config.getProperty("virtual.host", ConnectionFactory.DEFAULT_VHOST);
    m_exchangeName = config.getProperty("exchange.name", "");

    final String routingKeySuffix = config.getProperty("routing.key.suffix");
    if (routingKeySuffix != null) {
        StringTokenizer tokens = new StringTokenizer(routingKeySuffix, ",");
        while (tokens.hasMoreTokens()) {
            String[] parts = tokens.nextToken().split("\\.");
            if (parts.length == 2) {
                m_routingKeyColumns.put(parts[0].toLowerCase().trim(), parts[1].trim());
            }
        }
    }

    m_skipInternal = Boolean.parseBoolean(config.getProperty("skipinternals", "false"));

    if (Boolean.parseBoolean(config.getProperty("queue.durable", "true"))) {
        m_channelProperties = MessageProperties.PERSISTENT_TEXT_PLAIN;
    }

    m_connFactory = new ConnectionFactory();
    // Set the URI first, if other things are set, they'll overwrite the corresponding
    // parts in the URI.
    if (amqpUri != null) {
        m_connFactory.setUri(amqpUri);
    }
    m_connFactory.setHost(brokerHost);
    m_connFactory.setPort(brokerPort);
    m_connFactory.setUsername(username);
    m_connFactory.setPassword(password);
    m_connFactory.setVirtualHost(vhost);

    final TimeZone tz = TimeZone.getTimeZone(config.getProperty("timezone", VoltDB.GMT_TIMEZONE.getID()));

    m_binaryEncoding = ExportDecoderBase.BinaryEncoding
            .valueOf(config.getProperty("binaryencoding", "HEX").trim().toUpperCase());

    m_ODBCDateformat = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            SimpleDateFormat sdf = new SimpleDateFormat(Constants.ODBC_DATE_FORMAT_STRING);
            sdf.setTimeZone(tz);
            return sdf;
        }
    };

    slogger.info("Configured RabbitMQ export client");
}

From source file:org.voltdb.exportclient.TestRabbitMQExportClient.java

License:Open Source License

/**
 * Make sure we use sane defaults for optional config options.
 *///from   www .  ja  v a 2 s.  co m
@Test
public void testDefaultConfig() throws Exception {
    final RabbitMQExportClient dut = new RabbitMQExportClient();
    final Properties config = new Properties();
    config.setProperty("broker.host", "fakehost");
    dut.configure(config);
    assertEquals("fakehost", dut.m_connFactory.getHost());
    assertEquals(ConnectionFactory.DEFAULT_AMQP_PORT, dut.m_connFactory.getPort());
    assertEquals(ConnectionFactory.DEFAULT_USER, dut.m_connFactory.getUsername());
    assertEquals(ConnectionFactory.DEFAULT_PASS, dut.m_connFactory.getPassword());
    assertEquals(ConnectionFactory.DEFAULT_VHOST, dut.m_connFactory.getVirtualHost());
    assertEquals("", dut.m_exchangeName);
    assertTrue(dut.m_routingKeyColumns.isEmpty());
    assertFalse(dut.m_skipInternal);
    assertEquals(MessageProperties.PERSISTENT_TEXT_PLAIN, dut.m_channelProperties);
    assertEquals(ExportDecoderBase.BinaryEncoding.HEX, dut.m_binaryEncoding);
    assertEquals(TimeZone.getTimeZone(VoltDB.GMT_TIMEZONE.getID()), dut.m_ODBCDateformat.get().getTimeZone());
}

From source file:org.wso2.carbon.event.adapter.rabbitmq.internal.util.RabbitMQOutputEventAdapterPublisher.java

License:Open Source License

public void publish(String payload, String exchange) {

    LOGGER.debug("*** DEBUG RabbitMQOutputEventAdapterPublisher().publish()");

    try {//from  w  ww.java2  s . c  o  m
        //create Queue
        createQueue(exchange);
        // Create and configure a message
        if (payload instanceof String) {
            channel.basicPublish("", queue, MessageProperties.PERSISTENT_TEXT_PLAIN,
                    ((String) payload).getBytes());
        } else {
            channel.basicPublish("", queue, MessageProperties.PERSISTENT_TEXT_PLAIN,
                    payload.toString().getBytes());
        }
        LOGGER.debug("*** DEBUG: [x] Sent " + payload.getClass() + " type, '" + payload + "'");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.carbon.event.adaptor.rabbitmq.output.RabbitMQOutputEventAdaptorType.java

License:Open Source License

/**
 * <pre>/*from   w ww .  j a  v a 2s.c o m*/
 * publish
 * <pre>
 * 
 * @param outputEventAdaptorMessageConfiguration
 * @param message
 * @param outputEventAdaptorConfiguration
 * @param tenantId
 * @see org.wso2.carbon.event.output.adaptor.core.AbstractOutputEventAdaptor#publish(org.wso2.carbon.event.output.adaptor.core.message.config.OutputEventAdaptorMessageConfiguration, java.lang.Object, org.wso2.carbon.event.output.adaptor.core.config.OutputEventAdaptorConfiguration, int)
 */
@Override
protected void publish(OutputEventAdaptorMessageConfiguration outputEventAdaptorMessageConfiguration,
        Object message, OutputEventAdaptorConfiguration outputEventAdaptorConfiguration, int tenantId) {

    LOGGER.debug("*** DEBUG RabbitMQOutputEventAdaptorType.publish()");

    try {
        Channel channel = getChannel(outputEventAdaptorConfiguration, tenantId);

        String queue = outputEventAdaptorMessageConfiguration.getOutputMessageProperties()
                .get(RabbitMQEventAdaptorConstants.ADAPTOR_RABBITMQ_QUEUE);

        boolean isExist = false;
        try {
            channel.queueDeclarePassive(queue);
            isExist = true;
        } catch (IOException e) {
            LOGGER.info("*** INFO : [" + queue + "] does not exist.");
        }

        if (!isExist) {
            String dlmExchangeName = "exchange_dlm";
            String routingKey = queue;

            if (!channel.isOpen()) {
                channel = getChannel(outputEventAdaptorConfiguration, tenantId);
            }

            /**
             *  Add configuration for DLM
             */
            Map<String, Object> arg = new HashMap<String, Object>();
            arg.put("x-dead-letter-exchange", dlmExchangeName);
            arg.put("x-dead-letter-routing-key", routingKey);

            /**
             *  Create a queue and binding with DLM
             */
            channel.queueDeclare(queue, true, false, false, arg);
            channel.queueBind(queue, dlmExchangeName, routingKey);
        }

        if (message instanceof String) {
            channel.basicPublish("", queue, MessageProperties.PERSISTENT_TEXT_PLAIN,
                    ((String) message).getBytes());
        } else {
            channel.basicPublish("", queue, MessageProperties.PERSISTENT_TEXT_PLAIN,
                    message.toString().getBytes());
        }
        LOGGER.debug("*** DEBUG: [x] Sent " + message.getClass() + " type, '" + message + "'");
    } catch (IOException e) {
        throw new AdaptorRuntimeException(e);
    }
}

From source file:org.wso2.siddhi.debs2017.input.rabbitmq.RabbitMQSampleDataPublisher.java

License:Open Source License

public static void start(String[] argv) {

    try {/* ww  w  .  j  av  a2s . co m*/
        if (argv.length > 0) {
            TASK_QUEUE_NAME = argv[0];
        }
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
        String data = "";
        BufferedReader reader = new BufferedReader(new FileReader("frmattedData_63.nt"));//molding_machine_100M.nt rdfSample.txt //Machine_59 //frmattedData.txt
        // read file line by line
        String line;
        Scanner scanner;
        int count = 0;
        while ((line = reader.readLine()) != null) {
            scanner = new Scanner(line);
            while (scanner.hasNext()) {
                String dataInLine = scanner.next();
                if (dataInLine.contains("----")) {
                    if (data.length() > 100) {
                        for (int i = 0; i < 5; i++) {
                            count++;
                            System.out.println(count);
                            String data1 = data.replace("Machine_59", "Machine_" + i).replace("_59_",
                                    "_" + i + "_");
                            channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,
                                    data1.getBytes());
                        }
                    }
                    data = "";
                } else {
                    data += " " + dataInLine;
                    if (dataInLine.contains(".") && !dataInLine.contains("<")) {
                        data += "\n";
                    }
                }
            }
        }

        channel.close();
        connection.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.siddhi.debs2017.input.rabbitmq.RabbitMQSamplePublisher.java

License:Open Source License

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

    if (argv.length > 0) {
        TASK_QUEUE_NAME = argv[0];/*from  ww w . j  a v a2  s .co m*/
    }
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    String data = "";
    try {
        BufferedReader reader = new BufferedReader(new FileReader("frmattedData_63.nt"));//molding_machine_100M.nt rdfSample.txt //Machine_59 //frmattedData.txt
        // read file line by line
        String line;
        Scanner scanner;
        int count = 0;
        while ((line = reader.readLine()) != null) {
            scanner = new Scanner(line);
            while (scanner.hasNext()) {
                String dataInLine = scanner.next();
                if (dataInLine.contains("----")) {
                    if (data.length() > 100) {
                        for (int i = 0; i < 5; i++) {
                            count++;
                            System.out.println(count);
                            // System.out.println(data);
                            //Thread.sleep(5000);
                            String data1 = data.replace("Machine_59", "Machine_" + i).replace("_59_",
                                    "_" + i + "_");
                            channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,
                                    data1.getBytes());
                        }
                    }
                    data = "";
                } else {
                    data += " " + dataInLine;
                    if (dataInLine.contains(".") && !dataInLine.contains("<")) {
                        data += "\n";
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

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

From source file:play.modules.rabbitmq.RabbitMQPlugin.java

License:Apache License

/**
 * Gets the basic properties./*w  w  w .  j a v a2 s. co  m*/
 * 
 * @return the basic properties
 */
public static BasicProperties getBasicProperties() {
    if (isDurable() == false) {
        return null;
    }
    BasicProperties b = MessageProperties.PERSISTENT_TEXT_PLAIN;
    return b;
}

From source file:server.WorkerServer.java

License:Open Source License

private void doWork(HttpRequest request) throws Exception {
    // Parse the request
    try {/*from   w  w w. j ava 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:stock84885customer.CustomerController.java

private void sendOrder() throws InterruptedException, IOException, TimeoutException {
    ordersChannel = connection.createChannel();
    ordersChannel.queueDeclare(ordersExchangeName, true, //Passive declaration
            false, //Non-durable queue
            false, //Non-exclusive queue
            null //No arguments
    );//from w w  w.j  a  v a  2s . c om
    Order order = generateOrder();
    ordersChannel.basicPublish("", ordersExchangeName, MessageProperties.PERSISTENT_TEXT_PLAIN,
            order.serialize());
    logger.trace(name + " sent order " + order.toString());
}