javax.jms.JMSException Java Examples

The following examples show how to use javax.jms.JMSException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MessageListenerTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testConnectionProblemXA() throws JMSException, XAException, InterruptedException {
    TransactionManager transactionManager = new GeronimoTransactionManager();
    Connection connection = createXAConnection("brokerJTA", transactionManager);
    Queue dest = JMSUtil.createQueue(connection, "test");

    MessageListener listenerHandler = new TestMessageListener();
    TestExceptionListener exListener = new TestExceptionListener();

    PollingMessageListenerContainer container = //
        new PollingMessageListenerContainer(connection, dest, listenerHandler, exListener);
    container.setTransacted(false);
    container.setAcknowledgeMode(Session.SESSION_TRANSACTED);
    container.setTransactionManager(transactionManager);

    connection.close(); // Simulate connection problem
    container.start();
    Awaitility.await().until(() -> exListener.exception != null);
    JMSException ex = exListener.exception;
    assertNotNull(ex);
    // Closing the pooled connection will result in a NPE when using it
    assertEquals("Wrapped exception. null", ex.getMessage());
}
 
Example #2
Source File: JmsMessageBrowser.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Override
public void deleteMessage(String messageId) throws ListenerException {
	Session session=null;
	MessageConsumer mc = null;
	try {
		session = createSession();
		log.debug("retrieving message ["+messageId+"] in order to delete it");
		mc = getMessageConsumer(session, getDestination(), getCombinedSelector(messageId));
		mc.receive(getTimeOut());
	} catch (Exception e) {
		throw new ListenerException(e);
	} finally {
		try {
			if (mc != null) {
				mc.close();
			}
		} catch (JMSException e1) {
			throw new ListenerException("exception closing message consumer",e1);
		}
		closeSession(session);
	}
}
 
Example #3
Source File: SingleConnectionFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testWithQueueConnectionFactoryAndJms11Usage() throws JMSException {
	QueueConnectionFactory cf = mock(QueueConnectionFactory.class);
	QueueConnection con = mock(QueueConnection.class);

	given(cf.createConnection()).willReturn(con);

	SingleConnectionFactory scf = new SingleConnectionFactory(cf);
	Connection con1 = scf.createConnection();
	Connection con2 = scf.createConnection();
	con1.start();
	con2.start();
	con1.close();
	con2.close();
	scf.destroy();  // should trigger actual close

	verify(con).start();
	verify(con).stop();
	verify(con).close();
	verifyNoMoreInteractions(con);
}
 
Example #4
Source File: JMSPublisherConsumerTest.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
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.class));
    try {
        consumer.consume(destinationName, new ConsumerCallback() {
            @Override
            public void accept(JMSResponse response) {
                // noop
            }
        });
    } finally {
        ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
    }
}
 
Example #5
Source File: JmsContextTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testRuntimeExceptionOnCreateMapMessage() throws JMSException {
    JmsConnection connection = Mockito.mock(JmsConnection.class);
    JmsSession session = Mockito.mock(JmsSession.class);
    Mockito.when(connection.createSession(Mockito.anyInt())).thenReturn(session);
    JmsContext context = new JmsContext(connection, JMSContext.CLIENT_ACKNOWLEDGE);

    Mockito.doThrow(IllegalStateException.class).when(session).createMapMessage();

    try {
        context.createMapMessage();
        fail("Should throw ISRE");
    } catch (IllegalStateRuntimeException isre) {
    } finally {
        context.close();
    }
}
 
Example #6
Source File: MockJMSMapMessage.java    From pooled-jms with Apache License 2.0 6 votes vote down vote up
@Override
public long getLong(String name) throws JMSException {
    Object value = getObject(name);

    if (value instanceof Long) {
        return ((Long) value).longValue();
    } else if (value instanceof Integer) {
        return ((Integer) value).longValue();
    } else if (value instanceof Short) {
        return ((Short) value).longValue();
    } else if (value instanceof Byte) {
        return ((Byte) value).longValue();
    } else if (value instanceof String || value == null) {
        return Long.valueOf((String) value).longValue();
    } else {
        throw new MessageFormatException("Cannot read a long from " + value.getClass().getSimpleName());
    }
}
 
