Java Code Examples for javax.jms.Destination

The following are top voted examples for showing how to use javax.jms.Destination. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: flume-release-1.7.0   File: TestIntegrationActiveMQ.java   Source Code and License 12 votes vote down vote up
private void putTopic(List<String> events) throws Exception {
  ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME,
      PASSWORD, BROKER_BIND_URL);
  Connection connection = factory.createConnection();
  connection.start();

  Session session = connection.createSession(true,
      Session.AUTO_ACKNOWLEDGE);
  Destination destination = session.createTopic(DESTINATION_NAME);
  MessageProducer producer = session.createProducer(destination);

  for (String event : events) {
    TextMessage message = session.createTextMessage();
    message.setText(event);
    producer.send(message);
  }
  session.commit();
  session.close();
  connection.close();
}
 
Example 2
Project: DWSurvey   File: AdvancedNotifyMessageProducer.java   Source Code and License 9 votes vote down vote up
/**
 * 使用jmsTemplate的send/MessageCreator()发送Map类型的消息并在Message中附加属性用于消息过滤.
 */
private void sendMessage(final User user, Destination destination) {
	jmsTemplate.send(destination, new MessageCreator() {
		@Override
		public Message createMessage(Session session) throws JMSException {

			MapMessage message = session.createMapMessage();
			message.setString("userName", user.getName());
			message.setString("email", user.getEmail());

			message.setStringProperty("objectType", "user");

			return message;
		}
	});
}
 
Example 3
Project: karate   File: QueueUtils.java   Source Code and License 6 votes vote down vote up
public static void send(String queueName, String text, int delayMillis) {
    EXECUTOR.submit(() -> {
        try {
            logger.info("*** artificial delay {}: {}", queueName, delayMillis);
            Thread.sleep(delayMillis);
            Connection connection = getConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createQueue(queueName);
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            TextMessage message = session.createTextMessage(text);
            producer.send(message);
            logger.info("*** sent message {}: {}", queueName, text);
            session.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });
}
 
Example 4
Project: pooled-jms   File: JmsPoolMessageProducer.java   Source Code and License 6 votes vote down vote up
public JmsPoolMessageProducer(JmsPoolSession session, MessageProducer messageProducer, Destination destination, boolean shared) throws JMSException {
    this.session = session;
    this.messageProducer = messageProducer;
    this.destination = destination;
    this.shared = shared;
    this.anonymousProducer = destination == null;

    this.deliveryMode = messageProducer.getDeliveryMode();
    this.disableMessageID = messageProducer.getDisableMessageID();
    this.disableMessageTimestamp = messageProducer.getDisableMessageTimestamp();
    this.priority = messageProducer.getPriority();
    this.timeToLive = messageProducer.getTimeToLive();

    if (session.isJMSVersionSupported(2, 0)) {
        this.deliveryDelay = messageProducer.getDeliveryDelay();
    }
}
 
Example 5
Project: flume-release-1.7.0   File: TestIntegrationActiveMQ.java   Source Code and License 6 votes vote down vote up
private void putQueue(List<String> events) throws Exception {
  ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME,
      PASSWORD, BROKER_BIND_URL);
  Connection connection = factory.createConnection();
  connection.start();

  Session session = connection.createSession(true,
      Session.AUTO_ACKNOWLEDGE);
  Destination destination = session.createQueue(DESTINATION_NAME);
  MessageProducer producer = session.createProducer(destination);

  for (String event : events) {
    TextMessage message = session.createTextMessage();
    message.setText(event);
    producer.send(message);
  }
  session.commit();
  session.close();
  connection.close();
}
 
