Example usage for javax.jms BytesMessage writeBytes

List of usage examples for javax.jms BytesMessage writeBytes

Introduction

In this page you can find the example usage for javax.jms BytesMessage writeBytes.

Prototype


void writeBytes(byte[] value) throws JMSException;

Source Link

Document

Writes a byte array to the bytes message stream.

Usage

From source file:com.atlantbh.jmeter.plugins.jmstools.BinaryMessageConverter.java

@Override
public Message toMessage(Object arg0, Session session) throws JMSException, MessageConversionException {
    BytesMessage msg = session.createBytesMessage();
    msg.writeBytes(arg0.toString().getBytes());
    return msg;//  w  ww .j a v  a  2  s. c  om
}

From source file:com.espertech.esper.example.servershellclient.ServerShellClientMain.java

public ServerShellClientMain() throws Exception {
    log.info("Loading properties");
    Properties properties = new Properties();
    InputStream propertiesIS = ServerShellClientMain.class.getClassLoader()
            .getResourceAsStream(ServerShellConstants.CONFIG_FILENAME);
    if (propertiesIS == null) {
        throw new RuntimeException(
                "Properties file '" + ServerShellConstants.CONFIG_FILENAME + "' not found in classpath");
    }/*w ww.  j  a  v  a 2s  .c om*/
    properties.load(propertiesIS);

    // Attached via JMX to running server
    log.info("Attach to server via JMX");
    JMXServiceURL url = new JMXServiceURL(properties.getProperty(ServerShellConstants.MGMT_SERVICE_URL));
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    ObjectName mBeanName = new ObjectName(ServerShellConstants.MGMT_MBEAN_NAME);
    EPServiceProviderJMXMBean proxy = (EPServiceProviderJMXMBean) MBeanServerInvocationHandler
            .newProxyInstance(mbsc, mBeanName, EPServiceProviderJMXMBean.class, true);

    // Connect to JMS
    log.info("Connecting to JMS server");
    String factory = properties.getProperty(ServerShellConstants.JMS_CONTEXT_FACTORY);
    String jmsurl = properties.getProperty(ServerShellConstants.JMS_PROVIDER_URL);
    String connFactoryName = properties.getProperty(ServerShellConstants.JMS_CONNECTION_FACTORY_NAME);
    String user = properties.getProperty(ServerShellConstants.JMS_USERNAME);
    String password = properties.getProperty(ServerShellConstants.JMS_PASSWORD);
    String destination = properties.getProperty(ServerShellConstants.JMS_INCOMING_DESTINATION);
    boolean isTopic = Boolean.parseBoolean(properties.getProperty(ServerShellConstants.JMS_IS_TOPIC));
    JMSContext jmsCtx = JMSContextFactory.createContext(factory, jmsurl, connFactoryName, user, password,
            destination, isTopic);

    // Create statement via JMX
    log.info("Creating a statement via Java Management Extensions (JMX) MBean Proxy");
    proxy.createEPL("select * from SampleEvent where duration > 9.9", "filterStatement",
            new ClientSideUpdateListener());

    // Get producer
    jmsCtx.getConnection().start();
    MessageProducer producer = jmsCtx.getSession().createProducer(jmsCtx.getDestination());

    Random random = new Random();
    String[] ipAddresses = { "127.0.1.0", "127.0.2.0", "127.0.3.0", "127.0.4.0" };
    NumberFormat format = NumberFormat.getInstance();

    // Send messages
    for (int i = 0; i < 1000; i++) {
        String ipAddress = ipAddresses[random.nextInt(ipAddresses.length)];
        double duration = 10 * random.nextDouble();
        String durationStr = format.format(duration);
        String payload = ipAddress + "," + durationStr;

        BytesMessage bytesMessage = jmsCtx.getSession().createBytesMessage();
        bytesMessage.writeBytes(payload.getBytes());
        bytesMessage.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
        producer.send(bytesMessage);

        if (i % 100 == 0) {
            log.info("Sent " + i + " messages");
        }
    }

    // Create statement via JMX
    log.info("Destroing statement via Java Management Extensions (JMX) MBean Proxy");
    proxy.destroy("filterStatement");

    log.info("Shutting down JMS client connection");
    jmsCtx.destroy();

    log.info("Exiting");
    System.exit(-1);
}

From source file:TopicPublisher.java

private void publish() throws Exception {

    // send events
    BytesMessage msg = session.createBytesMessage();
    msg.writeBytes(payload);
    for (int i = 0; i < messages; i++) {
        publisher.send(msg);//from  w w  w.java  2  s  .  com
        if ((i + 1) % 1000 == 0) {
            System.out.println("Sent " + (i + 1) + " messages");
        }
    }

    // request report
    publisher.send(session.createTextMessage("REPORT"));
}

