javax.jms.XAConnection Java Examples

The following examples show how to use javax.jms.XAConnection. 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: ActiveMQJMSContext.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 *
 */
private void checkSession() {
   if (session == null) {
      synchronized (this) {
         if (closed)
            throw new IllegalStateRuntimeException("Context is closed");
         if (session == null) {
            try {
               if (xa) {
                  session = ((XAConnection) connection).createXASession();
               } else {
                  session = connection.createSession(sessionMode);
               }
            } catch (JMSException e) {
               throw JmsExceptionUtils.convertToRuntimeException(e);
            }
         }
      }
   }
}
 
Example #2
Source File: ActiveMQXAConnectionFactoryTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testRollbackXaErrorCode() throws Exception {
   String brokerName = "rollbackErrorCode";
   BrokerService broker = BrokerFactory.createBroker(new URI("broker:(tcp://localhost:0)/" + brokerName));
   broker.start();
   broker.waitUntilStarted();
   ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri());
   XAConnection connection = (XAConnection) cf.createConnection();
   connection.start();
   XASession session = connection.createXASession();
   XAResource resource = session.getXAResource();

   Xid tid = createXid();
   try {
      resource.rollback(tid);
      fail("Expected xa exception on no tx");
   } catch (XAException expected) {
      LOG.info("got expected xa", expected);
      assertEquals("no tx", XAException.XAER_NOTA, expected.errorCode);
   }
   connection.close();
   broker.stop();
}
 
Example #3
Source File: XATest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsSamRM() throws Exception {
   XAConnection conn = null;

   conn = xacf.createXAConnection();

   // Create a session
   XASession sess1 = conn.createXASession();
   XAResource res1 = sess1.getXAResource();

   // Create a session
   XASession sess2 = conn.createXASession();
   XAResource res2 = sess2.getXAResource();

   Assert.assertTrue(res1.isSameRM(res2));
}
 
Example #4
Source File: JMSContextImpl.java    From tomee with Apache License 2.0 6 votes vote down vote up
protected Session session() {
    if (session == null) {
        synchronized (this) {
            if (closed) {
                throw new IllegalStateRuntimeException("Context is closed");
            }
            if (session == null) {
                try {
                    Connection connection = connection();
                    if (xa) {
                        session = XAConnection.class.cast(connection).createXASession();
                    } else {
                        session = connection.createSession(sessionMode);
                    }
                } catch (final JMSException e) {
                    throw toRuntimeException(e);
                }
            }
        }
    }
    return session;
}
 
Example #5
Source File: SimpleOpenWireTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testXAResourceCommittedRemoved() throws Exception {
   Queue queue = null;

   Xid xid = newXID();
   try (XAConnection xaconnection = xaFactory.createXAConnection()) {
      XASession session = xaconnection.createXASession();
      queue = session.createQueue(queueName);
      session.getXAResource().start(xid, XAResource.TMNOFLAGS);
      MessageProducer producer = session.createProducer(queue);
      producer.send(session.createTextMessage("xa message"));
      session.getXAResource().end(xid, XAResource.TMSUCCESS);
      session.getXAResource().commit(xid, true);
   }
   XidImpl xid1 = new XidImpl(xid);
   Transaction transaction = server.getResourceManager().getTransaction(xid1);
   assertNull(transaction);
}
 
Example #6
Source File: SimpleOpenWireTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testXAPrepare() throws Exception {
   try {

      XAConnection connection = xaFactory.createXAConnection();

      XASession xasession = connection.createXASession();

      Xid xid = newXID();
      xasession.getXAResource().start(xid, XAResource.TMNOFLAGS);
      Queue queue = xasession.createQueue(queueName);
      MessageProducer producer = xasession.createProducer(queue);
      producer.send(xasession.createTextMessage("hello"));
      producer.send(xasession.createTextMessage("hello"));
      xasession.getXAResource().end(xid, XAResource.TMSUCCESS);

      xasession.getXAResource().prepare(xid);

      connection.close();

      System.err.println("Done!!!");
   } catch (Exception e) {
      e.printStackTrace();
   }
}
 
