Example usage for org.springframework.jms.core JmsTemplate send

List of usage examples for org.springframework.jms.core JmsTemplate send

Introduction

In this page you can find the example usage for org.springframework.jms.core JmsTemplate send.

Prototype

@Override
    public void send(final String destinationName, final MessageCreator messageCreator) throws JmsException 

Source Link

Usage

From source file:io.fabric8.quickstarts.activemq.App.java

public static void main(String[] args) {
    // Clean out any ActiveMQ data from a previous run
    FileSystemUtils.deleteRecursively(new File("activemq-data"));

    // Launch the application
    ConfigurableApplicationContext context = SpringApplication.run(App.class, args);

    // Send a message
    MessageCreator messageCreator = new MessageCreator() {
        @Override/*ww w. j av a2 s  . c o m*/
        public Message createMessage(Session session) throws JMSException {
            return session.createTextMessage("<hello>world!</hello>");
        }
    };
    JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);
    System.out.println("Sending a new message.");
    jmsTemplate.send(destination, messageCreator);
}

From source file:org.fatal1t.forexapp.spring.api.adapters.SyncListener.java

private void sendMessage(String message, String CorelId, Destination queue)
        throws JmsException, BeansException {
    MessageCreator messageCreator = (javax.jms.Session session1) -> {
        Message nMessage = session1.createTextMessage(message);
        nMessage.setJMSCorrelationID(CorelId);

        return nMessage;
    };/*from w ww  .j a  v a2s  .c o  m*/

    JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class);
    log.info("Target queue: " + queue.toString());
    log.info("Sending back: " + CorelId + " " + message.substring(0, 10));
    jmsTemplate.send(queue, messageCreator);
}

From source file:net.lr.jmsbridge.BridgeServlet.java

/**
 * Forward HTTP request to a jms queue and listen on a temporary queue for the reply.
 * Connects to the jms server by using the username and password from the HTTP basic auth.
 *///from w w w.  j a  v  a  2  s.  c  om
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String authHeader = req.getHeader("Authorization");
    if (authHeader == null) {
        resp.setHeader("WWW-Authenticate", "Basic realm=\"Bridge\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "auth");
        return;
    }
    UserNameAndPassword auth = extractUserNamePassword(authHeader);
    PrintStream out = new PrintStream(resp.getOutputStream());
    String contextPath = req.getContextPath();
    String uri = req.getRequestURI();
    String queueName = uri.substring(contextPath.length() + 1);
    final StringBuffer reqContent = retrieveRequestContent(req.getReader());

    ConnectionFactory cf = connectionPool.getConnectionFactory(auth);
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cf);
    jmsTemplate.setReceiveTimeout(10000);
    final Destination replyDest = connectionPool.getReplyDestination(cf, auth);
    jmsTemplate.send(queueName, new MessageCreator() {

        @Override
        public Message createMessage(Session session) throws JMSException {
            TextMessage message = session.createTextMessage(reqContent.toString());
            message.setJMSReplyTo(replyDest);
            return message;
        }

    });
    Message replyMsg = jmsTemplate.receive(replyDest);
    if (replyMsg instanceof TextMessage) {
        TextMessage replyTMessage = (TextMessage) replyMsg;
        try {
            out.print(replyTMessage.getText());
        } catch (JMSException e) {
            JmsUtils.convertJmsAccessException(e);
        }
    }
}

From source file:it.geosolutions.geoserver.jms.JMSPublisher.java

/**
 * Used to publish the event on the queue.
 * /*from   ww  w. j a va  2  s  . co  m*/
 * @param <S> a serializable object
 * @param <O> the object to serialize using a JMSEventHandler
 * @param destination
 * @param jmsTemplate the template to use to publish on the topic <br>
 *        (default destination should be already set)
 * @param props the JMSProperties used by this instance of GeoServer
 * @param object the object (or event) to serialize and send on the JMS topic
 * 
 * @throws JMSException
 */
public <S extends Serializable, O> void publish(final Topic destination, final JmsTemplate jmsTemplate,
        final Properties props, final O object) throws JMSException {
    try {

        final JMSEventHandler<S, O> handler = jmsManager.getHandler(object);

        // set the used SPI
        props.put(JMSEventHandlerSPI.getKeyName(), handler.getGeneratorClass().getSimpleName());

        // TODO make this configurable
        final MessageCreator creator = new JMSObjectMessageCreator(handler.serialize(object), props);

        jmsTemplate.send(destination, creator);

    } catch (Exception e) {
        if (LOGGER.isLoggable(java.util.logging.Level.SEVERE)) {
            LOGGER.severe(e.getLocalizedMessage());
        }
        final JMSException ex = new JMSException(e.getLocalizedMessage());
        ex.initCause(e);
        throw ex;
    }
}

