org.springframework.jms.core.JmsTemplate

Here are the examples of the java api org.springframework.jms.core.JmsTemplate taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

349 Examples 7

19 Source : AccountService.java
with Apache License 2.0
from yuanmabiji

@Service
@Transactional
public clreplaced AccountService {

    private final JmsTemplate jmsTemplate;

    private final AccountRepository accountRepository;

    public AccountService(JmsTemplate jmsTemplate, AccountRepository accountRepository) {
        this.jmsTemplate = jmsTemplate;
        this.accountRepository = accountRepository;
    }

    public void createAccountAndNotify(String username) {
        this.jmsTemplate.convertAndSend("accounts", username);
        this.accountRepository.save(new Account(username));
        if ("error".equals(username)) {
            throw new RuntimeException("Simulated error");
        }
    }
}

19 Source : JmsAutoConfigurationTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void testJmsTemplateWithMessageConverter() {
    this.contextRunner.withUserConfiguration(MessageConvertersConfiguration.clreplaced).run((context) -> {
        JmsTemplate jmsTemplate = context.getBean(JmsTemplate.clreplaced);
        replacedertThat(jmsTemplate.getMessageConverter()).isSameAs(context.getBean("myMessageConverter"));
    });
}

19 Source : NotifyMessageProducer.java
with GNU Affero General Public License v3.0
from wkeyuan

public void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}

19 Source : InvokeMessageProducer.java
with GNU Affero General Public License v3.0
from wkeyuan

public void setTemplate(JmsTemplate template) {
    this.template = template;
}

19 Source : JMSPublisherConsumerTest.java
with Apache License 2.0
from wangrenlei

/**
 * At the moment the only two supported message types are TextMessage and
 * BytesMessage which is sufficient for the type if JMS use cases NiFi is
 * used. The may change to the point where all message types are supported
 * at which point this test will no be longer required.
 */
@Test(expected = IllegalStateException.clreplaced)
public void validateFailOnUnsupportedMessageType() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);
    jmsTemplate.send(destinationName, new MessageCreator() {

        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createObjectMessage();
        }
    });
    JMSConsumer consumer = new JMSConsumer(jmsTemplate, mock(ComponentLog.clreplaced));
    try {
        consumer.consume(destinationName, new ConsumerCallback() {

            @Override
            public void accept(JMSResponse response) {
            // noop
            }
        });
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}

19 Source : CommonTest.java
with Apache License 2.0
from wangrenlei

static JmsTemplate buildJmsTemplateForDestination(boolean pubSub) {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
    connectionFactory = new CachingConnectionFactory(connectionFactory);
    JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
    jmsTemplate.setPubSubDomain(pubSub);
    jmsTemplate.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);
    return jmsTemplate;
}

19 Source : JMSWorker.java
with Apache License 2.0
from wangrenlei

/**
 * Base clreplaced for implementing publishing and consuming JMS workers.
 *
 * @see JMSPublisher
 * @see JMSConsumer
 */
abstract clreplaced JMSWorker {

    protected final JmsTemplate jmsTemplate;

    protected final ComponentLog processLog;

    /**
     * Creates an instance of this worker initializing it with JMS
     * {@link Connection} and creating a target {@link Channel} used by
     * sub-clreplacedes to interact with JMS systems
     *
     * @param jmsTemplate the instance of {@link JmsTemplate}
     * @param processLog the instance of {@link ComponentLog}
     */
    public JMSWorker(JmsTemplate jmsTemplate, ComponentLog processLog) {
        this.jmsTemplate = jmsTemplate;
        this.processLog = processLog;
    }

    /**
     */
    @Override
    public String toString() {
        return this.getClreplaced().getSimpleName() + "[destination:" + this.jmsTemplate.getDefaultDestinationName() + "; pub-sub:" + this.jmsTemplate.isPubSubDomain() + ";]";
    }
}

19 Source : JmsGatewaySupport.java
with MIT License
from Vip-Augus

/**
 * Convenient super clreplaced for application clreplacedes that need JMS access.
 *
 * <p>Requires a ConnectionFactory or a JmsTemplate instance to be set.
 * It will create its own JmsTemplate if a ConnectionFactory is preplaceded in.
 * A custom JmsTemplate instance can be created for a given ConnectionFactory
 * through overriding the {@link #createJmsTemplate} method.
 *
 * @author Mark Pollack
 * @since 1.1.1
 * @see #setConnectionFactory
 * @see #setJmsTemplate
 * @see #createJmsTemplate
 * @see org.springframework.jms.core.JmsTemplate
 */
