Example usage for javax.jms MessageProducer send

List of usage examples for javax.jms MessageProducer send

Introduction

In this page you can find the example usage for javax.jms MessageProducer send.

Prototype


void send(Message message) throws JMSException;

Source Link

Document

Sends a message using the MessageProducer 's default delivery mode, priority, and time to live.

Usage

From source file:de.elomagic.carafile.server.bl.SeedBean.java

public void seedChunk(final InputStream inputStream, final String chunkId)
        throws IOException, GeneralSecurityException, JMSException {
    LOG.debug("Seeding chunk " + chunkId);
    Chunk chunk = chunkDAO.findByIdentifier(chunkId);

    if (chunk == null) {
        throw new FileNotFoundException(
                "Chunk id " + chunkId + " not found. File already registered at registry?");
    }/*from w w  w.  j  a  v a2s .c o  m*/

    byte[] buf = new byte[chunk.getFileMeta().getChunkSize()];
    int bufferSize;
    try (InputStream in = inputStream) {
        bufferSize = readBlock(in, buf);
    } catch (IOException ex) {
        throw ex;
    }

    // Check SHA-1
    String sha1 = Hex.encodeHexString(DigestUtils.sha1(Arrays.copyOf(buf, bufferSize)));
    if (!chunk.getHash().equalsIgnoreCase(sha1)) {
        throw new GeneralSecurityException(
                "Chunk SHA-1 validation failed (Expected " + chunk.getHash() + ", but is " + sha1 + ")");
    }

    repositoryBean.writeChunk(chunkId, buf, bufferSize);

    LOG.debug("Chunk id " + chunkId + " seed");

    // Initiate to register at tracker
    LOG.debug("Queue up new file for registration.");
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer messageProducer = session.createProducer(chunkQueue);

    TextMessage message = session.createTextMessage(chunkId);
    messageProducer.send(message);
    connection.close();
}

From source file:de.elomagic.carafile.server.bl.SeedBean.java

public MetaData seedFile(final InputStream inputStream, final String filename)
        throws IOException, GeneralSecurityException, JMSException {
    LOG.debug("Seeding file " + filename);
    MetaData md;//from  ww w. j  a  va2  s .  c om
    md = new MetaData();
    md.setFilename(filename);
    md.setCreationDate(new Date());
    md.setChunkSize(DEFAULT_PIECE_SIZE);
    md.setRegistryURI(UriBuilder.fromUri(registryURI).build());

    MessageDigest messageDigest = DigestUtils.getSha1Digest();
    long totalBytes = 0;

    try (DigestInputStream dis = new DigestInputStream(inputStream, messageDigest)) {
        byte[] buffer = new byte[md.getChunkSize()];
        int bytesRead;
        while ((bytesRead = readBlock(dis, buffer)) > 0) {
            totalBytes += bytesRead;
            String chunkId = Hex
                    .encodeHexString(DigestUtils.sha1(new ByteArrayInputStream(buffer, 0, bytesRead)));

            repositoryBean.writeChunk(chunkId, buffer, bytesRead);

            URI uri = UriBuilder.fromUri(ownURI).build();

            ChunkData chunkData = new ChunkData(chunkId, uri);
            md.addChunk(chunkData);
        }
    }

    md.setSize(totalBytes);
    md.setId(Hex.encodeHexString(messageDigest.digest()));

    LOG.debug("File id of seed file is " + md.getId() + "; Size=" + md.getSize() + "; Chunks="
            + md.getChunks().size());

    // Initiate to register at tracker
    LOG.debug("Queue up new file for registration.");
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer messageProducer = session.createProducer(fileQueue);

    ObjectMessage message = session.createObjectMessage(md);

    messageProducer.send(message);

    connection.close();

    return md;
}

From source file:org.wildfly.camel.test.jms.TransactedJMSIntegrationTest.java

private void sendMessage(Connection connection, String jndiName, String message) throws Exception {
    InitialContext initialctx = new InitialContext();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = (Destination) initialctx.lookup(jndiName);
    MessageProducer producer = session.createProducer(destination);
    TextMessage msg = session.createTextMessage(message);
    producer.send(msg);
    connection.start();//from   w w w  .ja v a 2s .  c  o  m
}

From source file:org.sakaiproject.kernel.messaging.email.EmailMessagingService.java

