Java Examples for org.springframework.jms.core.JmsTemplate

The following java examples will help you to understand the usage of org.springframework.jms.core.JmsTemplate. These source code samples are taken from different open source projects.

Example 1
Project: jshoper3x-master  File: testJsm.java View source code
/**
	 * @param args
	 */
public static void main(String[] args) {
    System.out.println("�始化spring�准备开始接收�");
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    // SimpleJMSSender t=(SimpleJMSSender)
    // context.getBean("topicMessageSender");
    // t.sendMessage();
    //
    JmsTemplate jmsTemplate = (JmsTemplate) context.getBean("jmsTemplate");
    for (int i = 0; i < 10; i++) {
        jmsTemplate.send(new MessageCreator() {

            public Message createMessage(Session session) throws JMSException {
                TextMessage msg = session.createTextMessage();
                // 设置消�属性
                msg.setStringProperty("phrCode", "C001");
                // 设置消�内容
                msg.setText("Hello World!");
                return msg;
            }
        });
    }
}
Example 2
Project: lemon-master  File: UserPublisher.java View source code
public void sendNotification(String destinationName, Object object) {
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(connectionFactory);
    jmsTemplate.setPubSubDomain(true);
    try {
        jmsTemplate.convertAndSend(destinationName, jsonMapper.toJson(object));
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    }
}
Example 3
Project: Spring-Integration-in-Action-master  File: MessageListenerContainerDemo.java View source code
public static void main(String[] args) {
    // establish common resources
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
    Destination queue = new ActiveMQQueue("siia.queue");
    // setup and start listener container
    DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setDestination(queue);
    container.setMessageListener(new MessageListener() {

        public void onMessage(Message message) {
            try {
                if (!(message instanceof TextMessage)) {
                    throw new IllegalArgumentException("expected TextMessage");
                }
                System.out.println("received: " + ((TextMessage) message).getText());
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }
        }
    });
    container.afterPropertiesSet();
    container.start();
    // send Message
    JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
    jmsTemplate.setDefaultDestination(queue);
    jmsTemplate.convertAndSend("Hello World");
}
Example 4
Project: spring-advanced-marhshallers-and-service-exporters-master  File: TestJmsMessageConverter.java View source code
@Override
public void doWithActiveMq(BrokerService brokerService, JmsTemplate jmsTemplate) throws Throwable {
    String avroDestination = "thrift";
    jmsTemplate.convertAndSend(avroDestination, thriftCustomer);
    org.springframework.obm.thrift.crm.Customer customerReceived = (org.springframework.obm.thrift.crm.Customer) jmsTemplate.receiveAndConvert(avroDestination);
    Assert.assertEquals(thriftCustomer, customerReceived);
}
Example 5
Project: sagan-master  File: PostSummaryTests.java View source code
@Test
public void extractBasicSummary() {
    String content = "<p>this is a blog post</p>\n" + "<p>With the release of Spring 1.1 the Spring community was given it?s first taste of JMS support. This support included exception translation, message conversion, and a template class much like <a href=\"http://static.springframework.org/spring/docs/2.0-m3/api/org/springframework/jdbc/core/JdbcTemplate.html\">JdbcTemplate</a>. This support also took care of domain unification between the JMS 1.0.2 and 1.1 specs. The centerpieces of this support are the <a href=\"http://static.springframework.org/spring/docs/1.2.x/api/org/springframework/jms/core/JmsTemplate.html\">JmsTemplate</a> class and it?s JMS 1.0.2 counterpart <a href=\"http://static.springframework.org/spring/docs/1.2.x/api/org/springframework/jms/core/JmsTemplate102.html\">JmsTemplate102</a>.</p>\n" + "<p>This support was a great improvement over using the raw JMS APIs to do enterprise messaging. However it did have a shortcoming; the JmsTemplate only supported synchronous reception of messages using the <a href=\"http://static.springframework.org/spring/docs/1.2.x/api/org/springframework/jms/core/JmsTemplate.html#receive()\">JmsTemplate.receive()</a> methods. This behavior worked well for many people but the vast majority of users of ended up rolling their own implementations of an asynchronous consumer. In short, they wanted what EJB 2 called <a href=\"http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/EJBConcepts5.html\">Message Driven Beans</a>.</p>";
    String expected = "<p>this is a blog post</p>\n" + "<p>With the release of Spring 1.1 the Spring community was given it?s first taste of JMS support. This support included exception translation, message conversion, and a template class much like <a href=\"http://static.springframework.org/spring/docs/2.0-m3/api/org/springframework/jdbc/core/JdbcTemplate.html\">JdbcTemplate</a>. This support also took care of domain unification between the JMS 1.0.2 and 1.1 specs. The centerpieces of this support are the <a href=\"http://static.springframework.org/spring/docs/1.2.x/api/org/springframework/jms/core/JmsTemplate.html\">JmsTemplate</a> class and it?s JMS 1.0.2 counterpart <a href=\"http://static.springframework.org/spring/docs/1.2.x/api/org/springframework/jms/core/JmsTemplate102.html\">JmsTemplate102</a>.</p>\n";
    assertThat(postSummary.forContent(content, 50), is(expected));
}
Example 6
Project: gs-messaging-jms-master  File: Application.java View source code
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(Application.class, args);
    // Send a message
    MessageCreator messageCreator = new MessageCreator() {

        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createTextMessage("ping!");
        }
    };
    JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);
    System.out.println("Sending a new message.");
    jmsTemplate.send(mailboxDestination, messageCreator);
}
Example 7
Project: ivanova_p01-master  File: Launcher.java View source code
// ------------------------------------------------------------------------------------------------------
public static void main(String... args) {
    String CONTEXT_CONFIGURATION = "context-jms-integration.xml";
    CalculationRequest request = new CalculationRequest();
    request.setNumberA(23);
    request.setNumberB(40);
    request.setOperation(Operation.ADDITION);
    ApplicationContext context = new ClassPathXmlApplicationContext(CONTEXT_CONFIGURATION);
    ((AbstractApplicationContext) context).registerShutdownHook();
    JmsTemplate template = (JmsTemplate) context.getBean("jmsTemplate");
    Destination topic = (Destination) context.getBean("calculationRequestTopic");
    LOG.info("Sending calculation request: " + request);
    template.convertAndSend(topic, request);
}
Example 8
Project: jBilling-master  File: CommandsQueueSender.java View source code
/**
     * @param commands
     */
