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.chinamobile.bcbsp.comm.ProducerTool.java

/**
 * Send message into messageQueue, update information with serialize method.
 * @param session//from  w w  w  . ja  v  a 2s  . c o m
 * @param producer
 * @throws Exception
 *         e
 */
private void sendLoopOptimistic(final Session session, final MessageProducer producer) throws Exception {
    try {
        BSPMessage msg;
        int count = 0;
        int packCounts = messageQueue.size() / this.packSize;
        // LOG.info("send packSize = "+ this.packSize);
        int packCount = 0;
        while (packCount < packCounts) {
            BytesMessage message = session.createBytesMessage();
            long start = System.currentTimeMillis();
            /* Clock */
            message.writeInt(this.packSize);
            count = 0;
            while (count < this.packSize) {
                msg = (BSPMessage) messageQueue.poll();
                // LOG.info(msg.intoString());
                // message.setInt("dstPartition", msg.getDstPartition());
                message.writeInt(msg.getDstPartition());
                // message.writeUTF(msg.getSrcVertexID());
                // message.setString("dstVertexID", msg.getDstVertexID());
                message.writeUTF(msg.getDstVertexID());
                // message.setBytes("tag", msg.getTag());
                message.writeInt(msg.getTag().length);
                message.writeBytes(msg.getTag());
                // message.setBytes("data", msg.getData());
                message.writeInt(msg.getData().length);
                message.writeBytes(msg.getData());
                count++;
                this.messageCount++;
            }
            this.serializeTime += (System.currentTimeMillis() - start);
            /* Clock */
            start = System.currentTimeMillis();
            /* Clock */
            producer.send(message);
            this.sendTime += (System.currentTimeMillis() - start);
            /* Clock */
            packCount++;
            // if (messageCount % 100000 == 0 ){
            // LOG.info("send " + messageCount);
            // }
        }
        // send remaining messags
        int sendSize = messageQueue.size();
        if (sendSize != 0) {
            BytesMessage message = session.createBytesMessage();
            long start = System.currentTimeMillis();
            /* Clock */
            // message.setInt("packSize", sendSize);
            message.writeInt(sendSize);
            while ((msg = (BSPMessage) messageQueue.poll()) != null) {
                // message.setInt("dstPartition", msg.getDstPartition());
                message.writeInt(msg.getDstPartition());
                // message.setString("dstVertexID", msg.getDstVertexID());
                message.writeUTF(msg.getDstVertexID());
                // message.setBytes("tag", msg.getTag());
                message.writeInt(msg.getTag().length);
                message.writeBytes(msg.getTag());
                // message.setBytes("data", msg.getData());
                message.writeInt(msg.getData().length);
                message.writeBytes(msg.getData());
                this.messageCount++;
            }
            this.serializeTime += (System.currentTimeMillis() - start);
            /* Clock */
            start = System.currentTimeMillis();
            /* Clock */
            producer.send(message);
            this.sendTime += (System.currentTimeMillis() - start);
            /* Clock */
        }
    } catch (Exception e) {
        LOG.error("[ProducerTool] send loop ", e);
    }
}

From source file:gov.medicaid.services.impl.ProviderEnrollmentServiceBean.java

/**
 * Sends the given provider for export to the message queue.
 * @param ticketId the ticket id//www  . ja v  a  2s.co m
 */
@Override
public void sendSyncronizationRequest(long ticketId) {
    Session session = null;
    Connection connection = null;

    try {
        connection = mqConnectionFactory.createConnection();
        session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        MessageProducer sender = session.createProducer(dataSyncQueue);
        BytesMessage message = session.createBytesMessage();
        byte[] content = exportAsFlatFile(ticketId);
        getLog().log(Level.INFO, "Sending data sync request:" + new String(content));
        message.writeBytes(content);
        sender.send(message);
    } catch (PortalServiceException e) {
        getLog().log(Level.ERROR, e);
        throw new PortalServiceRuntimeException("While attempting to synchronize data", e);
    } catch (JMSException e) {
        getLog().log(Level.ERROR, e);
        throw new PortalServiceRuntimeException("While attempting to synchronize data", e);
    }
}

From source file:org.apache.activemq.bugs.AMQ6133PersistJMSRedeliveryTest.java

private void sendMessages() throws Exception {
    Connection connection = createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination queue = session.createQueue(QUEUE_NAME);
    Destination retainQueue = session.createQueue(QUEUE_NAME + "-retain");
    MessageProducer producer = session.createProducer(null);

    final byte[] payload = new byte[1000];
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    BytesMessage message = session.createBytesMessage();
    message.writeBytes(payload);

    // Build up a set of messages that will be redelivered and updated later.
    while (getLogFileCount() < 3) {
        producer.send(queue, message);/*from www  . ja  va2 s  .c  o  m*/
    }

    // Now create some space for files that are retained during the test.
    while (getLogFileCount() < 6) {
        producer.send(retainQueue, message);
    }

    connection.close();
}

From source file:org.apache.synapse.transport.jms.JMSSender.java