Example 6
Project: asw   File: SimpleFilter.java   Source Code and License 6 votes vote down vote up
public SimpleFilter(String name, String sorgenteMessaggi, String destinazioneMessaggi,
		String connectionFactory, SimpleMessageFilter mf, int maxDelay) {
	this.name = name;
   	this.messageSource = (Destination) JndiUtil.getInstance().jndiLookup(sorgenteMessaggi);
   	this.messageDestination = (Destination) JndiUtil.getInstance().jndiLookup(destinazioneMessaggi);
   	this.connectionFactory = (ConnectionFactory) JndiUtil.getInstance().jndiLookup(connectionFactory);
   	this.messageFilter = mf;

   	this.maxDelay = maxDelay;

   	/* crea un consumatore su sorgenteMessaggi: 
   	 * girera' messaggi a questo oggetto (this) */
   	this.consumer =
   			new SimpleAsynchConsumer("Consumatore messaggi per " + this.name,
   					this.messageSource, this.connectionFactory, this, 10);
       logger.info("Creato consumatore: " + consumer.toString());

       /* crea un produttore su destinazioneMessaggi */
   	this.producer = new SimpleProducer("Produttore messaggi per " + this.name,
   			this.messageDestination, this.connectionFactory, 10);
       logger.info("Creato produttore: " + producer.toString());

       this.messagesReceived = 0;
       this.cancelled = false;
}
 
Example 7
Project: ats-framework   File: JmsClient.java   Source Code and License 6 votes vote down vote up
private void doSendBinaryMessage( final Session session, final Destination destination,
                                  final byte[] bytes,
                                  final Map<String, ?> properties ) throws JMSException {

    try {
        BytesMessage message = session.createBytesMessage();
        message.writeBytes(bytes);
        if (properties != null) {
            // Note: Setting any properties (including JMS fields) using
            // setObjectProperty might not be supported by all providers
            // Tested with: ActiveMQ
            for (final Entry<String, ?> property : properties.entrySet()) {
                message.setObjectProperty(property.getKey(), property.getValue());
            }
        }
        final MessageProducer producer = session.createProducer(destination);
        producer.send(message);
    } finally {
        releaseSession(false);
    }
}
 
Example 8
Project: pooled-jms   File: MockJMSProducer.java   Source Code and License 6 votes vote down vote up
private void doSend(Destination destination, Message message) throws JMSException {

        if (message == null) {
            throw new MessageFormatException("Message must not be null");
        }

        for (Map.Entry<String, Object> entry : messageProperties.entrySet()) {
            message.setObjectProperty(entry.getKey(), entry.getValue());
        }

        if (correlationId != null) {
            message.setJMSCorrelationID(correlationId);
        }
        if (correlationIdBytes != null) {
            message.setJMSCorrelationIDAsBytes(correlationIdBytes);
        }
        if (type != null) {
            message.setJMSType(type);
        }
        if (replyTo != null) {
            message.setJMSReplyTo(replyTo);
        }

        session.send(producer, destination, message, deliveryMode, priority, timeToLive, disableMessageId, disableTimestamp, deliveryDelay, completionListener);
    }
 
Example 9
Project: testee.fi   File: JavaMessagingTest.java   Source Code and License 6 votes vote down vote up
private void testReception(
        final TestClass i,
        final Destination destination, final ThrowingConsumer<Destination> destinationCheck
) throws Exception {
    final Connection connection = i.connectionFactory.createConnection();
    assertNotNull(connection);
    final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    assertNotNull(session);
    final MessageProducer producer = session.createProducer(destination);
    assertNotNull(producer);
    final TextMessage message = session.createTextMessage();
    assertNotNull(message);
    message.setText("I am IronMan");
    producer.send(message);

    final List<ReceivedJmsMessage> messages = i.testQueue.drainReceivedMessages();
    assertEquals(1, messages.size());
    final ReceivedJmsMessage receivedMessage = messages.get(0);
    destinationCheck.accept(receivedMessage.getDestination());
    assertTrue(receivedMessage.getJmsMessage() instanceof TextMessage);
    final TextMessage receivedTextMessage = (TextMessage) receivedMessage.getJmsMessage();
    assertEquals("I am IronMan", receivedTextMessage.getText());
}
 
Example 10
Project: pooled-jms   File: JmsPoolSession.java   Source Code and License 5 votes vote down vote up
private MessageProducer getMessageProducer(Destination destination) throws JMSException {
    MessageProducer result = null;

    if (useAnonymousProducers) {
        result = safeGetSessionHolder().getOrCreateProducer();
    } else {
        result = getInternalSession().createProducer(destination);
    }

    return result;
}
 
