Example usage for javax.jms Session createTemporaryQueue

List of usage examples for javax.jms Session createTemporaryQueue

Introduction

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

Prototype


TemporaryQueue createTemporaryQueue() throws JMSException;

Source Link

Document

Creates a TemporaryQueue object.

Usage

From source file:org.apache.axis2.transport.jms.JMSUtils.java

/**
 * Create a temp queue or topic for synchronous receipt of responses, when a reply destination
 * is not specified//from  w w  w . j  a v  a  2s  . c om
 * @param session the JMS Session to use
 * @return a temporary Queue or Topic, depending on the session
 * @throws JMSException
 */
public static Destination createTemporaryDestination(Session session) throws JMSException {

    if (session instanceof QueueSession) {
        return session.createTemporaryQueue();
    } else {
        return session.createTemporaryTopic();
    }
}

From source file:org.genemania.connector.JmsEngineConnector.java

@Cacheable(cacheName = "searchResultsCache", keyGenerator = @KeyGenerator(name = "StringCacheKeyGenerator"))
public RelatedGenesWebResponseDto getRelatedGenes(final RelatedGenesWebRequestDto dto)
        throws ApplicationException {
    final String rgcid = String.valueOf(System.currentTimeMillis());
    RelatedGenesWebResponseDto ret = new RelatedGenesWebResponseDto();
    jmsTemplate.send(requestQueue, new MessageCreator() {
        public TextMessage createMessage(Session session) throws JMSException {
            LOG.debug("sending GetRelatedGenesMessage request to " + requestQueue.getQueueName());
            RelatedGenesRequestMessage request = BrokerUtils.dto2msg(dto);
            TextMessage ret = session.createTextMessage(request.toXml());
            ret.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
            ret.setJMSType(MessageType.RELATED_GENES.getCode());
            replyQueue = session.createTemporaryQueue();
            ret.setJMSReplyTo(replyQueue);
            ret.setJMSCorrelationID(rgcid);
            LOG.debug("getRelatedGenes waiting for reply on " + replyQueue.getQueueName());
            return ret;
        }/*from  w w w  .  j  ava2  s .c  o  m*/
    });
    sentMessages++;
    Message response;
    try {
        response = jmsTemplate.receive(replyQueue);
        receivedMessages++;
        if (response == null) {
            LOG.error("getRelatedGenes JMS response is null");
        } else if (!response.getJMSCorrelationID().equals(rgcid)) {
            LOG.error("JMS response id does not match request, sent " + rgcid + ", recieved "
                    + response.getJMSCorrelationID() + ", dropping response.");
        } else {
            LOG.debug("getRelatedGenes reply received");
            String responseBody = ((TextMessage) response).getText();
            if (StringUtils.isNotEmpty(responseBody)) {
                RelatedGenesResponseMessage responseMessage = RelatedGenesResponseMessage.fromXml(responseBody);
                LOG.debug("finished fromXml");
                LOG.debug("num attributes in response message: " + responseMessage.getAttributes().size());
                if (responseMessage.getErrorCode() == 0) {
                    // friendlyPrintNetworks("networks in response message: ",
                    // responseMessage.getNetworks());
                    // friendlyPrintCategories("categories in response message: ",
                    // responseMessage.getAnnotations());
                    RelatedGenesWebResponseDto hollowResponseDto = BrokerUtils.msg2dto(responseMessage);
                    LOG.debug("finished msg2dto");
                    ret = load(hollowResponseDto);
                    LOG.debug("finished hollowResponseDto");
                } else {
                    LOG.error(responseMessage.getErrorMessage());
                    appErrors++;
                    throw new ApplicationException(responseMessage.getErrorMessage(),
                            responseMessage.getErrorCode());
                }
            } else {
                LOG.error("getRelatedGenes empty response body");
            }
        }
        processedMessages++;
    } catch (JMSException e) {
        LOG.error("getRelatedGenes JMSException: " + e.getMessage());
        errors++;
        throw new ApplicationException(Constants.ERROR_CODES.APPLICATION_ERROR);
    } catch (DataStoreException e) {
        LOG.error("getRelatedGenes DataStoreException: " + e.getMessage());
        errors++;
        throw new ApplicationException(Constants.ERROR_CODES.DATA_ERROR);
    } finally {
        LOG.debug("messages sent/received/processed/errors: " + sentMessages + "/" + receivedMessages + "/"
                + processedMessages + "/" + errors);
        // updateStats();
    }
    LOG.debug("getRelatedGenes request processing completed");
    return ret;
}

From source file:org.genemania.connector.JmsEngineConnector.java