public String send(Email email) throws MessagingException, JMSException {
    try {//from ww  w .  j  a v a2  s.co m
        email.buildMimeMessage();
    } catch (Exception e) {
        // this is a lossy cast. This would be a commons EmailException
        // this up cast is to keep commons-email out of our direct bindings
        throw new MessagingException(e);
    }

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        email.getMimeMessage().writeTo(os);
    } catch (javax.mail.MessagingException e) {
        throw new MessagingException(e);

    } catch (IOException e) {
        throw new MessagingException(e);
    }

    String content = os.toString();
    Connection conn = connectionFactory.createTopicConnection();
    conn.setClientID(getNextId());
    Session clientSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination emailTopic = clientSession.createTopic(emailQueueName);
    MessageProducer client = clientSession.createProducer(emailTopic);
    ObjectMessage mesg = clientSession.createObjectMessage(content);
    mesg.setJMSType(emailJmsType);
    client.send(mesg);
    // TODO finish this
    return null;

}

From source file:org.springframework.integration.jms.request_reply.RequestReplyScenariosWithTempReplyQueuesTests.java

@Test
public void messageCorrelationBasedOnRequestCorrelationIdTimedOutFirstReply() throws Exception {
    ActiveMqTestUtils.prepare();/*from w  ww.jav a2  s.c  om*/
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "producer-temp-reply-consumers.xml", this.getClass());
    RequestReplyExchanger gateway = context.getBean(RequestReplyExchanger.class);
    ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class);

    final Destination requestDestination = context.getBean("siOutQueue", Destination.class);

    DefaultMessageListenerContainer dmlc = new DefaultMessageListenerContainer();
    dmlc.setConnectionFactory(connectionFactory);
    dmlc.setDestination(requestDestination);
    dmlc.setMessageListener((SessionAwareMessageListener<Message>) (message, session) -> {
        Destination replyTo = null;
        try {
            replyTo = message.getJMSReplyTo();
        } catch (Exception e1) {
            fail();
        }
        String requestPayload = (String) extractPayload(message);
        if (requestPayload.equals("foo")) {
            try {
                Thread.sleep(6000);
            } catch (Exception e2) {
                /*ignore*/ }
        }
        try {
            TextMessage replyMessage = session.createTextMessage();
            replyMessage.setText(requestPayload);
            replyMessage.setJMSCorrelationID(message.getJMSMessageID());
            MessageProducer producer = session.createProducer(replyTo);
            producer.send(replyMessage);
        } catch (Exception e3) {
            // ignore. the test will fail
        }
    });
    dmlc.afterPropertiesSet();
    dmlc.start();

    try {
        gateway.exchange(new GenericMessage<String>("foo"));
    } catch (Exception e) {
        // ignore
    }
    Thread.sleep(1000);
    try {
        assertEquals("bar", gateway.exchange(new GenericMessage<String>("bar")).getPayload());
    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
    context.close();
}

From source file:org.symplify.runtime.jms.JMSContextImpl.java

public void send(Channel channel, Message message) throws Exception {
    javax.jms.Queue queue = getQueue(channel);

    if (queue != null) {
        //queue.put(message);
        javax.jms.MessageProducer producer = m_session.createProducer(queue);

        javax.jms.Message m = m_session.createObjectMessage(message);

        producer.send(m); //, 0, 0, message.getTimeToLive());

        producer.close();//from  w  ww  . j  a v a  2  s.  c  om

    } else {
        throw new Exception("Unable to find queue for channel");
    }
}

From source file:eu.domibus.submission.jms.BackendJMSImpl.java

/**
 * This method is called when a message was received at the incoming queue
 *
 * @param message The incoming JMS Message
 *///ww  w  .java2 s. co  m
@Override
public void onMessage(final Message message) {
    final MapMessage map = (MapMessage) message;
    try {
        final Connection con = this.cf.createConnection();
        final Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final MapMessage res = session.createMapMessage();
        try {
            final String messageID = this.submit(map);
            res.setStringProperty("messageId", messageID);
        } catch (final TransformationException | ValidationException e) {
            BackendJMSImpl.LOG.error("Exception occurred: ", e);
            res.setString("ErrorMessage", e.getMessage());
        }

        res.setJMSCorrelationID(map.getJMSCorrelationID());
        final MessageProducer sender = session.createProducer(this.outQueue);
        sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        sender.send(res);
        sender.close();
        session.close();
        con.close();

    } catch (final JMSException ex) {
        BackendJMSImpl.LOG.error("Error while sending response to queue", ex);

    }
}