Example 11
Project: pooled-jms   File: JmsPoolJMSContext.java   Source Code and License 5 votes vote down vote up
@Override
public JMSConsumer createConsumer(Destination destination) {
    try {
        return startIfNeeded(new JmsPoolJMSConsumer((JmsPoolMessageConsumer) getSession().createConsumer(destination)));
    } catch (JMSException jmse) {
        throw JMSExceptionSupport.createRuntimeException(jmse);
    }
}
 
Example 12
Project: message-broker   File: QueueConsumerTest.java   Source Code and License 5 votes vote down vote up
@Parameters({ "broker-port"})
@Test
public void testConsumerProducerWithAutoAck(String port) throws Exception {
    String queueName = "testConsumerProducerWithAutoAck";
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder("admin", "admin", "localhost", port)
            .withQueue(queueName)
            .build();

    ConnectionFactory connectionFactory
            = (ConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    Connection connection = connectionFactory.createConnection();
    connection.start();

    // publish 100 messages
    Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = producerSession.createQueue(queueName);
    MessageProducer producer = producerSession.createProducer(queue);

    int numberOfMessages = 100;
    for (int i = 0; i < numberOfMessages; i++) {
        producer.send(producerSession.createTextMessage("Test message " + i));
    }
    producerSession.close();

    // Consume published messages
    Session subscriberSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination subscriberDestination = (Destination) initialContextForQueue.lookup(queueName);
    MessageConsumer consumer = subscriberSession.createConsumer(subscriberDestination);

    for (int i = 0; i < numberOfMessages; i++) {
        Message message = consumer.receive(5000);
        Assert.assertNotNull(message, "Message #" + i + " was not received");
    }

    connection.close();
}
 
Example 13
Project: flume-release-1.7.0   File: JMSMessageConsumerTestBase.java   Source Code and License 5 votes vote down vote up
@Before
public void setup() throws Exception {
  beforeSetup();
  connectionFactory = mock(ConnectionFactory.class);
  connection = mock(Connection.class);
  session = mock(Session.class);
  queue = mock(Queue.class);
  topic = mock(Topic.class);
  messageConsumer = mock(MessageConsumer.class);
  message = mock(TextMessage.class);
  when(message.getPropertyNames()).thenReturn(new Enumeration<Object>() {
    @Override
    public boolean hasMoreElements() {
      return false;
    }
    @Override
    public Object nextElement() {
      throw new UnsupportedOperationException();
    }
  });
  when(message.getText()).thenReturn(TEXT);
  when(connectionFactory.createConnection(USERNAME, PASSWORD)).thenReturn(connection);
  when(connection.createSession(true, Session.SESSION_TRANSACTED)).thenReturn(session);
  when(session.createQueue(destinationName)).thenReturn(queue);
  when(session.createConsumer(any(Destination.class), anyString())).thenReturn(messageConsumer);
  when(messageConsumer.receiveNoWait()).thenReturn(message);
  when(messageConsumer.receive(anyLong())).thenReturn(message);
  destinationName = DESTINATION_NAME;
  destinationType = JMSDestinationType.QUEUE;
  destinationLocator = JMSDestinationLocator.CDI;
  messageSelector = SELECTOR;
  batchSize = 10;
  pollTimeout = 500L;
  context = new Context();
  converter = new DefaultJMSMessageConverter.Builder().build(context);
  event = converter.convert(message).iterator().next();
  userName = Optional.of(USERNAME);
  password = Optional.of(PASSWORD);
  afterSetup();
}
 
Example 14
Project: java-jms   File: TracingMessageProducer.java   Source Code and License 5 votes vote down vote up
@Override
public void send(Destination destination, Message message, int deliveryMode, int priority,
    long timeToLive) throws JMSException {
  Span span = TracingMessageUtils.buildAndInjectSpan(destination, message, tracer);
  try {
    messageProducer.send(destination, message, deliveryMode, priority, timeToLive);
  } catch (Throwable e) {
    SpanJmsDecorator.onError(e, span);
    throw e;
  } finally {
    span.finish();
  }
}
 
Example 15
Project: cli-java   File: AccCoreMessageFormatter.java   Source Code and License 5 votes vote down vote up
@Override
protected String formatAddress(Destination destination) {
    if (destination == null) {
        return null;
    }
    if (!(destination instanceof ActiveMQDestination)) {
        throw new InvalidParameterException("Destination must be a Core destination, was " + destination.getClass());
    }

    String address = ((ActiveMQDestination) destination).getName();
    return dropDestinationPrefix(address);
}
 
Example 16
Project: pooled-jms   File: JmsPoolJMSProducer.java   Source Code and License 5 votes vote down vote up
private void doSend(Destination destination, Message message) throws JMSException {

        if (message == null) {
            throw new MessageFormatException("Message must not be null");
        }

        for (Map.Entry<String, Object> entry : messageProperties.entrySet()) {
            message.setObjectProperty(entry.getKey(), entry.getValue());
        }

        if (correlationId != null) {
            message.setJMSCorrelationID(correlationId);
        }
        if (correlationIdBytes != null) {
            message.setJMSCorrelationIDAsBytes(correlationIdBytes);
        }
        if (type != null) {
            message.setJMSType(type);
        }
        if (replyTo != null) {
            message.setJMSReplyTo(replyTo);
        }

        if (completionListener != null) {
            producer.send(destination, message, deliveryMode, priority, timeToLive, completionListener);
        } else {
            producer.send(destination, message, deliveryMode, priority, timeToLive);
        }
    }
 
Example 17
Project: pooled-jms   File: MockJMSQueueSession.java   Source Code and License 5 votes vote down vote up
@Override
public MessageConsumer createConsumer(Destination destination, String messageSelector) throws JMSException {
    if (destination instanceof Topic) {
        throw new IllegalStateException("Operation not supported by a QueueSession");
    }
    return super.createConsumer(destination, messageSelector);
}
 
Example 18
Project: ats-framework   File: JmsClient.java   Source Code and License 5 votes vote down vote up
private void sendTextMessage( final Connection connection, final Destination destination,
                              final String textMessage, final Map<String, ?> properties ) {

    try {
        final Session session = loadSession(false, Session.AUTO_ACKNOWLEDGE);
        doSendTextMessage(session, destination, textMessage, properties);
    } catch (Exception e) {
        throw new JmsMessageException("Failed to send message", e);
    }
}
 
Example 19
Project: org.ops4j.pax.transx   File: JMSContextImpl.java   Source Code and License 5 votes vote down vote up
@Override
public JMSConsumer createConsumer(Destination destination) {
    try {
        return startIfNeeded(new JMSConsumerImpl(this, getSession().createConsumer(destination)));
    } catch (JMSException jmse) {
        throw Utils.convertToRuntimeException(jmse);
    }
}
 
Example 20
Project: org.ops4j.pax.transx   File: JMSProducerImpl.java   Source Code and License 5 votes vote down vote up
@Override
public JMSProducer send(Destination destination, byte[] body) {
    try {
        BytesMessage message = context.createBytesMessage();
        message.writeBytes(body);
        doSend(destination, message);
    } catch (JMSException jmse) {
        throw Utils.convertToRuntimeException(jmse);
    }
    return this;
}
 
Example 21
Project: pooled-jms   File: MockJMSTopicSession.java   Source Code and License 5 votes vote down vote up
/**
 * @see javax.jms.Session#createConsumer(javax.jms.Destination, java.lang.String)
 */
@Override
public MessageConsumer createConsumer(Destination destination, String messageSelector) throws JMSException {
    if (destination instanceof Queue) {
        throw new IllegalStateException("Operation not supported by a TopicSession");
    }
    return super.createConsumer(destination, messageSelector);
}
 
Example 22
Project: org.ops4j.pax.transx   File: JMSContextImpl.java   Source Code and License 5 votes vote down vote up
@Override
public JMSConsumer createConsumer(Destination destination, String selector, boolean noLocal) {
    try {
        return startIfNeeded(new JMSConsumerImpl(this, getSession().createConsumer(destination, selector, noLocal)));
    } catch (JMSException jmse) {
        throw Utils.convertToRuntimeException(jmse);
    }
}
 
Example 23
Project: ats-framework   File: ManagedConnection.java   Source Code and License 5 votes vote down vote up
@Override
public ConnectionConsumer createConnectionConsumer(
                                                    Destination destination,
                                                    String messageSelector,
                                                    ServerSessionPool sessionPool,
                                                    int maxMessages ) throws JMSException {

    return connection.createConnectionConsumer(destination, messageSelector, sessionPool, maxMessages);
}
 
Example 24
Project: pooled-jms   File: MockJMSMessageProducer.java   Source Code and License 5 votes vote down vote up
@Override
public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive) throws JMSException {
    checkClosed();
    checkDestinationNotInvalid(destination);

    if (!anonymousProducer) {
        throw new UnsupportedOperationException("Using this method is not supported on producers created with an explicit Destination.");
    }

    session.send(this, destination, message, deliveryMode, priority, timeToLive, disableMessageId, disableTimestamp, deliveryMode, null);
}
 