From source file:com.opengamma.examples.analyticservice.ExampleAnalyticServiceUsage.java

private String generateTrade(String securityId, String destinationName, JmsConnector jmsConnector) {
    SimpleTrade trade = new SimpleTrade();
    trade.setCounterparty(COUNTERPARTY);
    trade.setPremiumCurrency(Currency.USD);
    trade.setQuantity(BigDecimal.valueOf(_random.nextInt(10) + 10));
    trade.setTradeDate(LocalDate.now());
    String providerId = GUIDGenerator.generate().toString();
    trade.addAttribute(PROVIDER_ID_NAME, RANDOM_ID_SCHEME + "~" + providerId);
    trade.setSecurityLink(new SimpleSecurityLink(ExternalSchemes.syntheticSecurityId(securityId)));
    s_logger.debug("Generated {}", trade);

    FudgeMsg msg = s_fudgeContext.toFudgeMsg(trade).getMessage();

    s_logger.debug("sending {} to {}", msg, destinationName);

    final byte[] bytes = s_fudgeContext.toByteArray(msg);

    jmsConnector.getJmsTemplateQueue().send(destinationName, new MessageCreator() {
        @Override//from  www. j av  a  2s. c o  m
        public Message createMessage(Session session) throws JMSException {
            BytesMessage bytesMessage = session.createBytesMessage();
            bytesMessage.writeBytes(bytes);
            return bytesMessage;
        }
    });
    return providerId;
}

From source file:com.microsoft.azure.servicebus.samples.jmstopicquickstart.JmsTopicQuickstart.java

public void run(String connectionString) throws Exception {

    // The connection string builder is the only part of the azure-servicebus SDK library 
    // we use in this JMS sample and for the purpose of robustly parsing the Service Bus 
    // connection string. 
    ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString);

    // set up the JNDI context 
    Hashtable<String, String> hashtable = new Hashtable<>();
    hashtable.put("connectionfactory.SBCF",
            "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true");
    hashtable.put("topic.TOPIC", "BasicTopic");
    hashtable.put("queue.SUBSCRIPTION1", "BasicTopic/Subscriptions/Subscription1");
    hashtable.put("queue.SUBSCRIPTION2", "BasicTopic/Subscriptions/Subscription2");
    hashtable.put("queue.SUBSCRIPTION3", "BasicTopic/Subscriptions/Subscription3");
    hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
    Context context = new InitialContext(hashtable);

    ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");

    // Look up the topic
    Destination topic = (Destination) context.lookup("TOPIC");

    // we create a scope here so we can use the same set of local variables cleanly 
    // again to show the receive side seperately with minimal clutter
    {//from  w  w  w.  ja v a  2 s  . c  o m
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        connection.start();
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

        // Create producer
        MessageProducer producer = session.createProducer(topic);

        // Send messaGES
        for (int i = 0; i < totalSend; i++) {
            BytesMessage message = session.createBytesMessage();
            message.writeBytes(String.valueOf(i).getBytes());
            producer.send(message);
            System.out.printf("Sent message %d.\n", i + 1);
        }

        producer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    // Look up the subscription (pretending it's a queue)
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION1");
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION2");
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION3");

    System.out.printf("Received all messages, exiting the sample.\n");
    System.out.printf("Closing queue client.\n");
}

From source file:com.microsoft.azure.servicebus.samples.jmsqueuequickstart.JmsQueueQuickstart.java

public void run(String connectionString) throws Exception {

    // The connection string builder is the only part of the azure-servicebus SDK library
    // we use in this JMS sample and for the purpose of robustly parsing the Service Bus 
    // connection string. 
    ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString);

    // set up JNDI context
    Hashtable<String, String> hashtable = new Hashtable<>();
    hashtable.put("connectionfactory.SBCF",
            "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true");
    hashtable.put("queue.QUEUE", "BasicQueue");
    hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
    Context context = new InitialContext(hashtable);
    ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");

    // Look up queue
    Destination queue = (Destination) context.lookup("QUEUE");

    // we create a scope here so we can use the same set of local variables cleanly 
    // again to show the receive side separately with minimal clutter
    {//w w  w. ja v  a  2  s. c om
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

        // Create producer
        MessageProducer producer = session.createProducer(queue);

        // Send messages
        for (int i = 0; i < totalSend; i++) {
            BytesMessage message = session.createBytesMessage();
            message.writeBytes(String.valueOf(i).getBytes());
            producer.send(message);
            System.out.printf("Sent message %d.\n", i + 1);
        }

        producer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    {
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        connection.start();
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        // Create consumer
        MessageConsumer consumer = session.createConsumer(queue);
        // create a listener callback to receive the messages
        consumer.setMessageListener(message -> {
            try {
                // receives message is passed to callback
                System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the tracking counter
                        message.getJMSMessageID());
                message.acknowledge();
            } catch (Exception e) {
                logger.error(e);
            }
        });

        // wait on the main thread until all sent messages have been received
        while (totalReceived.get() < totalSend) {
            Thread.sleep(1000);
        }
        consumer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    System.out.printf("Received all messages, exiting the sample.\n");
    System.out.printf("Closing queue client.\n");
}

