@Override public JMSContext createContext(String username, String password, int sessionMode) { if (stopped.get()) { LOG.debug("JmsPoolConnectionFactory is stopped, skip create new connection."); return null; } if (!jmsContextSupported) { throw new JMSRuntimeException("Configured ConnectionFactory is not JMS 2+ capable"); } if (isUseProviderJMSContext()) { return createProviderContext(username, password, sessionMode); } else { try { return newPooledConnectionContext(createJmsPoolConnection(username, password), sessionMode); } catch (JMSException e) { throw JMSExceptionSupport.createRuntimeException(e); } } }
@Test(timeout = 30000) public void testCreateJMSProducer() throws JMSException { JmsPoolJMSProducer producer = (JmsPoolJMSProducer) context.createProducer(); assertNotNull(producer); MockJMSMessageProducer mockProducer = (MockJMSMessageProducer) producer.getMessageProducer(); assertNotNull(mockProducer); // JMSProducer instances are always anonymous producers. assertNull(mockProducer.getDestination()); context.close(); try { producer.getMessageProducer(); fail("should throw on closed context."); } catch (JMSRuntimeException jmsre) {} }
@Test(timeout = 60000) public void testRun() throws Exception { JmsPoolConnection connection = (JmsPoolConnection) cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { session.run(); fail("Session should be unable to run outside EE."); } catch (JMSRuntimeException jmsre) {} session.close(); try { session.run(); fail("Session should be closed."); } catch (IllegalStateRuntimeException isre) {} }
@Test(timeout = 30000) public void testStartStopConnection() throws JMSException { JmsPoolJMSContext context = (JmsPoolJMSContext) cf.createContext(); context.setAutoStart(false); assertNotNull(context.createConsumer(context.createQueue(getTestName()))); MockJMSConnection connection = (MockJMSConnection) context.getConnection(); assertFalse(connection.isStarted()); context.start(); assertTrue(connection.isStarted()); // We cannot stop a JMS Connection from the pool as it is a shared resource. context.stop(); assertTrue(connection.isStarted()); context.close(); try { context.stop(); fail("Cannot call stop on a closed context."); } catch (JMSRuntimeException jmsre) {} }
/** * Closes the connection. */ public void close() { try { inflight = false; connected = false; if (jmsCtxt != null) { jmsCtxt.close(); } } catch (JMSRuntimeException jmse) { ; } finally { jmsCtxt = null; } }
/** * Internal method to connect to MQ. * * @throws RetriableException Operation failed, but connector should continue to retry. * @throws ConnectException Operation failed and connector should stop. */ private void connectInternal() throws ConnectException, RetriableException { if (connected) { return; } try { if (userName != null) { jmsCtxt = mqConnFactory.createContext(userName, password, JMSContext.SESSION_TRANSACTED); } else { jmsCtxt = mqConnFactory.createContext(JMSContext.SESSION_TRANSACTED); } jmsProd = jmsCtxt.createProducer(); jmsProd.setDeliveryMode(deliveryMode); jmsProd.setTimeToLive(timeToLive); connected = true; } catch (JMSRuntimeException jmse) { log.debug("JMS exception {}", jmse); handleException(jmse); } }
/** * Commits the current transaction. If the current transaction contains a message that could not * be processed, the transaction is "in peril" and is rolled back instead to avoid data loss. * * @throws RetriableException Operation failed, but connector should continue to retry. * @throws ConnectException Operation failed and connector should stop. */ public void commit() throws ConnectException, RetriableException { connectInternal(); try { if (inflight) { inflight = false; if (inperil) { inperil = false; log.trace("Rolling back in-flight transaction"); jmsCtxt.rollback(); throw new RetriableException("Transaction rolled back"); } else { jmsCtxt.commit(); } } } catch (JMSRuntimeException jmse) { log.debug("JMS exception {}", jmse); handleException(jmse); } }
/** * Internal method to connect to MQ. * * @throws RetriableException Operation failed, but connector should continue to retry. * @throws ConnectException Operation failed and connector should stop. */ private void connectInternal() throws ConnectException, RetriableException { if (connected) { return; } if (closeNow.get()) { throw new ConnectException("Connection closing"); } try { if (userName != null) { jmsCtxt = mqConnFactory.createContext(userName, password, JMSContext.SESSION_TRANSACTED); } else { jmsCtxt = mqConnFactory.createContext(JMSContext.SESSION_TRANSACTED); } jmsCons = jmsCtxt.createConsumer(queue); connected = true; } catch (JMSRuntimeException jmse) { log.debug("JMS exception {}", jmse); handleException(jmse); } }
/** * Internal method to close the connection. */ private void closeInternal() { try { inflight = false; inperil = false; connected = false; if (jmsCtxt != null) { jmsCtxt.close(); } } catch (JMSRuntimeException jmse) { ; } finally { jmsCtxt = null; } }
@Test public void testGetAnotherContextFromIt() { JMSContext c2 = context.createContext(Session.DUPS_OK_ACKNOWLEDGE); Assert.assertNotNull(c2); Assert.assertEquals(Session.DUPS_OK_ACKNOWLEDGE, c2.getSessionMode()); Message m2 = c2.createMessage(); Assert.assertNotNull(m2); c2.close(); // should close its session, but not its (shared) connection try { c2.createMessage(); Assert.fail("session should be closed..."); } catch (JMSRuntimeException expected) { // expected } Message m1 = context.createMessage(); Assert.assertNotNull("connection must be open", m1); }
@Test public void sharedNonDurableSubOnDifferentSelector() throws Exception { context = cf.createContext(); try { context.createSharedConsumer(topic1, "mySharedCon", "sel = 'sel1'"); try { context.createSharedConsumer(topic1, "mySharedCon", "sel = 'sel2'"); fail("expected JMSRuntimeException"); } catch (JMSRuntimeException jmse) { //pass } catch (Exception e) { fail("threw wrong exception expected JMSRuntimeException got " + e); } } finally { context.close(); } }
@Test public void sharedNonDurableSubOnDifferentSelectorSrcFilterNull() throws Exception { context = cf.createContext(); try { context.createSharedConsumer(topic1, "mySharedCon"); try { context.createSharedConsumer(topic1, "mySharedCon", "sel = 'sel2'"); fail("expected JMSRuntimeException"); } catch (JMSRuntimeException jmse) { //pass } catch (Exception e) { fail("threw wrong exception expected JMSRuntimeException got " + e); } } finally { context.close(); } }
@Test public void sharedNonDurableSubOnDifferentSelectorTargetFilterNull() throws Exception { context = cf.createContext(); try { context.createSharedConsumer(topic1, "mySharedCon", "sel = 'sel1'"); try { context.createSharedConsumer(topic1, "mySharedCon"); fail("expected JMSRuntimeException"); } catch (JMSRuntimeException jmse) { //pass } catch (Exception e) { fail("threw wrong exception expected JMSRuntimeException got " + e); } } finally { context.close(); } }
@Test public void sharedDurableSubOnDifferentTopic() throws Exception { context = cf.createContext(); try { context.createSharedDurableConsumer(topic1, "mySharedCon"); try { context.createSharedDurableConsumer(topic2, "mySharedCon"); fail("expected JMSRuntimeException"); } catch (JMSRuntimeException jmse) { //pass } catch (Exception e) { fail("threw wrong exception expected JMSRuntimeException got " + e); } } finally { context.close(); } }
@Test public void sharedDurableSubOnDifferentSelector() throws Exception { context = cf.createContext(); try { context.createSharedDurableConsumer(topic1, "mySharedCon", "sel = 'sel1'"); try { context.createSharedDurableConsumer(topic1, "mySharedCon", "sel = 'sel2'"); fail("expected JMSRuntimeException"); } catch (JMSRuntimeException jmse) { //pass } catch (Exception e) { fail("threw wrong exception expected JMSRuntimeException got " + e); } } finally { context.close(); } }
@Test public void sharedDurableSubOnDifferentSelectorSrcFilterNull() throws Exception { context = cf.createContext(); try { context.createSharedDurableConsumer(topic1, "mySharedCon"); try { context.createSharedDurableConsumer(topic1, "mySharedCon", "sel = 'sel2'"); fail("expected JMSRuntimeException"); } catch (JMSRuntimeException jmse) { //pass } catch (Exception e) { fail("threw wrong exception expected JMSRuntimeException got " + e); } } finally { context.close(); } }
@Test public void sharedDurableSubOnDifferentSelectorTargetFilterNull() throws Exception { context = cf.createContext(); try { context.createSharedDurableConsumer(topic1, "mySharedCon", "sel = 'sel1'"); try { context.createSharedDurableConsumer(topic1, "mySharedCon"); fail("expected JMSRuntimeException"); } catch (JMSRuntimeException jmse) { //pass } catch (Exception e) { fail("threw wrong exception expected JMSRuntimeException got " + e); } } finally { context.close(); } }
@Override public Set<String> getPropertyNames() { try { Set<SimpleString> simplePropNames = properties.getPropertyNames(); Set<String> propNames = new HashSet<>(simplePropNames.size()); for (SimpleString str : simplePropNames) { propNames.add(str.toString()); } return propNames; } catch (ActiveMQPropertyConversionException ce) { throw new MessageFormatRuntimeException(ce.getMessage()); } catch (RuntimeException e) { throw new JMSRuntimeException(e.getMessage()); } }
@Override public JMSContext createContext(int sessionMode) { switch (sessionMode) { case Session.AUTO_ACKNOWLEDGE: case Session.CLIENT_ACKNOWLEDGE: case Session.DUPS_OK_ACKNOWLEDGE: case Session.SESSION_TRANSACTED: case ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE: case ActiveMQJMSConstants.PRE_ACKNOWLEDGE: break; default: throw new JMSRuntimeException("Invalid ackmode: " + sessionMode); } refCounter.increment(); return new ActiveMQJMSContext(this, sessionMode, threadAwareContext); }
public JMSContextMock(ConnectionFactory factory, String clientId, boolean transacted, int acknowledgeMode) { try { connection = factory.createConnection(); clientId = clientId == null ? null : clientId.trim(); if (clientId != null && !clientId.isEmpty()) { connection.setClientID(clientId); } connection.start(); final ThreadLocal<Session> ls = new SessionThreadLocal(transacted, acknowledgeMode, connection); Class<?>[] sType = {Session.class}; ClassLoader cl = context(); session = (Session) newProxyInstance(cl, sType, (proxy, method, args) -> method.invoke(ls.get(), args)); } catch (JMSException e) { throw new JMSRuntimeException(e.getLocalizedMessage(), e.getErrorCode(), e); } }
public void sendGuestEvent(Guest guest) { if (null == jmsContext || null == guestEventQueue) { LOGGER.log(WARNING, () -> "Sending messages is deactivated!"); return; } LOGGER.info(() -> format("Sending info about %s to %s", guest, guestEventQueue)); try { StringWriter w = new StringWriter(); JAXB.marshal(guest, w); TextMessage textMessage = this.jmsContext.createTextMessage(w.toString()); this.jmsContext.createProducer().send(this.guestEventQueue, textMessage); } catch (JMSRuntimeException e) { LOGGER.log(SEVERE, e, () -> "Cannot send message due to technical reasons!"); } }
private String getSharedDurableSubLinkName(String subscriptionName, JmsConsumerInfo consumerInfo) { JmsDestination topic = consumerInfo.getDestination(); String selector = consumerInfo.getSelector(); SubDetails subDetails = null; if(sharedDurableSubs.containsKey(subscriptionName)) { subDetails = sharedDurableSubs.get(subscriptionName); if(subDetails.matches(topic, selector)){ subDetails.addSubscriber(consumerInfo); } else { throw new JMSRuntimeException("Subscription details dont match existing subscriber."); } } else { subDetails = new SubDetails(topic, selector, consumerInfo); } sharedDurableSubs.put(subscriptionName, subDetails); int count = subDetails.totalSubscriberCount(); return getDurableSubscriptionLinkName(subscriptionName, consumerInfo.isExplicitClientID(), count); }
protected int getSessionAcknowledgeMode(boolean transacted, int acknowledgeMode) throws JMSException { int result = acknowledgeMode; if (!transacted && acknowledgeMode == Session.SESSION_TRANSACTED) { throw new JMSException("acknowledgeMode SESSION_TRANSACTED cannot be used for an non-transacted Session"); } if (transacted) { result = Session.SESSION_TRANSACTED; } else { try { JmsSession.validateSessionMode(acknowledgeMode); } catch (JMSRuntimeException jmsre) { throw new JMSException("acknowledgeMode " + acknowledgeMode + " cannot be used for an non-transacted Session"); } } return result; }
@Test public void testReserveNextSubscriptionLinkNameSharedDurableWithNonMatchingTopic() { String topicName = "myTopic"; String subscriptionName1 = "mySubscription1"; AmqpSubscriptionTracker tracker = new AmqpSubscriptionTracker(); // For the first shared sub name on Topic JmsConsumerInfo sub1consumer1 = createConsumerInfo(subscriptionName1, topicName, true, true, true); assertEquals("Unexpected first sub link name", subscriptionName1, tracker.reserveNextSubscriptionLinkName(subscriptionName1, sub1consumer1)); // For the next shared sub name on different Topic JmsConsumerInfo sub1consumer2 = createConsumerInfo(subscriptionName1, topicName + "-Alt", true, true, true); try { tracker.reserveNextSubscriptionLinkName(subscriptionName1, sub1consumer2); fail("Expected JMSRuntimeException when Topic doesn't match previous subscription"); } catch (JMSRuntimeException jmsre) { } }
@Test public void testReserveNextSubscriptionLinkNameSharedVolatileWithNonMatchingTopic() { String topicName = "myTopic"; String subscriptionName1 = "mySubscription1"; AmqpSubscriptionTracker tracker = new AmqpSubscriptionTracker(); // For the first shared sub name with Topic JmsConsumerInfo sub1consumer1 = createConsumerInfo(subscriptionName1, topicName, true, false, true); assertEquals("Unexpected first sub link name", subscriptionName1 + SUB_NAME_DELIMITER + "volatile1", tracker.reserveNextSubscriptionLinkName(subscriptionName1, sub1consumer1)); // For the next shared sub name with different Topic JmsConsumerInfo sub1consumer2 = createConsumerInfo(subscriptionName1, topicName + "-alt", true, false, true); try { tracker.reserveNextSubscriptionLinkName(subscriptionName1, sub1consumer2); fail("Expected JMSRuntimeException when Topic doesn't match previous subscription"); } catch (JMSRuntimeException jmsre) { } }
/** * Displays the message text. * * @param message the incoming message */ @Override public void onMessage(Message m) { long i; try { if (m instanceof TextMessage) { i = count.incrementAndGet(); // Comment out the following line to receive many messages System.out.println("Reading message: " + m.getBody(String.class)); } else { System.out.println("Message is not a TextMessage"); } } catch (JMSException | JMSRuntimeException e) { System.err.println("JMSException in onMessage(): " + e.toString()); } }
@PreDestroy private void destroy() { if (contexts != null) { JMSRuntimeException jre = null; for (final JMSContext c : contexts.values()) { try { c.close(); } catch (final JMSRuntimeException e) { jre = e; } } if (jre != null) { throw jre; } } }
private ConnectionFactory connectionFactory() { if (connectionFactoryInstance != null) { return connectionFactoryInstance; } synchronized (this) { if (connectionFactoryInstance != null) { return connectionFactoryInstance; } try { return connectionFactoryInstance = ConnectionFactory.class.cast( SystemInstance.get().getComponent(ContainerSystem.class).getJNDIContext() .lookup(connectionFactory)); } catch (final NamingException e) { throw new JMSRuntimeException(e.getMessage(), null, e); } } }
private void validateSessionMode(int mode) { switch (mode) { case JMSContext.SESSION_TRANSACTED: case JMSContext.AUTO_ACKNOWLEDGE: case JMSContext.CLIENT_ACKNOWLEDGE: case JMSContext.DUPS_OK_ACKNOWLEDGE: return; default: throw new JMSRuntimeException("Invalid Session Mode: " + mode); } }
public void checkClientJMSVersionSupport(int requiredMajor, int requiredMinor, boolean runtimeEx) throws JMSException { if (jmsMajorVersion >= requiredMajor && jmsMinorVersion >= requiredMinor) { return; } String message = "JMS v" + requiredMajor + "." + requiredMinor + " client feature requested, " + "configured client supports JMS v" + jmsMajorVersion + "." + jmsMinorVersion; if (runtimeEx) { throw new JMSRuntimeException(message); } else { throw new JMSException(message); } }
@Override public JMSProducer setDeliveryMode(int deliveryMode) { switch (deliveryMode) { case DeliveryMode.PERSISTENT: case DeliveryMode.NON_PERSISTENT: this.deliveryMode = deliveryMode; return this; default: throw new JMSRuntimeException(String.format("Invalid DeliveryMode specified: %d", deliveryMode)); } }
@Override public JMSProducer setPriority(int priority) { if (priority < 0 || priority > 9) { throw new JMSRuntimeException(String.format("Priority value given {%d} is out of range (0..9)", priority)); } this.priority = priority; return this; }
public MessageProducer getMessageProducer() throws JMSRuntimeException { try { return producer.getMessageProducer(); } catch (JMSException jmsex) { throw JMSExceptionSupport.createRuntimeException(jmsex); } }
@Test public void testDeliveryDelay() { JMSProducer producer = context.createProducer(); assertEquals(0, producer.getDeliveryDelay()); try { producer.setDeliveryDelay(2000); fail("Pool JMSProducer can't modify shared session delay mode."); } catch (JMSRuntimeException jmsre) { } }
static void validateSessionMode(int mode) { switch (mode) { case JMSContext.AUTO_ACKNOWLEDGE: case JMSContext.CLIENT_ACKNOWLEDGE: case JMSContext.DUPS_OK_ACKNOWLEDGE: case JMSContext.SESSION_TRANSACTED: return; default: throw new JMSRuntimeException("Invalid Session Mode: " + mode); } }
@Test(timeout = 30000) public void testGetMetaData() { JMSContext context = cf.createContext(); assertNotNull(context.getMetaData()); context.close(); try { context.getMetaData(); fail("Should not be able to get MetaData from closed."); } catch (JMSRuntimeException jmsre) {} }
@Test(timeout = 30000) public void testGetClientID() { JMSContext context = cf.createContext(); assertNotNull(context.getClientID()); context.close(); try { context.getClientID(); fail("Should not be able to get ClientID from closed."); } catch (JMSRuntimeException jmsre) {} }
@Test(timeout = 30000) public void testGetConnectionAfterClosed() { JmsPoolJMSContext context = (JmsPoolJMSContext) cf.createContext(); assertNotNull(context.getConnection()); context.close(); try { context.getConnection(); fail("Should not be able to get connection from closed."); } catch (JMSRuntimeException jmsre) {} }