public abstract clreplaced JmsGatewaySupport implements InitializingBean {

    /**
     * Logger available to subclreplacedes.
     */
    protected final Log logger = LogFactory.getLog(getClreplaced());

    @Nullable
    private JmsTemplate jmsTemplate;

    /**
     * Set the JMS connection factory to be used by the gateway.
     * Will automatically create a JmsTemplate for the given ConnectionFactory.
     * @see #createJmsTemplate
     * @see #setConnectionFactory(javax.jms.ConnectionFactory)
     */
    public final void setConnectionFactory(ConnectionFactory connectionFactory) {
        this.jmsTemplate = createJmsTemplate(connectionFactory);
    }

    /**
     * Create a JmsTemplate for the given ConnectionFactory.
     * Only invoked if populating the gateway with a ConnectionFactory reference.
     * <p>Can be overridden in subclreplacedes to provide a JmsTemplate instance with
     * a different configuration.
     * @param connectionFactory the JMS ConnectionFactory to create a JmsTemplate for
     * @return the new JmsTemplate instance
     * @see #setConnectionFactory
     */
    protected JmsTemplate createJmsTemplate(ConnectionFactory connectionFactory) {
        return new JmsTemplate(connectionFactory);
    }

    /**
     * Return the JMS ConnectionFactory used by the gateway.
     */
    @Nullable
    public final ConnectionFactory getConnectionFactory() {
        return (this.jmsTemplate != null ? this.jmsTemplate.getConnectionFactory() : null);
    }

    /**
     * Set the JmsTemplate for the gateway.
     * @see #setConnectionFactory(javax.jms.ConnectionFactory)
     */
    public final void setJmsTemplate(@Nullable JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    /**
     * Return the JmsTemplate for the gateway.
     */
    @Nullable
    public final JmsTemplate getJmsTemplate() {
        return this.jmsTemplate;
    }

    @Override
    public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException {
        if (this.jmsTemplate == null) {
            throw new IllegalArgumentException("'connectionFactory' or 'jmsTemplate' is required");
        }
        try {
            initGateway();
        } catch (Exception ex) {
            throw new BeanInitializationException("Initialization of JMS gateway failed: " + ex.getMessage(), ex);
        }
    }

    /**
     * Subclreplacedes can override this for custom initialization behavior.
     * Gets called after population of this instance's bean properties.
     * @throws java.lang.Exception if initialization fails
     */
    protected void initGateway() throws Exception {
    }
}

19 Source : JmsGatewaySupport.java
with MIT License
from Vip-Augus

/**
 * Set the JmsTemplate for the gateway.
 * @see #setConnectionFactory(javax.jms.ConnectionFactory)
 */
public final void setJmsTemplate(@Nullable JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}

19 Source : ActivemqSendServiceImpl.java
with Apache License 2.0
from sunshinelyz

/**
 * @author binghe
 * @version 1.0.0
 * @description ActivemqSendServiceImpl
 */
public clreplaced ActivemqSendServiceImpl implements MykitMqSendService {

    private JmsTemplate jmsTemplate;

    public void setJmsTemplate(final JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    @Override
    public void sendMessage(final String destination, final Integer pattern, final byte[] message) {
        Destination queue = new ActiveMQQueue(destination);
        if (Objects.equals(MessageTypeEnum.P2P.getCode(), pattern)) {
            queue = new ActiveMQQueue(destination);
        } else if (Objects.equals(MessageTypeEnum.TOPIC.getCode(), pattern)) {
            queue = new ActiveMQTopic(destination);
        }
        jmsTemplate.convertAndSend(queue, message);
    }
}

19 Source : ActivemqSendServiceImpl.java
with Apache License 2.0
from sunshinelyz

public void setJmsTemplate(final JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}

19 Source : TopicSender.java
with Apache License 2.0
from sunshinelyz

/**
 * @author liuyazhuang
 * @version 1.0.0
 * @date 2019/6/12
 * @description Topic生产者发送消息到Topic
 */
public clreplaced TopicSender implements ActiveMQSender {

    private JmsTemplate jmsTemplate;

    public TopicSender(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    /**
     * 发送一条消息到指定的队列(目标)
     * @param topicName 队列名称
     * @param message 消息内容
     */
    @Override
    public void send(String topicName, final String message) {
        jmsTemplate.send(topicName, new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(message);
            }
        });
    }

    /**
     * 发送一条消息到指定的队列(目标)
     * @param topicName 队列名称
     * @param message 消息内容
     * @param scheduledDelayTime 间隔时间
     */
    @Override
    public void send(String topicName, final String message, final long scheduledDelayTime) {
        jmsTemplate.send(topicName, new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                TextMessage msg = session.createTextMessage(message);
                msg.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, scheduledDelayTime);
                return msg;
            }
        });
    }
}

19 Source : QueueSender.java
with Apache License 2.0
from sunshinelyz

/**
 * @author liuyazhuang
 * @version 1.0.0
 * @date 2019/6/12
 * @description 队列消息生产者,发送消息到队列
 */
public clreplaced QueueSender implements ActiveMQSender {

    private JmsTemplate jmsTemplate;

    public QueueSender(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    /**
     * 发送一条消息到指定的队列(目标)
     * @param queueName 队列名称
     * @param message 消息内容
     */
    @Override
    public void send(String queueName, final String message) {
        jmsTemplate.send(queueName, new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(message);
            }
        });
    }

    /**
     * 发送一条消息到指定的队列(目标)
     * @param queueName 队列名称
     * @param message 消息内容
     * @param scheduledDelayTime 间隔时间
     */
    @Override
    public void send(String queueName, final String message, final long scheduledDelayTime) {
        jmsTemplate.send(queueName, new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                TextMessage msg = session.createTextMessage(message);
                msg.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, scheduledDelayTime);
                return msg;
            }
        });
    }
}

19 Source : QueueSender.java
with Apache License 2.0
from sunshinelyz

/**
 * @author liuyazhuang
 * @description  队列消息生产者,发送消息到队列
 */