Example #7
Source File: ConnectionFactoryTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void assertConnectionType(Connection conn, String type) {
   if ("generic".equals(type) || "queue".equals(type) || "topic".equals(type)) {
      //generic
      Assert.assertFalse(conn instanceof XAConnection);
      Assert.assertTrue(conn instanceof QueueConnection);
      Assert.assertFalse(conn instanceof XAQueueConnection);
      Assert.assertTrue(conn instanceof TopicConnection);
      Assert.assertFalse(conn instanceof XATopicConnection);
   } else if ("xa".equals(type) || "xa-queue".equals(type) || "xa-topic".equals(type)) {
      Assert.assertTrue(conn instanceof XAConnection);
      Assert.assertTrue(conn instanceof QueueConnection);
      Assert.assertTrue(conn instanceof XAQueueConnection);
      Assert.assertTrue(conn instanceof TopicConnection);
      Assert.assertTrue(conn instanceof XATopicConnection);
   } else {
      Assert.fail("Unknown connection type: " + type);
   }
}
 
Example #8
Source File: ActiveMQRAConnectionFactoryImpl.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Create a XA connection
 *
 * @param userName The user name
 * @param password The password
 * @return The connection
 * @throws JMSException Thrown if the operation fails
 */
@Override
public XAConnection createXAConnection(final String userName, final String password) throws JMSException {
   if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
      ActiveMQRALogger.LOGGER.trace("createXAConnection(" + userName + ", ****)");
   }

   ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, cm, getResourceAdapter().getTM(), ActiveMQRAConnectionFactory.XA_CONNECTION);
   s.setUserName(userName);
   s.setPassword(password);
   validateUser(s);

   if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
      ActiveMQRALogger.LOGGER.trace("Created connection: " + s);
   }

   return s;
}
 
Example #9
Source File: SessionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetXAResource2() throws Exception {
   XAConnection conn = getXAConnectionFactory().createXAConnection();
   XASession sess = conn.createXASession();

   sess.getXAResource();
   conn.close();
}
 
Example #10
Source File: TibJmsTopicConfig.java    From reladomo with Apache License 2.0 5 votes vote down vote up
protected XAConnection createUnpooledConnection() throws JMSException, NamingException
{
    XAConnection connection = connect();
    String clientId = this.clientIdPrefix + "_" + publisherId.incrementAndGet();
    LOGGER.debug("Setting client id to {} for topic {} on broker {}", clientId, this.getTopicName(), this.brokerUrl);
    connection.setClientID(clientId);
    return connection;
}
 
Example #11
Source File: QueueDistributedTransactionTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublisherWithRollback() throws NamingException, JMSException, XAException, IOException {
    String queueName = "testPublisherWithRollback";
    String testMessage = "testPublisherWithRollback-Message";
    InitialContext initialContext = initialContextBuilder.withXaConnectionFactory()
                                                         .withQueue(queueName)
                                                         .build();

    XAConnectionFactory xaConnectionFactory =
            (XAConnectionFactory) initialContext.lookup(ClientHelper.XA_CONNECTION_FACTORY);

    XAConnection xaConnection = xaConnectionFactory.createXAConnection();
    XASession xaSession = xaConnection.createXASession();
    XAResource xaResource = xaSession.getXAResource();

    Session session = xaSession.getSession();
    Queue queue = session.createQueue(queueName);
    MessageProducer producer = session.createProducer(queue);
    xaConnection.start();

    XidImpl xid = new XidImpl(0, "branchId_1".getBytes(), "globalId_1".getBytes());
    xaResource.start(xid, XAResource.TMNOFLAGS);
    producer.send(session.createTextMessage(testMessage));
    xaResource.end(xid, XAResource.TMSUCCESS);

    int prepareOK = xaResource.prepare(xid);
    Assert.assertEquals(prepareOK, XAResource.XA_OK, "Prepare phase should return XA_OK");

    xaResource.rollback(xid);

    // Check whether the message is published to queue.
    QueueMetadata queueMetadata = restApiClient.getQueueMetadata(queueName);

    Assert.assertEquals((int) queueMetadata.getSize(), 0, "Queue should be empty");

    session.close();
    xaConnection.close();
}
 
Example #12
Source File: TibJmsTopicConfig.java    From reladomo with Apache License 2.0 5 votes vote down vote up
@Override
public XAConnection createConnection() throws JMSException, NamingException
{
    String durableConsumerName = this.getDurableConsumerName();
    if (durableConsumerName != null)
    {
        return createConnectionForDurable(durableConsumerName);
    }
    if (usePooling)
    {
        return getOrCreatePooledConnection();
    }
    return createUnpooledConnection();
}
 