Example 25
Project: oneops   File: OpsEventPublisher.java   Source Code and License 5 votes vote down vote up
/**
 * Inits the.
 *
 * @throws JMSException the jMS exception
 */
public void init() throws JMSException {

	connection = connectionFactory.createConnection();
	connection.start();
	
	// Create the session
	session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
	Destination destination = session.createQueue(queue);
	// Create the producer.
	producer = session.createProducer(destination);
	
	if (persistent) {
	    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
	} else {
	    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
	}
	if (timeToLive != 0) {
	    producer.setTimeToLive(timeToLive);
	}
   }
 
Example 26
Project: lemon   File: ProxyConnectionFactory.java   Source Code and License 5 votes vote down vote up
public void sendMessage(MessageContext messageContext,
        Destination destination, Message message) throws JMSException {
    String destinationName = destination.toString();

    if (destination instanceof Topic) {
        messageHandler.sendMessageToTopic(messageContext, destinationName,
                message);
    } else {
        messageHandler.sendMessageToQueue(messageContext, destinationName,
                message);
    }
}
 
Example 27
Project: java-jms   File: TracingMessageProducer.java   Source Code and License 5 votes vote down vote up
@Override
public void send(Destination destination, Message message) throws JMSException {
  Span span = TracingMessageUtils.buildAndInjectSpan(destination, message, tracer);
  try {
    messageProducer.send(destination, message);
  } catch (Throwable e) {
    SpanJmsDecorator.onError(e, span);
    throw e;
  } finally {
    span.finish();
  }
}
 