public UploadNetworkWebResponseDto uploadNetwork(final UploadNetworkWebRequestDto dto)
        throws ApplicationException {
    final String uncid = String.valueOf(System.currentTimeMillis());
    UploadNetworkWebResponseDto ret = new UploadNetworkWebResponseDto();
    jmsTemplate.send(requestQueue, new MessageCreator() {
        public TextMessage createMessage(Session session) throws JMSException {
            LOG.debug("sending UploadnetworkMessage request to " + requestQueue.getQueueName());
            UploadNetworkRequestMessage request = BrokerUtils.dto2msg(dto);
            TextMessage ret = session.createTextMessage(request.toXml());
            ret.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
            ret.setJMSType(MessageType.TEXT2NETWORK.getCode());
            replyQueue = session.createTemporaryQueue();
            ret.setJMSReplyTo(replyQueue);
            ret.setJMSCorrelationID(uncid);
            LOG.debug("uploadNetwork waiting for reply on " + replyQueue.getQueueName());
            sentMessages++;/*  w  w w . j  a va 2s. com*/
            return ret;
        }
    });
    Message response;
    try {
        response = jmsTemplate.receive(replyQueue);
        receivedMessages++;
        if (response.getJMSCorrelationID().equals(uncid)) {
            LOG.debug("uploadNetwork reply received");

            if (response != null) {
                String responseBody = ((TextMessage) response).getText();
                if (StringUtils.isNotEmpty(responseBody)) {
                    UploadNetworkResponseMessage responseMessage = UploadNetworkResponseMessage
                            .fromXml(responseBody);
                    if (responseMessage.getErrorCode() == 0) {
                        ret = BrokerUtils.msg2dto(responseMessage);
                    } else {
                        throw new ApplicationException(responseMessage.getErrorMessage(),
                                responseMessage.getErrorCode());
                    }
                } else {
                    LOG.error("uploadNetwork empty response body");
                }
            } else {
                LOG.error("uploadNetwork JMS response is null");
            }
        }
        processedMessages++;
    } catch (JMSException e) {
        errors++;
        throw new ApplicationException(Constants.ERROR_CODES.APPLICATION_ERROR);
    } finally {
        LOG.debug("messages sent/received/processed/appErrors/errors: " + sentMessages + "/" + receivedMessages
                + "/" + processedMessages + "/" + appErrors + "/" + errors);
        // updateStats();
    }
    LOG.debug("uploadNetwork request processing completed");
    return ret;
}

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

public Destination createTemporaryDestination(Session session, boolean topic) throws JMSException {
    if (session == null) {
        throw new IllegalArgumentException("Session cannot be null when creating a destination");
    }/*  www . ja v a 2 s  . c om*/

    if (topic) {
        return session.createTemporaryTopic();
    } else {
        return session.createTemporaryQueue();
    }
}

From source file:org.openengsb.ports.jms.JMSPortTest.java

private String sendWithTempQueue(final String msg) {
    String resultString = jmsTemplate.execute(new SessionCallback<String>() {
        @Override/*w  ww.j a va  2 s .c o m*/
        public String doInJms(Session session) throws JMSException {
            Queue queue = session.createQueue("receive");
            MessageProducer producer = session.createProducer(queue);
            TemporaryQueue tempQueue = session.createTemporaryQueue();
            MessageConsumer consumer = session.createConsumer(tempQueue);
            TextMessage message = session.createTextMessage(msg);
            message.setJMSReplyTo(tempQueue);
            producer.send(message);
            TextMessage response = (TextMessage) consumer.receive(10000);
            assertThat(
                    "server should set the value of the correltion ID to the value of the received message id",
                    response.getJMSCorrelationID(), is(message.getJMSMessageID()));
            JmsUtils.closeMessageProducer(producer);
            JmsUtils.closeMessageConsumer(consumer);
            return response != null ? response.getText() : null;
        }
    }, true);
    return resultString;
}

From source file:org.springframework.integration.jms.JmsOutboundGateway.java

private Destination determineReplyDestination(Message<?> message, Session session) throws JMSException {
    if (this.replyDestination != null) {
        return this.replyDestination;
    }/*from  w w w.  j a  va 2s . c  om*/
    if (this.replyDestinationName != null) {
        return this.resolveReplyDestination(this.replyDestinationName, session);
    }
    if (this.replyDestinationExpressionProcessor != null) {
        Object result = this.replyDestinationExpressionProcessor.processMessage(message);
        if (result instanceof Destination) {
            return (Destination) result;
        }
        if (result instanceof String) {
            return this.resolveReplyDestination((String) result, session);
        }
        throw new MessageDeliveryException(message,
                "Evaluation of replyDestinationExpression failed to produce a Destination or destination name. "
                        + "Result was: " + result);
    }
    return session.createTemporaryQueue();
}

