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:org.mitre.mpf.markup.MarkupRequestConsumer.java

public void onMessage(Message message) {
    Stopwatch stopwatch = Stopwatch.createStarted();

    if (message == null) {
        log.warn("Received a null JMS message. No action will be taken.");
        return;/*from w  w  w . j  a  v  a2s.co  m*/
    }

    if (!(message instanceof BytesMessage)) {
        log.warn("Received a JMS message, but it was not of the correct type. No action will be taken.");
        return;
    }

    try {
        log.info("Received JMS message. Type = {}. JMS Message ID = {}. JMS Correlation ID = {}.",
                message.getClass().getName(), message.getJMSMessageID(), message.getJMSCorrelationID());

        final Map<String, Object> requestHeaders = new HashMap<String, Object>();
        Enumeration<String> properties = message.getPropertyNames();

        String propertyName = null;
        while (properties.hasMoreElements()) {
            propertyName = properties.nextElement();
            requestHeaders.put(propertyName, message.getObjectProperty(propertyName));
        }

        byte[] messageBytes = new byte[(int) (((BytesMessage) message).getBodyLength())];
        ((BytesMessage) message).readBytes(messageBytes);
        Markup.MarkupRequest markupRequest = Markup.MarkupRequest.parseFrom(messageBytes);
        Markup.MarkupResponse.Builder markupResponseBuilder = initializeResponse(markupRequest);
        markupResponseBuilder.setRequestTimestamp(message.getJMSTimestamp());

        log.debug("Processing markup request. Media Index = {}. Media ID = {} (type = {}). Request ID = {}.",
                markupRequest.getMediaIndex(), markupRequest.getMediaId(), markupRequest.getMediaType(),
                markupRequest.getRequestId());

        try {
            if (!new File(URI.create(markupRequest.getDestinationUri())).canWrite()) {
                throw new Exception();
            }
        } catch (Exception exception) {
            markupResponseBuilder.setHasError(true);
            markupResponseBuilder.setErrorMessage(
                    String.format("The target URI '%s' is not writable.", markupRequest.getDestinationUri()));
        }

        try {
            if (!new File(URI.create(markupRequest.getSourceUri())).canRead()) {
                throw new Exception();
            }
        } catch (Exception exception) {
            markupResponseBuilder.setHasError(true);
            markupResponseBuilder.setErrorMessage(
                    String.format("The source URI '%s' is not readable.", markupRequest.getSourceUri()));
        }

        if (!markupResponseBuilder.getHasError()) {
            if (markupRequest.getMapEntriesCount() == 0) {
                try {
                    FileUtils.copyFile(new File(URI.create(markupRequest.getSourceUri())),
                            new File(URI.create(markupRequest.getDestinationUri())));
                    markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri());
                } catch (Exception exception) {
                    log.error("Failed to mark up the file '{}' because of an exception.",
                            markupRequest.getSourceUri(), exception);
                    finishWithError(markupResponseBuilder, exception);
                }
            } else if (markupRequest.getMediaType() == Markup.MediaType.IMAGE) {
                try {
                    if (markupImage(markupRequest)) {
                        markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri());
                    } else {
                        markupResponseBuilder.setOutputFileUri(markupRequest.getSourceUri());
                    }
                } catch (Exception exception) {
                    log.error("Failed to mark up the image '{}' because of an exception.",
                            markupRequest.getSourceUri(), exception);
                    finishWithError(markupResponseBuilder, exception);
                }
            } else {
                try {
                    if (markupVideo(markupRequest)) {
                        markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri());
                    } else {
                        markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri());
                    }
                } catch (Exception exception) {
                    log.error("Failed to mark up the video '{}' because of an exception.",
                            markupRequest.getSourceUri(), exception);
                    finishWithError(markupResponseBuilder, exception);
                }
            }
        }

        stopwatch.stop();
        markupResponseBuilder.setTimeProcessing(stopwatch.elapsed(TimeUnit.MILLISECONDS));
        final Markup.MarkupResponse markupResponse = markupResponseBuilder.build();

        log.info("Returning response for Media {}. Error: {}.", markupResponse.getMediaId(),
                markupResponse.getHasError());
        markupResponseTemplate.setSessionTransacted(true);
        markupResponseTemplate.setDefaultDestination(message.getJMSReplyTo());
        markupResponseTemplate.send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.writeBytes(markupResponse.toByteArray());
                for (Map.Entry<String, Object> entry : requestHeaders.entrySet()) {
                    bytesMessage.setObjectProperty(entry.getKey(), entry.getValue());
                }
                return bytesMessage;
            }
        });

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:org.mot.common.mq.ActiveMQFactory.java

/**
 * @param tick/*from www  . j  a  v  a 2  s. c om*/
 * @param ttl
 * @param persistent
 */