Example #13
Source File: TibJmsTopicConfig.java    From reladomo with Apache License 2.0 5 votes vote down vote up
protected XAConnection getOrCreatePooledConnection() throws JMSException, NamingException
{
    if (this.assignedPostfix < 0)
    {
        this.assignedPostfix = publisherId.get();
    }
    XaConnnectionKey key = makeConnectionKey();
    synchronized (pool)
    {
        RefCountedJmsXaConnection connection = pool.get(key);
        if (connection == null)
        {
            XAConnection underlying = connect();
            String clientId = this.clientIdPrefix + "_" + this.assignedPostfix + "_" + forcedConnectionCounter.incrementAndGet();
            LOGGER.info("Pooled publisher connection to broker {} for user {} with client id {}", this.brokerUrl, this.getUserName(), clientId);
            underlying.setClientID(clientId);

            connection = new RefCountedJmsXaConnection(underlying);
            pool.put(key, connection);
        }
        else
        {
            connection.incrementCount();
        }
        return connection;
    }
}
 
Example #14
Source File: TibJmsTopicConfig.java    From reladomo with Apache License 2.0 5 votes vote down vote up
protected XAConnection createConnectionForDurable(String durableConsumerName) throws JMSException, NamingException
{
    XAConnection connection = connect();
    LOGGER.debug("Setting client id to {} for topic {} on broker {}", durableConsumerName, this.getTopicName(), this.brokerUrl);
    connection.setClientID(durableConsumerName);
    return connection;
}
 
Example #15
Source File: ActiveMQRAConnectionFactoryImpl.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Create a XA connection
 *
 * @return The connection
 * @throws JMSException Thrown if the operation fails
 */
@Override
public XAConnection createXAConnection() throws JMSException {
   if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
      ActiveMQRALogger.LOGGER.trace("createXAConnection()");
   }

   ActiveMQRASessionFactoryImpl s = new ActiveMQRASessionFactoryImpl(mcf, cm, getResourceAdapter().getTM(), ActiveMQRAConnectionFactory.XA_CONNECTION);

   if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
      ActiveMQRALogger.LOGGER.trace("Created connection: " + s);
   }

   return s;
}
 
Example #16
Source File: JmsPoolXAConnectionFactory.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Override
protected XAConnection createProviderConnection(PooledConnectionKey key) throws JMSException {
    if (connectionFactory instanceof XAConnectionFactory) {
        if (key.getUserName() == null && key.getPassword() == null) {
            return ((XAConnectionFactory) connectionFactory).createXAConnection();
        } else {
            return ((XAConnectionFactory) connectionFactory).createXAConnection(key.getUserName(), key.getPassword());
        }
    } else {
        throw new IllegalStateException("connectionFactory should implement javax.jms.XAConnectionFactory");
    }
}
 
Example #17
Source File: TomEEManagedConnectionProxy.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public XASession createXASession() throws JMSException {
    XASession session = ((XAConnection) connection.getPhysicalConnection()).createXASession();
    try {
        OpenEJB.getTransactionManager().getTransaction().enlistResource(session.getXAResource());
    } catch (IllegalStateException | SystemException | RollbackException e) {
        throw new RuntimeException(e);
    }
    return session;
}
 
Example #18
Source File: SessionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSession2() throws Exception {
   deployConnectionFactory(0, JMSFactoryType.CF, "ConnectionFactory", "/ConnectionFactory");
   XAConnection conn = getXAConnectionFactory().createXAConnection();
   XASession sess = conn.createXASession();

   sess.getSession();
   conn.close();
}
 
Example #19
Source File: DtxPrepareNegativeTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if preparing a DTX branch after setting fail flag in dtx.end throws an exception
 */
@Test(groups = { "wso2.mb", "dtx" }, expectedExceptions = XAException.class)
public void prepareDtxBranchAfterEndFails()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "DtxPrepareTestCasePrepareDtxBranchAfterEndFails";

    InitialContext initialContext = JMSClientHelper
            .createInitialContextBuilder("admin", "admin", "localhost", getAMQPPort())
            .withQueue(queueName)
            .build();

    // Publish to queue and rollback
    XAConnectionFactory connectionFactory = (XAConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_XA_CONNECTION_FACTORY);

    XAConnection xaConnection = connectionFactory.createXAConnection();
    xaConnection.start();
    XASession xaSession = xaConnection.createXASession();

    XAResource xaResource = xaSession.getXAResource();
    Session session = xaSession.getSession();

    Destination xaTestQueue = (Destination) initialContext.lookup(queueName);
    session.createQueue(queueName);
    MessageProducer producer = session.createProducer(xaTestQueue);

    Xid xid = JMSClientHelper.getNewXid();

    // We are not starting the dtx branch
    xaResource.start(xid, XAResource.TMNOFLAGS);
    producer.send(session.createTextMessage("Test 1"));
    xaResource.end(xid, XAResource.TMFAIL);

    xaResource.prepare(xid);

    xaResource.rollback(xid);

    session.close();
    xaConnection.close();
}
 