From source file:org.apache.cxf.transport.jms.JMSConduit.java

/**
 * Send the JMS Request out and if not oneWay receive the response
 * /*from   w  w w.  jav a 2s.co  m*/
 * @param outMessage
 * @param request
 * @return inMessage
 */
public void sendExchange(final Exchange exchange, final Object request) {
    LOG.log(Level.FINE, "JMSConduit send message");

    final Message outMessage = exchange.getOutMessage();
    if (outMessage == null) {
        throw new RuntimeException("Exchange to be sent has no outMessage");
    }

    JMSMessageHeadersType headers = (JMSMessageHeadersType) outMessage
            .get(JMSConstants.JMS_CLIENT_REQUEST_HEADERS);

    JmsTemplate jmsTemplate = JMSFactory.createJmsTemplate(jmsConfig, headers);
    if (!exchange.isOneWay() && jmsListener == null) {
        jmsListener = JMSFactory.createJmsListener(jmsConfig, this, jmsConfig.getReplyDestination(), conduitId);
    }

    final javax.jms.Destination replyTo = exchange.isOneWay() ? null : jmsListener.getDestination();

    final String correlationId = (headers != null && headers.isSetJMSCorrelationID())
            ? headers.getJMSCorrelationID()
            : JMSUtils.createCorrelationId(jmsConfig.getConduitSelectorPrefix() + conduitId,
                    messageCount.incrementAndGet());

    MessageCreator messageCreator = new MessageCreator() {
        public javax.jms.Message createMessage(Session session) throws JMSException {
            String messageType = jmsConfig.getMessageType();
            final javax.jms.Message jmsMessage;
            jmsMessage = JMSUtils.buildJMSMessageFromCXFMessage(outMessage, request, messageType, session,
                    replyTo, correlationId);
            LOG.log(Level.FINE, "client sending request: ", jmsMessage);
            return jmsMessage;
        }
    };

    /**
     * If the message is not oneWay we will expect to receive a reply on the listener. To receive this
     * reply we add the correlationId and an empty CXF Message to the correlationMap. The listener will
     * fill to Message and notify this thread
     */
    if (!exchange.isOneWay()) {
        synchronized (exchange) {
            correlationMap.put(correlationId, exchange);
            jmsTemplate.send(jmsConfig.getTargetDestination(), messageCreator);

            if (exchange.isSynchronous()) {
                try {
                    exchange.wait(jmsTemplate.getReceiveTimeout());
                } catch (InterruptedException e) {
                    correlationMap.remove(correlationId);
                    throw new RuntimeException(e);
                }
                correlationMap.remove(correlationId);
                if (exchange.get(CORRELATED) == null) {
                    throw new RuntimeException("Timeout receiving message with correlationId " + correlationId);
                }

            }
        }
    } else {
        jmsTemplate.send(jmsConfig.getTargetDestination(), messageCreator);
    }
}

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

@SuppressWarnings("resource")
@Test//from w w w  . j  a  va2 s  .c  o  m
public void messageCorrelationBasedOnRequestMessageId() throws Exception {
    ActiveMqTestUtils.prepare();

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "producer-temp-reply-consumers.xml", this.getClass());
    RequestReplyExchanger gateway = context.getBean(RequestReplyExchanger.class);
    CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class);
    final JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);

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

    new Thread(() -> {
        final Message requestMessage = jmsTemplate.receive(requestDestination);
        Destination replyTo = null;
        try {
            replyTo = requestMessage.getJMSReplyTo();
        } catch (Exception e) {
            fail();
        }
        jmsTemplate.send(replyTo, (MessageCreator) session -> {
            try {
                TextMessage message = session.createTextMessage();
                message.setText("bar");
                message.setJMSCorrelationID(requestMessage.getJMSMessageID());
                return message;
            } catch (Exception e) {
                // ignore
            }
            return null;
        });
    }).start();
    gateway.exchange(new GenericMessage<String>("foo"));
    context.close();
}