public void publishTick(Tick tick, MessageProducer mp) {

    BytesMessage tickMessage;
    try {
        Session session = this.createSession();

        // Create a new ByteMessage
        tickMessage = session.createBytesMessage();

        // Serialize the tick content into the message
        tickMessage.writeBytes(tick.serialize());
        tickMessage.setStringProperty("Symbol", tick.getSymbol());
        tickMessage.setStringProperty("Currency", tick.getCurrency());

        mp.send(tickMessage);
        this.closeSession(session);
    } catch (JMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.mot.common.mq.ActiveMQFactory.java

/**
 * /* w w  w .ja v a2 s . c  o m*/
 * @param tick
 * @param ttl
 * @param persistent
 */
public void publishTicks(Tick[] tick, MessageProducer mp) {

    BytesMessage tickMessage;
    try {
        Session session = this.createSession();

        for (int i = 0; i < tick.length; i++) {
            // Create a new ByteMessage
            tickMessage = session.createBytesMessage();

            // Serialize the tick content into the message
            tickMessage.writeBytes(tick[i].serialize());
            tickMessage.setStringProperty("Symbol", tick[i].getSymbol());
            tickMessage.setStringProperty("Currency", tick[i].getCurrency());

            mp.send(tickMessage);
        }
        this.closeSession(session);
    } catch (JMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.mot.common.mq.ActiveMQFactory.java

/**
 * @param tickSize//ww  w.j  a  v  a2s. c  o  m
 * @param ttl
 * @param persistent
 */
public void publishTickSize(TickSize tickSize, MessageProducer mp) {

    BytesMessage tickMessage;
    try {
        Session session = this.createSession();

        // Create a new ByteMessage
        tickMessage = session.createBytesMessage();

        // Serialize the tick content into the message
        tickMessage.writeBytes(tickSize.serialize());
        tickMessage.setStringProperty("Symbol", tickSize.getSymbol());

        mp.send(tickMessage);
        this.closeSession(session);
    } catch (JMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.mot.common.mq.ActiveMQFactory.java

/**
 * @param order - Order to be placed//w  w  w  .j a v  a 2 s.  c o m
 * @param ttl - Time to live. Set to 0 for indefinite
 * @param deliveryMode - Set to 1 for non-persistent. Default 0
 */
public void publishOrder(Order order, MessageProducer mp) {
    BytesMessage orderMessage;
    try {
        Session session = this.createSession();

        // Create a new ByteMessage
        orderMessage = session.createBytesMessage();

        // Serialize the tick content into the message
        orderMessage.writeBytes(order.serialize());
        orderMessage.setStringProperty("Symbol", order.getSymbol());

        mp.send(orderMessage);
        this.closeSession(session);
    } catch (JMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.mot.common.mq.ActiveMQFactory.java

/**
 * Publish a simulation request/*w w w  . j a va  2 s.c o m*/
 * 
 * @param sr
 * @param ttl
 * @param persistent
 */
public void publishSimulationRequest(SimulationRequest sr, MessageProducer mp) {

    BytesMessage simulationMessage;
    try {
        Session session = this.createSession();

        // Create a new ByteMessage
        simulationMessage = session.createBytesMessage();

        // Serialize the simulation request content into the message
        simulationMessage.writeBytes(sr.serialize());
        simulationMessage.setStringProperty("Symbol", sr.getSymbol());
        simulationMessage.setStringProperty("LoadValues", String.valueOf(sr.getLoadValues()));
        simulationMessage.setStringProperty("StartDate", String.valueOf(sr.getStartDate()));
        simulationMessage.setStringProperty("EndDate", String.valueOf(sr.getEndDate()));

        mp.send(simulationMessage);
        this.closeSession(session);
    } catch (JMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.mot.common.mq.ActiveMQFactory.java

/**
 * Publish a tick history object/* w w  w.j  a  v a 2 s . co m*/
 * @param tick
 */
public void publishTickHistory(TickHistory tick, MessageProducer mp) {

    BytesMessage tickMessage;
    try {
        Session session = this.createSession();

        // Create a new ByteMessage
        tickMessage = session.createBytesMessage();

        // Serialize the tick content into the message
        tickMessage.writeBytes(tick.serialize());
        mp.send(tickMessage);
        this.closeSession(session);
    } catch (JMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.mule.transport.jms.JmsMessageUtils.java

private static Message byteArrayToMessage(byte[] value, Session session) throws JMSException {
    BytesMessage bMsg = session.createBytesMessage();
    bMsg.writeBytes(value);/*w ww  . j  av a 2  s.co m*/

    return bMsg;
}

From source file:org.mule.transport.jms.JmsMessageUtils.java

private static Message outputHandlerToMessage(OutputHandler value, Session session) throws JMSException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    try {/*from www  .ja  v a  2  s . c  o  m*/
        value.write(null, output);
    } catch (IOException e) {
        JMSException j = new JMSException("Could not serialize OutputHandler.");
        j.initCause(e);
        throw j;
    }

    BytesMessage bMsg = session.createBytesMessage();
    bMsg.writeBytes(output.toByteArray());

    return bMsg;
}

From source file:org.mule.transport.jms.JmsMessageUtilsTestCase.java

@Test
public void testConvertingByteArrayToBytesMessage() throws JMSException {
    Session session = mock(Session.class);
    when(session.createBytesMessage()).thenReturn(new ActiveMQBytesMessage());

    byte[] bytesArray = new byte[] { 1, 2 };
    BytesMessage message = (BytesMessage) JmsMessageUtils.toMessage(bytesArray, session);

    // Makes the message readable
    message.reset();/*from   w  w w  .  ja va 2 s  .co  m*/
    byte[] bytesArrayResult = new byte[(int) message.getBodyLength()];
    int length = message.readBytes(bytesArrayResult);
    assertEquals(2, length);
    assertEquals(bytesArray[0], bytesArrayResult[0]);
    assertEquals(bytesArray[1], bytesArrayResult[1]);
}