SlideShare a Scribd company logo
EJB Clients Roy Antony Arnold G Lecturer Panimalar Engineering College Chennai, Tamilnadu, India Unit – III Middleware Technologies
Topics EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
An EJB Bean as a Client to Another Bean EJB Client Bean import ….; public class ClientBean implements SessionBean { SessionContext ctx; public void ejbCreate() { } public void run() { try {  Properties p = new Properties(); 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); o1.remove(); o2.remove(); catch(NamingException e) { } catch (CreateExeception 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 Properties To define an environment property, two options available Deployment Descriptor can be used New Properties Object in the Client can be created and can be passed it to the InitialContext Constructor
The Client import javax.naming.InitialContext; public class ClientClient { public static void main(String[] args) throws Exception { InitialContext ic = new InitialContext(); ClientHome ch = (ClientHome) ic.lookup(“ClientHome”); Client c = ch.create(); c.run(); c.remove(); 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
Topics EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
Serializing a Handle A handle is a serializable reference to a bean; i.e. you can obtain a handle from a bean’s remote interface, write it out to persistent storage, and then close the program down. At 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 itself. The server-side object must still exist when attempting to reobtain the reference otherwise “NoSuchObjectException” 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 Client If 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 work.
beginWork() static void beginWork() { try { InitialContext ic = new InitialContext(); System.out.println(“looked up initial context”); OrderHome oh = (OrderHome) ic.lookup(“OrderHome”); Order o1 = oh.create(1, “1”,1); myHandle = o1.getHandle(); } catch (CreateException e) { System.out.println(“CreateException occurred:” + e); } catch (RemoteException e) { System.out.println(“RemoteException occurred:” + e); } catch (NamingException e) { System.out.println(“NamingException occurred:” + e); } } Creating an initial naming context Using the naming context to look up the home interface Using the home interface to create a bean. Obtains a handle and stores it in the myHandle static class variable. The writeHandle method later uses this value to write the object out to persistent storage.
writeHandle static void writeHandle() { try { FileOutputStream fos = new FileOutputStream (“beanhandle.ser”); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(myHandle); oos.flush(); oos.close(); } catch (IOException e) { System.out.println(“Exception occurred in writeHandle: “ + e); } }
readHandle() static void readHandle() { try { FileInputStream fis = new FileInputStream (“beanhandle.ser”); ObjectInputStream ois = new ObjectInputStream (fis); myHandle = (Handle) ois.readObject(); ois.close(); } catch (Exception e) { System.out.println(“Exception occurred in readHandle:” + e); }
finishWork() static void finishWork()  { 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); e.printStackTrace(); } catch (RemoveException e) { System.out.println(“RemoveException occurred” + e); e.printStackTrace(); } }
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 clients to write out a serialized handle java –Djava.naming.factory.initial=weblogic.jndi. T3InitialContextFactory HandleClient write to read the handle back in and finish working with it java –Djava.naming.factory.initial=weblogic.jndi. T3InitialContextFactory HandleClient read
Topics  EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
Transactions 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.
import …. public class ClientTx { public static void main(String[] argv) { UserTransaction utx = null; try { InitialContext ic = new InitialContext(); OrderHome oh = (OrderHome) ic.lookup(“OrderHome”);   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(); } catch (CreateException e) { if(utx!=null) { utx.rollback();} } catch (RemoteException e) { if(utx!=null) { utx.rollback();} } catch (NamingException e) { if(utx!=null) { utx.rollback(); } } } }
Guidelines for handling exceptions in TX Throwing a  TransactionRolledbackException  indicates that 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 client should rollback the TX. Recovering from a RemoteException is somewhat dicey. To preserve database consistency, it’s best to roll back and start over. A RemoteException generally indicates some sort of system-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 fixed.
Topics EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
Authentication in Clients The EJB specification does not dictate the mechanism by 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.
import … public class AuthClient { public static void main(String[] argv) { try { Properties p = new Properties(); p.put(Context. INITIAL_CONTEXT_FACTORY , “weblogic.jndi.T3InitialContextFactory”); p.put(Context.PROVIDER_URL, “t3://localhost:7001”); p.put(Context.SECURITY_PRINCIPAL, “panimalar”); p.put(Context.SECURITY_CREDENTIALS, “panimalar”); InitialContext ic = new InitialContext(p); OrderHome oh = (OrderHome) ic.lookup(“OrderHome”); 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(); } catch ()….. }
Topics EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
Getting Metadata Some clients may need to obtain  metadata  about the bean. In JDBC, two metadata classes are frequently used: DatabaseMetaData  – allows the client to query for information about  database  and the sorts of operations that it supports. ResultSetMetaData  – 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 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 builders 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); }
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); }
public static void printClassArray(Class[] ca)  { System.out.println(“--------------------”); if(ca.length ==0) System.out.println(“none”); else for(int i = 0; i<ca.length; i++)   System.out.println(“:” + ca[i]); System.out.println(“--------------------”); } public static void printMethods(Method[] ma) { System.out.println(“--------------------”); if(ma.length ==0) System.out.println(“none”); else for(int i = 0; i<ma.length; i++)   System.out.println(“:” + ma[i]); System.out.println(“--------------------”); } public static void printFields(Field[] fa)  { System.out.println(“--------------------”); if(fa.length ==0) System.out.println(“none”); else for(int i = 0; i<fa.length; i++)   System.out.println(“:” + fa[i]); System.out.println(“--------------------”); } public static void printConstructors(Constructor [] ca) { System.out.println(“--------------------”); if(ca.length ==0) System.out.println(“none”); else for(int i = 0; i<ca.length; i++)   System.out.println(“:” + ca[i]); System.out.println(“--------------------”); }
Topics EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
A Servlet Client Servlets are basically Java’s answer to CGI programming. These 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 invoked 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. In 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. Sevlets 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 Servlets To 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. 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  weblogic.httpd.register.foo.bar.ServletClient = book.servlet.ServletClient WebLogic should use the class  book.servlet.ServletClient.  This class 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.*; public class ServletClient extends HttpServlet { OrderHome oh; public void init() { 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 quantity = Integer.parseInt(req.getParameter(“quantity”));
out.println(“<HTML> <HEAD> <TITLE>”); 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(); out.println(“Removed bean <br>”); } catch (Exception e) { }  finally { out.println(“</BODY>”); out.println(“</HTML”); out.close(); } }
HTML to Make a Call to the Servlet <HTML> <HEAD> <TITLE> Servlet as EJB Client </TITLE> </HEAD> <BODY> <p> <h1> Servlet as EJB Client </h1> <hr> HTTP GET example <br> <FORM method=GET action=“http://localhost:7001/ServletClient”> … </FORM> HTTP POST example <br> <FORM method=POST action=“http://localhost:7001/ServletClient”> … </FORM>
In the  HTTP GET protocol , the input parameters are stored in an environment variable called  QUERY_STRING . In a CGI program, the program itself would 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 them.
Topics EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
An Applet Client import … import java.applet.Applet; public class EJBApplet extends Applet implements Runnable { String message; Thread t; public void init() { message = “Initializing Applet”; } public void doEJBStuff() { try { Properties p = new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY, “weblogic.jndi.TengahInitialContextFactory”); p.put(Context.PROVIDER_URL, “t3://”+getCodeBase().getHost()+ “:7001/”); InitialContext ic = new InitialContext(p);
message = “looked up initial context”; OrderHome oh = (OrderHome) ic.lookup(“OrderHome”); 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(); ic.close(); } catch (CreateException 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.start(); } public void stop() { t.stop(); t = null; } public void run() { doEJBStuff(); while(true) { repaint(); try { Thread.sleep(500); } catch (Exception e) { } } } }
BEA WebXpress recommends that use the Java Plug-in when using WebLogic as applets. The  Java Plug-in  (formerly known as the  Java Activator ) 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 control  under Internet Explorer. The Java Plug-in does not rely on the browser’s own virtual machine, so you can run a current VM even in old browsers. When 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 need  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. Two 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 Tag <APPLET  code = EJBApplet.class codebase = “/classes”  width = 2000 height=100> </APPLET>
Topics EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
CORBA Client Two 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 Service (OTS)  transactions.
import … import org.omg.CosNaming.*; Import org.omg.CosTransactions.*; import org.omg.CORBA.ORB; public class CorbaClientTx { public static void main (String[] argv) throws Exception { System.out.println(“Client is Running”); ORB orb = ORB.init(argv, null); NamingContext context = NamingContextHelper.narrow (orb.resolve_initial_references(“NameService”)); System.out.println(“looked up initial context”); 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 order { module OrderPK { public long custid; public string itemcode; }; interface Order : ::javax::ejb::EJBObject { readonly attribute string itemCode; attribute long quantity; readonly attribute long CustID; }; 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); ::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. The environment should support COS naming and provide a method of mapping from JNDI names to COS names. The environment should support OTS transactions.
HTTP Tunneling and SSL HTTP Tunneling and Secure Socket Layer (SSL) support are two features that are not specified in the EJB specification 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 and responses. This translation occurs transparently to the specification. That is, you don’t have to decompose your method invocations into HTTP – it’s handled for you by the protocol handler.
SSL is a standard for encryption. Like HTTP, SSL translation occurs “under the covers”, and the application program should not need to take special steps to use it. Unfortunately, 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 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 SSL.

More Related Content

PPT
PPT
PPTX
Enterprise Java Beans 3 - Business Logic
PPT
Ejb 2.0
PPT
Session 4 Tp4
PPTX
Skillwise EJB3.0 training
PDF
Ejb3 Presentation
PDF
Enterprise JavaBeans(EJB)
Enterprise Java Beans 3 - Business Logic
Ejb 2.0
Session 4 Tp4
Skillwise EJB3.0 training
Ejb3 Presentation
Enterprise JavaBeans(EJB)

What's hot (20)

PPT
Session 3 Tp3
PPTX
PPTX
EJB3 Advance Features
PDF
Enterprise Java Beans - EJB
PDF
EJB 3.0 - Yet Another Introduction
PDF
Ejb - september 2006
PPSX
Entity beans in java
PDF
Ejb notes
PPTX
Java Beans
PPT
Enterprise Java Beans( E)
PPTX
Java bean
PPTX
enterprise java bean
PPTX
Introduction to JPA (JPA version 2.0)
PPT
EJB 3.0 Java Persistence with Oracle TopLink
PPTX
Ejb3.1 for the starter
PPTX
Enterprise java beans
ODT
Types of Dependency Injection in Spring
PDF
EJB Interview Questions
DOCX
TY.BSc.IT Java QB U5&6
PPT
Java Persistence API (JPA) Step By Step
Session 3 Tp3
EJB3 Advance Features
Enterprise Java Beans - EJB
EJB 3.0 - Yet Another Introduction
Ejb - september 2006
Entity beans in java
Ejb notes
Java Beans
Enterprise Java Beans( E)
Java bean
enterprise java bean
Introduction to JPA (JPA version 2.0)
EJB 3.0 Java Persistence with Oracle TopLink
Ejb3.1 for the starter
Enterprise java beans
Types of Dependency Injection in Spring
EJB Interview Questions
TY.BSc.IT Java QB U5&6
Java Persistence API (JPA) Step By Step
Ad

Viewers also liked (6)

PPT
Ch 2 lattice & boolean algebra
PDF
Tutorial su JMS (Java Message Service)
PDF
PPT
Remote Method Invocation
PPTX
Chapter 3 servlet & jsp
PDF
JMS - Java Messaging Service
Ch 2 lattice & boolean algebra
Tutorial su JMS (Java Message Service)
Remote Method Invocation
Chapter 3 servlet & jsp
JMS - Java Messaging Service
Ad

Similar to EJB Clients (20)

PDF
Ejb examples
PPT
ADVANCED JAVA MODULE I & II.ppt
PPT
12 hibernate int&cache
PDF
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
PDF
What's New in Enterprise JavaBean Technology ?
PPT
Aravind vinnakota ejb_architecture
PDF
EJB et WS (Montreal JUG - 12 mai 2011)
PDF
Ejb intro
PPT
Unite5-EJB-2019.ppt
PPT
J2 Ee Overview
PPT
Enterprise java beans(ejb)
PDF
EJB 3.1 and GlassFish v3 Prelude
PPT
Enterprise java beans(ejb) Update 2
PPT
Enterprise java beans(ejb) update 2
ODP
EJB 3.0 Walkthrough (2006)
PDF
Ejb intro
PDF
Free EJB Tutorial | VirtualNuggets
PPT
J2EE - Practical Overview
ODP
Business layer and transactions
DOC
J2EE Online Training
Ejb examples
ADVANCED JAVA MODULE I & II.ppt
12 hibernate int&cache
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
What's New in Enterprise JavaBean Technology ?
Aravind vinnakota ejb_architecture
EJB et WS (Montreal JUG - 12 mai 2011)
Ejb intro
Unite5-EJB-2019.ppt
J2 Ee Overview
Enterprise java beans(ejb)
EJB 3.1 and GlassFish v3 Prelude
Enterprise java beans(ejb) Update 2
Enterprise java beans(ejb) update 2
EJB 3.0 Walkthrough (2006)
Ejb intro
Free EJB Tutorial | VirtualNuggets
J2EE - Practical Overview
Business layer and transactions
J2EE Online Training

More from Roy Antony Arnold G (20)

PDF
PDF
Reliability growth models for quality management
PDF
Quality management models
PDF
Pareto diagram
PDF
Ishikawa diagram
PDF
PDF
Customer satisfaction
PDF
Complexity metrics and models
PDF
Check lists
PDF
Capability maturity model
PDF
Structure chart
PDF
Seven new tools
PDF
Scatter diagram
PDF
Relations diagram
PDF
Rayleigh model
PDF
Defect removal effectiveness
PDF
Customer satisfaction
Reliability growth models for quality management
Quality management models
Pareto diagram
Ishikawa diagram
Customer satisfaction
Complexity metrics and models
Check lists
Capability maturity model
Structure chart
Seven new tools
Scatter diagram
Relations diagram
Rayleigh model
Defect removal effectiveness
Customer satisfaction

Recently uploaded (20)

PDF
Hybrid model detection and classification of lung cancer
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PPTX
A Presentation on Touch Screen Technology
PPTX
Tartificialntelligence_presentation.pptx
PDF
Getting Started with Data Integration: FME Form 101
PPTX
TLE Review Electricity (Electricity).pptx
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
project resource management chapter-09.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
WOOl fibre morphology and structure.pdf for textiles
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
A Presentation on Artificial Intelligence
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
Approach and Philosophy of On baking technology
Hybrid model detection and classification of lung cancer
SOPHOS-XG Firewall Administrator PPT.pptx
A comparative study of natural language inference in Swahili using monolingua...
Univ-Connecticut-ChatGPT-Presentaion.pdf
A Presentation on Touch Screen Technology
Tartificialntelligence_presentation.pptx
Getting Started with Data Integration: FME Form 101
TLE Review Electricity (Electricity).pptx
Group 1 Presentation -Planning and Decision Making .pptx
project resource management chapter-09.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Hindi spoken digit analysis for native and non-native speakers
MIND Revenue Release Quarter 2 2025 Press Release
DP Operators-handbook-extract for the Mautical Institute
WOOl fibre morphology and structure.pdf for textiles
Programs and apps: productivity, graphics, security and other tools
A Presentation on Artificial Intelligence
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
Approach and Philosophy of On baking technology

EJB Clients

  • 1. EJB Clients Roy Antony Arnold G Lecturer Panimalar Engineering College Chennai, Tamilnadu, India Unit – III Middleware Technologies
  • 2. Topics EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
  • 3. An EJB Bean as a Client to Another Bean EJB Client Bean import ….; public class ClientBean implements SessionBean { SessionContext ctx; public void ejbCreate() { } public void run() { try { Properties p = new Properties(); 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); o1.remove(); o2.remove(); catch(NamingException e) { } catch (CreateExeception e) {} catch(RemoveException e) {} catch (RemoteException e) {} } public void setSessionContext (SessionContext ctx) { this.ctx = ctx; } public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate{} }
  • 4. Environment Properties To define an environment property, two options available Deployment Descriptor can be used New Properties Object in the Client can be created and can be passed it to the InitialContext Constructor
  • 5. The Client import javax.naming.InitialContext; public class ClientClient { public static void main(String[] args) throws Exception { InitialContext ic = new InitialContext(); ClientHome ch = (ClientHome) ic.lookup(“ClientHome”); Client c = ch.create(); c.run(); c.remove(); 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
  • 6. Topics EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
  • 7. Serializing a Handle A handle is a serializable reference to a bean; i.e. you can obtain a handle from a bean’s remote interface, write it out to persistent storage, and then close the program down. At 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 itself. The server-side object must still exist when attempting to reobtain the reference otherwise “NoSuchObjectException” 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.
  • 8. The Client If 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 work.
  • 9. beginWork() static void beginWork() { try { InitialContext ic = new InitialContext(); System.out.println(“looked up initial context”); OrderHome oh = (OrderHome) ic.lookup(“OrderHome”); Order o1 = oh.create(1, “1”,1); myHandle = o1.getHandle(); } catch (CreateException e) { System.out.println(“CreateException occurred:” + e); } catch (RemoteException e) { System.out.println(“RemoteException occurred:” + e); } catch (NamingException e) { System.out.println(“NamingException occurred:” + e); } } Creating an initial naming context Using the naming context to look up the home interface Using the home interface to create a bean. Obtains a handle and stores it in the myHandle static class variable. The writeHandle method later uses this value to write the object out to persistent storage.
  • 10. writeHandle static void writeHandle() { try { FileOutputStream fos = new FileOutputStream (“beanhandle.ser”); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(myHandle); oos.flush(); oos.close(); } catch (IOException e) { System.out.println(“Exception occurred in writeHandle: “ + e); } }
  • 11. readHandle() static void readHandle() { try { FileInputStream fis = new FileInputStream (“beanhandle.ser”); ObjectInputStream ois = new ObjectInputStream (fis); myHandle = (Handle) ois.readObject(); ois.close(); } catch (Exception e) { System.out.println(“Exception occurred in readHandle:” + e); }
  • 12. finishWork() static void finishWork() { 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); e.printStackTrace(); } catch (RemoveException e) { System.out.println(“RemoveException occurred” + e); e.printStackTrace(); } }
  • 13. 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 clients to write out a serialized handle java –Djava.naming.factory.initial=weblogic.jndi. T3InitialContextFactory HandleClient write to read the handle back in and finish working with it java –Djava.naming.factory.initial=weblogic.jndi. T3InitialContextFactory HandleClient read
  • 14. Topics EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
  • 15. Transactions 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.
  • 16. import …. public class ClientTx { public static void main(String[] argv) { UserTransaction utx = null; try { InitialContext ic = new InitialContext(); OrderHome oh = (OrderHome) ic.lookup(“OrderHome”); 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(); } catch (CreateException e) { if(utx!=null) { utx.rollback();} } catch (RemoteException e) { if(utx!=null) { utx.rollback();} } catch (NamingException e) { if(utx!=null) { utx.rollback(); } } } }
  • 17. Guidelines for handling exceptions in TX Throwing a TransactionRolledbackException indicates that 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 client should rollback the TX. Recovering from a RemoteException is somewhat dicey. To preserve database consistency, it’s best to roll back and start over. A RemoteException generally indicates some sort of system-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 fixed.
  • 18. Topics EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
  • 19. Authentication in Clients The EJB specification does not dictate the mechanism by 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.
  • 20. import … public class AuthClient { public static void main(String[] argv) { try { Properties p = new Properties(); p.put(Context. INITIAL_CONTEXT_FACTORY , “weblogic.jndi.T3InitialContextFactory”); p.put(Context.PROVIDER_URL, “t3://localhost:7001”); p.put(Context.SECURITY_PRINCIPAL, “panimalar”); p.put(Context.SECURITY_CREDENTIALS, “panimalar”); InitialContext ic = new InitialContext(p); OrderHome oh = (OrderHome) ic.lookup(“OrderHome”); 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(); } catch ()….. }
  • 21. Topics EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
  • 22. Getting Metadata Some clients may need to obtain metadata about the bean. In JDBC, two metadata classes are frequently used: DatabaseMetaData – allows the client to query for information about database and the sorts of operations that it supports. ResultSetMetaData – 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 forth.
  • 23. 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 builders who wish to automatically generat connections among groups of already-installed beans.
  • 24. 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); } }
  • 25. 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); }
  • 26. 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); }
  • 27. public static void printClassArray(Class[] ca) { System.out.println(“--------------------”); if(ca.length ==0) System.out.println(“none”); else for(int i = 0; i<ca.length; i++) System.out.println(“:” + ca[i]); System.out.println(“--------------------”); } public static void printMethods(Method[] ma) { System.out.println(“--------------------”); if(ma.length ==0) System.out.println(“none”); else for(int i = 0; i<ma.length; i++) System.out.println(“:” + ma[i]); System.out.println(“--------------------”); } public static void printFields(Field[] fa) { System.out.println(“--------------------”); if(fa.length ==0) System.out.println(“none”); else for(int i = 0; i<fa.length; i++) System.out.println(“:” + fa[i]); System.out.println(“--------------------”); } public static void printConstructors(Constructor [] ca) { System.out.println(“--------------------”); if(ca.length ==0) System.out.println(“none”); else for(int i = 0; i<ca.length; i++) System.out.println(“:” + ca[i]); System.out.println(“--------------------”); }
  • 28. Topics EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
  • 29. A Servlet Client Servlets are basically Java’s answer to CGI programming. These 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 invoked 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. In 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. Sevlets 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.
  • 30. Setting up WebLogic Servlets To 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. 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 weblogic.httpd.register.foo.bar.ServletClient = book.servlet.ServletClient WebLogic should use the class book.servlet.ServletClient. This class 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
  • 31. import … import javax.servlet.*; import javax.servlet.http.*; public class ServletClient extends HttpServlet { OrderHome oh; public void init() { 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 quantity = Integer.parseInt(req.getParameter(“quantity”));
  • 32. out.println(“<HTML> <HEAD> <TITLE>”); 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(); out.println(“Removed bean <br>”); } catch (Exception e) { } finally { out.println(“</BODY>”); out.println(“</HTML”); out.close(); } }
  • 33. HTML to Make a Call to the Servlet <HTML> <HEAD> <TITLE> Servlet as EJB Client </TITLE> </HEAD> <BODY> <p> <h1> Servlet as EJB Client </h1> <hr> HTTP GET example <br> <FORM method=GET action=“http://localhost:7001/ServletClient”> … </FORM> HTTP POST example <br> <FORM method=POST action=“http://localhost:7001/ServletClient”> … </FORM>
  • 34. In the HTTP GET protocol , the input parameters are stored in an environment variable called QUERY_STRING . In a CGI program, the program itself would 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 them.
  • 35. Topics EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
  • 36. An Applet Client import … import java.applet.Applet; public class EJBApplet extends Applet implements Runnable { String message; Thread t; public void init() { message = “Initializing Applet”; } public void doEJBStuff() { try { Properties p = new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY, “weblogic.jndi.TengahInitialContextFactory”); p.put(Context.PROVIDER_URL, “t3://”+getCodeBase().getHost()+ “:7001/”); InitialContext ic = new InitialContext(p);
  • 37. message = “looked up initial context”; OrderHome oh = (OrderHome) ic.lookup(“OrderHome”); 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(); ic.close(); } catch (CreateException e) { } catch (RemoteException e) { } catch (NamingException e) { } } public void paint(Graphics g) { g.drawString(message, 10, 10); }
  • 38. public void start() { t = new Thread(this); t.start(); } public void stop() { t.stop(); t = null; } public void run() { doEJBStuff(); while(true) { repaint(); try { Thread.sleep(500); } catch (Exception e) { } } } }
  • 39. BEA WebXpress recommends that use the Java Plug-in when using WebLogic as applets. The Java Plug-in (formerly known as the Java Activator ) 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 control under Internet Explorer. The Java Plug-in does not rely on the browser’s own virtual machine, so you can run a current VM even in old browsers. When downloading the plug-in, you can also download an HTML converter that will automate this process.
  • 40. Another significant benefit of using the Java Plug-in is that, if you need 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. Two 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 Tag <APPLET code = EJBApplet.class codebase = “/classes” width = 2000 height=100> </APPLET>
  • 41. Topics EJB Bean as a Client to Another Bean Serializing a Handle Transactions in Clients Authentication in Clients Getting Meta Data Servlet Client Applet Client CORBA Client
  • 42. CORBA Client Two 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 Service (OTS) transactions.
  • 43. import … import org.omg.CosNaming.*; Import org.omg.CosTransactions.*; import org.omg.CORBA.ORB; public class CorbaClientTx { public static void main (String[] argv) throws Exception { System.out.println(“Client is Running”); ORB orb = ORB.init(argv, null); NamingContext context = NamingContextHelper.narrow (orb.resolve_initial_references(“NameService”)); System.out.println(“looked up initial context”); OrderHome oh; NameComponent nameComponent = new NameComponent(“OrderHome”, “ “); NameComponent[] nameComponent = { nameComponent }; oh = OrderHomeHelper.narrow(context.resolve(nameComponents)); System.out.println(“looked up home interface”);
  • 44. //IDL Generated for the Order Bean #include<ejb.idl> module book { module order { module OrderPK { public long custid; public string itemcode; }; interface Order : ::javax::ejb::EJBObject { readonly attribute string itemCode; attribute long quantity; readonly attribute long CustID; }; 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); ::java::util::Enumeration findBYCustID (in long arg0) raises (::javax::ejb::FinderEx); }; }; };
  • 45. 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. The environment should support COS naming and provide a method of mapping from JNDI names to COS names. The environment should support OTS transactions.
  • 46. HTTP Tunneling and SSL HTTP Tunneling and Secure Socket Layer (SSL) support are two features that are not specified in the EJB specification 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 and responses. This translation occurs transparently to the specification. That is, you don’t have to decompose your method invocations into HTTP – it’s handled for you by the protocol handler.
  • 47. SSL is a standard for encryption. Like HTTP, SSL translation occurs “under the covers”, and the application program should not need to take special steps to use it. Unfortunately, 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 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 SSL.