Tải bản đầy đủ - 0 (trang)
Chapter 28. Exercises for Chapter 11

Chapter 28. Exercises for Chapter 11

Tải bản đầy đủ - 0trang

28.1Exercise11.1:AStatelessSessionBean

Inthisexercise,youwillbuildandexamineastatelesssession

bean,ProcessPaymentEJB,whichwritespaymentinformation

tothedatabase.Youwillalsobuildaclientapplicationtotest

thisProcessPaymentbean.

Thebeaninsertsthepaymentinformationdatadirectlyintothe

database,withoutusinganintermediaryentitybean.



28.1.1ExaminetheEJB

ThisexampleisbasedontheCustomerandAddressEJBsand

theirrelateddataobjectsthatyouusedinExercise6.3.The

presentexerciseleavestheseEJBsunchanged,andfocuseson

theProcessPaymentstatelesssessionbean.

TheProcessPaymentbeanhasaverysimpleremoteinterface.

Itoffersoptionstoprocessapaymentbycheck,cash,orcredit

card.Eachpossibilityishandledbyadifferentmethod.



28.1.1.1ProcessPaymentRemote.java



publicinterfaceProcessPaymentRemoteextendsjavax.ejb.EJBObje

{

publicbooleanbyCheck(CustomerRemotecustomer,

CheckDOcheck,

doubleamount)



throwsRemoteException,PaymentException;



publicbooleanbyCash(CustomerRemotecustomer,

doubleamount)

throwsRemoteException,PaymentException;



publicbooleanbyCredit(CustomerRemotecustomer,

CreditCardDOcard,

doubleamount)

throwsRemoteException,PaymentException;

...

}



Eachmethod'sthirdparameterisasimpletransactionamount.

Theothertwoaremoreinteresting.

ThefirstisaCustomerRemoteinterface,whichenablesthe

ProcessPaymentEJBtogetanyinformationitneedsaboutthe

customer.



It'spossibletouseEJBremoteinterfacesasparametersofotherEJB

methodsbecausetheyextendEJBObject,whichinturnextends

java.rmi.Remote.ObjectsimplementingeitherRemoteor

SerializableareperfectlyvalidRMItypes.Thischoiceofparameter

typemakesnodifferenceatalltotheEJBcontainer.



Thesecondparameterconveysthedetailsofthetransactionin

adataobjectwithatypethatreflectstheformofpayment.A

dataobjectisaSerializableobjectthataclientandaremote

servercanpassbyvaluebackandforth.Mostofthetimeitisa

simpledatacontainer,withminimalbehavior.Forexample,the

CheckDOclasscontainsthecheck'snumberandbarcode.



28.1.1.2CheckDO.java

publicclassCheckDOimplementsjava.io.Serializable