Example #20
Source File: JmsTracingConfigurationTest.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
static void checkXAConnection(AssertableApplicationContext ctx) throws JMSException {
	// Not using try-with-resources as that doesn't exist in JMS 1.1
	XAConnection con = ctx.getBean(XAConnectionFactory.class).createXAConnection();
	try {
		con.setExceptionListener(exception -> {
		});
		assertThat(con.getExceptionListener().getClass().getName())
				.startsWith("brave.jms.TracingExceptionListener");
	}
	finally {
		con.close();
	}
}
 
Example #21
Source File: AMQXASupportTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void xaCode() throws Exception {
    assertNotNull(xacf);

    final Connection connection = xacf.createXAConnection();
    assertThat(connection, instanceOf(XAConnection.class));
    testConnection(connection);
}
 
Example #22
Source File: FailureXATest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void doTestCrashServerAfterXACommit(boolean onePhase) throws Exception {
   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
   XAConnection connection = connectionFactory.createXAConnection();

   try {
      Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
      Queue queue = session.createQueue("Queue1");
      final XASession xaSession = connection.createXASession();
      MessageConsumer consumer = xaSession.createConsumer(queue);

      MessageProducer producer = session.createProducer(queue);
      producer.send(session.createTextMessage("hello " + 1));
      session.commit();

      XAResource xaResource = xaSession.getXAResource();
      final Xid xid = newXID();
      xaResource.start(xid, XAResource.TMNOFLAGS);

      connection.start();
      Assert.assertNotNull(consumer.receive(5000));

      xaResource.end(xid, XAResource.TMSUCCESS);

      try {
         xaResource.commit(xid, onePhase);
         Assert.fail("didn't get expected exception!");
      } catch (XAException xae) {
         if (onePhase) {
            //expected error code is XAER_RMFAIL
            Assert.assertEquals(XAException.XAER_RMFAIL, xae.errorCode);
         } else {
            //expected error code is XA_RETRY
            Assert.assertEquals(XAException.XA_RETRY, xae.errorCode);
         }
      }
   } finally {
      connection.close();
   }
}
 
Example #23
Source File: ActiveMQXAConnectionFactoryTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testCloseSendConnection() throws Exception {
   String brokerName = "closeSend";
   BrokerService broker = BrokerFactory.createBroker(new URI("broker:(tcp://localhost:0)/" + brokerName));
   broker.start();
   broker.waitUntilStarted();
   ActiveMQXAConnectionFactory cf = new ActiveMQXAConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri());
   XAConnection connection = (XAConnection) cf.createConnection();
   connection.start();
   XASession session = connection.createXASession();
   XAResource resource = session.getXAResource();
   Destination dest = new ActiveMQQueue(getName());

   // publish a message
   Xid tid = createXid();
   resource.start(tid, XAResource.TMNOFLAGS);
   MessageProducer producer = session.createProducer(dest);
   ActiveMQTextMessage message = new ActiveMQTextMessage();
   message.setText(getName());
   producer.send(message);

   connection.close();

   //comment out this check as it doesn't apply to artemis
   //assertTransactionGoneFromBroker(tid);

   broker.stop();
}
 
Example #24
Source File: ManagedXAQueueTopicConnection.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
@Override
public XASession createXASession() throws JMSException {

    return addSession( ((XAConnection) connection).createXASession());
}
 
Example #25
Source File: ActiveMQConnectionFactory.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Override
public XAConnection createXAConnection(final String username, final String password) throws JMSException {
   return (XAConnection) createConnectionInternal(username, password, true, ActiveMQConnection.TYPE_GENERIC_CONNECTION);
}
 