Example #7
Source File: MessageListenerTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithJTA() throws JMSException, XAException, InterruptedException {
    TransactionManager transactionManager = new GeronimoTransactionManager();
    Connection connection = createXAConnection("brokerJTA", transactionManager);
    Queue dest = JMSUtil.createQueue(connection, "test");

    MessageListener listenerHandler = new TestMessageListener();
    ExceptionListener exListener = new TestExceptionListener();
    PollingMessageListenerContainer container = new PollingMessageListenerContainer(connection, dest,
                                                                                    listenerHandler, exListener);
    container.setTransacted(false);
    container.setAcknowledgeMode(Session.SESSION_TRANSACTED);
    container.setTransactionManager(transactionManager);
    container.start();

    testTransactionalBehaviour(connection, dest);

    container.stop();
    connection.close();
}
 
Example #8
Source File: SingleSubscriberSinglePublisherTopicTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Publish messages to a topic in a node and receive from the same node at a slow rate.
 *
 * @throws AndesEventAdminServiceEventAdminException
 * @throws org.wso2.mb.integration.common.clients.exceptions.AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws NamingException
 * @throws JMSException
 * @throws IOException
 */
@Test(groups = "wso2.mb", description = "Same node publisher, slow subscriber test case",
        enabled = true)
@Parameters({"messageCount"})
public void testSameNodeSlowSubscriber(long messageCount)
        throws AndesEventAdminServiceEventAdminException, AndesClientConfigurationException,
               XPathExpressionException, NamingException, JMSException, IOException, AndesClientException,
               DataAccessUtilException {
    this.runSingleSubscriberSinglePublisherTopicTestCase(
                    automationContextForMB2, automationContextForMB2, 10L, 0L, "singleTopic2", messageCount, true);
}
 
Example #9
Source File: ActiveMQRAMessage.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Set type
 *
 * @param type The value
 * @throws JMSException Thrown if an error occurs
 */
@Override
public void setJMSType(final String type) throws JMSException {
   if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
      ActiveMQRALogger.LOGGER.trace("setJMSType(" + type + ")");
   }

   message.setJMSType(type);
}
 
Example #10
Source File: JMSPublisherConsumerTest.java    From solace-integration-guides with Apache License 2.0 5 votes vote down vote up
@Test
public void validateConsumeWithCustomHeadersAndProperties() throws Exception {
    final String destinationName = "testQueue";
    JmsTemplate jmsTemplate = CommonTest.buildJmsTemplateForDestination(false);

    jmsTemplate.send(destinationName, new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            TextMessage message = session.createTextMessage("hello from the other side");
            message.setStringProperty("foo", "foo");
            message.setBooleanProperty("bar", false);
            message.setJMSReplyTo(session.createQueue("fooQueue"));
            return message;
        }
    });

    JMSConsumer consumer = new JMSConsumer(jmsTemplate, mock(ComponentLog.class));
    final AtomicBoolean callbackInvoked = new AtomicBoolean();
    consumer.consume(destinationName, new ConsumerCallback() {
        @Override
        public void accept(JMSResponse response) {
            callbackInvoked.set(true);
            assertEquals("hello from the other side", new String(response.getMessageBody()));
            assertEquals("fooQueue", response.getMessageHeaders().get(JmsHeaders.REPLY_TO));
            assertEquals("foo", response.getMessageProperties().get("foo"));
            assertEquals("false", response.getMessageProperties().get("bar"));
        }
    });
    assertTrue(callbackInvoked.get());

    ((CachingConnectionFactory) jmsTemplate.getConnectionFactory()).destroy();
}
 
Example #11
Source File: ActiveMQMessageTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testSetJMSDeliveryModeProperty() throws JMSException {
   ActiveMQMessage message = new ActiveMQMessage();
   String propertyName = "JMSDeliveryMode";

   // Set as Boolean
   message.setObjectProperty(propertyName, Boolean.TRUE);
   assertTrue(message.isPersistent());
   message.setObjectProperty(propertyName, Boolean.FALSE);
   assertFalse(message.isPersistent());
   message.setBooleanProperty(propertyName, true);
   assertTrue(message.isPersistent());
   message.setBooleanProperty(propertyName, false);
   assertFalse(message.isPersistent());

   // Set as Integer
   message.setObjectProperty(propertyName, DeliveryMode.PERSISTENT);
   assertTrue(message.isPersistent());
   message.setObjectProperty(propertyName, DeliveryMode.NON_PERSISTENT);
   assertFalse(message.isPersistent());
   message.setIntProperty(propertyName, DeliveryMode.PERSISTENT);
   assertTrue(message.isPersistent());
   message.setIntProperty(propertyName, DeliveryMode.NON_PERSISTENT);
   assertFalse(message.isPersistent());

   // Set as String
   message.setObjectProperty(propertyName, "PERSISTENT");
   assertTrue(message.isPersistent());
   message.setObjectProperty(propertyName, "NON_PERSISTENT");
   assertFalse(message.isPersistent());
   message.setStringProperty(propertyName, "PERSISTENT");
   assertTrue(message.isPersistent());
   message.setStringProperty(propertyName, "NON_PERSISTENT");
   assertFalse(message.isPersistent());
}
 