@Component("queueSender")
public clreplaced QueueSender {

    @Autowired
    @Qualifier("jmsQueueTemplate")
    private JmsTemplate // 通过@Qualifier修饰符来注入对应的bean
    jmsTemplate;

    /**
     * 发送一条消息到指定的队列(目标)
     * @param queueName 队列名称
     * @param message 消息内容
     */
    public void send(String queueName, final String message) {
        jmsTemplate.send(queueName, new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(message);
            }
        });
    }

    /**
     * 发送一条消息到指定的队列(目标)
     * @param queueName 队列名称
     * @param message 消息内容
     * @param scheduledDelayTime 间隔时间
     */
    public void send(String queueName, final String message, final long scheduledDelayTime) {
        jmsTemplate.send(queueName, new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                TextMessage msg = session.createTextMessage(message);
                msg.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, scheduledDelayTime);
                return msg;
            }
        });
    }
}

19 Source : ApplicationTests.java
with Apache License 2.0
from spring-cloud-samples

@Bean
MessageVerifier<Message> standaloneMessageVerifier(JmsTemplate jmsTemplate) {
    return new MessageVerifier<>() {

        @Override
        public Message receive(String destination, long timeout, TimeUnit timeUnit, @Nullable YamlContract contract) {
            return null;
        }

        @Override
        public Message receive(String destination, YamlContract contract) {
            return null;
        }

        @Override
        public void send(Message message, String destination, @Nullable YamlContract contract) {
        }

        @Override
        public <T> void send(T payload, Map<String, Object> headers, String destination, @Nullable YamlContract contract) {
            jmsTemplate.send(destination, session -> {
                Message message = session.createTextMessage(payload.toString());
                headers.forEach((s, o) -> {
                    try {
                        message.setStringProperty(s, o.toString());
                    } catch (JMSException e) {
                        throw new IllegalStateException(e);
                    }
                });
                return message;
            });
        }
    };
}

19 Source : MessageProducer.java
with Apache License 2.0
from SolaceLabs

public clreplaced MessageProducer {

    private JmsTemplate jmsTemplate;

    public void sendMessages(String messagetext) throws JMSException {
        getJmsTemplate().send(new MessageCreator() {

            public Message createMessage(Session session) throws JMSException {
                Message message = session.createTextMessage(messagetext);
                return message;
            }
        });
    }

    public JmsTemplate getJmsTemplate() {
        return jmsTemplate;
    }

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    public static void main(String[] args) throws JMSException {
        ClreplacedPathXmlApplicationContext context = new ClreplacedPathXmlApplicationContext(new String[] { "SolResources.xml" });
        MessageProducer producer = (MessageProducer) context.getBean("messageProducer");
        for (int i = 0; i < 10; i++) {
            String messagetext = "Test#" + i;
            System.out.println("Sending message " + messagetext);
            producer.sendMessages(messagetext);
        }
    // context.close();	// Not closing here because waiting for MessageConsumer to receive all the messages
    }
}

19 Source : JMSPublisherConsumerTest.java
with Apache License 2.0
from SolaceLabs

public void validateFailOnUnsupportedMessageTypeOverJNDI() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsJndiTemplateForDestination(false);
    jmsTemplate.send(destinationName, new MessageCreator() {

        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createObjectMessage();
        }
    });
    JMSConsumer consumer = new JMSConsumer(jmsTemplate, mock(ComponentLog.clreplaced));
    try {
        consumer.consume(destinationName, new ConsumerCallback() {

            @Override
            public void accept(JMSResponse response) {
            // noop
            }
        });
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}

19 Source : CommonTest.java
with Apache License 2.0
from SolaceLabs

static JmsTemplate buildJmsJndiTemplateForDestination(boolean pubSub) throws Exception {
    ConnectionFactory connectionFactory = buildJmsJndiConnectionFactory();
    connectionFactory = new CachingConnectionFactory(connectionFactory);
    JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
    jmsTemplate.setPubSubDomain(pubSub);
    jmsTemplate.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);
    return jmsTemplate;
}

19 Source : JmsUtil.java
with MIT License
from shuzheng

/**
 * 发送对象消息
 * @param jmsTemplate
 * @param destination
 * @param objectMessage
 */
public static void sendMessage(JmsTemplate jmsTemplate, Destination destination, final Serializable objectMessage) {
    jmsTemplate.send(destination, new MessageCreator() {

        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createObjectMessage(objectMessage);
        }
    });
}

19 Source : JmsUtil.java
with MIT License
from shuzheng

/**
 * 发送文本消息
 * @param jmsTemplate
 * @param destination
 * @param textMessage
 */
public static void sendMessage(JmsTemplate jmsTemplate, Destination destination, final String textMessage) {
    jmsTemplate.send(destination, new MessageCreator() {

        @Override
        public Message createMessage(Session session) throws JMSException {
            return session.createTextMessage(textMessage);
        }
    });
}

19 Source : JmsUtil.java
with MIT License
from shuzheng