From source file:QueueRoundTrip.java

private void QueueRoundTripper(String broker, String username, String password, int numTests) {

    try {/*from   w ww  . ja v a 2s  .co  m*/
        //Set up two sessions, one for sending and the other for receiving
        factory = new ActiveMQConnectionFactory(username, password, broker);
        connection = factory.createConnection(username, password);
        sendSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        receiveSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
    } catch (javax.jms.JMSException jmse) {
        System.err.println("error: Cannot connect to broker- " + broker + ".\n");
        jmse.printStackTrace();
        System.exit(1);
    }

    try {
        //Set up a temporary Queue:
        javax.jms.TemporaryQueue tempQueue = sendSession.createTemporaryQueue();
        receiver = receiveSession.createConsumer(tempQueue);
        sender = sendSession.createProducer(tempQueue);
        connection.start();
    } catch (javax.jms.JMSException jmse) {
        System.err.println("error: Connection couldn't be started.\n");
        jmse.printStackTrace();
        System.exit(1);
    }

    //Send messages using Temporary Queue:
    try {
        System.out.println("QueueRoundTrip application:");
        System.out.println("===========================");
        System.out.println("Sending Messages to Temporary Queue...");

        //create a message to send
        javax.jms.BytesMessage msg = sendSession.createBytesMessage();
        msg.writeBytes(msgBody);

        //send and receive the message the specified number of times:
        long time = System.currentTimeMillis();
        for (int i = 0; i < numTests; i++) {
            sender.send(msg);
            msg = (javax.jms.BytesMessage) receiver.receive();
        }
        time = System.currentTimeMillis() - time;

        System.out.println("\nTime for " + numTests + " sends and receives:\t\t" + time + "ms\n"
                + "Average Time per message:\t\t\t" + (float) time / (float) numTests + "ms\n");
        System.out.println("\n\nPress Enter to close this window.");
        java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
        stdin.readLine();
        System.exit(0);
    }

    catch (javax.jms.JMSException jmse) {
        System.err.println("error: message not sent/received.\n");
        jmse.printStackTrace();
        System.exit(1);
    }

    catch (java.io.IOException ioe) {
        ioe.printStackTrace();
    }

}

From source file:endpoint.protocol.jms.JMSBrokerController.java

public BytesMessage createBytesMessage(byte[] payload) {
    BytesMessage bm = null;
    try {// ww w .  j a v  a  2 s .  c o  m
        bm = this.session.createBytesMessage();
        bm.writeBytes(payload);
    } catch (JMSException e) {
        log.error("Error while sending message", e);
        Assert.fail();
    }
    return bm;
}

From source file:com.datatorrent.lib.io.jms.JMSObjectInputOperatorTest.java

private void createByteMsgs(int numMessages) throws Exception {
    BytesMessage message = testMeta.session.createBytesMessage();
    for (int i = 0; i < numMessages; i++) {
        message.writeBytes(("Message: " + i).getBytes());
        message.setIntProperty("counter", i);
        message.setJMSCorrelationID("MyCorrelationID");
        message.setJMSReplyTo(new ActiveMQQueue("MyReplyTo"));
        message.setJMSType("MyType");
        message.setJMSPriority(5);/*from  w w  w.  j a  v a  2  s .  c o m*/
        testMeta.producer.send(message);
    }
}

From source file:com.kinglcc.spring.jms.core.converter.Jackson2JmsMessageConverter.java

/**
 * Map the given object to a {@link BytesMessage}.
 * @param object the object to be mapped
 * @param session current JMS session// w ww . j a  v a 2  s  .  c om
 * @param objectMapper the mapper to use
 * @return the resulting message
 * @throws JMSException if thrown by JMS methods
 * @throws IOException in case of I/O errors
 * @see Session#createBytesMessage
 */
protected BytesMessage mapToBytesMessage(Object object, Session session, ObjectMapper objectMapper)
        throws JMSException, IOException {

    ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
    OutputStreamWriter writer = new OutputStreamWriter(bos, this.encoding);
    objectMapper.writeValue(writer, object);

    BytesMessage message = session.createBytesMessage();
    message.writeBytes(bos.toByteArray());
    if (this.encodingPropertyName != null) {
        message.setStringProperty(this.encodingPropertyName, this.encoding);
    }
    return message;
}