From source file:org.wso2.andes.systest.TestingBaseCase.java

/**
 * Create and start an asynchrounous publisher that will send MAX_QUEUE_MESSAGE_COUNT
 * messages to the provided destination. Messages are sent in a new connection
 * on a transaction. Any error is captured and the test is signalled to exit.
 *
 * @param destination/*  w  w w .  j  ava  2s. c  o m*/
 */
private void startPublisher(final Destination destination) {
    _publisher = new Thread(new Runnable() {

        public void run() {
            try {
                Connection connection = getConnection();
                Session session = connection.createSession(true, Session.SESSION_TRANSACTED);

                MessageProducer publisher = session.createProducer(destination);

                for (int count = 0; count < MAX_QUEUE_MESSAGE_COUNT; count++) {
                    publisher.send(createNextMessage(session, count));
                    session.commit();
                }
            } catch (Exception e) {
                _publisherError = e;
                _disconnectionLatch.countDown();
            }
        }
    });

    _publisher.start();
}

From source file:org.wso2.carbon.registry.caching.invalidator.connection.JMSNotification.java

@Override
public void publish(Object message) {
    Session pubSession = null;// w w w .ja v a  2s  .  co m
    try {
        if (connection != null) {
            pubSession = connection.createSession(false, TopicSession.AUTO_ACKNOWLEDGE);
            MessageProducer publisher = pubSession.createProducer(destination);
            BytesMessage bytesMessage = pubSession.createBytesMessage();
            bytesMessage.writeBytes((byte[]) message);
            publisher.send(bytesMessage);
        }
    } catch (JMSException e) {
        log.error("Global cache invalidation: Error in publishing the message", e);
    } finally {
        if (pubSession != null) {
            try {
                pubSession.close();
            } catch (JMSException e) {
                log.error("Global cache invalidation: Error in publishing the message", e);
            }
        }
    }
}

From source file:org.apache.activemq.broker.jmx.ConcurrentMoveTest.java

public void testConcurrentMove() throws Exception {

    // Send some messages
    connection = connectionFactory.createConnection();
    connection.start();//from w  w  w. j  a va 2s  .  com
    Session session = connection.createSession(transacted, authMode);
    destination = createDestination();
    MessageProducer producer = session.createProducer(destination);
    for (int i = 0; i < messageCount; i++) {
        Message message = session.createTextMessage("Message: " + i);
        producer.send(message);
    }

    long usageBeforMove = broker.getPersistenceAdapter().size();
    LOG.info("Store usage:" + usageBeforMove);

    // Now get the QueueViewMBean and purge
    String objectNameStr = broker.getBrokerObjectName().toString();
    objectNameStr += ",destinationType=Queue,destinationName=" + getDestinationString();
    ObjectName queueViewMBeanName = assertRegisteredObjectName(objectNameStr);
    final QueueViewMBean proxy = (QueueViewMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServer,
            queueViewMBeanName, QueueViewMBean.class, true);

    final ActiveMQQueue to = new ActiveMQQueue("TO");
    ((RegionBroker) broker.getRegionBroker()).addDestination(broker.getAdminConnectionContext(), to, false);

    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int i = 0; i < 50; i++) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    proxy.moveMatchingMessagesTo(null, to.getPhysicalName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    executorService.shutdown();
    executorService.awaitTermination(5, TimeUnit.MINUTES);

    long count = proxy.getQueueSize();
    assertEquals("Queue size", count, 0);
    assertEquals("Browse size", proxy.browseMessages().size(), 0);

    objectNameStr = broker.getBrokerObjectName().toString();
    objectNameStr += ",destinationType=Queue,destinationName=" + to.getQueueName();
    queueViewMBeanName = assertRegisteredObjectName(objectNameStr);
    QueueViewMBean toProxy = (QueueViewMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServer,
            queueViewMBeanName, QueueViewMBean.class, true);

    count = toProxy.getQueueSize();
    assertEquals("Queue size", count, messageCount);

    long usageAfterMove = broker.getPersistenceAdapter().size();
    LOG.info("Store usage, before: " + usageBeforMove + ", after:" + usageAfterMove);
    LOG.info("Store size increase:" + FileUtils.byteCountToDisplaySize(usageAfterMove - usageBeforMove));

    assertTrue("Usage not more than doubled", usageAfterMove < (usageBeforMove * 3));

    producer.close();
}