/**
 * 延迟发送对象消息
 * @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() {

        @Override
        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;
        }
    });
}

19 Source : MyMessageService.java
with Apache License 2.0
from saturnism

@Service
public clreplaced MyMessageService {

    private final JmsTemplate jmsTemplate;

    public MyMessageService(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    public void sendMyMessage(final String payload) throws JMSException {
        jmsTemplate.send("TEST", session -> {
            return session.createTextMessage(payload);
        });
    }
}

19 Source : OsgpCoreResponseMessageSender.java
with Apache License 2.0
from OSGP

// This clreplaced should send response messages to OSGP Core.
@Component(value = "domainSmartMeteringOutboundOsgpCoreResponsesMessageSender")
public clreplaced OsgpCoreResponseMessageSender {

    @Autowired
    @Qualifier("domainSmartMeteringOutboundOsgpCoreResponsesJmsTemplate")
    private JmsTemplate jmsTemplate;

    public void send(final ResponseMessage responseMessage, final String messageType) {
        this.jmsTemplate.send(new MessageCreator() {

            @Override
            public Message createMessage(final Session session) throws JMSException {
                final ObjectMessage objectMessage = session.createObjectMessage();
                objectMessage.setJMSType(messageType);
                objectMessage.setStringProperty(Constants.ORGANISATION_IDENTIFICATION, responseMessage.getOrganisationIdentification());
                objectMessage.setStringProperty(Constants.DEVICE_IDENTIFICATION, responseMessage.getDeviceIdentification());
                objectMessage.setObject(responseMessage);
                return objectMessage;
            }
        });
    }
}

19 Source : WebServiceResponseMessageSender.java
with Apache License 2.0
from OSGP

// Send response message to the responses queue of web service adapter.
@Component(value = "domainCoreOutboundWebServiceResponsesMessageSender")
public clreplaced WebServiceResponseMessageSender implements ResponseMessageSender {

    @Autowired
    @Qualifier("domainCoreOutboundWebServiceResponsesJmsTemplate")
    private JmsTemplate jmsTemplate;

    @Override
    public void send(final ResponseMessage responseMessage) {
        this.jmsTemplate.send(new MessageCreator() {

            @Override
            public Message createMessage(final Session session) throws JMSException {
                final ObjectMessage objectMessage = session.createObjectMessage(responseMessage);
                objectMessage.setJMSPriority(responseMessage.getMessagePriority());
                objectMessage.setJMSCorrelationID(responseMessage.getCorrelationUid());
                objectMessage.setStringProperty(Constants.ORGANISATION_IDENTIFICATION, responseMessage.getOrganisationIdentification());
                objectMessage.setStringProperty(Constants.DEVICE_IDENTIFICATION, responseMessage.getDeviceIdentification());
                objectMessage.setStringProperty(Constants.RESULT, responseMessage.getResult().toString());
                if (responseMessage.getOsgpException() != null) {
                    objectMessage.setStringProperty(Constants.DESCRIPTION, responseMessage.getOsgpException().getMessage());
                }
                return objectMessage;
            }
        });
    }
}

19 Source : WebServiceResponseMessageSender.java
with Apache License 2.0
from OSGP

// Send response message to the web service adapter.
@Component(value = "domainAdminOutboundWebServiceResponsesMessageSender")
public clreplaced WebServiceResponseMessageSender implements ResponseMessageSender {

    @Autowired
    @Qualifier("domainAdminOutboundWebServiceResponsesJmsTemplate")
    private JmsTemplate jmsTemplate;

    @Override
    public void send(final ResponseMessage responseMessage) {
        this.jmsTemplate.send(new MessageCreator() {

            @Override
            public Message createMessage(final Session session) throws JMSException {
                final ObjectMessage objectMessage = session.createObjectMessage(responseMessage);
                objectMessage.setJMSCorrelationID(responseMessage.getCorrelationUid());
                objectMessage.setStringProperty(Constants.ORGANISATION_IDENTIFICATION, responseMessage.getOrganisationIdentification());
                objectMessage.setStringProperty(Constants.DEVICE_IDENTIFICATION, responseMessage.getDeviceIdentification());
                objectMessage.setStringProperty(Constants.RESULT, responseMessage.getResult().toString());
                if (responseMessage.getOsgpException() != null) {
                    objectMessage.setStringProperty(Constants.DESCRIPTION, responseMessage.getOsgpException().getMessage());
                }
                return objectMessage;
            }
        });
    }
}

19 Source : JmsArtemisStarterTest.java
with Apache License 2.0
from opentracing-contrib

/**
 * @author Pavol Loffay
 */
@SpringBootTest(webEnvironment = WebEnvironment.NONE, clreplacedes = { MockTracingConfiguration.clreplaced, JmsArtemisStarterTest.JmsTestConfiguration.clreplaced })
@RunWith(SpringJUnit4ClreplacedRunner.clreplaced)
public clreplaced JmsArtemisStarterTest {

    private static final String QUEUE_NAME = "testQueue";

    @Configuration
    @EnableJms
    static clreplaced JmsTestConfiguration {

        @Bean
        public MsgListener msgListener() {
            return new MsgListener();
        }

        @Bean
        public JmsListenerContainerFactory<?> myFactory(ConnectionFactory connectionFactory, DefaultJmsListenerContainerFactoryConfigurer configurer) {
            DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
            // This provides all boot's default to this factory, including the message converter
            configurer.configure(factory, connectionFactory);
            // You could still override some of Boot's default if necessary.
            return factory;
        }

        public static clreplaced MsgListener {

            private Message message;

            public Message getMessage() {
                return message;
            }

            @JmsListener(destination = QUEUE_NAME, containerFactory = "myFactory")
            public void processMessage(Message msg) throws Exception {
                message = msg;
            }
        }
    }

    @Autowired
    private MockTracer tracer;

    @Autowired
    private JmsTestConfiguration.MsgListener msgListener;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Before
    public void before() {
        tracer.reset();
    }

    @Test
    public void testListenerSpans() throws JMSException {
        jmsTemplate.convertAndSend(QUEUE_NAME, "huhu");
        await().until(() -> {
            List<MockSpan> mockSpans = tracer.finishedSpans();
            return (mockSpans.size() == 2);
        });
        Message message = msgListener.getMessage();
        replacedertEquals("huhu", ((TextMessage) msgListener.getMessage()).getText());
        List<MockSpan> spans = tracer.finishedSpans();
        // HTTP server span, jms send, jms receive
        replacedertEquals(2, spans.size());
        TestUtils.replacedertSameTraceId(spans);
    }
}