Example 28
Project: pooled-jms   File: MockJMSContext.java   Source Code and License 5 votes vote down vote up
@Override
public JMSConsumer createConsumer(Destination destination) {
    try {
        return startIfNeeded(new MockJMSConsumer(getSession(), (MockJMSMessageConsumer) getSession().createConsumer(destination)));
    } catch (JMSException jmse) {
        throw JMSExceptionSupport.createRuntimeException(jmse);
    }
}
 
Example 29
Project: pooled-jms   File: MockJMSContext.java   Source Code and License 5 votes vote down vote up
@Override
public JMSConsumer createConsumer(Destination destination, String selector) {
    try {
        return startIfNeeded(new MockJMSConsumer(getSession(), (MockJMSMessageConsumer) getSession().createConsumer(destination, selector)));
    } catch (JMSException jmse) {
        throw JMSExceptionSupport.createRuntimeException(jmse);
    }
}
 
Example 30
Project: pooled-jms   File: MockJMSContext.java   Source Code and License 5 votes vote down vote up
@Override
public JMSConsumer createConsumer(Destination destination, String selector, boolean noLocal) {
    try {
        return startIfNeeded(new MockJMSConsumer(getSession(), (MockJMSMessageConsumer) getSession().createConsumer(destination, selector, noLocal)));
    } catch (JMSException jmse) {
        throw JMSExceptionSupport.createRuntimeException(jmse);
    }
}
 
Example 31
Project: pooled-jms   File: MockJMSProducer.java   Source Code and License 5 votes vote down vote up
@Override
public JMSProducer send(Destination destination, Message message) {
    try {
        doSend(destination, message);
    } catch (JMSException jmse) {
        throw JMSExceptionSupport.createRuntimeException(jmse);
    }

    return this;
}
 