Example #26
Source File: TracingXAConnection.java    From brave with Apache License 2.0 4 votes vote down vote up
static TracingXAConnection create(XAConnection delegate, JmsTracing jmsTracing) {
  if (delegate instanceof TracingXAConnection) return (TracingXAConnection) delegate;
  return new TracingXAConnection(delegate, jmsTracing);
}
 
Example #27
Source File: XATest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void test2PCSendFailOnPrepare() throws Exception {
   XAConnection conn = null;
   Connection conn2 = null;
   try {
      conn = xacf.createXAConnection();

      tm.begin();

      XASession sess = conn.createXASession();
      XAResource res = sess.getXAResource();

      // prevent 1Pc optimisation
      // res.setForceNotSameRM(true);

      XAResource res2 = new DummyXAResource(true);
      XAResource res3 = new DummyXAResource();
      XAResource res4 = new DummyXAResource();

      Transaction tx = tm.getTransaction();
      tx.enlistResource(res);
      tx.enlistResource(res2);
      tx.enlistResource(res3);
      tx.enlistResource(res4);

      MessageProducer prod = sess.createProducer(null);
      prod.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
      Message m = sess.createTextMessage("XATest1");
      prod.send(queue1, m);
      m = sess.createTextMessage("XATest2");
      prod.send(queue1, m);

      tx.delistResource(res, XAResource.TMSUCCESS);
      tx.delistResource(res2, XAResource.TMSUCCESS);
      tx.delistResource(res3, XAResource.TMSUCCESS);
      tx.delistResource(res4, XAResource.TMSUCCESS);

      try {
         tm.commit();

         Assert.fail("should not get here");
      } catch (Exception e) {
         // We should expect this
      }

      conn2 = cf.createConnection();
      conn2.start();
      Session sessReceiver = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer cons = sessReceiver.createConsumer(queue1);
      Message m2 = cons.receive(100);
      Assert.assertNull(m2);
   } finally {
      if (conn != null) {
         conn.close();
      }
      if (conn2 != null) {
         conn2.close();
      }
   }
}
 
Example #28
Source File: TracingXAConnectionFactory.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override public XAConnection createXAConnection() throws JMSException {
  XAConnectionFactory xacf = (XAConnectionFactory) delegate;
  return TracingXAConnection.create(xacf.createXAConnection(), jmsTracing);
}
 
Example #29
Source File: QueueDistributedTransactionTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Test
public void testPublisherWithCommit() throws NamingException, JMSException, XAException {

    String queueName = "testPublisherWithCommit";
    String testMessage = "testPublisherWithCommit-Message";
    InitialContext initialContext = initialContextBuilder.withXaConnectionFactory()
                                                         .withQueue(queueName)
                                                         .build();

    XAConnectionFactory xaConnectionFactory =
            (XAConnectionFactory) initialContext.lookup(ClientHelper.XA_CONNECTION_FACTORY);

    XAConnection xaConnection = xaConnectionFactory.createXAConnection();
    XASession xaSession = xaConnection.createXASession();
    XAResource xaResource = xaSession.getXAResource();

    Session session = xaSession.getSession();
    Queue queue = session.createQueue(queueName);
    MessageProducer producer = session.createProducer(queue);
    xaConnection.start();

    XidImpl xid = new XidImpl(0, "branchId_1".getBytes(), "globalId_1".getBytes());
    xaResource.start(xid, XAResource.TMNOFLAGS);
    producer.send(session.createTextMessage(testMessage));
    xaResource.end(xid, XAResource.TMSUCCESS);

    int prepareOK = xaResource.prepare(xid);
    Assert.assertEquals(prepareOK, XAResource.XA_OK, "Prepare phase should return XA_OK");

    xaResource.commit(xid, false);

    // Test by consuming the committed message.
    ConnectionFactory connectionFactory =
            (ConnectionFactory) initialContext.lookup(ClientHelper.XA_CONNECTION_FACTORY);
    Connection connection = connectionFactory.createConnection();
    Session receivingSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = receivingSession.createConsumer(receivingSession.createQueue(queueName));
    connection.start();
    TextMessage message = (TextMessage) consumer.receive(3000);

    Assert.assertNotNull(message, "Didn't receive a message");
    Assert.assertEquals(message.getText(), testMessage, "Received message should match sent message");

    session.close();
    xaConnection.close();
    connection.close();
}
 
Example #30
Source File: TracingConnectionFactoryBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
@Override
public XAConnection createXAConnection(String s, String s1) throws JMSException {
	return wrappedDelegate().createXAConnection(s, s1);
}