📄 pricerbean.java
字号:
package examples;
import javax.ejb.*;
import java.rmi.RemoteException;
import java.util.*;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;
/**
* Stateless Session Bean which computes prices based
* upon a set of pricing rules. The pricing rules are
* deployed with the bean as environment properties.
*/
public class PricerBean implements SessionBean {
// Constants used for reading properties
public static final String ENV_DISCOUNT = "java:comp/env/PricerProps/DISCOUNT_";
public static final String ENV_TAX_RATE = "java:comp/env/PricerProps/TAX_RATE";
/*
* Although this is a stateless session bean, we
* do have state - the session context. Remember
* that stateless session beans can store state, they
* just can't store state on behalf of particular
* clients.
*/
private SessionContext ctx;
//----------------------------------------------------
// Begin business methods
//----------------------------------------------------
/**
* Computes the total price of a cart. This includes
* subtotal and taxes. Sets the appropriate cart
* fields. We expose this coarse-grained method to
* avoid network roundtrips for pricing individual
* parts of a cart.
*/
public void price(Cart cart) throws PricerException, RemoteException {
priceSubtotal(cart);
priceTaxes(cart);
}
/**
* Computes the subtotal price for a set of Books the
* customer is interested in. The subtotal takes into
* account the price of each Book the customer wants,
* the quantity of each Book, and any discounts the
* customer gets. However, the subtotal ignores taxes.
*
* @param quote All the data needed to compute the
* subtotal is in this parameter.
*/
private void priceSubtotal(Cart cart) throws PricerException, RemoteException {
System.out.println("PricerBean.priceSubtotal() called");
/*
* Customers with certain names get discounts.
* The discount rules are stored in the
* environment properties that the bean is
* deployed with.
*
* Get the name of this customer.
*/
User user = getUser(cart.getOwner());
String customerName = user.getCustomerID();
double percentDiscount = 0;
boolean flag=true;
int i=0;
try {
Context initCtx = new InitialContext();
while(flag) {
/*
* Get the next discount equation from
* the environment properties. A
* discount equation has the form
* "<name>=<% discount>". For example,
* "Ed Roman=50" means that the
* Customer whose name is "Ed Roman"
* gets a 50% discount.
*/
String discount = (String) initCtx.lookup(ENV_DISCOUNT + i++);
System.out.println("Discount:"+discount);
/*
* Break the equation up into
* customer name, discount
*/
StringTokenizer tokens = new StringTokenizer(discount, "=", false);
String discountCustomerName = tokens.nextToken();
percentDiscount = Double.valueOf(tokens.nextToken()).doubleValue();
/*
* If this discount applies to this
* customer, then stop. Otherwise,
* move on to the next discount
* equation.
*/
if (discountCustomerName.equals(customerName)) {
break;
}
System.out.println("Pricer.priceSubtotal(): " + customerName + " gets a " + percentDiscount + "% discount.");
}
}catch(javax.naming.NameNotFoundException ne){
flag=false;
}catch (Exception e) {
e.printStackTrace();
System.out.println("Pricer.priceSubtotal(): " + customerName + " doesn't get a discount.");
}
/*
* Now we know how much discount to apply. The
* next step is to apply the discount to each
* Book the customer is interested in.
*
* We need to get the price and quantity of each
* Book the customer wants. The cart object
* stores this information in individual cart
* line-items. Each line-item has price and
* quantity information for a single Book.
*/
/*
* First, get the Line Items contained within the
* Cart.
*/
Enumeration lineItems = Collections.enumeration(cart.getAll());
/*
* Compute the subtotal
*/
double subTotal = 0;
try {
/*
* For each line item...
*/
while (lineItems.hasMoreElements()) {
LineItem li = (LineItem) lineItems.nextElement();
/*
* Get the price of the line item...
*/
double basePrice = li.getBasePrice();
/*
* Set the discount for this line item...
*/
li.setDiscount(basePrice * (percentDiscount/100));
/*
* Apply the discount...
*/
double aggregatePrice =
basePrice - (basePrice * percentDiscount/100);
/*
* And add the price to the subtotal.
*/
subTotal += aggregatePrice;
}
cart.setSubtotal(subTotal);
}catch (Exception e) {
throw new PricerException(e.toString());
}
}
/**
* This method uses UserManager session bean to retrive user information.
* User has customer id, name password and address.
*@param customerid id of the customer
*/
private User getUser(String customerId){
try{
Context ctx = new InitialContext();
UserManagerHome userManagerHome = (UserManagerHome)
PortableRemoteObject.narrow(
ctx.lookup("UserManagerHome"), UserManagerHome.class);
UserManager userManager=userManagerHome.create();
/*
* Usermanager returns user object for the given customerid
*/
User user=userManager.getUser(customerId);
return user;
}catch (Exception e) {
throw new EJBException(e);
}
}
/**
* Computes the taxes on a Cart.
* Since the taxes are based on the subtotal, we assume
* that the subtotal has already been calculated.
*/
private void priceTaxes(Cart cart) throws PricerException, RemoteException {
System.out.println("PricerBean.priceTaxes() called");
/*
* Compute the taxes
*/
try {
Context initCtx = new InitialContext();
String taxRateStr = (String) initCtx.lookup(ENV_TAX_RATE);
double taxRate = Double.valueOf(taxRateStr).doubleValue();
System.out.println("Tax Rate:"+taxRate);
double subTotal = cart.getSubtotal();
cart.setTaxes((taxRate/100) * subTotal);
}
catch (Exception e) {
e.printStackTrace();
throw new PricerException(e.toString());
}
}
//----------------------------------------------------
// End business methods
//----------------------------------------------------
//----------------------------------------------------
// Begin EJB-required methods. The methods below are
// called by the Container, and never called by client
// code.
//----------------------------------------------------
public void ejbCreate() throws RemoteException {
System.out.println("ejbCreate() called.");
}
public void ejbRemove() {
System.out.println("ejbRemove() called.");
}
public void ejbActivate() {
System.out.println("ejbActivate() called.");
}
public void ejbPassivate() {
System.out.println("ejbPassivate() called.");
}
public void setSessionContext(SessionContext ctx) {
System.out.println("setSessionContext() called");
this.ctx = ctx;
}
//----------------------------------------------------
// End EJB-required methods
//----------------------------------------------------
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -