Example usage for com.rabbitmq.client Channel basicPublish

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

Introduction

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

Prototype

void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException;

Source Link

Document

Publish a message.

Usage

From source file:org.wso2.siddhi.debs2017.output.AlertGenerator.java

License:Open Source License

/**
 * generate the rdf model and publish to rabbitmq
 */// www  .ja  v a  2 s. c  o m
public void generateAlert(Event event) {
    this.probThresh = Double.parseDouble(event.getData()[3].toString());
    //this.timestamp = transformTimestamp((String) event.getData()[1]);
    this.timestamp = (String) event.getData()[1];
    this.dimension = (String) event.getData()[2];
    this.machineNumber = (String) event.getData()[0];
    this.dispatchedTime = event.getTimestamp();

    Model model = ModelFactory.createDefaultModel();
    String anomalyName = "Anomaly_" + anomalyCount;
    Resource r1 = model.createResource(anomaly + anomalyName);
    Property type = model.createProperty(rdf + "type");
    Resource r2 = model.createResource(ar + "Anomaly");
    Property threshProb = model.createProperty(ar + "hasProbabilityOfObservedAbnormalSequence");
    Property time = model.createProperty(ar + "hasTimeStamp");
    Resource r4 = model.createResource(debs + timestamp);
    Property dim = model.createProperty(ar + "inAbnormalDimension");
    Resource r5 = model.createResource(wmm + dimension);
    Property machine = model.createProperty(i40 + "machine");
    Resource r6 = model.createResource(wmm + machineNumber);

    model.add(r1, threshProb, model.createTypedLiteral(probThresh)).add(r1, time, r4).add(r1, dim, r5)
            .add(r1, machine, r6).add(r1, type, r2);

    anomalyCount++;
    String str = "N-TRIPLES";
    out = new StringWriter();
    model.write(out, str);
    Channel channel = rabbitMQPublisher.getChannel();
    try {
        channel.basicPublish("", rabbitMQPublisher.getName(), MessageProperties.PERSISTENT_BASIC,
                out.toString().getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }

    sum += System.currentTimeMillis() - dispatchedTime;
    if (anomalyCount == 20000) {
        System.out.println("Average Latency : " + (sum / anomalyCount));
    }

}

From source file:org.wso2.siddhi.debs2017.output.AlertGenerator.java

License:Open Source License

public void terminate() {
    Channel channel = rabbitMQPublisher.getChannel();
    String TERMINATION_MESSAGE = "~~Termination Message~~";
    try {/* w  w  w.  j  a  v  a 2  s .c  om*/
        channel.basicPublish("", rabbitMQPublisher.getName(), MessageProperties.PERSISTENT_BASIC,
                TERMINATION_MESSAGE.toString().getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ox.softeng.gel.filereceive.FileReceive.java

public void generateStartupMessage() throws IOException {

    try {//from w  ww.j a v a 2s .  c om
        StringWriter writer;
        MessageDTO message = new MessageDTO();
        message.setSource("file-receiver");
        message.setDetails("Burst Service starting\n" + version());
        message.setSeverity(SeverityEnum.INFORMATIONAL);
        message.setDateTimeCreated(OffsetDateTime.now(ZoneId.of("UTC")));
        message.setTitle("File Receiver Startup");
        message.addTopic("service");
        message.addTopic("startup");
        message.addTopic("file-receiver");
        message.addMetadata("gmc", "gel");
        message.addMetadata("file_receiver_service_version", version());

        writer = new StringWriter();
        getMarshaller().marshal(message, writer);

        AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties().builder();
        builder.deliveryMode(2);
        builder.contentType("text/xml");
        builder.timestamp(Date.from(OffsetDateTime.now(ZoneId.systemDefault()).toInstant()));

        Channel channel = factory.newConnection().createChannel();
        channel.exchangeDeclare(exchangeName, "topic", true);
        channel.basicPublish(exchangeName, burstQueue, builder.build(), writer.toString().getBytes());
        channel.close();

    } catch (JAXBException | TimeoutException ignored) {
    }
}

From source file:pro.foundev.examples.spark_streaming.java.messaging.RabbitMQEmitWarnings.java

License:Apache License

public static void main(String[] argv) throws java.io.IOException {
    String master = Args.parseMaster(argv);

    mainThread = Thread.currentThread();

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(master);/*  ww w. j  a  v a  2s  .c o m*/
    final Connection connection = factory.newConnection();
    final Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            RabbitMQEmitWarnings.mainThread.interrupt();
            try {
                channel.close();
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    while (true) {
        String message = buildMessage();
        channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

From source file:pt.ua.ies.Main.java

public static void main(String[] args) {
    try {/*from   w  w w.  ja v  a2  s.co  m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

        String message = "Random Message " + new Random().nextInt(1000);
        channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");

        /**
         * Close the channel and the connection
         */
        channel.close();
        connection.close();
    } catch (Exception ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:rabbitirc.RabbitIRC.java

public static void main(String[] argv) throws java.io.IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Random rnd = new Random();
    int indeks = rnd.nextInt(usernamelist.length);
    String Randusername = usernamelist[indeks] + rnd.nextInt(100);

    user = Randusername;/*from w ww  . j  av a2  s .  c o  m*/
    channellist.add("lounge");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    String queueName = channel.queueDeclare().getQueue();
    channel.exchangeDeclare(EXCHANGE_NAME, "direct");

    Scanner sc = new Scanner(System.in);

    channel.queueBind(queueName, EXCHANGE_NAME, "lounge");
    channellist.add("lounge");
    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");
            System.out.println(" [x] Received :'" + message + "'");
        }
    };
    System.out.println(" Welcome " + user + " to Channel lounge");
    System.out.println(" Queries: ");
    System.out.println(" 1. /NICK <Username>            : Change username ");
    System.out.println(" 2. /JOIN <Channel Name>        : Join Channel");
    System.out.println(" 3. @<Channel Name> <Message>   : Send message to Spesific Channel");
    System.out.println(" 4. /LEAVE <Channel Name>       : Leave Channel");
    System.out.println(" 5. <Random text>               : BroadCast");
    System.out.println(" 6. /EXIT                       : Exit App");
    while (true) {
        channel.basicConsume(queueName, true, consumer);
        String input = sc.nextLine();
        String[] query;
        if ((query = CommandRegexes.NICK.match(input)) != null) {
            String Nickname = query[0];
            user = Nickname;
            System.out.println(" [x] Your Nickname '" + Nickname + "'");

        } else if ((query = CommandRegexes.JOIN.match(input)) != null) {
            String channel_name = query[0];
            channel.queueBind(queueName, EXCHANGE_NAME, channel_name);
            channellist.add(channel_name);
            System.out.println(" [x] you had Join '" + channel_name + "'");

        } else if ((query = CommandRegexes.LEAVE.match(input)) != null) {
            String channel_name = query[0];
            if (channellist.contains(channel_name)) {
                channellist.remove(channellist.indexOf(channel_name));
                channel.queueUnbind(queueName, EXCHANGE_NAME, channel_name);
                System.out.println(" [x] you had leave '" + channel_name);
            } else {
                System.out.println(" [x] you're not in the channel " + channel_name);
            }
            System.out.println(" [x] you had leave '" + channel_name + "'");

        } else if (CommandRegexes.EXIT.match(input) != null) {
            channel.close();
            connection.close();
            break;

        } else if ((query = CommandRegexes.MESSAGE_CHANNEL.match(input)) != null) {
            String channel_name = query[0];
            if (channellist.contains(channel_name)) {
                String message = "[" + channel_name + "] (" + user + ") " + query[1];
                channel.basicPublish(EXCHANGE_NAME, channel_name, null, message.getBytes());
                System.out.println(" [x] Sent '" + message + "'");
                System.out.println(" : to '" + channel_name + "'");
            } else {
                System.out.println(" [x] No Channel " + channel_name + " on your list");
            }
        } else {
            System.out.println(" [x] Broadcasting '" + input + "'");
            for (String channellist1 : channellist) {
                String messages = "[" + channellist1 + "] (" + user + ") " + input;
                channel.basicPublish(EXCHANGE_NAME, channellist1, null, messages.getBytes());
            }
            System.out.println(" [x] OK ;D");
        }
    }

}

From source file:rabbitmq.Producer.java

public void run() {
    try {/* ww w  .j  a  v  a2 s.c o m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

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

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        for (int i = 0; i < num; i++) {
            Mensaje persona = new Mensaje("RabbitMQ_Java", "Persona" + i, "ID" + i);
            Gson gson = new Gson();
            String message = gson.toJson(persona);

            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            System.out.println(" [" + id + "] Sent '" + message + "'");
        }

        channel.close();
        connection.close();
    } catch (IOException ex) {
        Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:rabbitmqapp.EmitLog.java

public static void main(String... args) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(Cons.RABBIT_MQ_URL);
    factory.setConnectionTimeout(3000);/*  w  w  w. ja va2  s .  c o m*/
    factory.setRequestedHeartbeat(30);

    //Create a connection
    Connection connection = factory.newConnection();
    //create a channel from connection
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(Cons.EXCHANGE_NAME, EXCHANGE_TYPE);
    String message = "Hello Dolly";

    channel.basicPublish(Cons.EXCHANGE_NAME, "", null, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");
    channel.close();
    connection.close();
}

From source file:rabbitmqapp.RabbitMQApp.java

/**
 * @param args the command line arguments
 *//*from w ww.ja  v a  2s .c  om*/
public static void main(String[] args) throws Exception {
    ProductOrder order = new ProductOrder("Thando Mlauzi", 34.50);
    ConnectionFactory factory = new ConnectionFactory();
    String uri = "amqp://ytsoedex:Qu2LCiBJ5x9fhRUyLYkMhJqsURJ9dkSP@chicken.rmq.cloudamqp.com/ytsoedex";
    factory.setUri(uri);

    //Recommended settings
    factory.setRequestedHeartbeat(30);
    factory.setConnectionTimeout(30000);

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

    channel.queueDeclare(QUENAME, false, false, false, null);
    String message = "Hello World!";
    channel.basicPublish("", QUENAME, null, RabbitUtility.convertToByteArray(order));
    System.out.println(" [x] Sent '" + order + "'");

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

}

From source file:reactor.rabbitmq.ConnectionRecoveryTests.java

License:Open Source License

@ParameterizedTest
@MethodSource("consumeArguments")
public void consumeConsumerShouldRecoverAutomatically(
        BiFunction<Receiver, String, Flux<? extends Delivery>> deliveryFactory) throws Exception {
    Channel channel = connection.createChannel();
    int nbMessages = 10;

    receiver = RabbitFlux.createReceiver(new ReceiverOptions().connectionMono(connectionMono));

    for (int $ : IntStream.range(0, 1).toArray()) {
        Flux<? extends Delivery> flux = deliveryFactory.apply(receiver, queue);
        for (int $$ : IntStream.range(0, nbMessages).toArray()) {
            channel.basicPublish("", queue, null, "Hello".getBytes());
        }//from   w w  w  .j a v a 2s. c  om

        CountDownLatch latch = new CountDownLatch(nbMessages * 2);
        AtomicInteger counter = new AtomicInteger();
        Disposable subscription = flux.subscribe(msg -> {
            counter.incrementAndGet();
            latch.countDown();
            if (msg instanceof AcknowledgableDelivery) {
                ((AcknowledgableDelivery) msg).ack();
            }
        });

        closeAndWaitForRecovery((RecoverableConnection) connectionMono.block());

        for (int $$ : IntStream.range(0, nbMessages).toArray()) {
            channel.basicPublish("", queue, null, "Hello".getBytes());
        }

        assertTrue(latch.await(1, TimeUnit.SECONDS));
        subscription.dispose();
        assertEquals(nbMessages * 2, counter.get());
    }
    assertNull(connection.createChannel().basicGet(queue, true));
}