📄 client.java
字号:
//定义本类在包examples.ejb.basic.containerManaged 中
package examples.ejb.basic.containerManaged;
//本类用到的其他类
import java.rmi.RemoteException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;
//本类用到的EJB类
import javax.ejb.CreateException;
import javax.ejb.DuplicateKeyException;
import javax.ejb.FinderException;
import javax.ejb.ObjectNotFoundException;
import javax.ejb.RemoveException;
//本类用到的名称服务类
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
/**
* 这个类演示了如何调用一个实体EJB,并进行如下操作:
* A:创建一个Account远程对象,存入一些钱。然后试图提取超过当前结算的金额。或抛出用户定义的异常,
* 最后,清除Account远程对象。
* B:创建一些新的账号,它们有不同的结算值。找到所有计算值大于给定数值的账号。找到结算职为0的账号。
* 试图查找账号类型为null的账号。最后,删除所有新创立的账号。
* 这个例子同时演示了怎样在JNDI树查找EJB主接口。
*/
public class Client {
//声明变量
private String url;
private String accountId;
private AccountHome home;
//构造方法
public Client(String url, String accountId)
throws NamingException {
this.url = url;
this.accountId = accountId;
//找找主接口,lookupHome是本例自定义方法。
home = lookupHome();
}
/**
* 在命令行运行这个实例:
* java examples.ejb.basic.containerManaged.Client "t3://localhost:7001"
* 参数是可选的
* @参数 url URL such as "t3://localhost:7001" of Server
* @参数 accountID String Account ID to test, default "10020"
*/
public static void main(String[] args) {
System.out.println("\nBeginning containerManaged.Client...\n");
String url = "t3://localhost:7001";
String accountId = "10020";
// Parse the argument list
switch(args.length) {
case 2:
accountId = args[1];
// fall through
case 1:
url = args[0];
break;
}
Client client = null;
try {
//实例化本类
client = new Client(url, accountId);
} catch (NamingException ne) {
//异常处理
log("Unable to look up the beans home: " + ne.getMessage());
System.exit(1);
}
try {
//运行实例A
client.runExamplePartA();
//运行实例B
client.runExamplePartB();
} catch (Exception e) {
//异常处理
log("There was an exception while creating and using the Accounts.");
log("This indicates that there was a problem communicating with the server: "+e);
}
System.out.println("\nEnd containerManaged.Client...\n");
}
/**
* 执行实例A
*
* A: 存入一定数量的金额,并试图提取超过结算的金额,会抛出应用定义的异常
*/
public void runExamplePartA() {
log("Starting Part A of the example...\n");
//初始化变量
double initialBalance = 3000;
String accountType = "Savings";
Account ac = null;
try {
//创建账号,createAccount是本类定义的方法
ac = createAccount(accountId, initialBalance, accountType);
} catch(DuplicateKeyException dke) {
//异常处理
log("An account with id " + accountId + " already exists!");
} catch(Exception e) {
//异常处理
log("Error creating account: " + e.getMessage());
System.exit(1);
}
//设置初始化变量
int amount = 2000;
double balance = 0;
log("\nPart A: Depositing $" + amount );
try {
//存入一定数量的金额,deposit是EJB远程方法
balance = ac.deposit(amount);
log("Current balance is $" + balance);
} catch (Exception e) {
log("Error during deposit: "+e.getMessage());
}
try {
log("Attempting to withdraw an amount greater than current balance. Expecting an exception...\n");
//试图提取超过结算的金额
balance = ac.withdraw(balance+1);
log("Error: expected an exception.");
} catch (ProcessingErrorException pe) {
//异常处理
log("Received expected Processing Error:\n" + pe);
} catch(Exception e) {
//异常处理
log("Error during withdraw: "+e.getMessage());
}
log("Removing account...\n");
try {
//清除账号ac,remove 是远程EJB方法
ac.remove();
} catch(Exception e) {
log("Error removing account: "+e.getMessage());
}
log("End Part A of the example...\n");
}
/**
* 例B
*
* B: 创建20个不同结算值的新账号。
* 找到所有结算值大于给定值的账号
* 结束时,清除账号
*/
public void runExamplePartB()
throws CreateException, RemoteException, FinderException,
RemoveException
{
log("Starting Part B of the example...\n");
//声明变量
int numBeans = 20;
//声明远程对象数组
Account [] accounts = new Account [numBeans];
// 创建20个有不同初值的账号
for (int i=0; i<numBeans; i++) {
// if (Math.IEEEremainder(i, 5) == 0)
if (i % 5 == 0) {
// 创建一些账号类型为null的账号。
// (仅仅是为了下面的查找)
accounts [i] = findOrCreateAccount("ID: "+i, i * 1000, null);
} else {
accounts [i] = findOrCreateAccount("ID: "+i, i * 1000, "Savings");
}
}
// 打印账号结算值
for (int i=0; i<numBeans; i++) {
log("Account: :"+accounts[i].getPrimaryKey()+
" has a balance of "+accounts[i].balance());
}
// 查找所有结算大于5000的账号
findBigAccounts(5000.0);
// 查找第一个结算值为0的账号
findAccountWithZeroBalance();
// 查找所有账号类型为null的账号
findNullAccounts();
// 清除所有账号
log("Removing beans...");
for (int i=0; i<numBeans; i++) {
accounts[i].remove();
}
log("End Part B of the example...\n");
}
/**
* 列出第一个结算值为0的账号
* 这个finder方法演示了只返回一个纪录的方法。
*/
private void findAccountWithZeroBalance()
throws FinderException, RemoteException
{
log("\nQuerying for an account with zero balance...");
try {
// 创建账号远程对象
Account zeroBalance = (Account)
PortableRemoteObject.narrow(home.findAccount(0), Account.class);
// Account zeroBalance = home.findAccount(0);
log("Account " + zeroBalance.getPrimaryKey() +
"; balance is zero");
} catch(ObjectNotFoundException onfe) {
//异常处理
log("No Account was found with a balance of zero");
}
}
/**
* 列出所有账号类型为null的账号
* 这个finder方法演示返回账号枚举
*/
private void findNullAccounts()
throws RemoteException, FinderException
{
log("\nQuerying for accounts with a null account type");
//账号枚举
Enumeration enum = home.findNullAccounts();
if(! enum.hasMoreElements()) {
log("No accounts were found with a null account type");
}
//创建账号远程对象
while (enum.hasMoreElements()) {
Account nullAccount= (Account)
PortableRemoteObject.narrow(enum.nextElement(), Account.class);
log("Account " + nullAccount.getPrimaryKey() + "; account type is " + nullAccount.accountType());
}
}
/**
* 列出所有结算大于给定值的账号
* 这个finder方法演示返回枚举账号
*/
private void findBigAccounts(double balanceGreaterThan)
throws RemoteException, FinderException
{
log("\nQuerying for accounts with a balance greater than " +
balanceGreaterThan + "...");
//调用主接口创建账号方法findBigAccounts,返回账号枚举
Enumeration enum = home.findBigAccounts(balanceGreaterThan);
if(! enum.hasMoreElements()) {
log("No accounts were found!");
}
while (enum.hasMoreElements()) {
Account bigAccount= (Account)
//创建远程对象
PortableRemoteObject.narrow(enum.nextElement(), Account.class);
log("Account " + bigAccount.getPrimaryKey() +
"; balance is $" + bigAccount.balance());
}
}
/**
* 如果对应id的账号以存在,则返回这个id,否则创建它
*/
private Account findOrCreateAccount(String id, double balance, String accountType)
throws CreateException, FinderException, RemoteException
{
Account remote = null;
try {
remote = (Account)
PortableRemoteObject.narrow(home.findByPrimaryKey(id),Account.class);
// remote = home.findByPrimaryKey(id);
} catch (ObjectNotFoundException onfe) {
// 账号不存在,创建它
remote = createAccount(id, balance, accountType);
}
return remote;
}
/**
* 给定id和结算创建一个新的账号
*/
private Account createAccount(String id, double balance, String accountType)
throws CreateException, RemoteException
{
log ("Creating account " + id + " with a balance of " +
balance + " account type " + accountType + "...");
//创建远程账号对象
Account ac = (Account) PortableRemoteObject.narrow(
home.create(id, balance, accountType), Account.class);
log("Account " + id + " successfully created");
return ac;
}
/**
* 使用JNDI查找bean的主接口
*/
private AccountHome lookupHome()
throws NamingException
{
Context ctx = getInitialContext();
try {
//查找主接口
Object home = (AccountHome) ctx.lookup("containerManaged.AccountHome");
return (AccountHome) PortableRemoteObject.narrow(home, AccountHome.class);
} catch (NamingException ne) {
//异常处理
log("The client was unable to lookup the EJBHome. Please make sure " +
"that you have deployed the ejb with the JNDI name " +
"containerManaged.AccountHome on the WebLogic server at "+url);
throw ne;
}
}
/**
* 获取初始化上下文
*/
private Context getInitialContext() throws NamingException {
try {
// 设置属性对象
Properties h = new Properties();
h.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
h.put(Context.PROVIDER_URL, url);
//创建初始化上下文
return new InitialContext(h);
} catch (NamingException ne) {
//异常处理
log("We were unable to get a connection to the WebLogic server at "+url);
log("Please make sure that the server is running.");
throw ne;
}
}
//控制台输出
private static void log(String s) {
System.out.println(s);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -