My Profile
Active Members
TodayLast 7 Days
more...
Awards & Gifts
Online Exams
Fresher Jobs
Our fresher job section is exclusively for fresh graduates! Find jobs for freshers in major Indian
cities including Bangalore, Chennai, Hyderabad, Pune or Kochi
Resources
Find educational articles, blogs, discussion threads and other resources.
Colleges
Find details about any college in India or search for courses.
|
Enterprise Java Beans (EJB)
|
Enterprise Java Beans
Sun Microsystems introduced the J2EE application server and the Enterprise JavaBean (EJB) specifications as a venture into the multitier server side component architecture market. It is important to note that though EJB and JavaBeans are both component models, they are not same. EJBs are interprocess components and JavaBeans are intraprocess components. EJB is a specification for creating server side components that enables and simplifies the task of creating distributed objects.
The Key features of EJB are as follows
? EJB components are server side components written using Java ? EJB components implement the business logic only. We need not write code for system level services, such as managing transactions and security. ? EJB components provides services, such as transaction and security management and can be customized during deployment. ? EJB can maintain state information across various method calls.
Enterprise JavaBeans Component Architecture
EJB Server which contains the EJB container. EJB container, which contains enterprise beans
Enterprise bean, which contains methods that implement the business logic.
EJB Server
EJB Server provides some low level services, such as network connectivity to the container. It also provides the following services:
1. Instance Passivation – If a container needs resource, it can decide to temporarily swap out a bean from the memory storage. 2. Instance Pooling – If an instance of the requested bean exists in the memory, the bean is reassigned to another client. 3. Database Connection Pooling – When an Enterprise bean wants the access a database, it does not create a new database connection of the database connection already exists in the pool.
4. Precached Instances – The EJB server maintains a cache. This cache information about the state of the enterpirse bean.
EJB Container
The EJB container acts as an interface between and Enterprise bean and the clients. Clients communicate with the enterprise bean through the Remote and Home Interfaces provide by the container.
The client communicating to the enterprise bean through the container enables the container to service the client’s request with great flexibility. For Instance, the container manages a pool of enterprise beans and uses them as the need arises, instead of creating a new instance of the bean for each client request.
The container also provides the following services:
1. Security 2. Transaction Management 3. Persistance -> Permanent Storage 4. Life Cycle Management
Enterprise Bean
Enterprise JavaBeans are write once, run anywhere, middle tier components that consists of methods that implements the business rule. The enterprise bean encapsulates the business logic. There are three types of enterprise bean.
1. Entity Bean 2. Session Bean 3. Message Driven Bean (JMS – Java Message Service)
Entity Bean
Entity Beans are enterprise beans that persist across multiple sessions and multiple clients. There are two types of Entity bean:
1. Bean Managed Persistance 2. Container Managed Persistence
In a Bean managed persistance, the programmer has to write the code for database calls. On the other hand, in container managed persistance, the container takes care of database calls.
Session Bean
Session bean perform business tasks without having a persistent storage mechanism, such as a database and can use the shared data. There are two types of session beans:
1. Stateful Session Bean 2. Stateless Session Bean
A Stateful session bean can store information in an instance variable to be used across various method calls. Some of the application require information to be stored across various method calls.
Stateless session beans do not have instance variables to store information. Hence, stateless session beans can be used in situations where information need not to be used across method calls.
Stages of stateless session bean:
Does not Exists -> when the bean has not been instantiated. Method Ready -> When the container requires it.
Class.newInstance() -> Create a new instance of the stateless session bean and allocates the required memory
SessionBean.setSessionContext(SessionContext ct) -> Sets the bean reference to the session context. A session context enables the enterprise bean to interact with the container. The enterprise bean can use the session context to query the container for information, such as transactional and security state.
ejbCreate() -> It is similar to the constructor of EJB class. It is invoked only once in the life cycle of the stateless session bean, when the client invokes the create() method of the home interface. The ejbCreate() method must not take any argument, as stateless session bean do not store any information in the instance variable.
ejbRemove() -> ends the life cycle of the stateless session bean. This method closes any open resource and frees the memory space.
Stateless Bean
Home Interface Remote Interface Bean Class Client Application
Remote Interface A remote interface defines all the business methods of the enterprise bean that the EJB client would invoke. The remove interface does not include system level operations, such as persistence, security and transactions.
Home Interface The home interface defines methods that allow EJB clients to create and find EJB components.
Bean Class The EJB class implements all the business methods declared in the remote interface.
Eg:
Calculator.java
//Remote Interface
import javax.ejb.EJBObject; import java.rmi.RemoteException;
public interface Calculator extends EJBObject { public double dollarToRs(double dollars) throws RemoteException; }
CalculatorHome.java
// Home Interface
import java.io.Serializable; import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBHome;
public interface CalculatorHome extends EJBHome { Calculator create() throws RemoteException, CreateException; }
CalculatorEJB.java
//Enterprise Bean class import java.rmi.RemoteException; import javax.ejb.SessionBean; import javax.ejb.SessionContext;
public class CalculatorEJB implements SessionBean { public double dollarToRs(double dollars) { return dollars * 47.20; }
public CalculatorEJB() {} public void ejbCreate() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {} }
EJB Servers Sun Java Server (J2EE Server) Web Logic (BEA) Websphere (IBM) J2EE SDK Architecture
It is a platform for developing and deploying enterprise and multitier applications in a distributed environment. The J2EE SDK architecture consists of :
• J2EE Server • EJB Container • Web Container
J2EE Server The J2EE server contains the EJB container and the Web Container. The J2EE server provides the following services to the EJB container and the Web container.
1. It enforces security by authenticating users. 2. It allows clients to interact with the enterprise beans 3. It facilitates a Web browser to access servlets and JSP files. 4. It provides naming and directory services to locate and search services and components.
EJB Container The EJB Container contains the enterprise bean. The container provides remote and home interfaces through which clients communicate with the enterprise bean. It also provides services such as transaction management, security, life cycle management and persistence.
Web Container The Web container is a runtime environment for servlets and JSP files.
J2EE application components A J2EE application is assembled from three components: J2EE application clients, enterprise beans, and web components. Each component is packaged into a file with a specific file format.
A J2EE application client is a Java application that runs in an environment, which enable it to access the J2EE services. A J2EE application client is packaged in to .jar file
A Web component may contain servlet, JSP, HTML and GIF files. These Web component files are packaged in a .war file.
An enterprise bean consists of three files: the EJB class, home and remote interfaces. The enterprise bean files are bundled into an EJB. Jar file.
The .jar,.war and EJB.jar files are assembled into a J2EE application, which is an .ear file. The .ear file is then deployed on the J2EE server.
Deployment Descriptor An enterprise beans has to be managed at runtime. Moreover, the J2EE server must know how to apply the primary services, such as security, naming, and transaction service. To do this, deployment descriptor is used.
Deployment descriptor is an .XML file and contains information about deployment of an enterprise bean.
JNDI JNDI is a standard extension to the Java platform that provides multiple naming and directory services. A naming services provides a mechanism for locating distributed objects.
The client uses JNDI to initiate a connection to and EJB server and to locate a specific EJB home.
Deploying an Enterprise JavaBean
d:\demo>md Calculator d:\demo>cd Calculator d:\demo\Calculator> Calculator.java CalculatorHome.java CalculatorEJB.java d:\demo\Calculator>c:\bea\user_Projects\domains\demo\setenv d:\demo\Calculator>set classpath=%classpath%;.; d:\demo\Calculator>javac *.java d:\demo\Calculator>java weblogic.marathon.ddinit.EJBInit . (create deployment descriptor) d:\demo\Calculator>cd meta-inf d:\demo\Calculator\META-INF>start wordpad ejb-jar.xml d:\demo\Calculator\META-INF>start wordpad weblogic-ejb-jar.xml JNDI -> CalculatorJNDI d:\demo\Calculator>jar cvf Calculator.jar .
Deployment ---------------- start-> Programs -> Internet Explorer
address: http://localhost:7001/console
Username: mylogic Password: myweblogic
Left Pane - Deployments - EJBModules 1. Deploy New EJB Modules 2. Upload Your Files 3. Browse -> Calculator.jar 4. click myserver 5. Upload 7. select "Calculator.jar" 8. Click Target Module 9. Click Deploy
CalculatorClient.java
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.rmi.PortableRemoteObject; import java.util.*;
public class CalculatorClient extends JFrame { public static int w = 500; public static int h = 95; public static String str = "Earnest Bank Welcomes You"; Container c;
JLabel l,result; JTextField t; JButton b;
public static String value; public static double dbl; public static double amt;
public CalculatorClient() { super(str);
c = getContentPane(); c.setLayout(new GridLayout(2,2,2,2));
l = new JLabel("Enter the amount in Dollars($)"); c.add(l);
t = new JTextField(10); c.add(t);
b = new JButton("Calculator"); c.add(b);
result = new JLabel(); c.add(result); value = t.getText(); b.addActionListener(new addEvent()); setSize(w,h); show(); } public class addEvent implements ActionListener { public void actionPerformed(ActionEvent e) { value = t.getText(); dbl = Double.parseDouble(value); try { Properties p = new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory"); p.put(Context.PROVIDER_URL,"t3://localhost:7001"); InitialContext ic = new InitialContext(p); Object obj = ic.lookup("CalculatorJNDI"); CalculatorHome home = (CalculatorHome) PortableRemoteObject.narrow(obj,CalculatorHome.class); Calculator calc = home.create(); amt = calc.dollarToRs(dbl); result.setText("Result(Rs.): " + String.valueOf(amt)); }catch(Exception ex) { System.err.println("Caught an unexpected exception!"); ex.printStackTrace(); } } } public static void main(String args[]) { CalculatorClient m = new CalculatorClient(); } }
Running Bean ------------------ d:\demo\Calculator>md Client d:\demo\Calculator>java weblogic.ejbc Calculator.jar CalculatorClient.jar d:\demo\Calculator>move CalculatorClient.jar .\Client d:\demo\Calculator\Client> CalculatorClient.jar wlclient.jar (c:\bea\weblogic81\server\lib\wlclient.jar) CalculatorClient.java d:\demo\Calculator\Client>set classpath=%classpath%;.\wlclient.jar;.\CalculatorClient.jar; d:\demo\Calculator\Client>javac CalculatorClient.java d:\demo\Calculator\Client>java CalculatorClient
Stateful Session Bean • The bean instance needs to be initialized when it is needed • The client application is an interactive one • The client is likely to invoke multiple method – calls • The bean needs to store client – specific information across method calls.
Eg:
Problem Statement
Earnest Bank’s Chief Technology Officer (CTO) has entrusted the development team with the task of creating an application to validate the credit card information entered by the user.
The team is responsible for justifying the choice of stateful session bean as the bean type and writing code for the required application
Eg:
Card.java
import javax.ejb.EJBObject; import java.rmi.RemoteException; public interface Card extends EJBObject { public int validate(String CardNo) throws RemoteException; }
CardHome.java
import java.io.Serializable; import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBHome;
public interface CardHome extends EJBHome { Card create(String person,String CardNo) throws RemoteException,CreateException; }
CardEJB.java
import javax.ejb.*; import java.rmi.RemoteException;
public class CardEJB implements SessionBean { String CustomerName; String CardNo; public void ejbCreate(String person,String cardNo) throws CreateException { if(person.equals("") || cardNo.equals("")) { throw new CreateException("Null person or card Number not allowed"); } CustomerName = person; CardNo = cardNo; }
public int validate(String cardNo) throws RemoteException { int len = CalcLen(cardNo); if (len > 16) return 0; else return 1; }
public int CalcLen(String cardNo) throws RemoteException { return cardNo.length(); } public CardEJB() {} public void ejbActivate() {} public void ejbPassivate() {} public void ejbRemove() {} public void setSessionContext(SessionContext ctx) {} }
CardClient.java
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.naming.Context; import javax.naming.InitialContext; import javax.rmi.PortableRemoteObject; import java.util.*;
public class CardClient extends JFrame { public static int w = 690; public static int h =95; public static String str = "Earnest Shopping Center Welcomes You"; Container c; JLabel lname,lcard,result; JTextField tname,tcard; JButton b;
public int res; public static String uname; public static String ccno; public CardClient() { super(str); c = getContentPane(); c.setLayout(new GridLayout(3,2,2,2)); lname = new JLabel("Name:"); c.add(lname); tname = new JTextField(20); c.add(tname); lcard = new JLabel("Card Number"); c.add(lcard); tcard = new JTextField(16); c.add(tcard); b = new JButton("Submit"); c.add(b); result = new JLabel(); c.add(result); b.addActionListener(new addEvent()); setSize(w,h); show(); }
public class addEvent implements ActionListener { public void actionPerformed(ActionEvent avt) { uname = tname.getText(); ccno = tcard.getText(); System.out.println(uname); System.out.println(ccno); try { Properties p = new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitalContextFactory"); p.put(Context.PROVIDER_URL,"t3://localhost:7001"); InitialContext initial = new InitialContext(p); Object objref = initial.lookup("CardJNDI"); CardHome home =(CardHome)PortableRemoteObject.narrow(objref,CardHome.class); Card Creditcard = home.create(uname,ccno); res = Creditcard.validate(ccno); System.out.println(res); if(res == 1) { result.setText("The Card Number " + ccno + " is valid"); } else { result.setText("Sorry! The card Number " + ccno + " is invalid"); } }catch(Exception ex) { System.out.println("Exception Raised : " + ex); result.setText("Check if you have entered your name and also card number!"); } } } public static void main(String args[]) { CardClient c; c = new CardClient(); } }
Deployment
Similar to Stateless Bean
Creating an Entity Bean Introduction: Persistent data is data that is stored in a data store. A data store is a database such as SQL Server, Cloudscape and so on. You need not to the entity beans in EJB applications where data about business entitties such as customers, accounts, and products have to be stored in a database. An entity bean is an enterprise bean that models persistent data. Session beans cannot be used to store data on a data store. They are used to model business processes. The following table describes the differences between session and entity beans.
Session Beans Entity Beans It is used to carry out tasks based on requests from clients. It is used to represent a business entity object in a data store. It can be accessed by just single client It can be accessed by the multiple clients. It cannot model persistent data. It can model persistent data.
Features: There are three key features 1. Persistence 2. Shared Access 3. Primary Key Persistance: Persistance is one of the key features of entity beans. An entity bean can exist even after an application is closed. So it is called persistent. In an entity bean, persistence is achieved by saving its state in a database. When a bean is created it is mapped to a row stored in the database. When the bean is saved, the row is updated. There are two kinds of entity beans. They are bean-managed persistent entity beans and container managed persistent entity beans. In the case of entity beans with bean managed persistence, the developer has to write the code to manage persistence. The code should contain the necessary statements to access the database. In the case of entity beans with container-managed persistence. The EJB container manages persistence. The container will automatically generate the required statements to access the database. The code that the developer wirtes need not contain calls to the database.
Shared Access: Multiple clients can acces an entity bean at a particular instant. While one client attempts to update a particular data value, another client might try to delete the same data simultaneously. Entity bean have to work within transactions to ensure that all data manipulations such as update, delete and modify are concurrent. The EJB container is responsible for handling transaction management.
Primary Key: The primary key is the unique identifier that enables a client to identify an entity bean. For example, an entity bean that represents a business entity such as a product can be identified by the product code.
Table Relationships: In RDBMS can have three types of relationships 1. One-to-One Relationships 2. One-to-many relationships 3. Many – to – many relationships
Transaction: A transaction is a series of steps, that execute as a single atomic operation. a transaction can be considered to be an indivisible unit of work. A transaction will be successful only if all the steps within it execute. The failure of a single step will lead to the transaction being unsuccessful. A program that represents a banking transaction can be written in pseudo-code as follows. begin transaction valid user display balance debit amount withdrawn update balance end transaction
All the steps listed have to be performed for the transaction to be complete. A transaction can end in a commit or a roll-back. When any step within the transactions fails, the transaction is aborted. For example, if the update balance step fails, the effects of the previous three steps are undone. When all the steps in a commit. The begin and end transactions statements mark the boundaries of the transaction.
Transactions are defined by certain properties, commonly referred to as the ACID properties. ACID stands for Atomicity, consistency, isolation, and durability. Transactions are atomic because all the individual units of work are executed as a single operation. After a transaction occurs, the state of the system remains consistent. For example, the rule for a banking system may state that the balance should never be below a certain minimum amount when a banking transaction completes, you can be assured that the balance is not less than the minimum amount. In other words, the system state will be consistent . Transactions ensure that when multiple clients perform operations, they are independent of each other. In other words, multiple transactions are isolated from each other. Durability means that all updates performed by transactions survive failure such as power failures, system crashes and so on.
In the case of enterprise beans, transactions can be container-managed transactions or bean-managed transactions.
Container Managed transactions: Container managed transactions are also called declarative transactions. In this type of transaction, it is not necessary for the programmer to specify a begin, commit, or abort statement. The EJB container manages the transactions. It is easy to develop container-managed transactions.
Bean Managed Transactions: Bean Managed Transactions are also called programmatic transactions. In this type of transactions, the programmer has to include the programming logic to issue a begin, commit, or abort statement.
Life Cycle of an Entity Bean An entity bean life cycle describes the different stages in the lifetype of the bean. The EJB container is responsible for the transactions between the different stages.
The three different states in the life cycle of an entity bean are as follows: • Does Not exist state • Pooled state • Ready State
The Does Not exist state represents entity beans that have not ye been instantiated by the EJB container. The setEntityContext() method is called after an entity bean has been instantiated by the EJB container. This method associates the bean with information about its environment such as security information.
After instantiation, the entity bean moves to the Pooled state. This state consists of a pool of entity beans that have been instantiated. The bean instance in this state does not have any database data or resources associated with it.
When the client invokes the create() method to access some data, the EJB container calls the ejbCreate() and the ejbPostCreate() methods. This causes the bean instance to move from the Pooled state to the ready state. A bean in the Ready state is initialized with specific data. In other words, a bean is associated with a specific EJB object. The ejbCreate() method is used to initialize an entity bean. An ejbPostCreate() method is associated with every ejbCreate() method. Both these methods should have the same parameters. A bean instance also moves to the Ready state when the EJB container calls the ejbActivate() method. This method is used to allocate resources such as sockets tot he entity bean. We can invoke the business methods of the bean in the Ready state.
When the client calls the remove() method, the EJB container invokes the ejbRemove() method. This causes the bean instance to move from the Ready state back to the Pooled state. The ejbRemove() method is used to delete the data associated with the bean from the database. The bean instance also moves back to the Pooled state from the Ready state when the EJB container invokes the ejbPassivate() method. When the ejbPassivate() method is called, all the bean-specific resources such as sockets are released.
The bean instance moves from the Pooled state back to the Does Not Exist state when the EJB container calls the unsetEntityContext() method. This method is used to disassociate a bean from its environment.
Eg:
cmpremote.java //remote interface import javax.ejb.*; import java.rmi.*;
public interface cmpremote extends EJBObject { public void setEname(String ename) throws RemoteException; public void setEmpid(String empid) throws RemoteException; public String getEname() throws RemoteException; public String getEmpid() throws RemoteException; }
cmphome.java
//home interface
import javax.ejb.*; import java.rmi.*;
public interface cmphome extends EJBHome { public cmpremote create(String empid,String ename) throws CreateException,RemoteException; public cmpremote findByPrimaryKey(String empid) throws FinderException,RemoteException; }
cmpbean.java
import javax.ejb.*; import java.rmi.*;
public abstract class cmpbean implements EntityBean { public abstract void setEname(String ename) throws RemoteException; public abstract void setEmpid(String empid) throws RemoteException; public abstract String getEname() throws RemoteException; public abstract String getEmpid() throws RemoteException; public void setEntityContext(EntityContext ctx) {} public void unsetEntityContext() {} public String ejbCreate(String empid, String ename) { try { setEmpid(empid); setEname(ename); }catch(Exception ex) {} return null; }
public void ejbPostCreate(String empid,String ename) {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void ejbLoad() {} public void ejbStore() {} }
Compilation
D:\demo\cmp> cmpremote.java cmphome.java cmpbean.java d:\demo\cmp>c:\bea\user_projects\domains\demo\setenv d:\demo\cmp>javac *.java d:\demo\cmp>java weblogic.marathon.ddinit.EJBInit . d:\demo\cmp>cd META-INF d:\demo\cmp\META-INF>start wordpad ejb-jar.xml change the primary key field d:\demo\cmp\META-INF>start wordpad weblogic-ejb-jar.xml change the JNDI name as “cmp” d:\demo\cmp\META-INF>cd.. d:\demo\cmp>jar cvf cmp.jar .
Deployment Creating DSN Open the Internet Explorer and login into Weblogic
Creating Connection Pool
1. Services -> JDBC -> Connection Pools 2. Configure a new JDBC Connection Pool 3. Database Type -> MS SQL Server 4. Database Driver -> Weblogic’s MS – SQL Server 5. Click Continue 6. Enter Name : MyDataSource, DatabaseName: master, HostName: server Database Username: sa, Password: killer, Confirm Password : Killer 7. Click Continue 8. Verify the Password and Click “Test Driver Configuration” 9. It displays “Connection Successful” 10. Click “Create and Deploy”
Creating Data Source
1. Configure a new JDBC Data Source 2. Enter “Name: MyDataSource, JNDI: MyDataSource” 3. Click Continue 4. Select “MyPool” as Connection Pool Name and Click Continue 5. Create
Deploying Bean
Similar to Stateless Bean
Running D:\demo\cmp>java weblogic.ejbc cmp.jar cmpclient.jar D:\demo\cmp>md Client D:\demo\cmp>move cmpclient.jar .\Client D:\demo\cmp>cd Client D:\demo\cmp\client>set classpath=%classpath%;.\wlclient.jar;.\cmpclient.jar;
Client
insertclient.java import java.util.*; import javax.naming.*; import java.rmi.*;
public class insertclient { public static void main(String args[]) throws Exception { try { Properties p = new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory"); p.put(Context.PROVIDER_URL,"t3://localhost:7001"); InitialContext ic = new InitialContext(p); cmphome h = (cmphome)ic.lookup("cmp"); cmpremote r = h.create(args[0],args[1]); System.out.println(r.getEmpid() + " : " + r.getEname() + " Record Inserted"); }catch(Exception ex) {} } }
updateclient.java
import java.util.*; import javax.naming.*; import java.rmi.*;
public class updateclient { public static void main(String args[]) throws Exception { try { Properties p = new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory"); p.put(Context.PROVIDER_URL,"t3://localhost:7001"); InitialContext ic = new InitialContext(p); cmphome h = (cmphome)ic.lookup("cmp"); cmpremote r = h.findByPrimaryKey(args[0]); r.setEname(args[1]); System.out.println(r.getEmpid() + " update with empname : " + r.getEname()); }catch(Exception ex) {} } }
listclient.java
import java.util.*; import javax.naming.*; import java.rmi.*;
public class listclient { public static void main(String args[]) throws Exception { try { Properties p = new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory"); p.put(Context.PROVIDER_URL,"t3://localhost:7001"); InitialContext ic = new InitialContext(p); cmphome h = (cmphome)ic.lookup("cmp"); cmpremote r = h.findByPrimaryKey(args[0]); System.out.println(r.getEmpid() + " " + r.getEname()); }catch(Exception ex) {} } }
Bean Managed Persistence Example
bmpremote.java
// bmpremote.java import javax.ejb.*; import java.rmi.*;
public interface bmpremote extends EJBObject { public void setEname(String ename) throws RemoteException; public void setEmpid(String empid) throws RemoteException; public String getEname() throws RemoteException; public String getEmpid() throws RemoteException; }
bmphome.java
// bmphome.java import javax.ejb.*; import java.rmi.*; public interface bmphome extends EJBHome { public bmpremote create(String empid, String ename) throws CreateException, RemoteException; public bmpremote findByPrimaryKey(String empid) throws FinderException, RemoteException; }
bmpbean.java
// bmpbean.java import javax.ejb.*; import java.rmi.*; import javax.sql.*; import java.sql.*; import javax.naming.*; public class bmpbean implements EntityBean { private String ename, empid; private EntityContext ctx; public void setEntityContext(EntityContext ctx) { this.ctx = ctx; } public void unsetEntityContext() { this.ctx = null; } public void ejbActivate() { } public void ejbPassivate() { } public String ejbCreate(String empid, String ename) throws CreateException { this.empid = empid; this.ename = ename; Connection con = null; PreparedStatement ps = null; try { con = getConnection(); ps = con.prepareStatement("insert into employee (empid, ename) values (?, ?)"); ps.setString(1, empid); ps.setString(2, ename); if (ps.executeUpdate() != 1) { throw new CreateException (); } return empid; } catch (SQLException sqe) { try { ejbFindByPrimaryKey(empid); } catch(ObjectNotFoundException onfe) { throw new CreateException (); } throw new DuplicateKeyException(); } finally { cleanup(con, ps); } } public void ejbPostCreate(String empid, String ename){} public void ejbLoad() { Connection con = null; PreparedStatement ps = null; empid = (String) ctx.getPrimaryKey(); try { con = getConnection(); ps = con.prepareStatement("select ename from employee where empid = ?"); ps.setString(1, empid); ps.executeQuery(); ResultSet rs = ps.getResultSet(); if (rs.next()) { ename = rs.getString(1); } else { throw new NoSuchEntityException (); } } catch (SQLException sqe) { throw new EJBException(sqe); } finally { cleanup(con, ps); } } public void ejbStore() { Connection con = null; PreparedStatement ps = null; try { con = getConnection(); ps = con.prepareStatement("update employee set ename = ? where empid = ?"); ps.setString(1, ename); ps.setString(2, empid); if (!(ps.executeUpdate() > 0)) { throw new NoSuchEntityException (); } } catch(SQLException sqe) { throw new EJBException (sqe); } finally { cleanup(con, ps); } } public void ejbRemove() { Connection con = null; PreparedStatement ps = null; try { con = getConnection(); empid = (String) ctx.getPrimaryKey(); ps = con.prepareStatement("delete from employee where empid = ?"); ps.setString(1, empid); if (!(ps.executeUpdate() > 0)) { throw new NoSuchEntityException (); } } catch (SQLException sqe) { throw new EJBException (sqe); } finally { cleanup(con, ps); } } public String ejbFindByPrimaryKey(String pk) throws ObjectNotFoundException { Connection con = null; PreparedStatement ps = null; try { con = getConnection(); ps = con.prepareStatement("select ename from employee where empid = ?"); ps.setString(1, pk); ResultSet rs = ps.executeQuery(); if (rs.next()) { ename = rs.getString(1); } else { throw new ObjectNotFoundException (); } } catch (SQLException sqe) { throw new EJBException (sqe); } finally { cleanup(con, ps); } return pk; } public void setEname(String ename) throws RemoteException {this.ename = ename;} public void setEmpid(String empid) throws RemoteException {this.empid = empid;} public String getEname() throws RemoteException { return ename; } public String getEmpid() throws RemoteException { return empid; } public Connection getConnection() { Connection con = null; try { InitialContext ic = new InitialContext(); DataSource d = (DataSource)ic.lookup("java:comp/env/jdbc/seminarDSN"); con = d.getConnection(); }catch(Exception ex) { System.out.println("Error: Connection" + ex);} return con; } public void cleanup(Connection con, PreparedStatement ps) { try { if(con != null) con.close(); if(ps != null) ps.close(); }catch(Exception ex) { System.out.println("Error: " + ex); } } }
Client
Insertclient.java
//insertclient.java import java.util.*; import javax.naming.*; import java.rmi.*; public class insertclient { public static void main(String args[]) throws Exception { try { Properties p = new Properties(); p.put(Context.PROVIDER_URL, "t3://localhost:7001"); p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); InitialContext ic = new InitialContext(p); bmphome h = (bmphome)ic.lookup("bmp"); bmpremote r = h.create(args[0], args[1]); System.out.println(r.getEmpid() + " : " + r.getEname() + " Record Inserted"); }catch(Exception ex) { System.out.println(ex);} } }
updateclient.java
//listclient.java import java.util.*; import javax.naming.*; import java.rmi.*; public class updateclient { public static void main(String args[]) throws Exception { try { Properties p = new Properties(); p.put(Context.PROVIDER_URL, "t3://localhost:7001"); p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); InitialContext ic = new InitialContext(p); bmphome h = (bmphome)ic.lookup("bmp"); bmpremote r = h.findByPrimaryKey(args[0]); r.setEname(args[1]); System.out.println("Record Updated: " + r.getEmpid() + " " + r.getEname()); }catch(Exception ex) { } } }
listclient.java
//listclient.java import java.util.*; import javax.naming.*; import java.rmi.*; public class listclient { public static void main(String args[]) throws Exception { try { Properties p = new Properties(); p.put(Context.PROVIDER_URL, "t3://localhost:7001"); p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); InitialContext ic = new InitialContext(p); bmphome h = (bmphome)ic.lookup("bmp"); bmpremote r = h.findByPrimaryKey(args[0]); System.out.println("Record Found: " + r.getEmpid() + " " + r.getEname()); }catch(Exception ex) { } } }
Compiling Bean Managed Persistence
javac *.java java weblogic.marathon.ddinit.EJBInit . cd META-INF start wordpad ejb-jar.xml
Add the following code between tag and tag
jdbc/seminarDSN javax.sql.DataSource Container
start wordpad weblogic-ejb-jar.xml
Remove the code from tag to and Add the following code between this tag
jdbc/seminarDSN jdbc/seminarDSN bmp
Create JAR file
Jar cvf bmp.jar .
Deploying BMP -> Similar to Stateless
|
Responses
|
| Author: Prasad 16 May 2008 | Member Level: Gold Points : 2 | Please give me information about Java Beans as detailed.
|
|
Watch TV Channels
|