From source file:org.springframework.integration.jms.JmsOutboundGatewayTests.java

@Test
public void testReplyContainerRecovery() throws Exception {
    JmsOutboundGateway gateway = new JmsOutboundGateway();
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    gateway.setConnectionFactory(connectionFactory);
    gateway.setRequestDestinationName("foo");
    gateway.setUseReplyContainer(true);//from   w w  w.j a va2  s  . c  om
    ReplyContainerProperties replyContainerProperties = new ReplyContainerProperties();
    final List<Throwable> errors = new ArrayList<Throwable>();
    ErrorHandlingTaskExecutor errorHandlingTaskExecutor = new ErrorHandlingTaskExecutor(
            Executors.newFixedThreadPool(10), new ErrorHandler() {

                @Override
                public void handleError(Throwable t) {
                    logger.info("Error:", t);
                    errors.add(t);
                    throw new RuntimeException(t);
                }
            });
    replyContainerProperties.setTaskExecutor(errorHandlingTaskExecutor);
    replyContainerProperties.setRecoveryInterval(100L);
    gateway.setReplyContainerProperties(replyContainerProperties);
    final Connection connection = mock(Connection.class);
    final AtomicInteger connectionAttempts = new AtomicInteger();
    doAnswer(new Answer<Connection>() {

        @SuppressWarnings("serial")
        @Override
        public Connection answer(InvocationOnMock invocation) throws Throwable {
            int theCount = connectionAttempts.incrementAndGet();
            if (theCount > 1 && theCount < 4) {
                throw new JmsException("bar") {
                };
            }
            return connection;
        }
    }).when(connectionFactory).createConnection();
    Session session = mock(Session.class);
    when(connection.createSession(false, 1)).thenReturn(session);
    MessageConsumer consumer = mock(MessageConsumer.class);
    when(session.createConsumer(any(Destination.class), anyString())).thenReturn(consumer);
    when(session.createTemporaryQueue()).thenReturn(mock(TemporaryQueue.class));
    final Message message = mock(Message.class);
    final AtomicInteger count = new AtomicInteger();
    doAnswer(new Answer<Message>() {

        @SuppressWarnings("serial")
        @Override
        public Message answer(InvocationOnMock invocation) throws Throwable {
            int theCount = count.incrementAndGet();
            if (theCount > 1 && theCount < 4) {
                throw new JmsException("foo") {
                };
            }
            if (theCount > 4) {
                Thread.sleep(100);
                return null;
            }
            return message;
        }
    }).when(consumer).receive(anyLong());
    when(message.getJMSCorrelationID()).thenReturn("foo");
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();
    beanFactory.registerSingleton("taskScheduler", taskScheduler);
    gateway.setBeanFactory(beanFactory);
    gateway.afterPropertiesSet();
    gateway.start();
    Thread.sleep(1000);
    assertTrue(count.get() > 4);
    assertEquals(0, errors.size());
}

From source file:test.SecureSampleApp.java

private static String sendMessage(final String encryptedMessage) {
    return template.execute(new SessionCallback<String>() {
        @Override//from  ww w .j a  v a 2  s  . c  o  m
        public String doInJms(Session session) throws JMSException {
            TextMessage message = session.createTextMessage(encryptedMessage);
            Queue outQueue = session.createQueue("receive");
            Destination inDest = session.createTemporaryQueue();
            String correlationID = UUID.randomUUID().toString();
            message.setJMSReplyTo(inDest);
            message.setJMSCorrelationID(correlationID);
            MessageProducer producer = session.createProducer(outQueue);
            producer.send(outQueue, message);
            return ((TextMessage) session.createConsumer(inDest).receive(10000)).getText();
        }
    }, true);
}

From source file:tools.ConsumerTool.java