19 Source : SensorPublisher.java
with Apache License 2.0
from oneops

/**
 * Close connection.
 */
public void closeConnection() {
    for (JmsTemplate jt : producers) {
        ((PooledConnectionFactory) jt.getConnectionFactory()).stop();
    }
    producers = null;
}

19 Source : SensorPublisher.java
with Apache License 2.0
from oneops

void setProducers(JmsTemplate[] producers) {
    this.producers = producers;
}

19 Source : QueueSender.java
with MIT License
from MRdoulestar

/**
 * @author liang
 * @description  队列消息生产者,发送消息到队列
 */
@Component("queueSender")
public clreplaced QueueSender {

    @Autowired
    @Qualifier("jmsQueueTemplate")
    private JmsTemplate // 通过@Qualifier修饰符来注入对应的bean
    jmsTemplate;

    /**
     * 发送一条消息到指定的队列(目标)
     * @param queueName 队列名称
     * @param message 消息内容
     */
    public void send(String queueName, final String message) {
        jmsTemplate.send(queueName, new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(message);
            }
        });
    }
}

19 Source : JmsGatewaySupport.java
with Apache License 2.0
from langtianya

/**
 * Convenient super clreplaced for application clreplacedes that need JMS access.
 *
 * <p>Requires a ConnectionFactory or a JmsTemplate instance to be set.
 * It will create its own JmsTemplate if a ConnectionFactory is preplaceded in.
 * A custom JmsTemplate instance can be created for a given ConnectionFactory
 * through overriding the {@link #createJmsTemplate} method.
 *
 * @author Mark Pollack
 * @since 1.1.1
 * @see #setConnectionFactory
 * @see #setJmsTemplate
 * @see #createJmsTemplate
 * @see org.springframework.jms.core.JmsTemplate
 */
public abstract clreplaced JmsGatewaySupport implements InitializingBean {

    /**
     * Logger available to subclreplacedes
     */
    protected final Log logger = LogFactory.getLog(getClreplaced());

    private JmsTemplate jmsTemplate;

    /**
     * Set the JMS connection factory to be used by the gateway.
     * Will automatically create a JmsTemplate for the given ConnectionFactory.
     * @see #createJmsTemplate
     * @see #setConnectionFactory(javax.jms.ConnectionFactory)
     */
    public final void setConnectionFactory(ConnectionFactory connectionFactory) {
        this.jmsTemplate = createJmsTemplate(connectionFactory);
    }

    /**
     * Create a JmsTemplate for the given ConnectionFactory.
     * Only invoked if populating the gateway with a ConnectionFactory reference.
     * <p>Can be overridden in subclreplacedes to provide a JmsTemplate instance with
     * a different configuration.
     * @param connectionFactory the JMS ConnectionFactory to create a JmsTemplate for
     * @return the new JmsTemplate instance
     * @see #setConnectionFactory
     */
    protected JmsTemplate createJmsTemplate(ConnectionFactory connectionFactory) {
        return new JmsTemplate(connectionFactory);
    }

    /**
     * Return the JMS ConnectionFactory used by the gateway.
     */
    public final ConnectionFactory getConnectionFactory() {
        return (this.jmsTemplate != null ? this.jmsTemplate.getConnectionFactory() : null);
    }

    /**
     * Set the JmsTemplate for the gateway.
     * @see #setConnectionFactory(javax.jms.ConnectionFactory)
     */
    public final void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    /**
     * Return the JmsTemplate for the gateway.
     */
    public final JmsTemplate getJmsTemplate() {
        return this.jmsTemplate;
    }

    @Override
    public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException {
        if (this.jmsTemplate == null) {
            throw new IllegalArgumentException("'connectionFactory' or 'jmsTemplate' is required");
        }
        try {
            initGateway();
        } catch (Exception ex) {
            throw new BeanInitializationException("Initialization of JMS gateway failed: " + ex.getMessage(), ex);
        }
    }

    /**
     * Subclreplacedes can override this for custom initialization behavior.
     * Gets called after population of this instance's bean properties.
     * @throws java.lang.Exception if initialization fails
     */
    protected void initGateway() throws Exception {
    }
}

19 Source : JmsGatewaySupport.java
with Apache License 2.0
from langtianya

/**
 * Set the JmsTemplate for the gateway.
 * @see #setConnectionFactory(javax.jms.ConnectionFactory)
 */
