How to get Remote EJB UserTransaction in JBoss EAP 8+ / 7.1+

Solution Verified - Updated

Environment

  • Red Hat JBoss Enterprise Application Platform (EAP)
    • 8.x
    • 7.4
    • 7.3
    • 7.2
    • 7.1

Issue

  • Get Remote EJB UserTransaction in JBoss EAP 8 and later
  • Get Remote EJB UserTransaction in JBoss EAP 7.1 and later

Resolution

Getting UserTransaction from a remote EAP

public void callRemoteEjb() {
   // Note: the UserTransaction and EJB Proxy must be looked up from the same Context, otherwise you will get an error such as: WFTXN0069: Connection does not match the transaction
   Context ctx = new getInitialContext(host, port, user, pass);
   UserTransaction utx = (UserTransaction) ctx.lookup("txn:UserTransaction");
   utx.setTransactionTimeout(5); // set transaction timeout to 5 seconds
   HelloRemote remote = (HelloRemote) ctx.lookup("ejb:helloWorld/helloWorld-ejb/HelloWorldSLSB!org.jboss.examples.ejb.HelloRemote");
   utx.begin():
   remote.helloWorld();
   ...
   utx.commit();
}
public static Context getInitialContext(String host, Integer port, String username, String password) {
   Properties props = new Properties();
   props.put(Context.INITIAL_CONTEXT_FACTORY,  "org.wildfly.naming.client.WildFlyInitialContextFactory");
   props.put(Context.PROVIDER_URL, String.format("%s://%s:%d", "remote+http", host, port));
   props.put(Context.SECURITY_PRINCIPAL, username)
   props.put(Context.SECURITY_CREDENTIALS, password);
   return new InitialContext(props);
}

Getting UserTransaction when the client is in EAP

Local UserTransaction can be looked up such as:

UserTransaction utx = new InitialContext().lookup("java:comp/UserTransaction");

Or injected such as

@Resource UserTransaction utx;

Related Solutions

Components
Category

This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.