Example 32
Project: pooled-jms   File: MockJMSProducer.java   Source Code and License 5 votes vote down vote up
@Override
public JMSProducer send(Destination destination, byte[] body) {
    try {
        BytesMessage message = session.createBytesMessage();
        message.writeBytes(body);
        doSend(destination, message);
    } catch (JMSException jmse) {
        throw JMSExceptionSupport.createRuntimeException(jmse);
    }

    return this;
}
 
Example 33
Project: pooled-jms   File: MockJMSProducer.java   Source Code and License 5 votes vote down vote up
@Override
public JMSProducer send(Destination destination, Map<String, Object> body) {
    try {
        MapMessage message = session.createMapMessage();
        for (Map.Entry<String, Object> entry : body.entrySet()) {
            message.setObject(entry.getKey(), entry.getValue());
        }

        doSend(destination, message);
    } catch (JMSException jmse) {
        throw JMSExceptionSupport.createRuntimeException(jmse);
    }

    return this;
}
 
Example 34
Project: java-jms   File: TracingMessageProducer.java   Source Code and License 5 votes vote down vote up
@Override
public void send(Destination destination, Message message) throws JMSException {
  Span span = TracingMessageUtils.buildAndInjectSpan(destination, message, tracer);
  try {
    messageProducer.send(destination, message);
  } catch (Throwable e) {
    SpanJmsDecorator.onError(e, span);
    throw e;
  } finally {
    span.finish();
  }
}
 
Example 35
Project: pooled-jms   File: PooledSessionTest.java   Source Code and License 5 votes vote down vote up
@Test(timeout = 60000)
public void testRepeatedCreateSessionProducerResultsInSame() throws Exception {
    JmsPoolConnection connection = (JmsPoolConnection) pooledFactory.createConnection();

    assertTrue(pooledFactory.isUseAnonymousProducers());

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic("test-topic");
    JmsPoolMessageProducer producer = (JmsPoolMessageProducer) session.createProducer(destination);
    MessageProducer original = producer.getMessageProducer();
    assertNotNull(original);
    session.close();

    assertEquals(1, brokerService.getAdminView().getDynamicDestinationProducers().length);

    for (int i = 0; i < 20; ++i) {
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = (JmsPoolMessageProducer) session.createProducer(destination);
        assertSame(original, producer.getMessageProducer());
        session.close();
    }

    assertEquals(1, brokerService.getAdminView().getDynamicDestinationProducers().length);

    connection.close();
    pooledFactory.clear();
}
 
Example 36
Project: java-jms   File: TracingMessageUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void buildAndInjectSpan() throws Exception {
  Destination destination = new ActiveMQQueue("queue");

  ActiveMQTextMessage message = new ActiveMQTextMessage();
  MockSpan span = mockTracer.buildSpan("test").start();
  mockTracer.scopeManager().activate(span, true);

  MockSpan injected = (MockSpan) TracingMessageUtils
      .buildAndInjectSpan(destination, message, mockTracer);

  assertFalse(message.getProperties().isEmpty());
  assertEquals(span.context().spanId(), injected.parentId());
}
 
Example 37
Project: oneops   File: SensorPublisher.java   Source Code and License 5 votes vote down vote up
/**
 * Inits the.
 *
 * @throws JMSException the jMS exception
 */
