Example usage for com.rabbitmq.client MessageProperties MINIMAL_PERSISTENT_BASIC

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

Introduction

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

Prototype

BasicProperties MINIMAL_PERSISTENT_BASIC

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

Click Source Link

Document

Empty basic properties, with only deliveryMode set to 2 (persistent)

Usage

From source file:edu.kit.dama.util.test.RabbitMQTest.java

License:Apache License

public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout", true, false, false, null);
    //channel.queueDeclare(QUEUE_NAME, true, false, false, null);
    /*String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, EXCHANGE_NAME, "");*/

    String message = "Hello!";

    channel.basicPublish(EXCHANGE_NAME, "", MessageProperties.MINIMAL_PERSISTENT_BASIC, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();// www  .jav a 2 s.c  om
    connection.close();

}

From source file:org.apache.synapse.message.store.impl.rabbitmq.RabbitMQProducer.java

License:Open Source License

public boolean storeMessage(MessageContext synCtx) {
    if (synCtx == null) {
        return false;
    }/*from   w  w  w  . ja  va 2 s.  c  om*/
    if (connection == null) {
        if (logger.isDebugEnabled()) {
            logger.error(getId() + " cannot proceed. RabbitMQ Connection is null.");
        }
        logger.warn(getId() + ". Ignored MessageID : " + synCtx.getMessageID());
        return false;
    }
    StorableMessage message = MessageConverter.toStorableMessage(synCtx);
    boolean error = false;
    Throwable throwable = null;
    Channel channel = null;
    try {
        //Serializing message
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ObjectOutput objOut = new ObjectOutputStream(os);
        objOut.writeObject(message);
        byte[] byteForm = os.toByteArray();
        objOut.close();
        os.close();
        //building AMQP message
        AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties().builder();
        builder.messageId(synCtx.getMessageID());
        builder.deliveryMode(MessageProperties.MINIMAL_PERSISTENT_BASIC.getDeliveryMode());
        builder.priority(message.getPriority(DEFAULT_PRIORITY));
        channel = connection.createChannel();
        if (exchangeName == null) {
            channel.basicPublish("", queueName, builder.build(), byteForm);
        } else {
            channel.basicPublish(exchangeName, queueName, builder.build(), byteForm);
        }
    } catch (IOException e) {
        throwable = e;
        error = true;
        isConnectionError = true;
    } catch (Throwable t) {
        throwable = t;
        error = true;
    } finally {
        if (channel != null && channel.isOpen())
            try {
                channel.close();
            } catch (IOException e) {
                logger.error("Error when closing connection" + synCtx.getMessageID() + ". " + e);
            }
    }
    if (error) {
        String errorMsg = getId() + ". Ignored MessageID : " + synCtx.getMessageID()
                + ". Could not store message to store [" + store.getName() + "]. Error:"
                + throwable.getLocalizedMessage();
        logger.error(errorMsg, throwable);
        store.closeProducerConnection();
        connection = null;
        if (logger.isDebugEnabled()) {
            logger.debug(getId() + ". Ignored MessageID : " + synCtx.getMessageID());
        }
        return false;
    }
    if (logger.isDebugEnabled()) {
        logger.debug(getId() + ". Stored MessageID : " + synCtx.getMessageID());
    }
    store.enqueued();
    return true;
}

From source file:org.hobbit.core.rabbit.SimpleFileSender.java

License:Open Source License

public void streamData(InputStream is, String name) throws IOException {
    int messageId = 0;
    int length = 0;
    byte[] nameBytes = RabbitMQUtils.writeString(name);
    byte[] array = new byte[messageSize + nameBytes.length + 8];
    ByteBuffer buffer = ByteBuffer.wrap(array);
    buffer.putInt(nameBytes.length);//from   www .j  a  va 2  s. com
    buffer.put(nameBytes);
    int messageIdPos = buffer.position();
    int dataStartPos = messageIdPos + 4;
    do {
        buffer.position(messageIdPos);
        buffer.putInt(messageId);
        length = is.read(array, dataStartPos, array.length - dataStartPos);
        queue.channel.basicPublish("", queue.name, MessageProperties.MINIMAL_PERSISTENT_BASIC,
                Arrays.copyOf(array, (length > 0) ? (dataStartPos + length) : dataStartPos));
        ++messageId;
    } while (length > 0);
}

From source file:org.smartdeveloperhub.curator.connector.BrokerController.java

License:Apache License

private void publishMessage(final String exchangeName, final String routingKey, final String message)
        throws IOException {
    final Channel aChannel = currentChannel();
    try {//from  www.j  a  va 2s . c o m
        LOGGER.debug("Publishing message to exchange '{}' and routing key '{}'. Payload: \n{}", exchangeName,
                routingKey, message);
        final Map<String, Object> headers = Maps.newLinkedHashMap();
        headers.put(BROKER_CONTROLLER_MESSAGE, this.messageCounter.incrementAndGet());
        aChannel.basicPublish(exchangeName, routingKey, true,
                MessageProperties.MINIMAL_PERSISTENT_BASIC.builder().headers(headers).build(),
                message.getBytes());
    } catch (final IOException e) {
        discardChannel(aChannel);
        LOGGER.warn("Could not publish message [{}] to exchange '{}' and routing key '{}': {}", message,
                exchangeName, routingKey, e.getMessage());
        throw e;
    } catch (final Exception e) {
        discardChannel(aChannel);
        final String errorMessage = String.format(
                "Unexpected failure while publishing message [%s] to exchange '%s' and routing key '%s' using broker %s:%s%s: %s",
                message, exchangeName, routingKey, this.broker.host(), this.broker.port(),
                this.broker.virtualHost(), e.getMessage());
        LOGGER.error(errorMessage);
        throw new IOException(errorMessage, e);
    }
}