/**
 * Create a JMS Message from the given MessageContext and using the given
 * session//from   w w w  . ja va 2  s . c  o  m
 *
 * @param msgContext the MessageContext
 * @param session    the JMS session
 * @return a JMS message from the context and session
 * @throws JMSException on exception
 * @throws AxisFault on exception
 */
private Message createJMSMessage(MessageContext msgContext, Session session) throws JMSException, AxisFault {

    Message message = null;
    String msgType = getProperty(msgContext, JMSConstants.JMS_MESSAGE_TYPE);

    // check the first element of the SOAP body, do we have content wrapped using the
    // default wrapper elements for binary (BaseConstants.DEFAULT_BINARY_WRAPPER) or
    // text (BaseConstants.DEFAULT_TEXT_WRAPPER) ? If so, do not create SOAP messages
    // for JMS but just get the payload in its native format
    String jmsPayloadType = guessMessageType(msgContext);

    if (jmsPayloadType == null) {

        OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
        MessageFormatter messageFormatter = null;
        try {
            messageFormatter = TransportUtils.getMessageFormatter(msgContext);
        } catch (AxisFault axisFault) {
            throw new JMSException("Unable to get the message formatter to use");
        }

        String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction());

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            messageFormatter.writeTo(msgContext, format, baos, true);
            baos.flush();
        } catch (IOException e) {
            handleException("IO Error while creating BytesMessage", e);
        }

        if (msgType != null && JMSConstants.JMS_BYTE_MESSAGE.equals(msgType)
                || contentType.indexOf(HTTPConstants.HEADER_ACCEPT_MULTIPART_RELATED) > -1) {
            message = session.createBytesMessage();
            BytesMessage bytesMsg = (BytesMessage) message;
            bytesMsg.writeBytes(baos.toByteArray());
        } else {
            message = session.createTextMessage(); // default
            TextMessage txtMsg = (TextMessage) message;
            txtMsg.setText(new String(baos.toByteArray()));
        }
        message.setStringProperty(BaseConstants.CONTENT_TYPE, contentType);

    } else if (JMSConstants.JMS_BYTE_MESSAGE.equals(jmsPayloadType)) {
        message = session.createBytesMessage();
        BytesMessage bytesMsg = (BytesMessage) message;
        OMElement wrapper = msgContext.getEnvelope().getBody()
                .getFirstChildWithName(BaseConstants.DEFAULT_BINARY_WRAPPER);
        OMNode omNode = wrapper.getFirstOMChild();
        if (omNode != null && omNode instanceof OMText) {
            Object dh = ((OMText) omNode).getDataHandler();
            if (dh != null && dh instanceof DataHandler) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    ((DataHandler) dh).writeTo(baos);
                } catch (IOException e) {
                    handleException("Error serializing binary content of element : "
                            + BaseConstants.DEFAULT_BINARY_WRAPPER, e);
                }
                bytesMsg.writeBytes(baos.toByteArray());
            }
        }

    } else if (JMSConstants.JMS_TEXT_MESSAGE.equals(jmsPayloadType)) {
        message = session.createTextMessage();
        TextMessage txtMsg = (TextMessage) message;
        txtMsg.setText(msgContext.getEnvelope().getBody()
                .getFirstChildWithName(BaseConstants.DEFAULT_TEXT_WRAPPER).getText());
    }

    // set the JMS correlation ID if specified
    String correlationId = getProperty(msgContext, JMSConstants.JMS_COORELATION_ID);
    if (correlationId == null && msgContext.getRelatesTo() != null) {
        correlationId = msgContext.getRelatesTo().getValue();
    }

    if (correlationId != null) {
        message.setJMSCorrelationID(correlationId);
    }

    if (msgContext.isServerSide()) {
        // set SOAP Action as a property on the JMS message
        setProperty(message, msgContext, BaseConstants.SOAPACTION);
    } else {
        String action = msgContext.getOptions().getAction();
        if (action != null) {
            message.setStringProperty(BaseConstants.SOAPACTION, action);
        }
    }

    JMSUtils.setTransportHeaders(msgContext, message);
    return message;
}

From source file:org.codehaus.stomp.jms.StompSession.java

protected Message convertFrame(StompFrame command)
        throws JMSException, UnsupportedEncodingException, ProtocolException, NamingException {
    final Map headers = command.getHeaders();
    final Message msg;
    if (headers.containsKey(Stomp.Headers.CONTENT_LENGTH)) {
        headers.remove(Stomp.Headers.CONTENT_LENGTH);
        BytesMessage bm = session.createBytesMessage();
        bm.writeBytes(command.getContent());
        msg = bm;//from w  w w.  ja  v a 2 s. c o  m
    } else {
        String text = new String(command.getContent(), StandardCharsets.UTF_8);
        msg = session.createTextMessage(text);
    }
    copyStandardHeadersFromFrameToMessage(command, msg);
    return msg;
}

From source file:org.codehaus.stomp.StompTest.java