public final void setJmsTemplate(JmsTemplate jmsTemplate) {
    this.jmsTemplate = jmsTemplate;
}

19 Source : TalosActiveMqJmsTemplate.java
with Apache License 2.0
from kplxq

public void setWrappedJmsTemplate(JmsTemplate wrappedJmsTemplate) {
    this.wrappedJmsTemplate = wrappedJmsTemplate;
}

19 Source : QueueJmsTemplateContainer.java
with Apache License 2.0
from jiangmin168168

public static void setQueJmsTemplateMap(String queueName, JmsTemplate jmsTemplate) {
    setQueJmsTemplateMap(queueName, jmsTemplate, false);
}

19 Source : JmsUtil.java
with MIT License
from javay

/**
 * 发送对象消息
 * @param jmsTemplate
 * @param destination
 * @param objectMessage
 */
public static void sendMessage(JmsTemplate jmsTemplate, Destination destination, final Serializable objectMessage) {
    jmsTemplate.send(destination, new MessageCreator() {

        public Message createMessage(Session session) throws JMSException {
            return session.createObjectMessage(objectMessage);
        }
    });
}

19 Source : JmsUtil.java
with MIT License
from javay

/**
 * 延迟发送对象消息
 * @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;
        }
    });
}

19 Source : JmsUtil.java
with MIT License
from javay

/**
 * 发送文本消息
 * @param jmsTemplate
 * @param destination
 * @param textMessage
 */
public static void sendMessage(JmsTemplate jmsTemplate, Destination destination, final String textMessage) {
    jmsTemplate.send(destination, new MessageCreator() {

        public Message createMessage(Session session) throws JMSException {
            return session.createTextMessage(textMessage);
        }
    });
}

19 Source : SpringMessageSender.java
with Apache License 2.0
from Illusionist80

/**
 * Sets the jms template.
 *
 * @param template the jms template
 */
public void setJmsTemplate(JmsTemplate tmpl) {
    this.jmsTemplate_i = tmpl;
}

19 Source : JmsTemplateTest.java
with Apache License 2.0
from Illusionist80

public static void main(String[] args) throws Exception {
    ApplicationContext ctx = new ClreplacedPathXmlApplicationContext("com/springtraining/jms/JmsTemplateTest-context.xml");
    JmsTemplate template = (JmsTemplate) ctx.getBean("jmsTemplate");
    // for(int i=0; i<10; i++) {
    template.send("SpringSendTestQueue", new MessageCreator() {

        public Message createMessage(Session session) throws JMSException {
            TextMessage tm = session.createTextMessage();
            tm.setText("This is a spring test message");
            return tm;
        }
    });
    System.out.println("Message sent");
    // }
    System.exit(1);
}

19 Source : BasicJMSChat.java
with Apache License 2.0
from Illusionist80

/**
 * Clreplaced handles incoming messages
 *
 * @see PointOfIssueMessageEvent
 */
public clreplaced BasicJMSChat implements MessageListener {

    private JmsTemplate chatJMSTemplate;

    private Topic chatTopic;

    private static String userId;

    /**
     * @param args
     * @throws JMSException
     * @throws IOException
     */
    public static void main(String[] args) throws JMSException, IOException {
        if (args.length != 1) {
            System.out.println("User Name is required....");
        } else {
            userId = args[0];
            ApplicationContext ctx = new ClreplacedPathXmlApplicationContext("com/springtraining/jms/spring-config.xml");
            BasicJMSChat basicJMSChat = (BasicJMSChat) ctx.getBean("basicJMSChat");
            TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) basicJMSChat.chatJMSTemplate.getConnectionFactory();
            TopicConnection tc = topicConnectionFactory.createTopicConnection();
            basicJMSChat.publish(tc, basicJMSChat.chatTopic, userId);
            basicJMSChat.subscribe(tc, basicJMSChat.chatTopic, basicJMSChat);
        }
    }

    /**
     * @param topicConnection
     * @param chatTopic
     * @param commandLineChat
     * @throws JMSException
     */
    void subscribe(TopicConnection topicConnection, Topic chatTopic, BasicJMSChat commandLineChat) throws JMSException {
        TopicSession tsession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        TopicSubscriber ts = tsession.createSubscriber(chatTopic);
        ts.setMessageListener(commandLineChat);
    }

    /**
     * @param topicConnection
     * @param chatTopic
     * @param userId
     * @throws JMSException
     * @throws IOException
     */
    void publish(TopicConnection topicConnection, Topic chatTopic, String userId) throws JMSException, IOException {
        TopicSession tsession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        TopicPublisher topicPublisher = tsession.createPublisher(chatTopic);
        topicConnection.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String msgToSend = reader.readLine();
            if (msgToSend.equalsIgnoreCase("exit")) {
                topicConnection.close();
                System.exit(0);
            } else {
                TextMessage msg = (TextMessage) tsession.createTextMessage();
                msg.setText("\n[" + userId + " : " + msgToSend + "]");
                topicPublisher.publish(msg);
            }
        }
    }

    /* (non-Javadoc)
	 * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
	 */
    public void onMessage(Message message) {
        /* The message must be of type TextMessage */
        if (message instanceof TextMessage) {
            try {
                String msgText = ((TextMessage) message).getText();
                // Avoid echo
                if (!msgText.startsWith("[" + userId))
                    System.out.println(msgText);
            } catch (JMSException jmsEx_p) {
                String errMsg = "An error occurred extracting message";
                jmsEx_p.printStackTrace();
            }
        } else {
            String errMsg = "Message is not of expected type TextMessage";
            System.err.println(errMsg);
            throw new RuntimeException(errMsg);
        }
    }

    public JmsTemplate getChatJMSTemplate() {
        return chatJMSTemplate;
    }

    public void setChatJMSTemplate(JmsTemplate chatJMSTemplate) {
        this.chatJMSTemplate = chatJMSTemplate;
    }

    public Topic getChatTopic() {
        return chatTopic;
    }

    public void setChatTopic(Topic chatTopic) {
        this.chatTopic = chatTopic;
    }
}