Example #12
Source File: ActiveMQJMSProducer.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public JMSProducer send(Destination destination, Map<String, Object> body) {
   MapMessage message = context.createMapMessage();
   if (body != null) {
      try {
         for (Entry<String, Object> entry : body.entrySet()) {
            final String name = entry.getKey();
            final Object v = entry.getValue();
            if (v instanceof String) {
               message.setString(name, (String) v);
            } else if (v instanceof Long) {
               message.setLong(name, (Long) v);
            } else if (v instanceof Double) {
               message.setDouble(name, (Double) v);
            } else if (v instanceof Integer) {
               message.setInt(name, (Integer) v);
            } else if (v instanceof Character) {
               message.setChar(name, (Character) v);
            } else if (v instanceof Short) {
               message.setShort(name, (Short) v);
            } else if (v instanceof Boolean) {
               message.setBoolean(name, (Boolean) v);
            } else if (v instanceof Float) {
               message.setFloat(name, (Float) v);
            } else if (v instanceof Byte) {
               message.setByte(name, (Byte) v);
            } else if (v instanceof byte[]) {
               byte[] array = (byte[]) v;
               message.setBytes(name, array, 0, array.length);
            } else {
               message.setObject(name, v);
            }
         }
      } catch (JMSException e) {
         throw new MessageFormatRuntimeException(e.getMessage());
      }
   }
   send(destination, message);
   return this;
}
 
Example #13
Source File: LargeMessageOverReplicationTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private MapMessage createLargeMessage() throws JMSException {
   MapMessage message = session.createMapMessage();

   for (int i = 0; i < 10; i++) {
      message.setBytes("test" + i, new byte[1024 * 1024]);
   }
   return message;
}
 
Example #14
Source File: MockJMSConnection.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Override
public TopicSession createTopicSession(boolean transacted, int acknowledgeMode) throws JMSException {
    checkClosedOrFailed();
    ensureConnected();
    int ackMode = getSessionAcknowledgeMode(transacted, acknowledgeMode);
    MockJMSTopicSession result = new MockJMSTopicSession(getNextSessionId(), ackMode, this);
    addSession(result);
    if (started.get()) {
        result.start();
    }
    return result;
}
 
Example #15
Source File: ActiveMQRAMapMessage.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Does the item exist
 *
 * @param name The name
 * @return True / false
 * @throws JMSException Thrown if an error occurs
 */
@Override
public boolean itemExists(final String name) throws JMSException {
   if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
      ActiveMQRALogger.LOGGER.trace("itemExists(" + name + ")");
   }

   return ((MapMessage) message).itemExists(name);
}
 
Example #16
Source File: UserCredentialsConnectionFactoryAdapter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Determine whether there are currently thread-bound credentials,
 * using them if available, falling back to the statically specified
 * username and password (i.e. values of the bean properties) else.
 * @see #doCreateConnection
 */
@Override
public final Connection createConnection() throws JMSException {
	JmsUserCredentials threadCredentials = this.threadBoundCredentials.get();
	if (threadCredentials != null) {
		return doCreateConnection(threadCredentials.username, threadCredentials.password);
	}
	else {
		return doCreateConnection(this.username, this.password);
	}
}
 
Example #17
Source File: ManagedConnection.java    From ats-framework with Apache License 2.0 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 #18
Source File: BrokerManagementHelper.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
public BrokerManagementHelper createKeyStore(final String keyStoreName,
                                             final String keyStoreLocation,
                                             final String keyStorePassword)
        throws JMSException
{
    final Map<String, Object> keyStoreAttributes = new HashMap<>();
    keyStoreAttributes.put("storeUrl", keyStoreLocation);
    keyStoreAttributes.put("password", keyStorePassword);
    keyStoreAttributes.put("keyStoreType", java.security.KeyStore.getDefaultType());
    return createEntity(keyStoreName, FileKeyStore.class.getName(), keyStoreAttributes);
}
 
