EJB ClientsEJB ClientsUnit – III
Middleware Technologiesg
Roy Antony Arnold GLecturer
P i l E i i C llPanimalar Engineering CollegeChennai, Tamilnadu, India
TopicsTopics
EJB Bean as a Client to Another BeanEJB Bean as a Client to Another BeanSerializing a HandleTransactions in ClientsTransactions in ClientsAuthentication in ClientsG tti M t D tGetting Meta DataServlet ClientApplet ClientCORBA Client
An EJB Bean as a Client to Another BeanEJB Client Bean
import ….;public class ClientBean implements SessionBean{ SessionContext ctx;{ SessionContext ctx;
public void ejbCreate() { }public void run() {
try { Properties p = new Properties();p put(Context INITIAL CONTEXT FACTORY “weblogic jndi TengahInitialContextFactory”);p.put(Context.INITIAL_CONTEXT_FACTORY, weblogic.jndi.TengahInitialContextFactory );
InitialContext ic = new InitialContext(p);OrderHome oh = (OrderHome) ic.lookup(“OrderHome”);Order o1 = oh.create(1, “1”, 1);Order o2 = oh create(1 “2” 1);Order o2 oh.create(1, 2 , 1);o1.remove();o2.remove();catch(NamingException e) { } catch (CreateExeception e) {}catch(RemoveException e) {} catch (RemoteException e) {}catch(RemoveException e) {} catch (RemoteException e) {}}
public void setSessionContext (SessionContext ctx) { this.ctx = ctx; }public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate{}
}}
Environment PropertiesEnvironment Properties
To define an environment property twoTo define an environment property, two options available
Deployment Descriptor can be usedDeployment Descriptor can be usedNew Properties Object in the Client can be created and can be passed it to thecreated and can be passed it to the InitialContext Constructor
The ClientThe Clientimport javax.naming.InitialContext;
bli l Cli tCli t {public class ClientClient {public static void main(String[] args) throws Exception {
InitialContext ic = new InitialContext();ClientHome ch = (ClientHome) ic.lookup(“ClientHome”);( ) p( );Client c = ch.create();c.run();c.remove();System out println(“Client is done”);System.out.println( Client is done );
}}Command-line parameter to define the initial naming factory can be used.For Example:
java –Djava.naming.factory.initial=weblogic.jndi. T3InitialContextFactory ClientClient
TopicsTopics
EJB Bean as a Client to Another BeanEJB Bean as a Client to Another BeanSerializing a HandleTransactions in ClientsTransactions in ClientsAuthentication in ClientsG tti M t D tGetting Meta DataServlet ClientApplet ClientCORBA Client
Serializing a HandleSerializing a Handle
A handle is a serializable reference to a bean; i.e. you bt i h dl f b ’ t i t f itcan obtain a handle from a bean’s remote interface, write
it out to persistent storage, and then close the program down.At l t ti d i d it t bt iAt some later time, you can read in and use it to obtain a new reference to a remote bean.This mechanism allows to serialize a remote reference to the bean but not to recreate the bean itselfthe bean – but not to recreate the bean itself.The server-side object must still exist when attempting to reobtain the reference otherwise “NoSuchObjectException” will be thrown by the handleNoSuchObjectException will be thrown by the handle. The bean’s create() or find() method can be invoked to know about the existence of the object in the container.
The ClientThe Client
If the client is called with the command-lineIf the client is called with the command line argument of “write”, it obtains a reference to an Order bean, obtains a handle to the reference and writes the handle to a file.If it is called with the command-line argument of “read”, it reads the handle back in from the file, reobtains the remote reference, and uses this reference to finish its workreference to finish its work.
beginWork()beginWork()static void beginWork() {
try {
1. Creating an initial naming context
2. Using the naming t t t l ktry {
InitialContext ic = new InitialContext();System.out.println(“looked up initial context”);OrderHome oh = (OrderHome) ic.lookup(“OrderHome”);Order o1 = oh create(1 “1” 1);
context to look up the home interface
3. Using the home interface to create a bOrder o1 = oh.create(1, 1 ,1);
myHandle = o1.getHandle();}catch (CreateException e) {
System out println(“CreateException occurred:” + e);
bean.
Obtains a handle and t it i thSystem.out.println( CreateException occurred: + e);
}catch (RemoteException e) {
System.out.println(“RemoteException occurred:” + e);}
stores it in the myHandle static class variable.The writeHandle
th d l t thi}catch (NamingException e) {
System.out.println(“NamingException occurred:” + e);}
}
method later uses this value to write the object out to persistent storage.
}
writeHandlewriteHandle
static void writeHandle() {{try {
FileOutputStream fos = new FileOutputStream (“beanhandle.ser”);
ObjectOutputStream oos = new ObjectOutputStream(fos);ObjectOutputStream oos = new ObjectOutputStream(fos);oos.writeObject(myHandle);oos.flush();oos.close();();
}catch (IOException e) {
System.out.println(“Exception occurred in writeHandle: “ + e);}
}
readHandle()readHandle()
static void readHandle(){{
try {FileInputStream fis = new FileInputStream (“beanhandle.ser”);ObjectInputStream ois = new ObjectInputStream (fis);ObjectInputStream ois = new ObjectInputStream (fis);myHandle = (Handle) ois.readObject();ois.close();
}}catch (Exception e) {
System.out.println(“Exception occurred in readHandle:” + e);}}
finishWork()finishWork()static void finishWork() {
try {try {System.out.println(“Using handle to obtain reference”);Order o1 = (Order) myHandle.getEJBObject();System.out.println(“removing”);o1.remove();
}catch(RemoteException e) {
System out println(“RemoteException Occurred:” + e);System.out.println( RemoteException Occurred: + e);e.printStackTrace();
}catch (RemoveException e) {
System.out.println(“RemoveException occurred” + e);e.printStackTrace();
}}}
Contd…Contd…
myHandle is a static variable of Handle type.Classes in the java.io package is used to store and retrieve the handle.If “read” or “write” is found on the command line, the routine invokes the appropriate procedures.Invoking the clientsto write out a serialized handleto write out a serialized handlejava –Djava.naming.factory.initial=weblogic.jndi. T3InitialContextFactory HandleClient write
to read the handle back in and finish working with itjava –Djava.naming.factory.initial=weblogic.jndi. T3InitialContextFactory HandleClient readT3InitialContextFactory HandleClient read
TopicsTopics
EJB Bean as a Client to Another BeanEJB Bean as a Client to Another BeanSerializing a HandleTransactions in ClientsTransactions in ClientsAuthentication in ClientsG tti M t D tGetting Meta DataServlet ClientApplet ClientCORBA Client
Transactions in ClientsTransactions in Clients
A client can create its own transaction context and use it to manage transactions across multiple invocations.
javax.jts.UserTransaction interface is imported. This is part of the Java Transaction Services (JTS) Specification.Specification.
import ….public class ClientTx {
bli t ti id i (St i [] ) {public static void main(String[] argv) {UserTransaction utx = null;try {
InitialContext ic = new InitialContext();InitialContext ic = new InitialContext();OrderHome oh = (OrderHome) ic.lookup(“OrderHome”);
utx = (UserTransaction) ic.lookup (“javax.jts.UserTransaction”);utx.begin();utx.begin();Order o1 = oh.create(1, “1”, 1);Order o2 = oh.create(1, “2”, 1);utx.commit(); // or utx.rollback();() ()
}catch (CreateException e) {
if(utx!=null) { utx.rollback();} }catch (RemoteException e) {
if(utx!=null) { utx.rollback();} }catch (NamingException e) {
if( t ! n ll) { t rollback() } }if(utx!=null) { utx.rollback(); } }}
}
Guidelines for handling exceptions in TXGuidelines for handling exceptions in TX
Throwing a TransactionRolledbackException indicates g pthat the TX has been rolled back and cannot be recovered. So, attempt the TX again from the beginning.If a RemoteException occurs during an TX, the clientIf a RemoteException occurs during an TX, the client should rollback the TX. Recovering from a RemoteException is somewhat dicey. To preserve database consistency it’s best to roll back and startdatabase consistency, it s best to roll back and start over.A RemoteException generally indicates some sort of system level failure (ex: server crash) If thesystem-level failure (ex: server crash). If the RemoteException occurred because of a loss of network connectivity, it may be pointless to attempt to continue work until that problem is fixedwork until that problem is fixed.
TopicsTopics
EJB Bean as a Client to Another BeanEJB Bean as a Client to Another BeanSerializing a HandleTransactions in ClientsTransactions in ClientsAuthentication in ClientsG tti M t D tGetting Meta DataServlet ClientApplet ClientCORBA Client
Authentication in ClientsAuthentication in Clients
The EJB specification does not dictate the mechanism pby which clients are authenticated by the EJB Server
Although it discusses about the ACL, it never specifies exactly how information about a client’s identity is passed from the client to the remote server.passed from the client to the remote server.
import …public class AuthClient {
public static void main(String[] argv) {public static void main(String[] argv) {try {Properties p = new Properties();p.put(Context.INITIAL_CONTEXT_FACTORY, p p (
“weblogic.jndi.T3InitialContextFactory”);p.put(Context.PROVIDER_URL, “t3://localhost:7001”);p.put(Context.SECURITY_PRINCIPAL, “panimalar”);p put(Context SECURITY CREDENTIALS “panimalar”);p.put(Context.SECURITY_CREDENTIALS, “panimalar”);InitialContext ic = new InitialContext(p);OrderHome oh = (OrderHome) ic.lookup(“OrderHome”);UserTransaction utx = (UserTransaction)UserTransaction utx = (UserTransaction)
ic.lookup(“javax.jts.UserTransaction”);utx.begin();Order o1 = oh.create(1, “1”, 1);Order o2 = oh.create(1, “2”, 1);utx.commit(); //or utx.rollback();}
h ()catch ()…..}
TopicsTopics
EJB Bean as a Client to Another BeanEJB Bean as a Client to Another BeanSerializing a HandleTransactions in ClientsTransactions in ClientsAuthentication in ClientsG tti M t D tGetting Meta DataServlet ClientApplet ClientCORBA Client
Getting MetadataGetting Metadata
Some clients may need to obtain metadataSome clients may need to obtain metadataabout the bean.In JDBC, two metadata classes are frequently , q yused:
DatabaseMetaData – allows the client to query for information about database and the sorts of operations that it supports.ResultSetMetaData – allows the client to dynamicallyResultSetMetaData allows the client to dynamically discover metadata about the ResultSet, such as the number of columns that it contains, the name and type of each column ad so fortheach column, ad so forth.
Contd…In EJB, this retrieval takes place via the getEJBMetaData() method provided as part of a bean’s home interface.The container generates getEJBMetaData() method at deployment time.This method will be used by clients that wish to automatically discover information about a bean.Typically, EJB metadata will be used by tool yp y, ybuilders who wish to automatically generat connections among groups of already-installed beans.
import …import.javax.ejb.EJBMetaData;public class Metadata {
public static void main (String[] argv) {try {
InitialContext ic = new InitialContext();System.out.println(“Looked up initial context”);OrderHome oh = (OrderHome) ic.lookup(“OrderHome”);EJBMetaData emd = oh.getEJBMetaData();printMetaData(emd);
}catch(RemoteException e) {
System.out.println(“CreateException occurred: “ + e);}catch (NamingException e) {
System.out.println(“NamingException occurred:” + e);}
}
public static void printMetaData(EJBMetaData emd) {EJBHome eh = emd.getEJBHome();printEJBHomeInterface(eh);Class hi = emd.getHomeInterfaceClass();printClass(hi);Class pk = emd.getPrimaryKeyClass();printClass(pk);boolean isSession = emd.isSession();if(isSession)
System.out.println(“\n\nThe Bean is a Session Bean”);else
System.out.println(“\n\nThe bean is not a Session Bean”);}
public void static printEJBHomeInterface(EJBHome eh) {System.out.println(“\n\nHome Interface: “ + eh);y p ( \ \ );
}
public static void printClass(Class c) {System.out.println(\n\nDisplaying information on class:” + c.getName());Class[] array = c.getInterfaces();System.out.println(“\n Interfaces”);printClassArray(array);array = c.getClasses();System.out.println(“Classes”);printClassArray(array);System.out.println(“Fields”);Field[] f = c.getFields();printFields(f);System.out.println(“Methods”);Method [] m = c.getMethods();printMethods(m);System.out.println(“Constructors”);Constructor [] co = c.getConstructors();printConstructors(co);p ( );
}
public static void printClassArray(Class[] ca)
{
public static void printFields(Field[] fa)
{
System.out.println(“--------------------”);
if(ca.length ==0)
System.out.println(“none”);
l
System.out.println(“--------------------”);
if(fa.length ==0)
System.out.println(“none”);
elseelse
for(int i = 0; i<ca.length; i++)
System.out.println(“:” + ca[i]);
System.out.println(“--------------------”);
else
for(int i = 0; i<fa.length; i++)
System.out.println(“:” + fa[i]);
System.out.println(“--------------------”);System.out.println( );
}
public static void printMethods(Method[] ma)
}
public static void printConstr ctors(Constr ctor [] ca)
{
System.out.println(“--------------------”);
if(ma.length ==0)
S t t i tl (“ ”)
printConstructors(Constructor [] ca)
{
System.out.println(“--------------------”);
if(ca.length ==0)System.out.println(“none”);
else
for(int i = 0; i<ma.length; i++)
System.out.println(“:” + ma[i]);
( g )
System.out.println(“none”);
else
for(int i = 0; i<ca.length; i++)System.out.println( : + ma[i]);
System.out.println(“--------------------”);
}
System.out.println(“:” + ca[i]);
System.out.println(“--------------------”);
}
TopicsTopics
EJB Bean as a Client to Another BeanEJB Bean as a Client to Another BeanSerializing a HandleTransactions in ClientsTransactions in ClientsAuthentication in ClientsG tti M t D tGetting Meta DataServlet ClientApplet ClientCORBA Client
A Servlet ClientServlets are basically Java’s answer to CGI programming.These small programs are invoked by a Web ServerThese small programs are invoked by a Web Server.Selvlets offer several advantages over CGI programs:
Servlets do not require a new process for each invoation; they are finvoked as part of a new thread, which is a considerably lighter-
weight operation in terms of server resources.Servlets have a fairly straightforward interface for input and output. I CGI i i i f lib i h l d h hIn CGI scripting, interface libraries have evolved over the years that make input and output more straightforward, but are not necessarily built into the Web Server.S l t ll t it i J It’ ibl t it CGISevlets allow you to write in Java.It’s possible to write a CGI program using Java, but several hacks are invovled. Servlets are much clearner way to use Java for Server-Side web programming.
Setting up WebLogic ServletsTo install a Servlet in BEA WebXpress WebLogic, add the following line
to your weblogic.properties file:weblogic.httpd.register.ServletClient=book.servlet.ServletClient
This line tells the server several things:The Server should use the alias ServletClient for invovation YouThe Server should use the alias ServletClient for invovation. You can precede this alias with path entries if you wish. For Example, if the class should be invoked as http://localhost:7001/foo/bar/ServletClient, you would say p , y yweblogic.httpd.register.foo.bar.ServletClient = book.servlet.ServletClientWebLogic should use the class book.servlet.ServletClient. This gclass must be installed somewhere in WebLogic’s class path. For example, assuming that a directory called c:\weblogic\classes appears in your class path, you would install the ServletClient class in the directory c:\weblogic\classes\book\servlet
import …import javax.servlet.*;import javax servlet http *;import javax.servlet.http. ;public class ServletClient extends HttpServlet {
OrderHome oh;public void init() {p () {
try {InitialContext ic = new InitialContext();oh = (OrderHome) ic.lookup (“OrderHome”);
}catch (NamingException e) {}catch (RemoteException e) {}
}}
public void service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {PrintWriter out = res.getWriter();int custid = Integer.parseInt(req.getParameter(“custid”));String itemcode = req.getParameter(“itemcode”));int q antit Integer parseInt(req getParameter(“q antit ”))int quantity = Integer.parseInt(req.getParameter(“quantity”));
out.println(“<HTML> <HEAD> <TITLE>”);out.println(“Servlet as an EJB Client Example”);out.println( Servlet as an EJB Client Example );out.println(“</TITLE> </HEAD> “);out.println(“<BODY>”);out.println(“This example illustrates a servlet calling an EJB bean <br>”);try {
Order o1 = oh.create(custid, itemcode, quantity);out.println(“Created bean <br>”);o1 remove();o1.remove();out.println(“Removed bean <br>”);
}catch (Exception e) { }catch (Exception e) { } finally {
out.println(“</BODY>”);out.println(“</HTML”);out.close();
}}
HTML to Make a Call to the Servlet<HTML><HTML><HEAD><TITLE> Servlet as EJB Client </TITLE></HEAD></HEAD><BODY><p> <h1> Servlet as EJB Client </h1>
h<hr>HTTP GET example <br><FORM method=GET action=“http://localhost:7001/ServletClient”>…</FORM>
HTTP POST l bHTTP POST example <br><FORM method=POST action=“http://localhost:7001/ServletClient”>…</FORM>
In the HTTP GET protocol, the input parameters are p , p pstored in an environment variable called QUERY_STRING. In a CGI program, the program itself would decode the values in QUERY STRING; withwould decode the values in QUERY_STRING; with servlets, the servlet environment takes care of the decoding.In the HTTP POST protocol, a CGI program would have to open standard input for reading, read in the parameters and then use themparameters, and then use them.
TopicsTopics
EJB Bean as a Client to Another BeanEJB Bean as a Client to Another BeanSerializing a HandleTransactions in ClientsTransactions in ClientsAuthentication in ClientsG tti M t D tGetting Meta DataServlet ClientApplet ClientCORBA Client
An Applet Clientimport …import java.applet.Applet;public class EJBApplet extends Applet implements Runnable {public class EJBApplet extends Applet implements Runnable {
String message;Thread t;public void init() {public void init() {
message = “Initializing Applet”;}public void doEJBStuff() {p () {
try {Properties p = new Properties();p.put(Context.INITIAL_CONTEXT_FACTORY,
“ bl i j di T hI iti lC t tF t ”)“weblogic.jndi.TengahInitialContextFactory”);p.put(Context.PROVIDER_URL,
“t3://”+getCodeBase().getHost()+ “:7001/”);InitialContext ic = new InitialContext(p);InitialContext ic new InitialContext(p);
message = “looked up initial context”;OrderHome oh = (OrderHome) ic.lookup(“OrderHome”);O de o e o (O de o e) c oo up( O de o e );UserTransaction utx = (UserTransaction) ic.lookup (“javax.jts.UserTransaction”);utx.begin();Order o1 = oh.create(1,”1”,1);Order o1 oh.create(1, 1 ,1);Order o2 = oh.create(1, “2”, 1);utx.commit();ic.close();ic.close();}catch (CreateException e) { }catch (RemoteException e) { }catch (RemoteException e) { }catch (NamingException e) { }}
public void paint(Graphics g) {g.drawString(message, 10, 10);
}}
public void start() {t = new Thread(this);t new Thread(this);t.start();
}public void stop() {
t.stop();t = null;
}public void run() {
doEJBStuff();while(true) {
repaint();repaint();try {
Thread.sleep(500);}}catch (Exception e) { }
}}}}
BEA WebXpress recommends that use the Java Plug-in p gwhen using WebLogic as applets.The Java Plug-in (formerly known as the Java A ti t ) i J Vi t l M hi (JVM) th t bActivator) is a Java Virtual Machine (JVM) that can be used instead of the browser’s own virtual machine.It acts as a plug-in under Netscape and as ActiveX p g pcontrol under Internet Explorer.The Java Plug-in does not rely on the browser’s own i t l hi t VM i ldvirtual machine, so you can run a current VM even in old
browsers.When downloading the plug-in, you can also downloadWhen downloading the plug in, you can also download an HTML converter that will automate this process.
Another significant benefit of using the Java Plug-in is that, if you ot e s g ca t be e t o us g t e Ja a ug s t at, youneed signed applets, you can sign them one way. The Java plug-in provides an option – sign your code so that it works with the plug-in, and then use the plug-in any client browsers.p g , p g yTwo general reasons for signing the code:
Provides the user with some evidence that you are who you say you are. The user can then make an informed decision about whether to allow your code to run.Signed applets can potentially do more than unsigned applets. In JDK1.1, a signed applet is granted the same level of privilege as a locally running Java application. In Java 2, the permissions granted to a signed applet are specified at a finer level of granularity, but you can still grant a signed applet virtually any permission to which the user agrees.
The Applet TagThe Applet Tag<APPLET code = EJBApplet.class codebase = “/classes” width = 2000 height=100> </APPLET>
TopicsTopics
EJB Bean as a Client to Another BeanEJB Bean as a Client to Another BeanSerializing a HandleTransactions in ClientsTransactions in ClientsAuthentication in ClientsG tti M t D tGetting Meta DataServlet ClientApplet ClientCORBA Client
CORBA ClientCORBA Client
Two key differences between “normal” EJBTwo key differences between normal EJB clients and CORBA EJB Clients:
Instead of JNDI, CORBA clients use COS naming to look up home interfaces.CORBA clients that employ client-demarcated transactions use CORBA Object Transaction Servicetransactions use CORBA Object Transaction Service (OTS) transactions.
import …import org.omg.CosNaming.*;po t o g o g Cos a g ;Import org.omg.CosTransactions.*;import org.omg.CORBA.ORB;public class CorbaClientTx {public class CorbaClientTx {
public static void main (String[] argv) throws Exception {System.out.println(“Client is Running”);ORB orb = ORB.init(argv, null);ORB orb ORB.init(argv, null);NamingContext context = NamingContextHelper.narrow
(orb.resolve_initial_references(“NameService”));System.out.println(“looked up initial context”);y p ( p );OrderHome oh;NameComponent nameComponent = new
NameComponent(“OrderHome”, “ “);NameComponent[] nameComponent = { nameComponent };oh = OrderHomeHelper.narrow(context.resolve(nameComponents));System.out.println(“looked up home interface”);
//IDL Generated for the Order Bean#include<ejb.idl>module book {module book {module order {module OrderPK {
public long custid;public string itemcode;
};interface Order : ::javax::ejb::EJBObject {
readonly attribute string itemCode;readonly attribute string itemCode;attribute long quantity;readonly attribute long CustID;
};interface OrderHome : ::javax::ejb::EJBHome {interface OrderHome : ::javax::ejb::EJBHome {
::book::order::Order findByPrimaryKey (in::book::order::OrderPK arg0) raises (::javax::ejb::FinderEX);
::book::order::Order create (in long arg0), in string arg1, in long arg2) raises (::javax::ejb::CreateEx);(::javax::ejb::CreateEx);
::java::util::Enumeration findBYCustID (in long arg0) raises (::javax::ejb::FinderEx);};};};
What to Look for in a CORBA-Compliant EJB Implementation
The CORBA implementation should provide IDL for the core EJB classes.
A tool to generate IDL directly from your EJB interface classes would be helpful.p
The environment should support COS naming and provide a method of mapping from JNDI names to COS namesof mapping from JNDI names to COS names.
The environment should support OTS transactions.
HTTP Tunneling and SSLHTTP Tunneling and Secure Socket Layer (SSL) support are two features that are not specified in the EJB specification itself but should be widely implemented inspecification itself, but should be widely implemented in various vendor-specific ways.HTTP Tunneling is a way to allow objects to communicate through a firewall. In HTTP tunneling, the various method invocations are translated into a series of HTTP requests andtranslated into a series of HTTP requests and responses.This translation occurs transparently to the specification. p y pThat is, you don’t have to decompose your method invocations into HTTP – it’s handled for you by the protocol handlerprotocol handler.
SSL is a standard for encryption. Like HTTP, SSL yp ,translation occurs “under the covers”, and the application program should not need to take special steps to use it.U f t t l th EJB ifi ti t l fUnfortunately, the EJB specification steers clear of issues involving the transport layer, so no standard approach to either HTTP tunneling or SSL exists at this time.If you need either SSL or HTTP tunneling right now, one option is to use servlets as wrappers for your EJBoption is to use servlets as wrappers for your EJB classes.You can then communicate purely over HTTP and use the SSL support provided by the browser itself.The next generation of environments may provide more built in support for HTTP tunneling and SSLbuilt-in support for HTTP tunneling and SSL.