19 Source : BasicJMSChat.java
with Apache License 2.0
from Illusionist80

public void setChatJMSTemplate(JmsTemplate chatJMSTemplate) {
    this.chatJMSTemplate = chatJMSTemplate;
}

19 Source : AccountService.java
with Apache License 2.0
from hello-shf

@Service
@Transactional
public clreplaced AccountService {

    private final JmsTemplate jmsTemplate;

    private final AccountRepository accountRepository;

    public AccountService(JmsTemplate jmsTemplate, AccountRepository accountRepository) {
        this.jmsTemplate = jmsTemplate;
        this.accountRepository = accountRepository;
    }

    public void createAccountAndNotify(String username) {
        this.jmsTemplate.convertAndSend("accounts", username);
        this.accountRepository.save(new Account(username));
        if ("error".equals(username)) {
            throw new SampleRuntimeException("Simulated error");
        }
    }
}

19 Source : JmsOrderMessagingService.java
with Apache License 2.0
from habuma

@Service
public clreplaced JmsOrderMessagingService implements OrderMessagingService {

    private JmsTemplate jms;

    @Autowired
    public JmsOrderMessagingService(JmsTemplate jms) {
        this.jms = jms;
    }

    @Override
    public void sendOrder(Order order) {
        jms.convertAndSend("tacocloud.order.queue", order, this::addOrderSource);
    }

    private Message addOrderSource(Message message) throws JMSException {
        message.setStringProperty("X_ORDER_SOURCE", "WEB");
        return message;
    }
}

19 Source : MQProducerServiceImpl.java
with GNU General Public License v3.0
from gxing19

/**
 * @name: MQSendServiceImpl
 * @desc: TODO
 * @author: gxing
 * @date: 2018-10-18 14:07
 */
@Service
public clreplaced MQProducerServiceImpl implements MQProducerService {

    @Autowired
    private JmsTemplate jmsTemplate;

    /**
     * 发送queue消息
     *
     * @param msg
     * @throws JMSException
     */
    @Override
    public void activeMQSend(String msg) throws JMSException {
        MessageCreator messageCreator = session -> session.createTextMessage(msg);
        // 发布queue
        Destination queueDestination = new ActiveMQQueue("my-queue");
        jmsTemplate.send(queueDestination, messageCreator);
        jmsTemplate.convertAndSend(queueDestination, "Hello Queue");
        // 发布topic
        Destination topicDestination = new ActiveMQTopic("my-topic");
        jmsTemplate.send(topicDestination, messageCreator);
        jmsTemplate.convertAndSend(queueDestination, "Hello Topic");
    }
}

19 Source : SampleService.java
with MIT License
from gexiangdong

@Service
public clreplaced SampleService {

    private Log log = LogFactory.getLog(SampleService.clreplaced);

    /**
     * 装载JmsTemplate构件,可以通过这个构件给JMS(ActiveMQ)发送消息
     */
    @Autowired
    JmsTemplate jmsTemplate;

    /**
     * 发送消息可以是String, Map, Integer... Object(实现Serializable)需要在系统变量里声明安全
     * 不建议使用Object类型,因为不利于解耦
     */
    @Scheduled(fixedRate = 10000)
    public void sendMessage() {
        String message = "Hello, from sendMEssage() at " + new Date();
        if (log.isTraceEnabled()) {
            log.trace("@Scheduled sendMessage <" + message + ">");
        }
        jmsTemplate.convertAndSend("addtvseriesevents", message);
    }

    public void sendMessage(String message) {
        if (log.isTraceEnabled()) {
            log.trace("sendMessage <" + message + ">");
        }
        // 使用jsmTEmplate往addtvseriesevents队列里发送消息
        jmsTemplate.convertAndSend("addtvseriesevents", message);
    }

    /**
     * JmsListener注解可以声明这个方法用于接收JMS(ActiveMQ)消息队列里的消息
     * @param message
     */
    @JmsListener(destination = "addtvseriesevents")
    public void receiveMessage(String message) {
        if (log.isTraceEnabled()) {
            log.trace("Received <" + message + ">");
        }
    }
}

19 Source : MessageBasedJobManager.java
with Apache License 2.0
from flowable

/**
 * @author Joram Barrez
 */
