Example usage for javax.jms Session createProducer

List of usage examples for javax.jms Session createProducer

Introduction

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

Prototype


MessageProducer createProducer(Destination destination) throws JMSException;

Source Link

Document

Creates a MessageProducer to send messages to the specified destination.

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?");
    }//ww  w  . j  a v  a2 s .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;/* w ww .  j  a v  a2  s.c o  m*/
    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.logicblaze.lingo.jmx.remote.jms.activemq.ActiveMQServerListenerInfo.java

ActiveMQServerListenerInfo(String id, Map holder, Destination replyTo, Session session) throws JMSException {
    this.id = id;
    this.holder = holder;
    this.replyTo = replyTo;
    this.session = session;
    this.producer = session.createProducer(replyTo);
    Topic advisoryTopic = AdvisorySupport.getConsumerAdvisoryTopic((ActiveMQDestination) replyTo);
    advisoryConsumer = session.createConsumer(advisoryTopic);
    advisoryConsumer.setMessageListener(this); //
}

From source file:org.logicblaze.lingo.jmx.remote.jms.ServerListenerInfo.java

ServerListenerInfo(String id, Map holder, Destination replyTo, Session session) throws JMSException {
    this.id = id;
    this.holder = holder;
    this.replyTo = replyTo;
    this.session = session;
    this.producer = session.createProducer(replyTo);
    Topic advisoryTopic = AdvisorySupport.getConsumerAdvisoryTopic((ActiveMQDestination) replyTo);
    advisoryConsumer = session.createConsumer(advisoryTopic);
    advisoryConsumer.setMessageListener(this);
}

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

private Boolean submitToBackend(final String messageId) {
    Connection connection;//from w  ww  . ja v a  2  s  .  co m
    MessageProducer producer;

    try {
        connection = this.cf.createConnection();
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(this.receivingQueue);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        final MapMessage resMessage = session.createMapMessage();
        this.downloadMessage(messageId, resMessage);
        producer.send(resMessage);
        producer.close();
        session.close();

        connection.close();
    } catch (JMSException | ValidationException e) {
        BackendJMSImpl.LOG.error("", e);
        return false;
    }
    return true;
}

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//from  ww w  .  j av a 2 s.  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.logicblaze.lingo.jms.impl.DefaultJmsProducer.java

public DefaultJmsProducer(Connection connection, Session session, JmsProducerConfig config,
        boolean ownsConnection) throws JMSException {
    this.connection = connection;
    this.session = session;
    this.ownsConnection = ownsConnection;
    this.producer = session.createProducer(null);
    config.configure(producer);/*from  www  . ja  v  a  2s . c o  m*/
}

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

private Boolean submitErrorMessage(String messageId) {
    Connection connection;//from www  .  j a v  a 2 s  . c  om
    MessageProducer producer;
    List<ErrorLogEntry> errors = this.errorLogDao.getUnnotifiedErrorsForMessage(messageId);

    try {
        connection = this.cf.createConnection();
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(this.receivingQueue);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        final MapMessage resMessage = session.createMapMessage();
        for (int i = 0; i < errors.size(); ++i) {
            resMessage.setString(String.valueOf(i), errors.get(i).toString());
            errors.get(i).setNotified(new Date());
            this.errorLogDao.update(errors.get(i));
        }

        producer.send(resMessage);
        producer.close();
        session.close();

        connection.close();
    } catch (JMSException e) {
        BackendJMSImpl.LOG.error("", e);
        return false;
    }
    return true;
}

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 ww .j a v  a2  s.  c  o m*/
    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();
}

From source file:org.jbpm.jms.JmsConnectorService.java

final void sendMessage(Job job) throws JMSException {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    try {/*from  w w w  . j ava  2 s  .co m*/
        Message message = session.createMessage();
        populateMessage(message, job);

        MessageProducer messageProducer = session.createProducer(serviceFactory.getDestination());
        messageProducer.send(message);
    } finally {
        // there is no need to close the producers of a closed session
        session.close();
    }
}