public void postCommandsQueue(LinkedList<LinkedList<StringPair>> commands, final String eventType) throws JMSException {
    LOG.debug("calling postCommandsQueue()");
    if (commands == null) {
        LOG.debug("Found NULL commands queue Object");
        return;
    }
    if (commands.isEmpty()) {
        LOG.debug("Found empty commands queue. No commands to post. Returning. ");
        return;
    }
    JmsTemplate jmsTemplate = (JmsTemplate) Context.getBean(Context.Name.JMS_TEMPLATE);
    for (Iterator<LinkedList<StringPair>> it = commands.iterator(); it.hasNext(); ) {
        final LinkedList<StringPair> commandQueue = (LinkedList<StringPair>) it.next();
        Destination destination = (Destination) Context.getBean(Context.Name.PROVISIONING_COMMANDS_DESTINATION);
        jmsTemplate.send(destination, new MessageCreator() {

            public Message createMessage(Session session) throws JMSException {
                MapMessage message = session.createMapMessage();
                postCommand(commandQueue, eventType, message);
                return message;
            }
        });
    }
}
Example 9
Project: message-queue-client-framework-master  File: MessageProducerTest.java View source code
@Test
public void test() throws Exception {
    MessageProducer<String> producer = new MessageProducer<String>();
    Assert.assertNull(producer.getDestination());
    Destination destination = new ActiveMQTempQueue("TempQueue");
    producer.setDestination(destination);
    Assert.assertNull(producer.getJmsTemplate());
    JmsTemplate jmsTemplate = new JmsTemplateImpl();
    producer.setJmsTemplate(jmsTemplate);
    Assert.assertEquals("TempQueue", producer.getProducerKey());
    producer.send("test");
    Destination destination2 = new ActiveMQTempTopic("TempTopic");
    producer.setDestination(destination2);
    JmsTemplate jmsTemplate2 = new JmsTemplateImpl2();
    producer.setJmsTemplate(jmsTemplate2);
    Assert.assertEquals("TempTopic", producer.getProducerKey());
    try {
        producer.send("test");
    } catch (Exception e) {
        Assert.assertTrue(e instanceof MQException);
    }
    producer.setDestination(new Destination() {

        @Override
        public String toString() {
            return "TempDestination";
        }
    });
    Assert.assertEquals("TempDestination", producer.getProducerKey());
    producer.setDestination(new Queue() {

        @Override
        public String getQueueName() throws JMSException {
            throw new JMSException("test");
        }
    });
    try {
        producer.getProducerKey();
    } catch (Exception e) {
        Assert.assertTrue(e instanceof MQException);
    }
    producer.setDestination(new Topic() {

        @Override
        public String getTopicName() throws JMSException {
            throw new JMSException("test");
        }
    });
    try {
        producer.getProducerKey();
    } catch (Exception e) {
        Assert.assertTrue(e instanceof MQException);
    }
    producer.setProducerKey("QUEUE.TEST");
    Assert.assertEquals("QUEUE.TEST", producer.getProducerKey());
}
Example 10
Project: SeavusJB3-master  File: CommandsQueueSender.java View source code
/**
     * @param commands
     */
public void postCommandsQueue(LinkedList<LinkedList<StringPair>> commands, final String eventType) throws JMSException {
    LOG.debug("calling postCommandsQueue()");
    if (commands == null) {
        LOG.debug("Found NULL commands queue Object");
        return;
    }
    if (commands.isEmpty()) {
        LOG.debug("Found empty commands queue. No commands to post. Returning. ");
        return;
    }
    JmsTemplate jmsTemplate = (JmsTemplate) Context.getBean(Context.Name.JMS_TEMPLATE);
    for (Iterator<LinkedList<StringPair>> it = commands.iterator(); it.hasNext(); ) {
        final LinkedList<StringPair> commandQueue = (LinkedList<StringPair>) it.next();
        Destination destination = (Destination) Context.getBean(Context.Name.PROVISIONING_COMMANDS_DESTINATION);
        jmsTemplate.send(destination, new MessageCreator() {

            public Message createMessage(Session session) throws JMSException {
                MapMessage message = session.createMapMessage();
                postCommand(commandQueue, eventType, message);
                return message;
            }
        });
    }
}
Example 11
Project: spring-data-jdbc-ext-master  File: TextPayloadTests.java View source code
@Transactional
@Test
@Rollback(false)
public void sendMessage() {
    jmsTemplate.send("jmsadmin.jms_text_queue", new MessageCreator() {

        public Message createMessage(Session session) throws JMSException {
            TextMessage msg = session.createTextMessage();
            msg.setText("Hello Spring, from JmsTemplate!");
            return msg;
        }
    });
}
Example 12
Project: spring-framework-2.5.x-master  File: JmsTransactionManagerTests.java View source code
public void testTransactionCommit() throws JMSException {
    MockControl cfControl = MockControl.createControl(ConnectionFactory.class);
    ConnectionFactory cf = (ConnectionFactory) cfControl.getMock();
    MockControl conControl = MockControl.createControl(Connection.class);
    Connection con = (Connection) conControl.getMock();
    MockControl sessionControl = MockControl.createControl(Session.class);
    final Session session = (Session) sessionControl.getMock();
    cf.createConnection();
    cfControl.setReturnValue(con, 1);
    con.createSession(true, Session.AUTO_ACKNOWLEDGE);
    conControl.setReturnValue(session, 1);
    session.commit();
    sessionControl.setVoidCallable(1);
    session.close();
    sessionControl.setVoidCallable(1);
    con.close();
    conControl.setVoidCallable(1);
    sessionControl.replay();
    conControl.replay();
    cfControl.replay();
    JmsTransactionManager tm = new JmsTransactionManager(cf);
    TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
    JmsTemplate jt = new JmsTemplate(cf);
    jt.execute(new SessionCallback() {

        public Object doInJms(Session sess) {
            assertTrue(sess == session);
            return null;
        }
    });
    tm.commit(ts);
    sessionControl.verify();
    conControl.verify();
    cfControl.verify();
}
Example 13
Project: spring-framework-issues-master  File: MainThread.java View source code
public static void main(String[] args) throws Exception {
    Topic request = new ActiveMQTopic("request");
    for (int i = 0; i < 100; i++) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml");
        ctx.start();
        Connection conn = null;
        Session requestSession = null;
        try {
            ConnectionFactory connFactory = (ConnectionFactory) ctx.getBean("connectionFactory");
            EchoMessageListener messageListener = ctx.getBean(EchoMessageListener.class);
            conn = connFactory.createConnection();
            requestSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageConsumer requestConsumer = requestSession.createConsumer(request);
            requestConsumer.setMessageListener(messageListener);
            conn.start();
            JmsTemplate template = ctx.getBean(JmsTemplate.class);
            template.send(request, new MessageCreator() {

                @Override
                public Message createMessage(Session session) throws JMSException {
                    return session.createBytesMessage();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (requestSession != null) {
                requestSession.close();
            }
            if (conn != null) {
                conn.close();
            }
        }
        ctx.close();
    }
}
Example 14
Project: spring-framework-master  File: JmsTransactionManagerTests.java View source code
@Test
public void testTransactionCommit() throws JMSException {
    ConnectionFactory cf = mock(ConnectionFactory.class);
    Connection con = mock(Connection.class);
    final Session session = mock(Session.class);
    given(cf.createConnection()).willReturn(con);
    given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);
    JmsTransactionManager tm = new JmsTransactionManager(cf);
    TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
    JmsTemplate jt = new JmsTemplate(cf);
    jt.execute(new SessionCallback<Void>() {

        @Override
        public Void doInJms(Session sess) {
            assertTrue(sess == session);
            return null;
        }
    });
    tm.commit(ts);
    verify(session).commit();
    verify(session).close();
    verify(con).close();
}
Example 15
Project: spring-integration-ha-demo-master  File: Main.java View source code
public static void main(String[] args) throws Exception {
    if (args.length > 0 && "amq".equals(args[0])) {
        new ClassPathXmlApplicationContext("/META-INF/spring/integration/amq-broker-context.xml");
        System.out.println("Broker started; Hit Enter to terminate");
        System.in.read();
        System.exit(0);
    }
    AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("/META-INF/spring/integration/sample-strict-order-context.xml");
    System.out.println("Enter \n to terminate; otherwise message");
    boolean amqp = System.getProperty("spring.profiles.active").contains("amqp");
    AmqpTemplate amqpTemplate = null;
    JmsTemplate jmsTemplate = null;
    if (amqp) {
        amqpTemplate = ctx.getBean(AmqpTemplate.class);
    } else {
        jmsTemplate = ctx.getBean(JmsTemplate.class);
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        String msg = br.readLine();
        if (msg.length() == 0) {
            break;
        }
        if (amqp) {
            amqpTemplate.convertAndSend("cluster.inbound", msg);
        } else {
            jmsTemplate.convertAndSend(msg);
        }
    }
    ctx.close();
}
Example 16
Project: spring-integration-master  File: OutboundGatewayFunctionTests.java View source code
@Test
public void testContainerWithDest() throws Exception {
    BeanFactory beanFactory = mock(BeanFactory.class);
    when(beanFactory.containsBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)).thenReturn(true);
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.initialize();
    when(beanFactory.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class)).thenReturn(scheduler);
    final JmsOutboundGateway gateway = new JmsOutboundGateway();
    gateway.setBeanFactory(beanFactory);
    ConnectionFactory connectionFactory = getConnectionFactory();
    gateway.setConnectionFactory(connectionFactory);
    gateway.setRequestDestination(requestQueue1);
    gateway.setReplyDestination(replyQueue1);
    gateway.setCorrelationKey("JMSCorrelationID");
    gateway.setUseReplyContainer(true);
    gateway.afterPropertiesSet();
    gateway.start();
    final AtomicReference<Object> reply = new AtomicReference<Object>();
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    Executors.newSingleThreadExecutor().execute(() -> {
        latch1.countDown();
        try {
            reply.set(gateway.handleRequestMessage(new GenericMessage<String>("foo")));
        } finally {
            latch2.countDown();
        }
    });
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    JmsTemplate template = new JmsTemplate();
    template.setConnectionFactory(connectionFactory);
    template.setReceiveTimeout(10000);
    javax.jms.Message request = template.receive(requestQueue1);
    assertNotNull(request);
    final javax.jms.Message jmsReply = request;
    template.send(request.getJMSReplyTo(), (MessageCreator)  session -> jmsReply);
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    assertNotNull(reply.get());
    gateway.stop();
    scheduler.destroy();
}
Example 17
Project: zheng-master  File: JmsUtil.java View source code
/**
     * 延迟��对象消�
     * @param jmsTemplate
     * @param destination
     * @param objectMessage
     * @param delay
     */