From source file:org.smartdeveloperhub.harvesters.it.notification.CollectorController.java

License:Apache License

private void publish(final Channel aChannel, final String exchangeName, final String routingKey,
        final String payload) throws ControllerException {
    try {/*www  .  ja  v  a2 s .  com*/
        LOGGER.trace("Publishing message to exchange '{}' and routing key '{}'. Payload: \n{}", exchangeName,
                routingKey, payload);
        final Map<String, Object> headers = Maps.newLinkedHashMap();
        headers.put(HttpHeaders.CONTENT_TYPE, Notifications.MIME);
        aChannel.basicPublish(exchangeName, routingKey, true,
                MessageProperties.MINIMAL_PERSISTENT_BASIC.builder().headers(headers).build(),
                payload.getBytes());
    } catch (final IOException e) {
        this.manager.discardChannel();
        final String errorMessage = String.format(
                "Could not publish message [%s] to exchange '%s' and routing key '%s' using broker %s:%s%s: %s",
                payload, exchangeName, routingKey, this.collector.getBrokerHost(),
                this.collector.getBrokerPort(), this.collector.getVirtualHost(), e.getMessage());
        LOGGER.error(errorMessage, e);
        throw new ControllerException(this.collector.getBrokerHost(), this.collector.getBrokerPort(),
                this.collector.getVirtualHost(), errorMessage, e);
    } catch (final Exception e) {
        this.manager.discardChannel();
        final String errorMessage = String.format(
                "Unexpected failure while publishing message [%s] to exchange '%s' and routing key '%s' using broker %s:%s%s: %s",
                payload, exchangeName, routingKey, this.collector.getBrokerHost(),
                this.collector.getBrokerPort(), this.collector.getVirtualHost(), e.getMessage());
        LOGGER.error(errorMessage, e);
        throw new ControllerException(this.collector.getBrokerHost(), this.collector.getBrokerPort(),
                this.collector.getVirtualHost(), errorMessage, e);
    }
}

From source file:org.smartdeveloperhub.harvesters.it.notification.CollectorControllerTest.java

License:Apache License

@Test
public void testPublishEvent$usesCurrentChannelAndImplementsNotificationProtocol(@Mocked final Channel channel)
        throws Exception {
    new MockUp<ConnectionManager>() {
        private boolean connected = false;

        @Mock(invocations = 1)/* w ww . j  av  a2s.c om*/
        void connect() {
            this.connected = true;
        }

        @Mock(invocations = 1)
        void disconnect() {
        }

        @Mock
        boolean isConnected() {
            return this.connected;
        }

        @Mock
        Channel channel() {
            return channel;
        }

        @Mock(invocations = 1)
        Channel currentChannel() {
            return channel;
        }

        @Mock(invocations = 0)
        void discardChannel() {
        }
    };
    final CollectorConfiguration defaultCollector = defaultCollector();
    new Expectations() {
        {
            channel.basicPublish(defaultCollector.getExchangeName(),
                    Notifications.routingKey(ProjectCreatedEvent.class), true, (BasicProperties) this.any,
                    (byte[]) this.any);
        }
    };
    final CollectorController sut = CollectorController.createPublisher(defaultCollector);
    final ProjectCreatedEvent event = new ProjectCreatedEvent();
    event.setInstance(defaultCollector.getInstance());
    event.setNewProjects(Arrays.asList("1", "2"));
    sut.connect();
    try {
        sut.publishEvent(event);
    } finally {
        sut.disconnect();
    }
    new Verifications() {
        {
            BasicProperties props;
            byte[] body;
            channel.basicPublish(defaultCollector.getExchangeName(),
                    Notifications.routingKey(ProjectCreatedEvent.class), true, props = withCapture(),
                    body = withCapture());
            assertThat(new String(body), equalTo(EventUtil.marshall(event)));
            assertThat(props.getHeaders().get(CONTENT_TYPE), equalTo((Object) Notifications.MIME));
            assertThat(props.getDeliveryMode(),
                    equalTo(MessageProperties.MINIMAL_PERSISTENT_BASIC.builder().build().getDeliveryMode()));
        }
    };
}

From source file:org.smartdeveloperhub.harvesters.scm.backend.notification.CollectorControllerTest.java

License:Apache License