public void sendBytesMessage(byte[] msg) throws Exception {
    MessageProducer producer = session.createProducer(queue);
    BytesMessage message = session.createBytesMessage();
    message.writeBytes(msg);
    producer.send(message);//www.  j  a va 2s .  c om
}

From source file:org.eclipse.smila.connectivity.queue.worker.internal.task.impl.Send.java

/**
 * Creates message./*from  w w  w  .  ja v  a2s .c  om*/
 * 
 * @param config
 *          the config
 * @param record
 *          the record
 * @param messageProperties
 *          the jms message properties
 * @param session
 *          the session
 * 
 * @return the message
 * 
 * @throws JMSException
 *           the JMS exception
 */
private Message createMessage(final SendType config, final Record record, final Properties messageProperties,
        final Session session) throws JMSException {
    final BytesMessage message = session.createBytesMessage();

    // set dynamic message properties
    if (messageProperties != null) {
        final Enumeration<?> propertyNames = messageProperties.propertyNames();
        while (propertyNames.hasMoreElements()) {
            final String name = (String) propertyNames.nextElement();
            message.setStringProperty(name, messageProperties.getProperty(name));
        }
    }

    // get static properties of config file
    for (final PropertyType property : config.getSetProperty()) {
        message.setStringProperty(property.getName(), property.getValue());
    }

    final byte[] serialized = XmlSerializationUtils.serialize2byteArray(record);
    message.writeBytes(serialized);
    return message;
}

From source file:org.exist.messaging.JmsMessageSender.java

private Message createMessage(Session session, Item item, MessagingMetadata mdd, XQueryContext xqcontext)
        throws JMSException, XPathException {

    Message message = null;/*from   w  w w  . ja  v a  2 s . c om*/

    mdd.add("exist.datatype", Type.getTypeName(item.getType()));

    if (item.getType() == Type.ELEMENT || item.getType() == Type.DOCUMENT) {
        LOG.debug("Streaming element or document node");

        if (item instanceof NodeProxy) {
            NodeProxy np = (NodeProxy) item;
            String uri = np.getDocument().getBaseURI();
            LOG.debug("Document detected, adding URL " + uri);
            mdd.add("exist.document-uri", uri);
        }

        // Node provided
        Serializer serializer = xqcontext.getBroker().newSerializer();

        NodeValue node = (NodeValue) item;
        InputStream is = new NodeInputStream(serializer, node);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            IOUtils.copy(is, baos);
        } catch (IOException ex) {
            LOG.error(ex);
            throw new XPathException(ex);
        }
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(baos);

        BytesMessage bytesMessage = session.createBytesMessage();
        bytesMessage.writeBytes(baos.toByteArray());

        message = bytesMessage;

    } else if (item.getType() == Type.BASE64_BINARY || item.getType() == Type.HEX_BINARY) {
        LOG.debug("Streaming base64 binary");

        if (item instanceof Base64BinaryDocument) {
            Base64BinaryDocument b64doc = (Base64BinaryDocument) item;
            String uri = b64doc.getUrl();
            LOG.debug("Base64BinaryDocument detected, adding URL " + uri);
            mdd.add("exist.document-uri", uri);
        }

        BinaryValue binary = (BinaryValue) item;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = binary.getInputStream();

        //TODO consider using BinaryValue.getInputStream()
        //byte[] data = (byte[]) binary.toJavaObject(byte[].class);

        try {
            IOUtils.copy(is, baos);
        } catch (IOException ex) {
            LOG.error(ex);
            throw new XPathException(ex);
        }
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(baos);

        BytesMessage bytesMessage = session.createBytesMessage();
        bytesMessage.writeBytes(baos.toByteArray());

        message = bytesMessage;
    } else if (item.getType() == Type.STRING) {
        TextMessage textMessage = session.createTextMessage();
        textMessage.setText(item.getStringValue());
        message = textMessage;

    } else {
        ObjectMessage objectMessage = session.createObjectMessage();
        //objectMessage.setObject(item.toJavaObject(Object.class)); TODO hmmmm
        message = objectMessage;
    }

    return message;
}

From source file:org.frameworkset.mq.RequestDispatcher.java

public void send(InputStream in, JMSProperties properties, Logger log) throws JMSException {

    BytesMessage msg = createBytesMessage();

    byte[] send = null;

    /* ? *//* w  w  w .  j a v  a 2 s . c o  m*/
    if (properties.isEncrypt()) {
        try {
            send = MQUtil.readTxtFileByte(in);
        } catch (Exception e) {
            throw new JMSException(e.getMessage());
        }
        //         if (send == null || send.length == 0)
        //            return;
        // String name = file.getName();

        if (send != null) {
            EncryptDecryptAlgo ed = new EncryptDecryptAlgo();
            send = ed.encrypt(send);
        }

        if (properties != null)
            MQUtil.initMessage(msg, properties);
        msg.writeBytes(send);
        send = null;
    } else {
        if (properties != null)
            MQUtil.initMessage(msg, properties);
        if (!MQUtil.readTxtFileByte(msg, in))
            //            return;
            ;

    }
    send(msg, (JMSProperties) null);
}

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

    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);
    }
}