public clreplaced MessageBasedJobManager extends AbstractMessageBasedJobManager {

    protected JmsTemplate jmsTemplate;

    protected JmsTemplate historyJmsTemplate;

    @Override
    protected void sendMessage(final JobInfo job) {
        JmsTemplate actualJmsTemplate = (job instanceof HistoryJob) ? historyJmsTemplate : jmsTemplate;
        actualJmsTemplate.send(new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(job.getId());
            }
        });
    }

    public JmsTemplate getJmsTemplate() {
        return jmsTemplate;
    }

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    public JmsTemplate getHistoryJmsTemplate() {
        return historyJmsTemplate;
    }

    public void setHistoryJmsTemplate(JmsTemplate historyJmsTemplate) {
        this.historyJmsTemplate = historyJmsTemplate;
    }
}

19 Source : MessageBasedJobManager.java
with Apache License 2.0
from flowable

public void setHistoryJmsTemplate(JmsTemplate historyJmsTemplate) {
    this.historyJmsTemplate = historyJmsTemplate;
}

19 Source : ActiveMQEventPublisherImpl.java
with Apache License 2.0
from edgexfoundry

/**
 * Note - this message publisher is not used by default configuration. To use this publisher, you
 * need to change the spring-config.xml file to use this publisher versus the ZeroMQ publisher.
 */
public clreplaced ActiveMQEventPublisherImpl implements EventPublisher {

    private static final org.edgexfoundry.support.logging.client.EdgeXLogger logger = org.edgexfoundry.support.logging.client.EdgeXLoggerFactory.getEdgeXLogger(ActiveMQEventPublisherImpl.clreplaced);

    private JmsTemplate template;

    /**
     * Send a message containing the serialized Event (and Readings) into an Active MQ queue to allow
     * a rules engine or other service to act on new sensor/device readings.
     *
     * @param event - the Event object (with embedded Readings) to be placed in the queue.
     */
    public void sendEventMessage(final Event event) {
        template.send(new MessageCreator() {

            public Message createMessage(Session session) throws JMSException {
                ObjectMessage message = session.createObjectMessage(event);
                logger.info("Sent event/readings with id:  " + event.getId());
                return message;
            }
        });
    }

    /**
     * Get the Spring JMS Template object used to communicate with the ActiveMQ queue broker
     *
     * @return - the Spring JMS Template
     */
    public JmsTemplate getTemplate() {
        return template;
    }

    /**
     * Set the Spring JMS Template object used to communicate with the ActiveMQ queue broker. Used by
     * the Spring DI engine.
     *
     * @param template - the Spring JMS Template
     */
    public void setTemplate(JmsTemplate template) {
        this.template = template;
    }
}

19 Source : ActiveMQEventPublisherImpl.java
with Apache License 2.0
from edgexfoundry

/**
 * Set the Spring JMS Template object used to communicate with the ActiveMQ queue broker. Used by
 * the Spring DI engine.
 *
 * @param template - the Spring JMS Template
 */
public void setTemplate(JmsTemplate template) {
    this.template = template;
}

19 Source : ActivemqSendServiceImpl.java
with Apache License 2.0
from dromara

/**
 * ActivemqSendServiceImpl.
 *
 * @author xiaoyu(Myth)
 */
public clreplaced ActivemqSendServiceImpl implements MythMqSendService {

    private JmsTemplate jmsTemplate;

    public void setJmsTemplate(final JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    @Override
    public void sendMessage(final String destination, final Integer pattern, final byte[] message) {
        Destination queue = new ActiveMQQueue(destination);
        if (Objects.equals(P2P.getCode(), pattern)) {
            queue = new ActiveMQQueue(destination);
        } else if (Objects.equals(TOPIC.getCode(), pattern)) {
            queue = new ActiveMQTopic(destination);
        }
        jmsTemplate.convertAndSend(queue, message);
    }
}

19 Source : MessageBasedJobManager.java
with Apache License 2.0
from dingziyang

/**
 * @author Joram Barrez
 */
public clreplaced MessageBasedJobManager extends DefaultJobManager {

    protected JmsTemplate jmsTemplate;

    public MessageBasedJobManager() {
        super(null);
    }

    public MessageBasedJobManager(ProcessEngineConfigurationImpl processEngineConfiguration) {
        super(processEngineConfiguration);
    }

    @Override
    protected void triggerExecutorIfNeeded(final JobEnreplacedy jobEnreplacedy) {
        sendMessage(jobEnreplacedy);
    }

    @Override
    public void unacquire(final Job job) {
        if (job instanceof JobEnreplacedy) {
            JobEnreplacedy jobEnreplacedy = (JobEnreplacedy) job;
            // When unacquiring, we up the lock time again., so that it isn't cleared by the reset expired thread.
            jobEnreplacedy.setLockExpirationTime(new Date(processEngineConfiguration.getClock().getCurrentTime().getTime() + processEngineConfiguration.getAsyncExecutor().getAsyncJobLockTimeInMillis()));
        }
        sendMessage(job);
    }

    protected void sendMessage(final Job jobEnreplacedy) {
        Context.getTransactionContext().addTransactionListener(TransactionState.COMMITTED, new TransactionListener() {

            public void execute(CommandContext commandContext) {
                jmsTemplate.send(new MessageCreator() {

                    public Message createMessage(Session session) throws JMSException {
                        return session.createTextMessage(jobEnreplacedy.getId());
                    }
                });
            }
        });
    }

    public JmsTemplate getJmsTemplate() {
        return jmsTemplate;
    }

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }
}

See More Examples