EJB - Enterprise Java Bean
EJB separates busines logic from transactions, security, scalability and the other technical details.
It works with Application Servers and EJB containers, so main benefit is safe bean distribution (scalability).
The scalability is costly in performance, so EJB is not adviced if one server is sufficient for your application.
- Session : for business process and web services. Stateful or stateless. NOT Persistant.
- Entity : for busines entity. Statefull. Persistant.
- Message : to listen and process Java Messages.
- For business process (e.g. verifying a credit card) and web services.
- At any given time, only one client has access to the bean instance.
- Not persistant on DB.
- May fetch from a DB read-only data.
- There is no bean property (=state).
- Can support multi clients.
- Can be shared among clients but not at the same time.
- Does not maintain conversational state (there is no state).
- Offer better rerformance than statefull beans.
- Can implement web services but others not.
- Bean properties are states.
- Represents a single client.
- Cannot be shared among clients.
- Maintains conversational state (=bean states in terms of the serialisation protocol).
- When client terminates, then it is no more associated to the client.
- Manages the workflow of several enterprise beans.
- For business entity (e.g. credit card).
- Typically, each entity bean has an underlying table.
- Typically, each instance of the bean corresponds to a row in that table.
- Persistant on DB : container managed, bean managed.
- Has a primary key.
- Has finder methods (at least one for the primary key).
- Can participate in relationships with other entity beans.
- Allows shared access.
Abstract schema (container managed)
- Defines the bean's persistent fields and relationships.
- Distinguished from the physical schema (DB).
- Specify its name in deployement descriptor.
- This name is referenced by queries written in EJB QL (Query Language).
- Every finder method must be implemented by EJB QL.
- Peristent fields are states stored in DB.
- The EJB container automatically synchronizes this state with the database.
- A relationship field is like a foreign key in a DB.
- A relationship field does not represent the bean's state.
- The multiplicities: one-to-one, one-to-many, many-to-one, and many-to-many.
- In a bidirectional relationship, each entity bean has a relationship field that refers to the other bean.
- In a unidirectional relationship, only one entity bean has a relationship field that refers to the other.
Message Bean
- Processes messages asynchronously.
- Acts as a JMS message listener.
- The client has not access through interfaces.
- Has only a bean class.
- Does not maintain conversational state (there is no state).
- All instances of a message-driven bean are equivalent.
- The container can pool these instances to process messages concurrently.
- Can invoke a session or entity bean to process or store it in a database.
- Can be transaction aware.
- Implements onMessage method to process the message.
- Implements onMessage method to process the message.
- Relatively short-lived.
- Avoids tying-up.
ejbApplicationName.ear
├ META-INF
│ ├ MANIFEST.MF
│ ├ application.xml
│ ├ sun-application.xml
│ └ sun-j2ee-ri.xml
├ DukesBankAC.jar
├ DukesBankEJB.jar
└ DukesBank.war
application.xml :
<?xml version="1.0" encoding="UTF-8"?>
<application version="1.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/application_1_4.xsd">
<description>Application description</description>
<display-name>DukesBankApp</display-name>
<module>
<web>
<web-uri>DukesBankWAR.war</web-uri>
<context-root>/bank</context-root>
</web>
</module>
<module>
<java>DukesBankACJAR.jar</java>
</module>
<module>
<ejb>DukesBankEJBJAR.jar</ejb>
</module>
</application>
sun-application.xml :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-application PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 8.0 J2EE Application 1.4//EN" "http://www.sun.com/software/appserver/dtds/sun-application_1_4-0.dtd">
<sun-application>
<pass-by-reference>false</pass-by-reference>
<security-role-mapping>
<role-name>bankAdmin</role-name>
<principal-name>bankadmin</principal-name>
<group-name>bankAdmin</group-name>
</security-role-mapping>
<security-role-mapping>
<role-name>bankCustomer</role-name>
<principal-name>200</principal-name>
<group-name>bankCustomer</group-name>
</security-role-mapping>
</sun-application>
DukesBankEJB.jar
├ META-INF
│ ├ MANIFEST.MF
│ ├ ejb-jar.xml
│ ├ sun-cmp-mappings.xml
│ └ sun-ejb-jar.xml.
└ com.sun.eBank...*.class
ejb-jar.xml:
<!DOCTYPE ejb-jar PUBLIC
'-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN'
'http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd'>
<ejb-jar>
<enterprise-beans>
<!-- A minimal session EJB deployment -->
<session>
<ejb-name>PostingEJB</ejb-name>
<home>ejbs.PostingHome</home>
<remote>ejbs.Posting</remote>
<ejb-class>ejbs.PostingBean</ejb-class>
<!-- or Stateless -->
<session-type>Stateful</session-type>
<transaction-type>Container</transaction-type>
</session>
<!-- A minimal CMP entity EJB deployment -->
<entity>
<ejb-name>Bid</ejb-name>
<home>ejbe.BidHome</home>
<remote>ejbe.Bid</remote>
<ejb-class>ejbe.BidBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>ejbe.BidPK</prim-key-class>
<reentrant>False</reentrant>
<cmp-field><field-name>bid</field-name></cmp-field>
<cmp-field><field-name>bidder</field-name></cmp-field>
<cmp-field><field-name>bidDate</field-name></cmp-field>
<cmp-field><field-name>id</field-name></cmp-field>
</entity>
<!-- A minimal BMP entity EJB deployment -->
<entity>
<ejb-name>BidBMP</ejb-name>
<home>com.bea.EJBE.solutions.BidBMPHome</home>
<remote>com.bea.EJBE.solutions.BidBMP</remote>
<ejb-class>com.bea.EJBE.solutions.BidBMPBean</ejb-class>
<persistence-type>Bean</persistence-type>
<prim-key-class>pkg.BidBMPPK</prim-key-class>
<reentrant>False</reentrant>
</entity>
</enterprise-beans>
<assembly-descriptor></assembly-descriptor>
</ejb-jar>
sun-cmp-mappings.xml :
<sun-cmp-mappings>
<sun-cmp-mapping>
<schema>dukesbank</schema>
<entity-mapping>
<ejb-name>AccountBean</ejb-name>
<table-name>ACCOUNT</table-name>
<cmp-field-mapping>
<field-name>accountId</field-name>
<column-name>ACCOUNT.ACCOUNT_ID</column-name>
<fetched-with>
<default />
</fetched-with>
</cmp-field-mapping>
<cmp-field-mapping>
<field-name>balance</field-name>
<column-name>ACCOUNT.BALANCE</column-name>
<fetched-with>
<default />
</fetched-with>
</cmp-field-mapping>
<cmr-field-mapping>
<cmr-field-name>customers</cmr-field-name>
<column-pair>
<column-name>ACCOUNT.ACCOUNT_ID</column-name>
<column-name>CUSTOMER_ACCOUNT_XREF.ACCOUNT_ID</column-name>
</column-pair>
<column-pair>
<column-name>CUSTOMER_ACCOUNT_XREF.CUSTOMER_ID</column-name>
<column-name>CUSTOMER.CUSTOMER_ID</column-name>
</column-pair>
<fetched-with>
<none />
</fetched-with>
</cmr-field-mapping>
</entity-mapping>
<entity-mapping>
<ejb-name>CustomerBean</ejb-name>
<table-name>CUSTOMER</table-name>
<cmp-field-mapping>
<field-name>city</field-name>
<column-name>CUSTOMER.CITY</column-name>
<fetched-with>
<default />
</fetched-with>
</cmp-field-mapping>
<cmp-field-mapping>
<field-name>customerId</field-name>
<column-name>CUSTOMER.CUSTOMER_ID</column-name>
<fetched-with>
<default />
</fetched-with>
</cmp-field-mapping>
<cmr-field-mapping>
<cmr-field-name>accounts</cmr-field-name>
<column-pair>
<column-name>CUSTOMER.CUSTOMER_ID</column-name>
<column-name>CUSTOMER_ACCOUNT_XREF.CUSTOMER_ID</column-name>
</column-pair>
<column-pair>
<column-name>CUSTOMER_ACCOUNT_XREF.ACCOUNT_ID</column-name>
<column-name>ACCOUNT.ACCOUNT_ID</column-name>
</column-pair>
<fetched-with>
<none />
</fetched-with>
</cmr-field-mapping>
</entity-mapping>
</sun-cmp-mapping>
</sun-cmp-mappings>
sun-ejb-jar.xml :
<sun-ejb-jar>
<enterprise-beans>
<name>DukesBankEJBJAR</name>
<ejb>
<ejb-name>AccountBean</ejb-name>
</ejb>
<ejb>
<ejb-name>CustomerBean</ejb-name>
</ejb>
<ejb>
<ejb-name>AccountControllerBean</ejb-name>
<jndi-name>AccountControllerBean</jndi-name>
</ejb>
<ejb>
<ejb-name>CustomerControllerBean</ejb-name>
<jndi-name>CustomerControllerBean</jndi-name>
</ejb>
<cmp-resource>
<jndi-name>jdbc/BankDB</jndi-name>
</cmp-resource>
</enterprise-beans>
</sun-ejb-jar>
J2EE – 1.5 :
@Entity
@Table(name = "EJB_ORDER_VENDOR_PART")
@NamedQueries({
@NamedQuery(name = "findAverageVendorPartPrice",query = "SELECT AVG(vp.price) "
+ "FROM VendorPart vp")
, @NamedQuery(name = "findTotalVendorPartPricePerVendor", query = "SELECT SUM(vp.price) "
+ "FROM VendorPart vp " + "WHERE vp.vendor.vendorId = :id")
})
public class VendorPart implements java.io.Serializable {
private Long vendorPartNumber;
private Part part;
private String description;
private Vendor vendor;
private double price;
public VendorPart() {
}
public VendorPart(
String description,
double price,
Part part) {
this.description = description;
this.price = price;
this.part = part;
part.setVendorPart(this);
}
@TableGenerator(name = "vendorPartGen", table = "EJB_ORDER_SEQUENCE_GENERATOR", pkColumnName = "GEN_KEY", valueColumnName = "GEN_VALUE", pkColumnValue = "VENDOR_PART_ID", allocationSize = 10)
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "vendorPartGen")
public Long getVendorPartNumber() {
return vendorPartNumber;
}
public void setVendorPartNumber(Long vendorPartNumber) {
this.vendorPartNumber = vendorPartNumber;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@OneToOne
@JoinColumns({
@JoinColumn(name = "PARTNUMBER",referencedColumnName = "PARTNUMBER")
, @JoinColumn(name = "PARTREVISION", referencedColumnName = "REVISION")
})
public Part getPart() {
return part;
}
public void setPart(Part part) {
this.part = part;
}
@JoinColumn(name = "VENDORID")
@ManyToOne
public Vendor getVendor() {
return vendor;
}
public void setVendor(Vendor vendor) {
this.vendor = vendor;
}
}
@Remote
public interface Request {
void addLineItem(
Integer orderId,
String partNumber,
int revision,
int quantity);
void addPartToBillOfMaterial(
String bomPartNumber,
int bomRevision,
String partNumber,
int revision);
void adjustOrderDiscount(int adjustment);
int countAllItems();
void createOrder(
Integer orderId,
char status,
int discount,
String shipmentInfo);
void createPart(
String partNumber,
int revision,
String description,
Date revisionDate,
String specification,
Serializable drawing);
void createVendor(
int vendorId,
String name,
String address,
String contact,
String phone);
void createVendorPart(
String partNumber,
int revision,
String description,
double price,
int vendorId);
Double getAvgPrice();
double getBillOfMaterialPrice(
String bomPartNumber,
int bomRevision,
String partNumber,
int revision);
double getOrderPrice(Integer orderId);
Double getTotalPricePerVendor(int vendorId);
Collection<String> locateVendorsByPartialName(String name);
void removeOrder(Integer orderId);
String reportVendorsByOrder(Integer orderId);
}
@Stateful
public class RequestBean implements Request {
@PersistenceContext
private EntityManager em;
public void createPart(
String partNumber,
int revision,
String description,
java.util.Date revisionDate,
String specification,
Serializable drawing) {
try {
Part part = new Part(
partNumber,
revision,
description,
revisionDate,
specification,
drawing);
em.persist(part);
} catch (Exception ex) {
throw new EJBException(ex.getMessage());
}
}
public void addPartToBillOfMaterial(
String bomPartNumber,
int bomRevision,
String partNumber,
int revision) {
try {
PartKey bomKey = new PartKey();
bomKey.setPartNumber(bomPartNumber);
bomKey.setRevision(bomRevision);
Part bom = em.find(Part.class, bomKey);
PartKey partKey = new PartKey();
partKey.setPartNumber(partNumber);
partKey.setRevision(revision);
Part part = em.find(Part.class, partKey);
bom.getParts()
.add(part);
part.setBomPart(bom);
} catch (EJBException e) {
e.printStackTrace();
}
}
public void createVendor(
int vendorId,
String name,
String address,
String contact,
String phone) {
try {
Vendor vendor = new Vendor(vendorId, name, address, contact, phone);
em.persist(vendor);
} catch (Exception e) {
throw new EJBException(e);
}
}
public void createVendorPart(
String partNumber,
int revision,
String description,
double price,
int vendorId) {
try {
PartKey pkey = new PartKey();
pkey.setPartNumber(partNumber);
pkey.setRevision(revision);
Part part = em.find(Part.class, pkey);
VendorPart vendorPart = new VendorPart(description, price, part);
em.persist(vendorPart);
Vendor vendor = em.find(Vendor.class, vendorId);
vendor.addVendorPart(vendorPart);
vendorPart.setVendor(vendor);
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public void createOrder(
Integer orderId,
char status,
int discount,
String shipmentInfo) {
try {
Order order = new Order(orderId, status, discount, shipmentInfo);
em.persist(order);
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public void addLineItem(
Integer orderId,
String partNumber,
int revision,
int quantity) {
try {
Order order = em.find(Order.class, orderId);
PartKey pkey = new PartKey();
pkey.setPartNumber(partNumber);
pkey.setRevision(revision);
Part part = em.find(Part.class, pkey);
LineItem lineItem = new LineItem(
order,
quantity,
part.getVendorPart());
order.addLineItem(lineItem);
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public double getBillOfMaterialPrice(
String bomPartNumber,
int bomRevision,
String partNumber,
int revision) {
double price = 0.0;
try {
PartKey bomkey = new PartKey();
bomkey.setPartNumber(bomPartNumber);
bomkey.setRevision(bomRevision);
Part bom = em.find(Part.class, bomkey);
Collection<Part> parts = bom.getParts();
for (Iterator iterator = parts.iterator(); iterator.hasNext();) {
Part part = (Part) iterator.next();
VendorPart vendorPart = part.getVendorPart();
price += vendorPart.getPrice();
}
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
return price;
}
public double getOrderPrice(Integer orderId) {
double price = 0.0;
try {
Order order = em.find(Order.class, orderId);
price = order.calculateAmmount();
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
return price;
}
public void adjustOrderDiscount(int adjustment) {
try {
List orders = em.createNamedQuery("findAllOrders")
.getResultList();
for (Iterator it = orders.iterator(); it.hasNext();) {
Order order = (Order) it.next();
int newDiscount = order.getDiscount() + adjustment;
order.setDiscount((newDiscount > 0) ? newDiscount : 0);
}
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public Double getAvgPrice() {
try {
return (Double) em.createNamedQuery("findAverageVendorPartPrice")
.getSingleResult();
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public Double getTotalPricePerVendor(int vendorId) {
try {
return (Double) em.createNamedQuery(
"findTotalVendorPartPricePerVendor")
.setParameter("id", vendorId)
.getSingleResult();
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public Collection<String> locateVendorsByPartialName(String name) {
Collection<String> names = new ArrayList<String>();
try {
List vendors = em.createNamedQuery("findVendorsByPartialName")
.setParameter("name", name)
.getResultList();
for (Iterator iterator = vendors.iterator(); iterator.hasNext();) {
Vendor vendor = (Vendor) iterator.next();
names.add(vendor.getName());
}
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
return names;
}
public int countAllItems() {
int count = 0;
try {
count = em.createNamedQuery("findAllLineItems")
.getResultList()
.size();
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
return count;
}
public void removeOrder(Integer orderId) {
try {
Order order = em.find(Order.class, orderId);
em.remove(order);
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public String reportVendorsByOrder(Integer orderId) {
StringBuffer report = new StringBuffer();
try {
List vendors = em.createNamedQuery("findVendorByOrder")
.setParameter("id", orderId)
.getResultList();
for (Iterator iterator = vendors.iterator(); iterator.hasNext();) {
Vendor vendor = (Vendor) iterator.next();
report.append(vendor.getVendorId())
.append(' ')
.append(vendor.getName())
.append(' ')
.append(vendor.getContact())
.append('\n');
}
} catch (Exception e) {
throw new EJBException(e);
}
return report.toString();
}
}
public class OrderClient {
@EJB
private static Request request;
private static MessageFormat mf = new MessageFormat(
": {0, number, $#,##0.##}");
/** Creates a new instance of OrderClient */
public OrderClient(String[] args) {
}
public static void main(String[] args) {
OrderClient client = new OrderClient(args);
try {
client.createData();
client.printData();
} catch (Exception ex) {
System.err.println("Caught an exception in main():");
ex.printStackTrace();
}
}
private static void createData() {
try {
request.createPart(
"1234-5678-01",
1,
"ABC PART",
new java.util.Date(),
"PARTQWERTYUIOPASXDCFVGBHNJMKL",
null);
request.createPart(
"9876-4321-02",
2,
"DEF PART",
new java.util.Date(),
"PARTQWERTYUIOPASXDCFVGBHNJMKL",
null);
request.createPart(
"5456-6789-03",
3,
"GHI PART",
new java.util.Date(),
"PARTQWERTYUIOPASXDCFVGBHNJMKL",
null);
request.createPart(
"ABCD-XYZW-FF",
5,
"XYZ PART",
new java.util.Date(),
"PARTQWERTYUIOPASXDCFVGBHNJMKL",
null);
request.createPart(
"SDFG-ERTY-BN",
7,
"BOM PART",
new java.util.Date(),
"PARTQWERTYUIOPASXDCFVGBHNJMKL",
null);
request.addPartToBillOfMaterial(
"SDFG-ERTY-BN",
7,
"1234-5678-01",
1);
request.addPartToBillOfMaterial(
"SDFG-ERTY-BN",
7,
"9876-4321-02",
2);
request.addPartToBillOfMaterial(
"SDFG-ERTY-BN",
7,
"5456-6789-03",
3);
request.addPartToBillOfMaterial(
"SDFG-ERTY-BN",
7,
"ABCD-XYZW-FF",
5);
request.createVendor(
100,
"WidgetCorp",
"111 Main St., Anytown, KY 99999",
"Mr. Jones",
"888-777-9999");
request.createVendor(
200,
"Gadget, Inc.",
"123 State St., Sometown, MI 88888",
"Mrs. Smith",
"866-345-6789");
request.createVendorPart("1234-5678-01", 1, "PART1", 100.00, 100);
request.createVendorPart("9876-4321-02", 2, "PART2", 10.44, 200);
request.createVendorPart("5456-6789-03", 3, "PART3", 76.23, 200);
request.createVendorPart("ABCD-XYZW-FF", 5, "PART4", 55.19, 100);
request.createVendorPart("SDFG-ERTY-BN", 7, "PART5", 345.87, 100);
Integer orderId = new Integer(1111);
request.createOrder(
orderId,
'N',
10,
"333 New Court, NewCity, CA 90000");
request.addLineItem(orderId, "1234-5678-01", 1, 3);
request.addLineItem(orderId, "9876-4321-02", 2, 5);
request.addLineItem(orderId, "ABCD-XYZW-FF", 5, 7);
orderId = new Integer(4312);
request.createOrder(
orderId,
'N',
0,
"333 New Court, NewCity, CA 90000");
request.addLineItem(orderId, "SDFG-ERTY-BN", 7, 1);
request.addLineItem(orderId, "ABCD-XYZW-FF", 5, 3);
request.addLineItem(orderId, "1234-5678-01", 1, 15);
} catch (Exception ex) {
System.err.println("Caught an exception in createData():");
ex.printStackTrace();
}
}
private static void printData() {
try {
double price = request.getBillOfMaterialPrice(
"SDFG-ERTY-BN",
7,
null,
0);
System.out.println(
"Cost of Bill of Material for PN " + "SDFG-ERTY-BN"
+ " Rev: " + 7
+ mf.format(new Object[] { new Double(price) }));
printCostOfOrders();
System.out.println("\nAdding 5% discount");
request.adjustOrderDiscount(5);
printCostOfOrders();
System.out.println("\nRemoving 7% discount");
request.adjustOrderDiscount(-7);
printCostOfOrders();
java.lang.Double price0 = request.getAvgPrice();
if (price0 == null) {
System.out.println("\nNo parts found");
} else {
System.out.println(
"\nAverage price of all parts"
+ mf.format(new Object[] { price0 }));
}
price0 = request.getTotalPricePerVendor(100);
if (price0 == null) {
System.out.println("\nNo parts found for Vendor " + 100);
} else {
System.out.println(
"\nTotal price of parts for Vendor " + 100 + ""
+ mf.format(new Object[] { price0 }));
}
System.out.println("\nOrdered list of vendors for order 1111");
System.out.println(request.reportVendorsByOrder(new Integer(1111)));
System.out.println("Counting all line items");
int count = request.countAllItems();
System.out.println("Found " + count + " line items");
System.out.println("\nRemoving Order 4312");
request.removeOrder(new Integer(4312));
System.out.println("Counting all line items");
count = request.countAllItems();
System.out.println("Found " + count + " line items");
Collection names = request.locateVendorsByPartialName("I");
System.out.println(
"\nFound " + names.size()
+ " out of 2 vendors with 'I' in the name:");
for (Iterator it = names.iterator(); it.hasNext();) {
System.out.println(it.next());
}
} catch (Exception ex) {
System.err.println("Caught an exception in printData():");
ex.printStackTrace();
}
}
private static void printCostOfOrders() {
Integer orderId = new Integer(1111);
double price = request.getOrderPrice(orderId);
System.out.println(
"Cost of Order " + orderId
+ mf.format(new Object[] { new Double(price) }));
orderId = new Integer(4312);
price = request.getOrderPrice(orderId);
System.out.println(
"Cost of Order " + orderId
+ mf.format(new Object[] { new Double(price) }));
}
}
J2EE – 1.4 :
CMP – Many2Many - LocalEntity – Session - Client:
public interface LocalVendorPartHome extends EJBLocalHome {
public LocalVendorPart findByPrimaryKey(Object aKey)
throws FinderException;
public LocalVendorPart create(String description, double price,
LocalPart part) throws CreateException;
public Double getAvgPrice();
public Double getTotalPricePerVendor(int vendorId);
}
public interface LocalVendorPart extends EJBLocalObject {
public double getPrice();
}
public abstract class VendorPartBean implements EntityBean {
private EntityContext context;
/**
* @see EntityBean#setEntityContext(EntityContext)
*/
public void setEntityContext(EntityContext aContext) {
context = aContext;
}
/**
* @see EntityBean#ejbActivate()
*/
public void ejbActivate() {
}
/**
* @see EntityBean#ejbPassivate()
*/
public void ejbPassivate() {
}
/**
* @see EntityBean#ejbRemove()
*/
public void ejbRemove() {
}
/**
* @see EntityBean#unsetEntityContext()
*/
public void unsetEntityContext() {
context = null;
}
/**
* @see EntityBean#ejbLoad()
*/
public void ejbLoad() {
}
/**
* @see EntityBean#ejbStore()
*/
public void ejbStore() {
}
public abstract String getDescription();
public abstract void setDescription(String description);
public abstract double getPrice();
public abstract void setPrice(double price);
public abstract LocalPart getPart();
public abstract void setPart(LocalPart part);
public abstract LocalVendor getVendor();
public abstract void setVendor(LocalVendor vendor);
public Object ejbCreate(String description, double price, LocalPart part)
throws CreateException {
setDescription(description);
setPrice(price);
return null;
}
public void ejbPostCreate(String description, double price, LocalPart part)
throws CreateException {
setPart(part);
}
public abstract Double ejbSelectAvgPrice() throws FinderException;
public abstract Double ejbSelectTotalPricePerVendor(int vendorId)
throws FinderException;
public Double ejbHomeGetAvgPrice() throws FinderException {
return ejbSelectAvgPrice();
}
public Double ejbHomeGetTotalPricePerVendor(int vendorId)
throws FinderException {
return ejbSelectTotalPricePerVendor(vendorId);
}
}
public interface RequestHome extends EJBHome {
public request.Request create() throws CreateException, RemoteException;
}
public interface Request extends EJBObject {
public void createPart(PartRequest partRequest) throws RemoteException;
public void addPartToBillOfMaterial(BomRequest bomRequest)
throws RemoteException;
public void createVendor(VendorRequest vendorRequest)
throws RemoteException;
public void createVendorPart(VendorPartRequest vendorPartRequest)
throws RemoteException;
public void createOrder(OrderRequest orderRequest)
throws RemoteException;
public void addLineItem(LineItemRequest lineItemRequest)
throws RemoteException;
public double getBillOfMaterialPrice(BomRequest bomRequest)
throws RemoteException;
public Double getAvgPrice() throws RemoteException;
public Double getTotalPricePerVendor(VendorRequest vendorRequest)
throws RemoteException;
public double getOrderPrice(Integer orderId) throws RemoteException;
public void adjustOrderDiscount(int adjustment) throws RemoteException;
public Collection locateVendorsByPartialName(String name)
throws RemoteException;
public String reportVendorsByOrder(Integer orderId)
throws RemoteException;
public int countAllItems() throws RemoteException;
public void removeOrder(Integer orderId) throws RemoteException;
}
public class RequestBean implements SessionBean {
private SessionContext context;
private LocalLineItemHome lineItemHome = null;
private LocalOrderHome orderHome = null;
private LocalPartHome partHome = null;
private LocalVendorHome vendorHome = null;
private LocalVendorPartHome vendorPartHome = null;
/**
* @see SessionBean#setSessionContext(SessionContext)
*/
public void setSessionContext(SessionContext aContext) {
context = aContext;
}
/**
* @see SessionBean#ejbActivate()
*/
public void ejbActivate() {
}
/**
* @see SessionBean#ejbPassivate()
*/
public void ejbPassivate() {
}
/**
* @see SessionBean#ejbRemove()
*/
public void ejbRemove() {
}
/**
* See section 7.10.3 of the EJB 2.0 specification
*/
public void ejbCreate() {
try {
lineItemHome = lookupLineItem();
orderHome = lookupOrder();
partHome = lookupPart();
vendorHome = lookupVendor();
vendorPartHome = lookupVendorPart();
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public void createPart(PartRequest partRequest) {
try {
LocalPart part =
partHome.create(partRequest.partNumber, partRequest.revision,
partRequest.description, partRequest.revisionDate,
partRequest.specification, partRequest.drawing);
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public void addPartToBillOfMaterial(BomRequest bomRequest) {
try {
PartKey bomkey = new PartKey();
bomkey.partNumber = bomRequest.bomPartNumber;
bomkey.revision = bomRequest.bomRevision;
LocalPart bom = partHome.findByPrimaryKey(bomkey);
PartKey pkey = new PartKey();
pkey.partNumber = bomRequest.partNumber;
pkey.revision = bomRequest.revision;
LocalPart part = partHome.findByPrimaryKey(pkey);
part.setBomPart(bom);
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public void createVendor(VendorRequest vendorRequest) {
try {
LocalVendor vendor =
vendorHome.create(vendorRequest.vendorId, vendorRequest.name,
vendorRequest.address, vendorRequest.contact,
vendorRequest.phone);
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public void createVendorPart(VendorPartRequest vendorPartRequest) {
try {
PartKey pkey = new PartKey();
pkey.partNumber = vendorPartRequest.partNumber;
pkey.revision = vendorPartRequest.revision;
LocalPart part = partHome.findByPrimaryKey(pkey);
LocalVendorPart vendorPart =
vendorPartHome.create(vendorPartRequest.description,
vendorPartRequest.price, part);
VendorKey vkey = new VendorKey();
vkey.vendorId = vendorPartRequest.vendorId;
LocalVendor vendor = vendorHome.findByPrimaryKey(vkey);
vendor.addVendorPart(vendorPart);
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public void createOrder(OrderRequest orderRequest) {
try {
LocalOrder order =
orderHome.create(orderRequest.orderId, orderRequest.status,
orderRequest.discount, orderRequest.shipmentInfo);
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public void addLineItem(LineItemRequest lineItemRequest) {
try {
LocalOrder order =
orderHome.findByPrimaryKey(lineItemRequest.orderId);
PartKey pkey = new PartKey();
pkey.partNumber = lineItemRequest.partNumber;
pkey.revision = lineItemRequest.revision;
LocalPart part = partHome.findByPrimaryKey(pkey);
LocalLineItem lineItem =
lineItemHome.create(order, lineItemRequest.quantity,
part.getVendorPart());
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public double getBillOfMaterialPrice(BomRequest bomRequest) {
double price = 0.0;
try {
PartKey bomkey = new PartKey();
bomkey.partNumber = bomRequest.bomPartNumber;
bomkey.revision = bomRequest.bomRevision;
LocalPart bom = partHome.findByPrimaryKey(bomkey);
Collection parts = bom.getParts();
for (Iterator iterator = parts.iterator(); iterator.hasNext();) {
LocalPart part = (LocalPart) iterator.next();
LocalVendorPart vendorPart = part.getVendorPart();
price += vendorPart.getPrice();
}
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
return price;
}
public double getOrderPrice(Integer orderId) {
double price = 0.0;
try {
LocalOrder order = orderHome.findByPrimaryKey(orderId);
price = order.calculateAmmount();
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
return price;
}
public void adjustOrderDiscount(int adjustment) {
orderHome.adjustDiscount(adjustment);
}
public Double getAvgPrice() {
return vendorPartHome.getAvgPrice();
}
public Double getTotalPricePerVendor(VendorRequest vendorRequest) {
return vendorPartHome.getTotalPricePerVendor(vendorRequest.vendorId);
}
public Collection locateVendorsByPartialName(String name) {
Collection names = new ArrayList();
try {
Collection vendors = vendorHome.findByPartialName(name);
for (Iterator iterator = vendors.iterator(); iterator.hasNext();) {
LocalVendor vendor = (LocalVendor) iterator.next();
names.add(vendor.getName());
}
} catch (FinderException e) {
}
return names;
}
public int countAllItems() {
int count = 0;
try {
count = lineItemHome.findAll()
.size();
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
return count;
}
public void removeOrder(Integer orderId) {
try {
orderHome.remove(orderId);
} catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public String reportVendorsByOrder(Integer orderId) {
StringBuffer report = new StringBuffer();
try {
Collection vendors = vendorHome.findByOrder(orderId);
for (Iterator iterator = vendors.iterator(); iterator.hasNext();) {
LocalVendor vendor = (LocalVendor) iterator.next();
report.append(vendor.getVendorId())
.append(' ')
.append(vendor.getName())
.append(' ')
.append(vendor.getContact())
.append('\n');
}
} catch (FinderException e) {
throw new EJBException(e.getMessage());
}
return report.toString();
}
private LocalLineItemHome lookupLineItem() throws NamingException {
Context initial = new InitialContext();
Object objref = initial.lookup("java:comp/env/ejb/SimpleLineItem");
return (LocalLineItemHome) objref;
}
private LocalOrderHome lookupOrder() throws NamingException {
Context initial = new InitialContext();
Object objref = initial.lookup("java:comp/env/ejb/SimpleOrder");
return (LocalOrderHome) objref;
}
private LocalPartHome lookupPart() throws NamingException {
Context initial = new InitialContext();
Object objref = initial.lookup("java:comp/env/ejb/SimplePart");
return (LocalPartHome) objref;
}
private LocalVendorHome lookupVendor() throws NamingException {
Context initial = new InitialContext();
Object objref = initial.lookup("java:comp/env/ejb/SimpleVendor");
return (LocalVendorHome) objref;
}
private LocalVendorPartHome lookupVendorPart() throws NamingException {
Context initial = new InitialContext();
Object objref = initial.lookup("java:comp/env/ejb/SimpleVendorPart");
return (LocalVendorPartHome) objref;
}
}
public class Client {
private static OrderRequest orderRequest;
private static MessageFormat mf =
new MessageFormat(": {0, number, $#,##0.##}");
public static void main(String[] args) {
try {
Context initial = new InitialContext();
Object objref = initial.lookup("java:comp/env/ejb/Request");
RequestHome home =
(RequestHome) PortableRemoteObject.narrow(objref,
RequestHome.class);
Request request = home.create();
createData(request);
printData(request);
} catch (Exception ex) {
System.err.println("Caught an exception:");
ex.printStackTrace();
}
}
private static void createData(Request request) {
try {
request.createPart(new PartRequest("1234-5678-01", 1, "ABC PART",
new java.util.Date(), "PARTQWERTYUIOPASXDCFVGBHNJMKL", null));
request.createPart(new PartRequest("9876-4321-02", 2, "DEF PART",
new java.util.Date(), "PARTQWERTYUIOPASXDCFVGBHNJMKL", null));
request.createPart(new PartRequest("5456-6789-03", 3, "GHI PART",
new java.util.Date(), "PARTQWERTYUIOPASXDCFVGBHNJMKL", null));
request.createPart(new PartRequest("ABCD-XYZW-FF", 5, "XYZ PART",
new java.util.Date(), "PARTQWERTYUIOPASXDCFVGBHNJMKL", null));
request.createPart(new PartRequest("SDFG-ERTY-BN", 7, "BOM PART",
new java.util.Date(), "PARTQWERTYUIOPASXDCFVGBHNJMKL", null));
request.addPartToBillOfMaterial(new BomRequest("SDFG-ERTY-BN", 7,
"1234-5678-01", 1));
request.addPartToBillOfMaterial(new BomRequest("SDFG-ERTY-BN", 7,
"9876-4321-02", 2));
request.addPartToBillOfMaterial(new BomRequest("SDFG-ERTY-BN", 7,
"5456-6789-03", 3));
request.addPartToBillOfMaterial(new BomRequest("SDFG-ERTY-BN", 7,
"ABCD-XYZW-FF", 5));
request.createVendor(new VendorRequest(100, "WidgetCorp",
"111 Main St., Anytown, KY 99999", "Mr. Jones",
"888-777-9999"));
request.createVendor(new VendorRequest(200, "Gadget, Inc.",
"123 State St., Sometown, MI 88888", "Mrs. Smith",
"866-345-6789"));
request.createVendorPart(new VendorPartRequest("1234-5678-01", 1,
"PART1", 100.00, 100));
request.createVendorPart(new VendorPartRequest("9876-4321-02", 2,
"PART2", 10.44, 200));
request.createVendorPart(new VendorPartRequest("5456-6789-03", 3,
"PART3", 76.23, 200));
request.createVendorPart(new VendorPartRequest("ABCD-XYZW-FF", 5,
"PART4", 55.19, 100));
request.createVendorPart(new VendorPartRequest("SDFG-ERTY-BN", 7,
"PART5", 345.87, 100));
Integer orderId = new Integer(1111);
request.createOrder(new OrderRequest(orderId, 'N', 10,
"333 New Court, NewCity, CA 90000"));
request.addLineItem(new LineItemRequest(orderId, "1234-5678-01", 1,
3));
request.addLineItem(new LineItemRequest(orderId, "9876-4321-02", 2,
5));
request.addLineItem(new LineItemRequest(orderId, "ABCD-XYZW-FF", 5,
7));
orderId = new Integer(4312);
request.createOrder(new OrderRequest(orderId, 'N', 0,
"333 New Court, NewCity, CA 90000"));
request.addLineItem(new LineItemRequest(orderId, "SDFG-ERTY-BN", 7,
1));
request.addLineItem(new LineItemRequest(orderId, "ABCD-XYZW-FF", 5,
3));
request.addLineItem(new LineItemRequest(orderId, "1234-5678-01", 1,
15));
} catch (Exception ex) {
System.err.println("Caught an exception:");
ex.printStackTrace();
}
}
private static void printData(Request request) {
try {
BomRequest bomRequest = new BomRequest("SDFG-ERTY-BN", 7, null, 0);
double price = request.getBillOfMaterialPrice(bomRequest);
System.out.println("Cost of Bill of Material for PN " +
bomRequest.bomPartNumber + " Rev: " + bomRequest.bomRevision +
mf.format(new Object[] { new Double(price) }));
printCostOfOrders(request);
System.out.println("\nAdding 5% discount");
request.adjustOrderDiscount(5);
printCostOfOrders(request);
System.out.println("\nRemoving 7% discount");
request.adjustOrderDiscount(-7);
printCostOfOrders(request);
java.lang.Double price0 = request.getAvgPrice();
if (price0 == null) {
System.out.println("\nNo parts found");
} else {
System.out.println("\nAverage price of all parts" +
mf.format(new Object[] { price0 }));
}
VendorRequest vendorRequest =
new VendorRequest(100, null, null, null, null);
price0 = request.getTotalPricePerVendor(vendorRequest);
if (price0 == null) {
System.out.println("\nNo parts found for Vendor " +
vendorRequest.vendorId);
} else {
System.out.println("\nTotal price of parts for Vendor " +
vendorRequest.vendorId + "" +
mf.format(new Object[] { price0 }));
}
System.out.println("\nOrdered list of vendors for order 1111");
System.out.println(request.reportVendorsByOrder(new Integer(1111)));
System.out.println("Counting all line items");
int count = request.countAllItems();
System.out.println("Found " + count + " line items");
System.out.println("\nRemoving Order");
request.removeOrder(new Integer(4312));
count = request.countAllItems();
System.out.println("Found " + count + " line items");
Collection names = request.locateVendorsByPartialName("I");
System.out.println("\nFound " + names.size() +
" out of 2 vendors with 'I' in the name:");
for (Iterator it = names.iterator(); it.hasNext();) {
System.out.println(it.next());
}
} catch (Exception ex) {
System.err.println("Caught an exception:");
ex.printStackTrace();
}
}
private static void printCostOfOrders(Request request)
throws java.rmi.RemoteException {
Integer orderId = new Integer(1111);
double price = request.getOrderPrice(orderId);
System.out.println("Cost of Order " + orderId +
mf.format(new Object[] { new Double(price) }));
orderId = new Integer(4312);
price = request.getOrderPrice(orderId);
System.out.println("Cost of Order " + orderId +
mf.format(new Object[] { new Double(price) }));
}
}