Download Exploring Enterprise Java Beans (EJBs): Entity, Session, Interceptors, and JMS and more Study notes Computers and Information technologies in PDF only on Docsity!
Web Based Commerce 514H3 Dr Kingsley Sage
Room 2R308, Chichester II khs20@sussex.ac.uk
© University of Sussex 2009
Lecture 6
!! More about Enterprise Java Beans (Lots of code examples and snippets that you should be able to use as references for yourEJBs)
! own coding workInterceptors
Enterprise Java Beans components! A server side technology for developing and deploying
! components^ enterprise applicationEJB components are:^ containing^ the^ business^ logic^ of^ an
– – – scalabletransactionalmulti-user secure
! Three types of bean: – – – EntitySessionMessage beans beans driven beans
Enterprise Java Beans components
!! Component interface:In EJB 3, beans do not have component and home interfaces - they are intended as far as possible to look and feel like – defines the bean’s business logic methods
!! POJOsBuild on examples from previous lecture (taken from the EJB 3.0 book)Let’s start by looking at an entity bean …
Developing a session bean! Now we need to create a session bean that will act as
!! theWe shall start by using a stateless session beanThis^ interface session^ forbean^ interacting will take^ withon the^ the business^ Cabin^ entity process
! and responsibilities of a travel agent and will be called^ theNeed to define:^ TravelAgentEJB
– – aThe TravelAgent TravelAgentBean remote interfaceclass itself
// The remote interface import javax.ejb.Remote; import ….Cabin;
@Remote public interface TravelAgentRemote { public void createCabin(Cabin cabin); public Cabin findCabin(int id);
! The container that this particular interface is the remote business interface of the TravelAgentEJB @javax.ejb.Remote annotation tells the EJB
import import import import javax.ejb.Stateless;javax.persistence.EntityManager;javax.persistence.PersistenceContext;… .Cabin; @Stateless public @PersistenceContext( public manager.persist(cabin); class void TravelAgentBean createCabin(CabinunitName= implements“titan” cabin)) {TravelAgentRemoteprivate EntityManager { manager; }^ }^ public^ }^ return^ Cabin^ manager.find(Cabin.class,^ findCabin(int^ pKey)^ {^ pKey); !! The fileThe it must persistence.xml. persistence@PersistenceContext set the manager unit Inname this field iscase, withset annotation determinedit’ans titan.EntityManager Ittells could by the the be EJB XML anything instancecontainer deployment that ! manager.persist() persistence. written to the When database, this method ismaking an example isit called,persistent of containerthe dataentity managedbean cabin is
create ( ID SHIP_ID int table primary int, CABIN key NOT NULL, )^ BED_COUNT^ NAME^ DECK_LEVEL^ char(30),^ int,^ int !! Of theIn supported thiscourse, back case, end bywe using databaseJ2EE) must MySQL remember system!! (although to create it could an appropriate be any other CABIN RDMS table in !! OtherwiseOK, so let’s the look persistence at a client managerthat invokes will ourthrow stateless an exception session bean …
More on session beans (2)
!! Whether or not session beans are stateful, they are not persistent like entity beansSession beans do not represent persistent data and are not
! saved to any database. Instead, for^ you have the notion of “Conversational state can take whatever useful form isconversational state”^ stateful session beans
required e.g. session Ids, user name, date …
More on session beans (3)! Stateless session beans can have access to the
javax.ejb. SessionContext interface’s to the EJB container to obtain information about the context of the method invocation callSessionContext object can be used as the bean interface. The
!! Session bean can obtain a reference to its SessionContextUseful, for example, when fine grained access control by using the @Resource annotation
cannot be handled by security services alone because they involve business logic …
@Stateless public class Boolean implements Bank { @Resource SessionContext context; public void withdraw(int acctid, double amount)
throws AccessDeniedException { if (amount > 10000) { boolean isManager = context.isCallerInRole(“ if(!isManager) { Manager”);
}^ }^ // Only managers can withdraw more than £10k^ throw new AccessDeniedException();
}^ }^ …
More on session beans (4)! Stateless session beans only exist for the duration of
! their^ of^ canStateful session beans exist from the moment they are^ scope,^ be^ invocation.^ garbage^ they^ are^ collectedOnce^ released^ client^ byreleases^ the^ EJB^ them^ container^ or^ goes^ and^ out
first – – They are removed by the clientThey time out (vendor dependent) invoked and continue to exist until:
! OK, so let’s look at a stateful session bean …^ –^ The^ EJB^ container^ is^ shutdown
JMS and message beans! JMS is an API that can be used to access enterprise
!! messaging systemsCan be used to enable clients to message one anotherIn EJB 3.0, enterprise beans of all types can use JMS
! to send messagesDon’ messages – use message beans specifically insteadt try to write entity and session beans that receive
! Messaging models: – – PublishPoint to andpoint subscribe : one to one: one to many
! Let’s start by looking at a session bean sending a message to a JMS enabled application client …
@Resource(mappedName=“ private @Resource(mappedName=“ private ConnectionGactoryTopic topic; ConnectionFactoryNameGoesHere”TicketTopic” connectionFactory;) ) @Remove public if try throws (^) throw (^) (customer==nullTicketDO{ IncompleteConversationalStatenew IncompleteConversationalState();bookPassage(CreditCardDO, || cruise==null || {cabin==null)double price) Reservation entityManager.persist(reservation); // TicketDO new Some Reservation(customer,cruise,cabin,price, credit ticket reservation card = new processing TicketDO(customer,cruise,cabin,price); = might go here … new Date()); Connection Session MessageProducer TextMessage textMsg.setText( producer.send(textMsg); session connect textMsg (^) messageticketDescription);= connect.createSession(true,0);= =factory.createConnection(); session.createTextMessage(); = session.createProducer(topic); } }^ connect.close();^ returncatch(Exception throw newticket; EJBException(e); e) { }
import public public if (^) throwjavax.jms.*;class(args.length!=2) static newJmsClient_1 voidException(“ import main(String implements javax.naming.InitialContext;Wrong []number javax.jms,MessageListenerargs) of throws arguments”); Exception { { public^ } InitialCOntext ConnectionFactory^ new^ while(true){Thread.sleep(10000);} JmsClient_1(StringJmsClient_1(args[0],args[1]); jndiContext factory factoryName, == (ConnectionFactory)getInitialContext(); String topicName) throws Exception { Topic Conection Session MessageConsumer consumer.setMessageListener(this);^ jndiCOntext.lookup(“ConnectionFactoryNameGoesHere” topic session connect = (Topic) =consumer =connect.createSession(false, factory.createConnection(); jndiContext.lookup(“TopicNameGoesHere” = session.createConsumer(topic); Session,); AUTO_ACKNOWLEDGE);); } public^ connect.start(); try TextMessage String {void textonMessage(Message textMsg= textMsg. = (TextMessage)getText(); message) { message; } public^ }^ }^ System.out.println(“catch^ jmsE.printStackTrace(); static^ (JMSException InitialContext^ \nMESSAGEjmsE) getInitialContext(){^ RECEIVED:^ \n”^ + {text); }^ }^ //^ create^ vendor^ specific^ JNDI^ context^ here
Message driven beans! Enables asynchronous clients to access the business
!! logic in the EJB tierActivatedA client does not directly access a message driven by a message received from a JMS queue
! bean – instead a client asynchronously sends a^ message to a JMS queueDo not maintain state on behalf of a client
! OK, so let’s see an example of a message driven bean …
Interceptors (2)! In essence, interceptors give you a way to add
! functionality to your business methods without^ modifying the methods' codeFor example, you can use an interceptor to validate
! parameters before they're passed to a business^ method, or perform security checks at the time the^ business method is calledAlso useful for actions such as logging and profiling
! that cut across multiple components in an application^ (these are sometimes called "crosscutting" operations)You also have the flexibility to chain interceptors together
Defining an interceptor! You can use interceptor methods to intercept either a
! businessAn interceptor that intercepts a business method is typically called an^ method^ or AroundInvoke^ lifecycle^ event method because it
! can be defined by annotating the method with an^ @AroundInvokeYou can define an enterprise bean itself or on an external class. An^ annotation AroundInvoke method on the
interceptor class is just like any other class in the Java platform. It does not need to extend any special class or implement any interface
Writing an! You can use interceptor AroundInvoke methods to intercept method either a
! businessAn interceptor that intercepts a business method is typically called an^ method^ or AroundInvoke^ lifecycle^ event method because it
! can be defined by annotating the method with an^ @AroundInvokeYou can define an enterprise bean itself or on an external class. An^ annotation AroundInvoke method on the
interceptor class is just like any other class in the Java platform. It does not need to extend any special class or implement any interface
! Let’ Here s see an example … is an interceptor class that prints the time it takes
to run an intercepted business method: import javax.interceptor.AroundInvoke; public class MethodProfiler { public MethodProfiler() { }
@AroundInvoke private Object profile(InvocationContext invCtx) throws Exception { long t1 = System.nanoTime(); Object result = invCtx.proceed();
long t2 = System.nanoTime(); System.out.println( return result; "(" + invCtx. ((t2 - t1)/ 1000.0) + " nano seconds.");getParameters()[0] + ") took: " +invCtx.getMethod().getName() +
}^ }
Next time …
!! OurSpaceWeb services … overview