Example #19
Source File: AmqpJmsMessagePropertyIntercepter.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
public Object getProperty(AmqpJmsMessageFacade message) throws JMSException {
    if (message instanceof AmqpJmsObjectMessageFacade) {
        return ((AmqpJmsObjectMessageFacade) message).isAmqpTypedEncoding();
    }

    return null;
}
 
Example #20
Source File: JmsBasedRequestResponseClient.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Gets a String valued property from a JMS message.
 *
 * @param message The message.
 * @param name The property name.
 * @return The property value or {@code null} if the message does not contain the corresponding property.
 */
public static String getStringProperty(final Message message, final String name)  {
    try {
        return message.getStringProperty(name);
    } catch (final JMSException e) {
        return null;
    }
}
 
Example #21
Source File: JmsSendReceiveWithMessageExpirationTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
protected MessageConsumer createConsumer() throws JMSException {
   if (durable) {
      LOG.info("Creating durable consumer");
      return session.createDurableSubscriber((Topic) consumerDestination, getName());
   }
   return session.createConsumer(consumerDestination);
}
 
Example #22
Source File: ActiveMQMessageTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testSetReadOnly() {
   ActiveMQMessage msg = new ActiveMQMessage();
   msg.setReadOnlyProperties(true);
   boolean test = false;
   try {
      msg.setIntProperty("test", 1);
   } catch (MessageNotWriteableException me) {
      test = true;
   } catch (JMSException e) {
      e.printStackTrace(System.err);
      test = false;
   }
   assertTrue(test);
}
 
Example #23
Source File: JmsPoolJMSProducer.java    From pooled-jms with Apache License 2.0 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 #24
Source File: ManagedQueueTopicConnection.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
@Override
public TopicSession createTopicSession(
                                        boolean transacted,
                                        int acknowledgeMode ) throws JMSException {

    return addSession( ((TopicConnection) connection).createTopicSession(transacted, acknowledgeMode));
}
 
Example #25
Source File: JmsPoolJMSContext.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Override
public Message createMessage() {
    try {
        return getSession().createMessage();
    } catch (JMSException jmse) {
        throw JMSExceptionSupport.createRuntimeException(jmse);
    }
}
 
Example #26
Source File: MdbUtil.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static void close(final Connection closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (final JMSException e) {
        }
    }
}
 
Example #27
Source File: ActiveMQMapMessage.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] getBytes(final String name) throws JMSException {
   try {
      return map.getBytesProperty(new SimpleString(name));
   } catch (ActiveMQPropertyConversionException e) {
      throw new MessageFormatException(e.getMessage());
   }
}
 
Example #28
Source File: MQCommandProcessor.java    From perf-harness with MIT License 5 votes vote down vote up
/**
 * Apply vendor-specific settings for building up a connection factory to
 * WMQ.
 * 
 * @param cf
 * @throws JMSException
 */
protected void configureMQConnectionFactory(MQConnectionFactory cf)
		throws JMSException {

	// always client bindings
	cf.setTransportType(JMSC.MQJMS_TP_CLIENT_MQ_TCPIP);
	cf.setHostName(Config.parms.getString("cmd_jh"));
	cf.setPort(Config.parms.getInt("cmd_p"));
	cf.setChannel(Config.parms.getString("cmd_jc"));

	cf.setQueueManager(Config.parms.getString("cmd_jb"));

}
 
Example #29
Source File: RefCountedJmsXaConnection.java    From reladomo with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void stop() throws JMSException
{
    int count = startCount.decrementAndGet();
    if (count == 0)
    {
        underlying.stop();
    }
}
 
Example #30
Source File: MessagePropertyConversionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * if a property is set as a <code>byte</code>,
 * it can also be read as a <code>long</code>.
 */
@Test
public void testByte2Long() {
   try {
      Message message = senderSession.createMessage();
      message.setByteProperty("prop", (byte) 127);
      Assert.assertEquals(127L, message.getLongProperty("prop"));
   } catch (JMSException e) {
      fail(e);
   }
}