public void init() throws JMSException {
    Properties properties = new Properties();
    try {
        properties.load(this.getClass().getResourceAsStream("/sink.properties"));
    } catch (IOException e) {
        logger.error("got: " + e.getMessage());
    }

    user = properties.getProperty("amq.user");
    password = System.getenv("KLOOPZ_AMQ_PASS");


    if (password == null) {
        throw new JMSException("missing KLOOPZ_AMQ_PASS env var");
    }

    AMQConnectorURI connectStringGenerator = new AMQConnectorURI();
    connectStringGenerator.setHost("opsmq");
    connectStringGenerator.setProtocol("tcp");
    connectStringGenerator.setPort(61616);
    connectStringGenerator.setTransport("failover");
    connectStringGenerator.setDnsResolve(true);
    connectStringGenerator.setKeepAlive(true);
    HashMap<String, String> transportOptions = new HashMap<>();
    transportOptions.put("initialReconnectDelay", "1000");
    transportOptions.put("startupMaxReconnectAttempts", mqConnectionStartupRetries);
    transportOptions.put("timeout", mqConnectionTimeout);
    transportOptions.put("useExponentialBackOff", "false");
    connectStringGenerator.setTransportOptions(transportOptions);
    url = connectStringGenerator.build();

    showParameters();

    // Create the connection.
    ActiveMQConnectionFactory amqConnectionFactory = new ActiveMQConnectionFactory(user, password, url);
    amqConnectionFactory.setUseAsyncSend(true);
    PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory(amqConnectionFactory);
    pooledConnectionFactory.setMaxConnections(amqConnectionPoolSize);
    pooledConnectionFactory.setIdleTimeout(10000);

    for (int i = 0; i < poolsize; i++) {
        JmsTemplate producerTemplate = new JmsTemplate(pooledConnectionFactory);
        producerTemplate.setSessionTransacted(false);
        int shard = i + 1;
        Destination perfin = new org.apache.activemq.command.ActiveMQQueue(queueBase + "-" + shard);
        producerTemplate.setDefaultDestination(perfin);
        producerTemplate.setDeliveryPersistent(false);
        producers[i] = producerTemplate;
    }


}
 
Example 38
Project: org.ops4j.pax.transx   File: JMSProducerImpl.java   Source Code and License 5 votes vote down vote up
private void doSend(Destination destination, Message message) throws JMSException {
    if (message == null) {
        throw new MessageFormatException("Message must not be null");
    }
    for (Map.Entry<String, Object> entry : messageProperties.entrySet()) {
        message.setObjectProperty(entry.getKey(), entry.getValue());
    }
    if (correlationId != null) {
        message.setJMSCorrelationID(correlationId);
    }
    if (correlationIdBytes != null) {
        message.setJMSCorrelationIDAsBytes(correlationIdBytes);
    }
    if (type != null) {
        message.setJMSType(type);
    }
    if (replyTo != null) {
        message.setJMSReplyTo(replyTo);
    }
    producer.setDeliveryMode(deliveryMode);
    producer.setPriority(priority);
    producer.setTimeToLive(timeToLive);
    producer.setDisableMessageID(disableMessageId);
    producer.setDisableMessageTimestamp(disableTimestamp);
    // producer.setDeliveryDelay(deliveryDelay);
    try {
        producer.send(destination, message);
        if (completionListener != null) {
            completionListener.onCompletion(message);
        }
    } catch (Exception e) {
        if (completionListener != null) {
            completionListener.onException(message, e);
        }
    }
}
 
Example 39
Project: ats-framework   File: JmsClient.java   Source Code and License 5 votes vote down vote up
/**
 * Receive a message
 *
 * @param destination remote destination
 * @param timeout timeout period in milliseconds
 * @return the received message
 */
@PublicAtsApi
public Message receiveMessage( final Destination destination, final long timeout ) {

    try {
        final Session session = loadSession(false, Session.AUTO_ACKNOWLEDGE);
        return doReceiveMessage(session, destination, timeout);
    } catch (Exception e) {
        throw new JmsMessageException("Failed to read message from " + destination, e);
    }
}
 
Example 40
Project: elephant   File: MQAutoConfiguration.java   Source Code and License 5 votes vote down vote up
private void registerListener(String registerBeanName,Destination destination,Object bean,Method method,int retryTimes,boolean isRetry){
	DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)this.applicationContext.getAutowireCapableBeanFactory();  
         
       BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(DefaultMessageListenerContainer.class);  
       beanDefinitionBuilder.addPropertyValue("connectionFactory",this.connectionFactory);  
       beanDefinitionBuilder.addPropertyValue("destination", destination);  
       beanDefinitionBuilder.addPropertyValue("messageListener",new SessionAwareMessageListenerImpl(bean, method,retryTimes,isRetry,this.jmsTemplate));
       beanDefinitionBuilder.addPropertyValue("sessionAcknowledgeMode",4);
       
       beanFactory.registerBeanDefinition(registerBeanName, beanDefinitionBuilder.getBeanDefinition());
}