@Override
public void run() {
    Connection connection = null;
    Session session = null;
    try {/*w w  w  .  j  av  a 2  s .  com*/
        connection = connectionFactory.createConnection();
        if (clientId != null) {
            connection.setClientID(clientId);
        }
        connection.start();
        session = connection.createSession(transacted, acknowledgeMode);
        Destination destination = null;
        if (jndiLookupDestinations) {
            destination = (Destination) context.lookup(destinationName);
        } else {
            if (useQueueDestinations) {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryQueue();
                } else {
                    destination = session.createQueue(destinationName);
                }
            } else {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryTopic();
                } else {
                    destination = session.createTopic(destinationName);
                }
            }
        }

        if (useQueueBrowser) {
            runQueueBrowser(session, (Queue) destination);
        } else {
            MessageConsumer consumer = null;
            if (useQueueDestinations) { //Queues
                if (selector != null) {
                    consumer = session.createConsumer(destination, selector);
                } else {
                    consumer = session.createConsumer(destination);
                }
            } else { //Queues
                if (durable) { //Durable Subscribers
                    if (selector != null) {
                        consumer = session.createDurableSubscriber((Topic) destination, subscriptionName,
                                selector, false);
                    } else {
                        consumer = session.createDurableSubscriber((Topic) destination, subscriptionName);
                    }
                } else { //Non-Durable Subscribers
                    if (selector != null) {
                        consumer = session.createConsumer(destination, selector);
                    } else {
                        consumer = session.createConsumer(destination);
                    }
                }
            }

            if (useAsyncListener) {
                final Session consumerSession = session;

                final AtomicInteger perConsumerReceivedMessages = new AtomicInteger(0);
                consumer.setMessageListener(new MessageListener() {

                    @Override
                    public void onMessage(Message message) {
                        perConsumerReceivedMessages.incrementAndGet();
                        handleMessage(consumerSession, message, perConsumerReceivedMessages.get());
                    }
                });
                while (perConsumerReceivedMessages.get() < numMessages) {
                    Thread.sleep(100);
                }
            } else {
                int perConsumerReceivedMessages = 0;
                while (perConsumerReceivedMessages < numMessages) {

                    Message message = null;
                    if (receiveTimeoutMS > -1) {
                        message = consumer.receive(receiveTimeoutMS);
                    } else {
                        message = consumer.receive();
                    }

                    if (message != null) {
                        perConsumerReceivedMessages++;
                        handleMessage(session, message, perConsumerReceivedMessages);
                    }
                }
            }
            consumer.close();
        }

    } catch (Exception ex) {
        LOGGER.error("ConsumerTool hit exception: " + ex.getMessage(), ex);
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing connection", e);
            }
        }
    }
}

From source file:tools.ProducerTool.java

@Override
public void run() {
    Connection connection = null;
    Session session = null;
    try {/*w ww .  j  ava 2s . c  o m*/
        connection = connectionFactory.createConnection();
        if (clientId != null) {
            connection.setClientID(clientId);
        }
        session = connection.createSession(transacted, acknowledgeMode);
        Destination destination = null;
        if (jndiLookupDestinations) {
            destination = (Destination) context.lookup(destinationName);
        } else {
            if (useQueueDestinations) {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryQueue();
                } else {
                    destination = session.createQueue(destinationName);
                }
            } else {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryTopic();
                } else {
                    destination = session.createTopic(destinationName);
                }
            }
        }

        MessageProducer producer = session.createProducer(destination);
        if (durable) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }

        int numMessagesToSend = useFinalControlMessage ? numMessages - 1 : numMessages;

        for (int i = 0; i < numMessagesToSend; i++) {
            String messageText = "Message " + i + " at " + new Date();
            if (bytesLength > -1) {
                byte[] messageTextBytes = messageText.getBytes(StandardCharsets.UTF_8);
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.writeBytes(messageTextBytes);
                if (messageTextBytes.length < bytesLength) {
                    byte[] paddingBytes = new byte[bytesLength - messageTextBytes.length];
                    bytesMessage.writeBytes(paddingBytes);
                }
                if (messageGroupId != null) {
                    bytesMessage.setStringProperty("JMSXGroupID", messageGroupId);
                }
                LOGGER.info("Sending bytes message");
                producer.send(bytesMessage);
            } else {
                TextMessage textMessage = session.createTextMessage(messageText);
                if (messageGroupId != null) {
                    textMessage.setStringProperty("JMSXGroupID", messageGroupId);
                }
                LOGGER.info("Sending text message: " + messageText);
                producer.send(textMessage);
            }

            if (perMessageSleepMS > 0) {
                Thread.sleep(perMessageSleepMS);
            }
            if (transacted) {
                if ((i + 1) % batchSize == 0) {
                    session.commit();
                }
            }
        }
        if (useFinalControlMessage) {
            Message message = session.createMessage();
            if (messageGroupId != null) {
                message.setStringProperty("JMSXGroupID", messageGroupId);
            }
            LOGGER.info("Sending message");
            producer.send(message);
            if (transacted) {
                session.commit();
            }
        }
        producer.close();
    } catch (Exception ex) {
        LOGGER.error("ProducerTool hit exception: " + ex.getMessage(), ex);
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
    }
}