Example usage for javax.jms Session createBytesMessage

List of usage examples for javax.jms Session createBytesMessage

Introduction

In this page you can find the example usage for javax.jms Session createBytesMessage.

Prototype

BytesMessage createBytesMessage() throws JMSException;

Source Link

Document

Creates a BytesMessage object.

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  w  w. jav  a 2 s . c om*/
}

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 w ww  . j a v a 2  s  . c o m
        public Message createMessage(Session session) throws JMSException {
            BytesMessage bytesMessage = session.createBytesMessage();
            bytesMessage.writeBytes(bytes);
            return bytesMessage;
        }
    });
    return providerId;
}

From source file:me.norman.maurer.james.queue.HornetQMailQueue.java

@Override
protected void produceMail(Session session, Map<String, Object> props, int msgPrio, Mail mail)
        throws JMSException, MessagingException, IOException {
    MessageProducer producer = null;//from  w  w  w  .ja  v a  2  s  . c  o  m
    try {
        BytesMessage message = session.createBytesMessage();
        Iterator<String> propIt = props.keySet().iterator();
        while (propIt.hasNext()) {
            String key = propIt.next();
            message.setObjectProperty(key, props.get(key));
        }
        // set the stream to read frome
        message.setObjectProperty("JMS_HQ_InputStream",
                new BufferedInputStream(new MimeMessageInputStream(mail.getMessage())));
        Queue q = session.createQueue(queuename);
        producer = session.createProducer(q);
        producer.send(message, Message.DEFAULT_DELIVERY_MODE, msgPrio, Message.DEFAULT_TIME_TO_LIVE);
    } finally {
        if (producer != null) {
            producer.close();
        }
    }
}

From source file:org.bremersee.common.jms.DefaultJmsConverter.java

private Message createSerializedMessage(Serializable object, Session session) throws JMSException {
    try {/* ww  w  .  j  a  va2  s  .co m*/
        BytesMessage msg = session.createBytesMessage();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.flush();
        msg.writeBytes(outputStream.toByteArray());
        msg.setJMSType(object.getClass().getName());
        return msg;

    } catch (Throwable t) { // NOSONAR
        log.info("Creating Serialized JMS from object of type ["
                + (object == null ? "null" : object.getClass().getName()) + "] failed.");
        return null;
    }
}

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 .j a 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
    {/*from  w ww. j  a  v a2 s. c o m*/
        // 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:com.eviware.soapui.impl.wsdl.submit.transports.jms.HermesJmsRequestTransport.java

private Message createBytesMessageFromText(SubmitContext submitContext, String requestContent, Session session)
        throws JMSException {
    BytesMessage bytesMessage = session.createBytesMessage();
    bytesMessage.writeBytes(requestContent.getBytes());
    return bytesMessage;
}

From source file:com.mirth.connect.connectors.jms.JmsMessageUtils.java

public static Message getMessageForObject(Object object, Session session) throws JMSException {
    if (object instanceof Message) {
        return (Message) object;
    } else if (object instanceof String) {
        TextMessage text = session.createTextMessage((String) object);
        return text;
    } else if (object instanceof Map) {
        MapMessage map = session.createMapMessage();
        Map.Entry entry = null;//from  www .  j av  a  2 s  .  c o  m
        Map temp = (Map) object;

        for (Iterator i = temp.entrySet().iterator(); i.hasNext();) {
            entry = (Map.Entry) i.next();
            map.setObject(entry.getKey().toString(), entry.getValue());
        }

        return map;
    } else if (object instanceof InputStream) {
        StreamMessage stream = session.createStreamMessage();
        InputStream temp = (InputStream) object;

        byte[] buffer = new byte[1024 * 4];
        int len = 0;
        try {
            while ((len = temp.read(buffer)) != -1) {
                stream.writeBytes(buffer, 0, len);
            }
        } catch (IOException e) {
            throw new JMSException("Failed to read input stream to create a stream message: " + e);
        }

        return stream;
    } else if (object instanceof byte[]) {
        BytesMessage bytes = session.createBytesMessage();
        byte[] buf = (byte[]) object;
        for (int i = 0; i < buf.length; i++) {
            bytes.writeByte(buf[i]);
        }

        return bytes;
    } else if (object instanceof Serializable) {
        ObjectMessage oMsg = session.createObjectMessage();
        oMsg.setObject((Serializable) object);
        return oMsg;
    } else {
        throw new JMSException(
                "Source was not a supported type, data must be Serializable, String, byte[], Map or InputStream");
    }
}

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 w  w  . j  a  v a  2  s. com*/
 * @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;
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.jms.HermesJmsRequestTransport.java

private Message createBytesMessage(Request request, Session session) {
    try {/*w  w  w .  j  a  va2s .c  o m*/
        InputStream in = request.getAttachments()[0].getInputStream();
        int buff = -1;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((buff = in.read()) != -1) {
            baos.write(buff);
        }
        BytesMessage bytesMessage = session.createBytesMessage();
        bytesMessage.writeBytes(baos.toByteArray());
        return bytesMessage;
    } catch (Exception e) {
        SoapUI.logError(e);
    }
    return null;
}