Sunday, March 4, 2007

Standalone EJB 3.0 client for remote EJB server

In order for a client to connect to your remote GlassFish server you need to add a second IIOP listener with the hostname listening at a different port (ex: 3701). You can do this via the GlassFish admin console.

Create a Java project in Eclipse that will be a standalone EJB 3.0 client application.

When deploying the previously created EJB jar on glassfish using the admin console check the option that creates the client .jar file. Then locate the *Client.jar file on the server and make your project depend on this jar.

Your client app should have code similar to below:

public class Client {

@SuppressWarnings("unchecked")
public void runTest() throws Exception {
Properties props = new Properties();

props.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("org.omg.CORBA.ORBInitialHost", "");
// NOTE: IIOP is set on port 3701 but this works on port 3700
props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");

InitialContext ctx = new InitialContext(props);

OrderBean bean = (OrderBean) ctx.lookup("ejb/OrderBean");

Order result = bean.findByOrderNum(9);
System.out.println(result.getDescript());
}

public static void main(String[] args) {
Client cli = new Client();
try {
cli.runTest();
} catch (Exception e) {
e.printStackTrace();
}
}
}

EJB 3.0 + Glassfish + JPA + Eclipse

Follow instructions here to create the EJB project in eclipse.

http://www.webagesolutions.com/knowledgebase/javakb/jkb005/index.html

Create the jdbc connection pool and the corresponding resource via the GlassFish admin console.

Now create a persistence.xml fiel in the src/META-INF folder in your project to point to the JDBC resource.

<persistence>
<persistence-unit name=\"myPU\">
<jta-data-source>jdbc/MyDB</jta-data-source>
<properties>
<property name=\"toplink.logging.level\" value=\"FINEST\" />
</properties>
</persistence-unit>
</persistence>

In the bean implementation class use

@PersistenceContext(unitName = "myPU")
protected EntityManager em;

to inject the EntityManager. Change the unitName value to your persistence definition in the persistence.xml.

The exported jar file can be deployed into either the local or a remote glassfish instance.

Stay tuned for the next post on writing a standalone client to access this ejb.