📄 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";
public static final String ENV_BULK_DISCOUNT_RATE =
"java:comp/env/PricerProps/BULK_DISCOUNT_RATE";
/**
* bulk discounts apply to quantities of BULK or more items
*/
private static final int BULK = 5;
/*
* 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);
}
/**
* This method computes the applicable discount in absolute
* figure, based on bulk and personal discounts that may apply.
*
* @param quantity the number of items that a user intends to buy
* @param basePrice the overall, non-discounted volume of the
* purchase (individual price times quantity)
* @param the user name
* @return the subTotal for the line item after applying any
* applicable discounts, excluding taxes
*/
public double getDiscount(int quantity, double basePrice, String user)
{
double discountRate = getPersonalDiscountRate(user);
if( quantity >= BULK )
{
discountRate += getBulkDiscountRate();
}
/*
* Calculate the discount in absolute figures
*/
return basePrice * (discountRate/100);
}
/**
* A bulk discount applies to quantities of more than 5 pieces.
* @return the bulk discount rate int percent
*/
public double getBulkDiscountRate()
{
double discountRate = 0;
try
{
Context initCtx = new InitialContext();
String discountRateStr = (String)initCtx.lookup(ENV_BULK_DISCOUNT_RATE);
discountRate = Double.valueOf(discountRateStr).doubleValue();
System.out.println("Bulk Discount Rate:" + discountRate);
}
catch (Exception e)
{
e.printStackTrace();
}
return discountRate;
}
/**
* Customers with certain names get discounts. The discount rules
* are stored in the environment properties that the bean is
* deployed with.
*/
public double getPersonalDiscountRate(String userName)
{
/*
* Get the name of this customer.
*/
User user = getUser(userName);
String customerName = user.getCustomerID();
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();
double discountPercent =
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))
{
System.out.println("Pricer.priceSubtotal(): " +
customerName + " gets a " +
discountPercent + "% discount.");
return discountPercent;
}
}
}
catch(javax.naming.NameNotFoundException ne)
{
flag=false;
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Pricer.priceSubtotal(): " + customerName +
" doesn't get a discount.");
}
return 0;
}
/**
* Computes the subtotal price for a set of products the customer
* is interested in. The subtotal takes into account the price of
* each product the customer wants, the quantity of each product,
* and any personal 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");
/*
* First, get the user name and the Line Items contained
* within the Cart.
*/
String user = cart.getOwner();
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();
double discount = getDiscount( li.quantity, li.getBasePrice(), user);
li.setDiscount(discount);
/*
* And add the price to the subtotal.
*/
subTotal += (li.getBasePrice() - discount);
}
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("ejb/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 quote.
* 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");
try
{
double taxRate = getTaxRate();
double subTotal = cart.getSubtotal();
cart.setTaxes((taxRate/100) * subTotal);
}
catch (Exception e)
{
e.printStackTrace();
throw new PricerException(e.toString());
}
}
/**
* @return the applicable tax rate
*/
public double getTaxRate()
{
double taxRate = 0;
try
{
Context initCtx = new InitialContext();
String taxRateStr = (String) initCtx.lookup(ENV_TAX_RATE);
taxRate = Double.valueOf(taxRateStr).doubleValue();
System.out.println("Tax Rate:"+taxRate);
}
catch (Exception e)
{
e.printStackTrace();
}
return taxRate;
}
//----------------------------------------------------
// 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("Pricer.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 + -