{

publicStringcheckBarCode;

publicintcheckNumber;



publicCheckDO(StringbarCode,intnumber)

{

this.checkBarCode=barCode;

this.checkNumber=number;

}



FocusontheProcessPaymentEJBimplementationforalittle

while.Eachremotemethodfirstperformsvaliditytests

appropriatetothetypeofpayment.Eventuallyallofthemcall

thesameprivatemethod:process(),whichinsertsthe

paymentinformationintothedatabase.Forexample,

byCredit()implementsthislogicasshown.



28.1.1.3ProcessPaymentBean.java

publicbooleanbyCredit(CustomerRemotecustomer,

CreditCardDOcard,

doubleamount)

throwsPaymentException

{

if(card.expiration.before(newjava.util.Date()))

{



thrownewPaymentException("Expirationdatehaspassed")

}

else

{

return

process(getCustomerID(customer),

amount,



CREDIT,

null,

-1,

card.number,



newjava.sql.Date(card.expiration.getTime(

}

}



Ifthecreditcardhasexpired,themethodthrowsanapplication

exception.Ifnot,itsimplydelegatesthechoreofinsertingthe

paymentinformationintothedatabasetoprocess().Note

thatsomeparameterspassedtoprocess()aremeaningless.

Forexample,thefourthparameterrepresentsthecheckbar

code,whichmeansnothinginacreditcardpayment,so

byCredit()passesadummyvalue.

Theprocess()methodisverysimilartotheejbCreate()

methodoftheBMPexampleinChapter10.Itsimplygetsa

data-sourceconnection,createsaPreparedStatement,and

insertsthepaymentinformationintothePAYMENTtable:

...

con=getConnection();



ps=con.prepareStatement



("INSERTINTOpayment(customer_id,amount,"+

"type,check_bar_code,"+

"check_number,credit_number,"+

"credit_exp_date)"+

"VALUES(?,?,?,?,?,?,?)");

ps.setInt(1,customerID.intValue());

ps.setDouble(2,amount);

ps.setString(3,type);

ps.setString(4,checkBarCode);

ps.setInt(5,checkNumber);

ps.setString(6,creditNumber);

ps.setDate(7,creditExpDate);



intretVal=ps.executeUpdate();

if(retVal!=1)

{

thrownewEJBException("Paymentinsertfailed");

}



returntrue;

...



Notethatthereturnedvalueisnotsignificant.Themethod

eitherreturnstrueorthrowsanapplicationexception,soits

returntypecouldaseasilybevoid.



28.1.2ExaminetheEJBStandardDeployment

Descriptor

TheProcessPaymentstandarddeploymentdescriptorisvery

similartooneyou'vealreadyseen.



28.1.2.1ejb-jar.xml

...





Aservicethathandlesmonetarypayments



ProcessPaymentEJB



com.titan.processpayment.ProcessPaymentHomeRemote


com.titan.processpayment.ProcessPaymentRemote


com.titan.processpayment.ProcessPaymentBean
Stateless

Container



minCheckNumber

java.lang.Integer

2000







DataSourcefortheTitandatabase
jdbc/titanDB

javax.sql.DataSource

Container





...



NotethattheProcessPaymentEJB'stagisset



toStatelessanditstagissetto

Container.Thesesettingsensurethatthecontainerwill

automaticallymanagethetransactionsandenlistany

transactionalresourcesthebeanuses.Chapter16oftheEJB

sectionofthisbookexplainshowthesetaskscanbehandledby

theEJBitself(ifit'sasessionbeanoramessage-drivenbean).

Thedescriptorcontainsareferencetoadatasourceitwilluse

tostorethepayments.Youusethisdatasourcethesameway

youdidintheBMPexampleinChapter10.



28.1.2.2ProcessPaymentBean.java

privateConnectiongetConnection()throwsSQLException

{

try

{

InitialContextjndiCntx=newInitialContext();



DataSourceds=(DataSource)

jndiCntx.lookup("java:comp/env/jdbc/titanDB");



returnds.getConnection();

}

catch(NamingExceptionne)



{

thrownewEJBException(ne);

}

}



Theejb-jar.xmlfilealsospecifiesanenvironmentproperty,

minCheckNumber.Environmentpropertiesprovideaveryflexible

waytoparameterizeabean'sbehavioratdeploymenttime.The

tagforminCheckNumberspecifiestheproperty's

type(java.lang.Integer)andadefaultvalue(2000).The

ProcessPaymentEJBaccessesthevalueofthispropertythrough

itsJNDIENC.



28.1.2.3ProcessPaymentBean.java

...

InitialContextjndiCntx=newInitialContext();



Integervalue=(Integer)jndiCntx.lookup

("java:comp/env/minCheckNumber");

...



Oneveryinterestingpointtonoteisthatalthoughthe



ProcessPaymentbeanworkswithCustomerbeans(recallthat

eachremotemethod'sfirstparameterisaCustomerinterface),

thedeploymentdescriptordoesn'tdeclareanyreferencetothe

CustomerEJB.Noortagis

neededbecausetheProcessPaymentbeanwon'tfindorcreate

CustomerbeansthroughtheCustomerRemoteHomeinterface,

butinsteadreceivesCustomerbeansdirectlyfromtheclient

application.Thus,fromtheProcessPaymentEJB'spointofview,

theCustomerisastandardremoteJavaobject.



28.1.3ExaminetheJBossDeployment

Descriptors

TheJBoss-specificdeploymentdescriptorforthe

ProcessPaymentbeanisverysimple.Itonlymapsthedata

sourcetotheembeddeddatabaseinJboss.



28.1.3.1jboss.xml



ProcessPaymentEJB

ProcessPaymentHomeRemote



jdbc/titanDB

java:/DefaultDS







Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 28. Exercises for Chapter 11

Tải bản đầy đủ ngay(0 tr)

×