public static void sendMessageDelay(JmsTemplate jmsTemplate, Destination destination, final Serializable objectMessage, final long delay) {
    jmsTemplate.send(destination, new MessageCreator() {

        public Message createMessage(Session session) throws JMSException {
            ObjectMessage om = session.createObjectMessage(objectMessage);
            om.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
            om.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 1 * 1000);
            om.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, 1);
            return om;
        }
    });
}
Example 18
Project: camel-master  File: JmsConfiguration.java View source code
/**
     * Creates a {@link JmsOperations} object used for request/response using a request timeout value
     */
public JmsOperations createInOutTemplate(JmsEndpoint endpoint, boolean pubSubDomain, String destination, long requestTimeout) {
    JmsOperations answer = createInOnlyTemplate(endpoint, pubSubDomain, destination);
    if (answer instanceof JmsTemplate && requestTimeout > 0) {
        JmsTemplate jmsTemplate = (JmsTemplate) answer;
        jmsTemplate.setExplicitQosEnabled(true);
        // prefer to use timeToLive over requestTimeout if both specified
        long ttl = timeToLive > 0 ? timeToLive : requestTimeout;
        if (ttl > 0 && !isDisableTimeToLive()) {
            // only use TTL if not disabled
            jmsTemplate.setTimeToLive(ttl);
        }
        jmsTemplate.setSessionTransacted(isTransactedInOut());
        if (isTransactedInOut()) {
            jmsTemplate.setSessionAcknowledgeMode(Session.SESSION_TRANSACTED);
        } else {
            if (acknowledgementMode >= 0) {
                jmsTemplate.setSessionAcknowledgeMode(acknowledgementMode);
            } else if (acknowledgementModeName != null) {
                jmsTemplate.setSessionAcknowledgeModeName(acknowledgementModeName);
            } else {
                // default to AUTO
                jmsTemplate.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE);
            }
        }
    }
    return answer;
}
Example 19
Project: geoserver-enterprise-master  File: JMSPublisher.java View source code
/**
     * Used to publish the event on the queue.
     * 
     * @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;
    }
}
Example 20
Project: geoserver-master  File: JMSPublisher.java View source code
/**
     * Used to publish the event on the queue.
     * 
     * @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;
    }
}
Example 21
Project: nifi-master  File: JMSPublisherConsumerTest.java View source code
@Test
public void validateBytesConvertedToBytesMessageOnSend() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);
    JMSPublisher publisher = new JMSPublisher(jmsTemplate, mock(ComponentLog.class));
    publisher.publish(destinationName, "hellomq".getBytes());
    Message receivedMessage = jmsTemplate.receive(destinationName);
    assertTrue(receivedMessage instanceof BytesMessage);
    byte[] bytes = new byte[7];
    ((BytesMessage) receivedMessage).readBytes(bytes);
    assertEquals("hellomq", new String(bytes));
    ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
}
Example 22
Project: OG-Platform-master  File: LiveMarketDataProviderFactoryComponentFactory.java View source code
/**
   * Creates a live data client based on the information in the remote metadata.
   * 
   * @param provider the metadata provider, null returns null
   * @param jmsConnector the JMS connector, not null
   * @return the client
   */