@Test
public void testPublishEvent$usesCurrentChannelAndImplementsNotificationProtocol(@Mocked final Channel channel)
        throws Exception {
    new MockUp<ConnectionManager>() {
        private boolean connected = false;

        @Mock(invocations = 1)//from  w  w w .ja  v a 2 s  . co m
        void connect() {
            this.connected = true;
        }

        @Mock(invocations = 1)
        void disconnect() {
        }

        @Mock
        boolean isConnected() {
            return this.connected;
        }

        @Mock
        Channel channel() {
            return channel;
        }

        @Mock(invocations = 1)
        Channel currentChannel() {
            return channel;
        }

        @Mock(invocations = 0)
        void discardChannel() {
        }
    };
    final Collector defaultCollector = defaultCollector();
    new Expectations() {
        {
            channel.basicPublish(defaultCollector.getExchangeName(),
                    Notifications.routingKey(RepositoryCreatedEvent.class), true, (BasicProperties) this.any,
                    (byte[]) this.any);
        }
    };
    final CollectorController sut = CollectorController.createPublisher(defaultCollector);
    final RepositoryCreatedEvent event = new RepositoryCreatedEvent();
    event.setInstance(defaultCollector.getInstance());
    event.setNewRepositories(Arrays.asList("1", "2"));
    sut.connect();
    try {
        sut.publishEvent(event);
    } finally {
        sut.disconnect();
    }
    new Verifications() {
        {
            BasicProperties props;
            byte[] body;
            channel.basicPublish(defaultCollector.getExchangeName(),
                    Notifications.routingKey(RepositoryCreatedEvent.class), true, props = withCapture(),
                    body = withCapture());
            assertThat(new String(body), equalTo(EventUtil.marshall(event)));
            assertThat(props.getHeaders().get(HttpHeaders.CONTENT_TYPE), equalTo((Object) Notifications.MIME));
            assertThat(props.getDeliveryMode(),
                    equalTo(MessageProperties.MINIMAL_PERSISTENT_BASIC.builder().build().getDeliveryMode()));
        }
    };
}

From source file:org.thingsboard.rule.engine.rabbitmq.TbRabbitMqNode.java

License:Apache License

private static AMQP.BasicProperties convert(String name) throws TbNodeException {
    switch (name) {
    case "BASIC":
        return MessageProperties.BASIC;
    case "TEXT_PLAIN":
        return MessageProperties.TEXT_PLAIN;
    case "MINIMAL_BASIC":
        return MessageProperties.MINIMAL_BASIC;
    case "MINIMAL_PERSISTENT_BASIC":
        return MessageProperties.MINIMAL_PERSISTENT_BASIC;
    case "PERSISTENT_BASIC":
        return MessageProperties.PERSISTENT_BASIC;
    case "PERSISTENT_TEXT_PLAIN":
        return MessageProperties.PERSISTENT_TEXT_PLAIN;
    default://from   w  w  w .j  a  v a  2 s . c  om
        throw new TbNodeException("Message Properties: '" + name + "' is undefined!");
    }
}

From source file:org.thingsboard.server.extensions.rabbitmq.plugin.RabbitMqMsgHandler.java

License:Apache License

private static AMQP.BasicProperties convert(String name) throws RuleException {
    switch (name) {
    case "BASIC":
        return MessageProperties.BASIC;
    case "TEXT_PLAIN":
        return MessageProperties.TEXT_PLAIN;
    case "MINIMAL_BASIC":
        return MessageProperties.MINIMAL_BASIC;
    case "MINIMAL_PERSISTENT_BASIC":
        return MessageProperties.MINIMAL_PERSISTENT_BASIC;
    case "PERSISTENT_BASIC":
        return MessageProperties.PERSISTENT_BASIC;
    case "PERSISTENT_TEXT_PLAIN":
        return MessageProperties.PERSISTENT_TEXT_PLAIN;
    default:/*from   w w w . jav a2 s .c om*/
        throw new RuleException("Message Properties: '" + name + "' is undefined!");
    }
}

From source file:ru.kinomir.queue.QueueSender.java

public synchronized void sendToQueue(Object data, String queueName, String queueHost, String userName,
        String password, String port, String virtualHost) {
    Channel channel = null;//from   ww  w  . j a  v a2 s. c o  m
    Connection connection = null;
    try {
        logger.info("Send message to queue '" + queueName + "'");
        ConnectionFactory factory = new ConnectionFactory();
        if (!StringTools.isEmpty(userName)) {
            factory.setUsername(userName);
        }
        if (!StringTools.isEmpty(password)) {
            factory.setPassword(password);
        }
        if (!StringTools.isEmpty(port)) {
            try {
                factory.setPort(Integer.parseInt(port));
            } catch (NumberFormatException ignore) {

            }
        }
        if (!StringTools.isEmpty(virtualHost)) {
            factory.setVirtualHost(virtualHost);
        }
        factory.setHost(queueHost);

        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(queueName, true, false, false, null);
        String message = convertToString(data);
        logger.info("Message text: " + message);
        channel.basicPublish("", queueName, MessageProperties.MINIMAL_PERSISTENT_BASIC, message.getBytes());
        logger.info("Message was sent");
    } catch (Exception ex) {
        logger.error("Uneble send message: " + convertToString(data));
        logger.debug(ex.getMessage(), ex);
    } finally {
        try {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception ignore) {

        }
    }
}