@SuppressWarnings("deprecation")
public static LiveDataClient createLiveDataClient(LiveDataMetaDataProvider provider, JmsConnector jmsConnector) {
    ArgumentChecker.notNull(jmsConnector, "jmsConnector");
    LiveDataMetaData metaData = provider.metaData();
    URI jmsUri = metaData.getJmsBrokerUri();
    if (metaData.getServerType() != LiveDataServerTypes.STANDARD || jmsUri == null) {
        s_logger.warn("Unsupported live data server type " + metaData.getServerType() + " for " + metaData.getDescription() + " live data provider. This provider will not be available.");
        return null;
    }
    if (!jmsConnector.getClientBrokerUri().equals(jmsUri)) {
        JmsConnectorFactoryBean jmsFactory = new JmsConnectorFactoryBean(jmsConnector);
        jmsFactory.setClientBrokerUri(jmsUri);
        jmsConnector = jmsFactory.getObjectCreating();
    }
    JmsTemplate jmsTemplate = jmsConnector.getJmsTemplateTopic();
    JmsByteArrayRequestSender jmsSubscriptionRequestSender;
    if (metaData.getJmsSubscriptionQueue() != null) {
        JmsTemplate subscriptionRequestTemplate = jmsConnector.getJmsTemplateQueue();
        jmsSubscriptionRequestSender = new JmsByteArrayRequestSender(metaData.getJmsSubscriptionQueue(), subscriptionRequestTemplate);
    } else {
        jmsSubscriptionRequestSender = new JmsByteArrayRequestSender(metaData.getJmsSubscriptionTopic(), jmsTemplate);
    }
    ByteArrayFudgeRequestSender fudgeSubscriptionRequestSender = new ByteArrayFudgeRequestSender(jmsSubscriptionRequestSender);
    JmsByteArrayRequestSender jmsEntitlementRequestSender = new JmsByteArrayRequestSender(metaData.getJmsEntitlementTopic(), jmsTemplate);
    ByteArrayFudgeRequestSender fudgeEntitlementRequestSender = new ByteArrayFudgeRequestSender(jmsEntitlementRequestSender);
    final JmsLiveDataClient liveDataClient = new JmsLiveDataClient(fudgeSubscriptionRequestSender, fudgeEntitlementRequestSender, jmsConnector, OpenGammaFudgeContext.getInstance(), JmsLiveDataClient.DEFAULT_NUM_SESSIONS);
    liveDataClient.setFudgeContext(OpenGammaFudgeContext.getInstance());
    if (metaData.getJmsHeartbeatTopic() != null) {
        JmsByteArrayMessageSender jmsHeartbeatSender = new JmsByteArrayMessageSender(metaData.getJmsHeartbeatTopic(), jmsTemplate);
        liveDataClient.setHeartbeatMessageSender(jmsHeartbeatSender);
    }
    liveDataClient.start();
    liveDataClient.registerMetrics(OpenGammaMetricRegistry.getSummaryInstance(), OpenGammaMetricRegistry.getDetailedInstance(), "LiveDataClient - " + provider.metaData().getDescription());
    return liveDataClient;
}
Example 23
Project: openengsb-master  File: JMSPortTest.java View source code
@Before
public void setup() {
    System.setProperty("org.apache.activemq.default.directory.prefix", tempFolder.getRoot().getAbsolutePath() + "/");
    setupKeys();
    String num = UUID.randomUUID().toString();
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost" + num);
    jmsTemplate = new JmsTemplate(connectionFactory);
    jmsTemplateFactory = new JMSTemplateFactory() {

        @Override
        public SimpleMessageListenerContainer createMessageListenerContainer() {
            return simpleMessageListenerConainer;
        }

        @Override
        public JmsTemplate createJMSTemplate(DestinationUrl destinationUrl) {
            return jmsTemplate;
        }
    };
    simpleMessageListenerConainer = new SimpleMessageListenerContainer();
    incomingPort = new JMSIncomingPort();
    incomingPort.setFactory(jmsTemplateFactory);
    incomingPort.setConnectionFactory(connectionFactory);
    RequestHandlerImpl requestHandlerImpl = new RequestHandlerImpl();
    requestHandlerImpl.setUtilsService(new DefaultOsgiUtilsService(bundleContext));
    handler = requestHandlerImpl;
    TestInterface mock2 = mock(TestInterface.class);
    registerServiceViaId(mock2, "test", TestInterface.class);
    when(mock2.method(anyString(), anyInt(), any(TestClass.class))).thenReturn(new TestClass("test"));
    Map<String, String> metaData = Maps.newHashMap(ImmutableMap.of("serviceId", "test"));
    MethodCall methodCall = new MethodCall("method", new Object[] { "123", 5, new TestClass("test") }, metaData);
    call = new MethodCallMessage(methodCall, "123");
    call.setDestination("host?receive");
    MethodResult result = new MethodResult(new TestClass("test"));
    result.setMetaData(metaData);
    methodReturn = new MethodResultMessage(result, "123");
    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(Constants.PROVIDED_CLASSES_KEY, Password.class.getName());
    props.put(Constants.DELEGATION_CONTEXT_KEY, org.openengsb.core.api.Constants.DELEGATION_CONTEXT_CREDENTIALS);
    registerService(new ClassProviderImpl(bundle, Sets.newHashSet(Password.class.getName())), props, ClassProvider.class);
    DefaultSecurityManager securityManager = new DefaultSecurityManager();
    securityManager.setAuthenticator(new Authenticator() {

        @Override
        public AuthenticationInfo authenticate(AuthenticationToken authenticationToken) throws org.apache.shiro.authc.AuthenticationException {
            return new SimpleAuthenticationInfo(authenticationToken.getPrincipal(), authenticationToken.getCredentials(), "openengsb");
        }
    });
    SecurityUtils.setSecurityManager(securityManager);
}
Example 24
Project: spring-batch-master  File: SynchronousTests.java View source code
@Transactional
@Test
public void testPartialRollback() throws Exception {
    // The JmsTemplate is used elsewhere outside a transaction, so
    // we need to use one here that is transaction aware.
    final JmsTemplate txJmsTemplate = new JmsTemplate((ConnectionFactory) applicationContext.getBean("txAwareConnectionFactory"));
    txJmsTemplate.setReceiveTimeout(100L);
    txJmsTemplate.setSessionTransacted(true);
    assertInitialState();
    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {

        @Override
        public Void doInTransaction(org.springframework.transaction.TransactionStatus status) {
            repeatTemplate.iterate(new RepeatCallback() {

                @Override
                public RepeatStatus doInIteration(RepeatContext context) throws Exception {
                    String text = (String) txJmsTemplate.receiveAndConvert("queue");
                    list.add(text);
                    jdbcTemplate.update("INSERT into T_BARS (id,name,foo_date) values (?,?,null)", list.size(), text);
                    return RepeatStatus.continueIf(text != null);
                }
            });
            // Simulate a message system failure before the main transaction
            // commits...
            txJmsTemplate.execute(new SessionCallback<Void>() {

                @Override
                public Void doInJms(Session session) throws JMSException {
                    try {
                        assertTrue("Not a SessionProxy - wrong spring version?", session instanceof SessionProxy);
                        ((SessionProxy) session).getTargetSession().rollback();
                    } catch (JMSException e) {
                        throw e;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            });
            return null;
        }
    });
    String text = "";
    List<String> msgs = new ArrayList<String>();
    while (text != null) {
        text = (String) txJmsTemplate.receiveAndConvert("queue");
        msgs.add(text);
    }
    // The database portion committed...
    int count = jdbcTemplate.queryForObject("select count(*) from T_BARS", Integer.class);
    assertEquals(2, count);
    // ...but the JMS session rolled back, so the message is still there
    assertTrue("Foo not on queue", msgs.contains("foo"));
    assertTrue("Bar not on queue", msgs.contains("bar"));
}
Example 25
Project: vnet-sms-master  File: GatewayServerChannelPipelineFactoryTest.java View source code
@Test(expected = IllegalArgumentException.class)
public final void assertThatConstructorRejectsNullPduType() {
    final JmsTemplate jmsTemplate = createNiceMock(JmsTemplate.class);
    new GatewayServerChannelPipelineFactory<Integer, ReferenceableMessageContainer>("assertThatConstructorRejectsNullPduType", null, new DelimiterBasedFrameDecoder(0, ChannelBuffers.EMPTY_BUFFER), new Base64Decoder(), new Base64Encoder(), new SerializationTransportProtocolAdaptingUpstreamChannelHandler(), new SerializationTransportProtocolAdaptingDownstreamChannelHandler(), new IncomingMessagesForwardingJmsBridge<Integer>(jmsTemplate), 10, 1000L, new AcceptAllAuthenticationManager(), 1000L, new SerialIntegersMessageReferenceGenerator(), 2, 2000L, new MBeanExporter(), new InitialChannelEventsMonitor(), Metrics.defaultRegistry(), new HashedWheelTimer(), new DefaultChannelGroup());
}
Example 26
Project: activemq-artemis-master  File: AMQStackOverFlowTest.java View source code
public void testStackOverflow() throws Exception {
    BrokerService brokerService1 = null;
    BrokerService brokerService2 = null;
    try {
        brokerService1 = createBrokerService("broker1", URL1, URL2);
        brokerService1.start();
        brokerService2 = createBrokerService("broker2", URL2, URL1);
        brokerService2.start();
        final ActiveMQConnectionFactory cf1 = new ActiveMQConnectionFactory(URL1);
        cf1.setUseAsyncSend(false);
        final ActiveMQConnectionFactory cf2 = new ActiveMQConnectionFactory(URL2);
        cf2.setUseAsyncSend(false);
        final JmsTemplate template1 = new JmsTemplate(cf1);
        template1.setReceiveTimeout(10000);
        template1.send("test.q", new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage("test");
            }
        });
        final JmsTemplate template2 = new JmsTemplate(cf2);
        template2.setReceiveTimeout(10000);
        final Message m = template2.receive("test.q");
        assertTrue(m instanceof TextMessage);
        final TextMessage tm = (TextMessage) m;
        assertEquals("test", tm.getText());
        template2.send("test2.q", new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage("test2");
            }
        });
        final Message m2 = template1.receive("test2.q");
        assertNotNull(m2);
        assertTrue(m2 instanceof TextMessage);
        final TextMessage tm2 = (TextMessage) m2;
        assertEquals("test2", tm2.getText());
    } finally {
        brokerService1.stop();
        brokerService1 = null;
        brokerService2.stop();
        brokerService2 = null;
    }
}
Example 27
Project: activemq-master  File: LoadBalanceTest.java View source code
@Override
public Object call() throws Exception {
    try {
        final ActiveMQConnectionFactory connectionFactory2 = new ActiveMQConnectionFactory("vm://two");
        final SingleConnectionFactory singleConnectionFactory2 = new SingleConnectionFactory(connectionFactory2);
        singleConnectionFactory2.setReconnectOnException(true);
        final DefaultMessageListenerContainer container2 = new DefaultMessageListenerContainer();
        container2.setConnectionFactory(singleConnectionFactory2);
        container2.setMaxConcurrentConsumers(1);
        container2.setDestination(new ActiveMQQueue("testingqueue"));
        container2.setMessageListener(new MessageListener() {

            @Override
            public void onMessage(final Message message) {
                broker2Count.incrementAndGet();
            }
        });
        container2.afterPropertiesSet();
        container2.start();
        consumer2Started.countDown();
        assertTrue("wait for start signal", startProducer.await(20, TimeUnit.SECONDS));
        final CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(singleConnectionFactory2);
        final JmsTemplate template = new JmsTemplate(cachingConnectionFactory);
        final ActiveMQQueue queue = new ActiveMQQueue("testingqueue");
        for (int i = 0; i < total; i++) {
            template.send(queue, new MessageCreator() {

                @Override
                public Message createMessage(final Session session) throws JMSException {
                    final TextMessage message = session.createTextMessage();
                    message.setText("Hello World!");
                    return message;
                }
            });
        }
        // give spring time to scale back again
        while (container2.getActiveConsumerCount() > 1) {
            System.out.println("active consumer count: " + container2.getActiveConsumerCount());
            System.out.println("concurrent consumer count: " + container2.getConcurrentConsumers());
            Thread.sleep(1000);
        }
        cachingConnectionFactory.destroy();
        container2.destroy();
    } catch (final Throwable t) {
        t.printStackTrace();
    }
    return null;
}
Example 28
Project: spring-boot-master  File: JmsAutoConfigurationTests.java View source code
@Test
public void testDefaultJmsConfiguration() {
    load(TestConfiguration.class);
    ActiveMQConnectionFactory connectionFactory = this.context.getBean(ActiveMQConnectionFactory.class);
    JmsTemplate jmsTemplate = this.context.getBean(JmsTemplate.class);
    JmsMessagingTemplate messagingTemplate = this.context.getBean(JmsMessagingTemplate.class);
    assertThat(connectionFactory).isEqualTo(jmsTemplate.getConnectionFactory());
    assertThat(messagingTemplate.getJmsTemplate()).isEqualTo(jmsTemplate);
    assertThat(((ActiveMQConnectionFactory) jmsTemplate.getConnectionFactory()).getBrokerURL()).isEqualTo(ACTIVEMQ_EMBEDDED_URL);
    assertThat(this.context.containsBean("jmsListenerContainerFactory")).isTrue();
}
Example 29
Project: spring-xd-master  File: AmqBrokerAndTest.java View source code
public static void main(String[] args) throws Exception {
    String xdHome = null;
    if (args.length > 0) {
        xdHome = args[0];
    }
    Assert.notNull(xdHome, "need an XD_HOME argument");
    String destinationName = "jmsTest";
    if (args.length > 1) {
        destinationName = args[1];
    }
    boolean topic = false;
    if (args.length > 2 && args[2].equals("topic")) {
        topic = true;
    }
    BrokerService broker = new BrokerService();
    Properties props = new Properties();
    PropertiesLoaderUtils.fillProperties(props, new FileSystemResource(xdHome + "/config/jms-activemq.properties"));
    String brokerURL = props.getProperty("amq.url");
    broker.addConnector(brokerURL);
    broker.start();
    ConnectionFactory cf = new ActiveMQConnectionFactory(brokerURL);
    CachingConnectionFactory ccf = new CachingConnectionFactory(cf);
    Destination destination = topic ? new ActiveMQTopic(destinationName) : new ActiveMQQueue(destinationName);
    JmsTemplate template = new JmsTemplate(ccf);
    template.setDefaultDestination(destination);
    System.out.println("Enter test messages for destination " + destination + ", 'quit' to end");
    Scanner scanner = new Scanner(System.in);
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (line.equalsIgnoreCase("quit")) {
            break;
        }
        template.convertAndSend(line);
    }
    scanner.close();
    broker.stop();
}
Example 30
Project: STARDOM-master  File: ALERTSimulator.java View source code
private static int handleFile(ApplicationContext context, String topic, String commitFile) {
    Properties systemProperties = (Properties) context.getBean("systemProperties");
    if (StringUtils.isEmpty(commitFile)) {
        return 0;
    }
    File file = new File(commitFile);
    if (file.exists() && file.canRead()) {
        //determine service
        String absolutePath = file.getAbsolutePath();
        String service = "zipSimulationService";
        if (absolutePath.toLowerCase().endsWith("tar.gz")) {
            service = "targzSimulationService";
        } else if (absolutePath.toLowerCase().endsWith("rar")) {
            service = "rarSimulationService";
        } else if (absolutePath.toLowerCase().endsWith("zip")) {
            service = "zipSimulationService";
        } else {
            logger.error("Couldn't find service for this file");
            return 0;
        }
        logger.info("Using service {} ", service);
        return ((SimulationService) context.getBean(service)).start(absolutePath, new InputStreamTopicVisitor(topic, !Boolean.valueOf(systemProperties.getProperty("activemq.processDisabled")), (JmsTemplate) context.getBean("jmsTemplate")));
    } else {
        logger.error("Couldn't handle {} ", commitFile);
    }
    return -1;
}
Example 31
Project: symmetric-ds-master  File: SimpleJmsPublisher.java View source code
@ManagedOperation(description = "Publishes the message text passed in as an argument")
@ManagedOperationParameters({ @ManagedOperationParameter(name = "text", description = "The message text that will be published") })
public boolean publish(String text) {
    try {
        log.debug("Publishing {}", text);
        if (enabled) {
            ((JmsTemplate) beanFactory.getBean(jmsTemplateBeanName)).convertAndSend(text);
            return true;
        } else {
            log.info("Message was not published because the publisher is not enabled: \n" + text);
            return false;
        }
    } catch (RuntimeException ex) {
        log.error("Failed to publish message: \n" + text, ex);
        throw ex;
    }
}
Example 32
Project: Anicetus-master  File: SessionTest.java View source code
@Test
public void testBasicRequest() throws Exception {
    m_server.start();
    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet("http://localhost:" + s_PORT + "/?a=1&b=2");
    get.setHeader("Content-Type", "text/plain");
    HttpResponse resp = client.execute(get);
    HttpEntity entity = resp.getEntity();
    JsonNode node = parseResponse(entity);
    ApplicationContext curCtx = WebApplicationContextUtils.getWebApplicationContext(m_servletHolder.getServlet().getServletConfig().getServletContext());
    JmsTemplate tmpl = (JmsTemplate) curCtx.getBean("consumeTempl");
    Object obj = tmpl.receiveAndConvert();
    assertNotNull(obj);
    assertTrue(obj instanceof TelemetryHttpSession);
    TelemetryHttpSession hsess = (TelemetryHttpSession) obj;
    validateHeaders(node, resp, hsess);
    validateParams(node, hsess);
    m_server.stop();
}
Example 33
Project: jmeter-plugins-master  File: JmsUtil.java View source code
@Override
public SampleResult runTest(JavaSamplerContext ctx) {
    SampleResult result = new SampleResult();
    result.setContentType("plain/text");
    result.setDataType(SampleResult.TEXT);
    result.setDataEncoding(SampleResult.DEFAULT_HTTP_ENCODING);
    String connectionUrl = ctx.getParameter("connection.url");
    String bindingUrl = ctx.getParameter("binding.url");
    String message = ctx.getParameter("message");
    if (connectionUrl == null || "".equals(connectionUrl)) {
        result.setSuccessful(false);
        result.setResponseMessage("Connection URL cannot be empty.");
        result.setResponseCode("0xDEAD");
    } else {
        if (bindingUrl == null || "".equals(bindingUrl)) {
            result.setSuccessful(false);
            result.setResponseMessage("Binding URL cannot be empty.");
            result.setResponseCode("0xDEAD");
        } else {
            try {
                ConnectionFactory connectionFactory = new AMQConnectionFactory(connectionUrl);
                AMQBindingURL burl = new AMQBindingURL(bindingUrl);
                Destination destinationProducer = new AMQAnyDestination(burl);
                JmsTemplate sender = new JmsTemplate();
                sender.setConnectionFactory(connectionFactory);
                sender.setDefaultDestination(destinationProducer);
                BinaryMessageConverter bmc = new BinaryMessageConverter();
                sender.setMessageConverter(bmc);
                BinaryMessagepostProcessor postProcessor = new BinaryMessagepostProcessor();
                sender.setDeliveryMode(2);
                int rt = 30000;
                try {
                    rt = Integer.valueOf(ctx.getParameter("receive.timeout"));
                } catch (Exception e) {
                }
                sender.setReceiveTimeout(rt);
                String direction = ctx.getParameter("direction");
                if (direction == null || "".equals(direction)) {
                    direction = "send";
                }
                if (direction.toLowerCase().equals("send")) {
                    Map<String, String> mp = getMessageProperties(ctx.getParameter("header.properties"));
                    postProcessor.setMessageProperties(mp);
                    sender.convertAndSend((Object) message, postProcessor);
                    result.setSuccessful(true);
                    result.setResponseMessage("Message sent.");
                } else {
                    if (direction.toLowerCase().equals("receive")) {
                        System.out.println("Receive");
                        String messageSelector = ctx.getParameter("message.selector");
                        System.out.println("Selector: " + messageSelector);
                        Object obj = null;
                        if (messageSelector != null && !"".equals(messageSelector)) {
                            obj = sender.receiveSelectedAndConvert(messageSelector);
                        } else {
                            obj = sender.receiveAndConvert();
                        }
                        if (obj != null) {
                            result.setSuccessful(true);
                            result.setResponseData(obj.toString().getBytes());
                            String paramName = ctx.getParameter("header.property.reference");
                            if (paramName != null && !"".equals(paramName))
                                JMeterUtils.setProperty(paramName, concatProperties(bmc.getMessageProperties()));
                        } else {
                            result.setSuccessful(false);
                            result.setResponseData("Conection timeout".getBytes());
                        }
                    } else {
                        result.setSuccessful(false);
                        result.setResponseMessage("Unknown direction.");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                result.setSuccessful(false);
                result.setResponseMessage("Exception");
                result.setResponseData(e.getMessage().getBytes());
            }
        }
    }
    return result;
}
Example 34
Project: spring-roo-custom-master  File: JmsOperationsImpl.java View source code
private void addDefaultDestination(final Document appCtx, final String name) {
    // If we do already have a default destination configured then do
    // nothing
    final Element root = appCtx.getDocumentElement();
    if (null != XmlUtils.findFirstElement("/beans/bean[@class = 'org.springframework.jms.core.JmsTemplate']/property[@name = 'defaultDestination']", root)) {
        return;
    }
    // Otherwise add it
    final Element jmsTemplate = XmlUtils.findRequiredElement("/beans/bean[@class = 'org.springframework.jms.core.JmsTemplate']", root);
    final Element defaultDestination = appCtx.createElement("property");
    defaultDestination.setAttribute("ref", name);
    defaultDestination.setAttribute("name", "defaultDestination");
    jmsTemplate.appendChild(defaultDestination);
}
Example 35
Project: marketcetera-master  File: ReceiverModule.java View source code
@Override
protected void preStart() throws ModuleException {
    //Check if the broker URL is supplied
    String url = getURL();
    if (url == null || url.trim().isEmpty()) {
        //If no URL specified do not perform remoting.
        Messages.NO_URL_SPECIFIED_LOG.info(this);
        return;
    }
    if (!mSkipJAASConfiguration) {
        //Setup the JAAS configuration
        JaasConfiguration.setup();
        mDoneJaasConfiguration = true;
    }
    //Create spring contexts to initialize the broker and messaging topic
    try {
        StaticApplicationContext parent = new StaticApplicationContext();
        //$NON-NLS-1$
        SpringUtils.addStringBean(parent, "brokerURI", url);
        //$NON-NLS-1$ 
        SpringUtils.addStringBean(//$NON-NLS-1$ 
        parent, //$NON-NLS-1$ 
        "userName", ClientLoginHelper.getUserName());
        //$NON-NLS-1$
        SpringUtils.addStringBean(//$NON-NLS-1$
        parent, //$NON-NLS-1$
        "password", ClientLoginHelper.getPassword());
        parent.refresh();
        mContext = new ClassPathXmlApplicationContext(new String[] { "remoting_server.xml" }, //$NON-NLS-1$
        parent);
        mContext.start();
        mSender = (JmsTemplate) //$NON-NLS-1$
        mContext.getBean(//$NON-NLS-1$
        "sender", JmsTemplate.class);
        Messages.RECIEVER_REMOTING_CONFIGURED.info(this, url);
    } catch (Exception e) {
        throw new ModuleException(e, Messages.ERROR_STARTING_MODULE);
    }
}
Example 36
Project: spring-integration-samples-master  File: JmsMockTests.java View source code
/**
	 * Provide a message via a mock JMS template and wait for the specified timeout to receive the message
	 * on the expected channel
	 * @param obj The message provided to the poller (currently must be a String)
	 * @param expectedOutputChannel The expected output channel
	 * @param handler An instance of CountDownHandler to handle (verify) the output message
	 * @param timeoutMillisec The timeout period. Note that this must allow at least enough time
	 * to process the entire flow. Only set if the default is
	 * not long enough
	 * @return true if the message was received on the expected channel
	 * @throws JMSException
	 * @throws InterruptedException
	 */
protected boolean verifyJmsMessageOnOutputChannel(Object obj, SubscribableChannel expectedOutputChannel, CountDownHandler handler, int timeoutMillisec) throws JMSException, InterruptedException {
    if (!(obj instanceof String)) {
        throw new IllegalArgumentException("Only TextMessage is currently supported");
    }
    /*
		 * Use mocks to create a message returned to the JMS inbound adapter. It is assumed that the JmsTemplate
		 * is also a mock.
		 */
    this.testMessageHolder.set((String) obj);
    CountDownLatch latch = new CountDownLatch(1);
    handler.setLatch(latch);
    expectedOutputChannel.subscribe(handler);
    this.jmsInboundChannelAdapter.start();
    boolean latchCountedToZero = latch.await(timeoutMillisec, TimeUnit.MILLISECONDS);
    if (!latchCountedToZero) {
        LOGGER.warn(String.format("The specified waiting time of the latch (%s ms) elapsed.", timeoutMillisec));
    }
    return latchCountedToZero;
}
Example 37
Project: spring-integration-sandbox-fork-master  File: Client.java View source code
/**
	 * @param args
	 */
@SuppressWarnings("unused")
public static void main(String[] args) {
    if (args.length < 2) {
        System.out.println("usage: Client queueName numServers, e.g. Client queue.ordered 3");
        System.exit(0);
    }
    if (StringUtils.isEmpty(args[0]) || StringUtils.isEmpty(args[1])) {
        System.out.println("usage: Client queueName numServers, e.g. Client queue.ordered 3");
        System.exit(0);
    }
    //'queue.ordered' or 'queue.unordered' (to bypass the Dispatcher)  - See jms config
    String queueName = args[0];
    //the number of servers used in the test
    int numServers = Integer.parseInt(args[1]);
    // Create test parameters to initialize servers
    Map<String, Object> testParameters = initTestParameters(queueName, numServers);
    ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/jms-infrastructure-config.xml", "META-INF/spring/client-config.xml");
    // Re-initialize each server using the server's control queue
    JmsTemplate jmsTemplate = context.getBean("jmsTemplate", JmsTemplate.class);
    while (true) {
        final KeyGenerator keyGen = new KeyGenerator(MAX_IDS, REPEAT_KEY_PERCENT, MAX_REPEATS);
        // Keep track of message count (sequence number) for each key to verify strict ordering
        sequenceMap = new HashMap<String, Integer>();
        for (int i = 1; i <= numServers; i++) {
            jmsTemplate.convertAndSend(QUEUE_SERVER_CONTROL + i, testParameters);
        }
        // Send messages
        logger.info("sending messages to " + queueName);
        for (int i = 0; i < MAX_MESSAGES; i++) {
            jmsTemplate.send(queueName, new MessageCreator() {

                @Override
                public Message createMessage(Session session) throws JMSException {
                    TextMessage textMessage = session.createTextMessage();
                    String payload = "order-" + keyGen.nextKey();
                    textMessage.setText(payload);
                    int sequence = getSequence(payload);
                    textMessage.setIntProperty("sequence", sequence);
                    logger.debug("sending message " + "[" + payload + "] sequence [" + sequence + "]");
                    return textMessage;
                }

                // Track the sequence number for each key
                private int getSequence(String payload) {
                    if (null == sequenceMap.get(payload)) {
                        sequenceMap.put(payload, 0);
                    }
                    int sequence = sequenceMap.get(payload);
                    sequenceMap.put(payload, ++sequence);
                    return sequence;
                }
            });
            if (SEND_DELAY_MS > 0) {
                try {
                    Thread.sleep(SEND_DELAY_MS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        logger.info(MAX_MESSAGES + " messages sent");
        System.out.println("quit to terminate, <ENTER> to run again");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        try {
            String answer = bufferedReader.readLine();
            if (answer.equalsIgnoreCase("quit")) {
                System.exit(0);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Example 38
Project: spring-integration-java-dsl-master  File: JmsTests.java View source code
@Test
public void testPubSubFlow() {
    JmsTemplate template = new JmsTemplate(this.jmsConnectionFactory);
    template.setPubSubDomain(true);
    template.setDefaultDestinationName("pubsub");
    template.convertAndSend("foo");
    Message<?> received = this.jmsPubSubBridgeChannel.receive(5000);
    assertNotNull(received);
    assertEquals("foo", received.getPayload());
}
Example 39
Project: jadira-master  File: BatchedJmsTemplate.java View source code
protected Message doSingleReceive(Session session, MessageConsumer consumer) throws JMSException {
    if (!session.getTransacted() || isSessionLocallyTransacted(session)) {
        // If we are not using JTA we should use standard JmsTemplate behaviour
        return super.doReceive(session, consumer);
    }
    // batch
    try {
        final Message message;
        if (Boolean.TRUE.equals(IS_START_OF_BATCH.get())) {
            // Register Synchronization
            TransactionSynchronizationManager.registerSynchronization(BATCH_SYNCHRONIZATION);
            // Use transaction timeout (if available).
            long timeout = determineTimeout();
            message = doReceive(consumer, timeout);
            IS_START_OF_BATCH.set(Boolean.FALSE);
        } else {
            message = doReceive(consumer, RECEIVE_TIMEOUT_NO_WAIT);
        }
        if (isClientAcknowledge(session)) {
            // Manually acknowledge message, if any.
            if (message != null) {
                message.acknowledge();
            }
        }
        return message;
    } finally {
        JmsUtils.closeMessageConsumer(consumer);
    }
}
Example 40
Project: toobs-master  File: AbstractJmsReceiver.java View source code
/**
   * @return Returns the jmsTemplate.
   */
public JmsTemplate getJmsTemplate() {
    return jmsTemplate;
}
Example 41
Project: corespring-master  File: JmsDiningBatchProcessor.java View source code
public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}
Example 42
Project: learning-spring-boot-code-1.2-master  File: Application.java View source code
@Bean
NetworkEventSimulator simulator(JmsTemplate jmsTemplate) {
    return new NetworkEventSimulator(jmsTemplate, MAILBOX);
}
Example 43
Project: learning-spring-boot-code-master  File: Application.java View source code
@Bean
NetworkEventSimulator simulator(JmsTemplate jmsTemplate) {
    return new NetworkEventSimulator(jmsTemplate, MAILBOX);
}
Example 44
Project: WInS_Demos-master  File: QueueSender.java View source code
public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}
Example 45
Project: ismp_manager-master  File: ObjectSender.java View source code
public JmsTemplate getJmsTemplate() {
    return jmsTemplate;
}
Example 46
Project: spring-boot-web-blank-master  File: SpringConfigActivemq.java View source code
@Bean(name = "jmsTemplate")
public JmsTemplate jmsTemplate() {
    JmsTemplate template = new JmsTemplate();
    template.setConnectionFactory(connectionFactory());
    return template;
}
Example 47
Project: activemq-in-action-master  File: JmsMessageSenderService.java View source code
public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}
Example 48
Project: deliciousfruit-master  File: NotifyMessageProducer.java View source code
public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}
Example 49
Project: java_learn-master  File: JmsMessageSenderService.java View source code
public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}
Example 50
Project: springlab-master  File: NotifyMessageProducer.java View source code
public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}
Example 51
Project: Tanaguru-master  File: TanaguruMsgOutServiceImpl.java View source code
public JmsTemplate getJmsTemplate() {
    return jmsTemplate;
}
Example 52
Project: yesnotify-master  File: JmsQueueNotificationProducer.java View source code
public JmsTemplate getJmsTemplate() {
    return jmsTemplate;
}
Example 53
Project: atlas-lb-master  File: AsyncServiceImpl.java View source code
public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}
Example 54
Project: spring-mvc-qq-weibo-master  File: AdvancedNotifyMessageProducer.java View source code
public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}
Example 55
Project: activemq-course-master  File: MessageTimerTask.java View source code
public void setTemplate(JmsTemplate template) {
    this.template = template;
}
Example 56
Project: Broadleaf-eCommerce-master  File: JMSArchivedPagePublisher.java View source code
public JmsTemplate getArchivePageTemplate() {
    return archivePageTemplate;
}
Example 57
Project: BroadleafCommerce-master  File: JMSArchivedPagePublisher.java View source code
public JmsTemplate getArchivePageTemplate() {
    return archivePageTemplate;
}
Example 58
Project: cmestemp22-master  File: QueueTaskHandler.java View source code
/**
     * The connection factory used to create the jms template.
     * 
     * @param connectionFactory
     *            the connection factory
     */
@Required
public void setConnectionFactory(final ConnectionFactory connectionFactory) {
    this.jmsTemplate = new JmsTemplate(connectionFactory);
}
Example 59
Project: commerce-master  File: JMSArchivedPagePublisher.java View source code
public JmsTemplate getArchivePageTemplate() {
    return archivePageTemplate;
}
Example 60
Project: elpaaso-core-master  File: UnexpectedErrorMessageListener.java View source code
public void setJmsErrorTemplate(JmsTemplate jmsErrorTemplate) {
    this.jmsErrorTemplate = jmsErrorTemplate;
}
Example 61
Project: esper-master  File: SpringJMSTemplateInputAdapter.java View source code
/**
     * Returns the jms template.
     *
     * @return Spring JMS template
     */
public JmsTemplate getJmsTemplate() {
    return jmsTemplate;
}
Example 62
Project: appverse-web-master  File: OtherSampleRepositoryImpl.java View source code
/* 
	 * This method must be overwritten to provide a publishing JmsTemplate
	 */
@Override
public JmsTemplate getTemplatePublisher() {
    return jmsTemplate;
}
Example 63
Project: carewebframework-core-master  File: JMSUtil.java View source code
/**
     * @return JmsTemplate
     */
public static JmsTemplate getJmsTopicTemplate() {
    return SpringUtil.getBean(JMS_TOPIC_TEMPLATE, JmsTemplate.class);
}
Example 64
Project: eGov-master  File: JMSConfiguration.java View source code
@Bean
public JmsTemplate jmsTemplate(CachingConnectionFactory cacheConnectionFactory) {
    return new JmsTemplate(cacheConnectionFactory);
}
Example 65
Project: lorsource-master  File: SearchQueueSender.java View source code
@Autowired
public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}
Example 66
Project: mtools-master  File: JmsSender.java View source code
public JmsTemplate getJmsTemplate() {
    return jmsTemplate;
}
Example 67
Project: opennms_dashboard-master  File: JmsNorthbounder.java View source code
@Override
public void onPreStart() throws NorthbounderException {
    m_template = new JmsTemplate(m_connectionFactory);
}
Example 68
Project: RSB-master  File: JmsMessageDispatcher.java View source code
// exposed for unit tests
void setJmsTemplate(final JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}
Example 69
Project: simba-os-master  File: EventService.java View source code
@PostConstruct
public void createJMSTemplate() {
    jmsTemplate = new JmsTemplate(connectionFactory);
}
Example 70
Project: axon-auction-example-master  File: AuctionMessageProducer.java View source code
/**
	 * Sets the JMS template to a new value.
	 * 
	 * @param jmsTemplate
	 *            Template to set.
	 */
protected final void setJmsTemplate(final JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}
Example 71
Project: spring-flex-master  File: JmsAdapter.java View source code
/**
     * Returns the {@link JmsTemplate} used by this adapter
     * 
     * @return the jms template
     */
public JmsTemplate getJmsTemplate() {
    return this.jmsTemplate;
}
Example 72
Project: Carolina-Digital-Repository-master  File: OperationsMessageSender.java View source code
public JmsTemplate getJmsTemplate() {
    return jmsTemplate;
}