Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Important Parts of Specification - Oracle Certified Expert, Enterprise Java Beans Developer

Tags: bean
(Revision Notes)

Session Beans

Object passed to a bean’s remote business view methods are always passed by value. Local – passed by ref – same object.
Only stateless and singleton beans can be used for web-service.
Passing multiple local or remote interfaces - @Local/@Remote({XLocal.class,YLocal.class})
Methods exposed to another bean deployed from same ejb-jar- all public methods defined in the bean.
To expose only one method as a webservice – annotate class with @WebService, annotate method with @WebMethod.
Stateless – constructor, setSessionContext, @PostConstruct, business method, @PreDestroy.
If system exception is thrown, container won’t call @PreDestroy. Interceptor methods in the chain should perform any necessary cleanup operations as the interceptor chain unwinds.
Stateless cannot access resource managers in @PostConstruct or @PreDestroy.
Remote parameter passing is done over RMI-IIOP.
Value given in <ejb-ref-name> must be used exactly as it is for “name” in @EJB. beanName must be name of target bean, in this case, target is given in <ejb-link> element. Variable type should be the value inside the local element.
Stateful can retrieve resource managers in their ejbCreate method. Stateless can do so in business methods because their ejbCreate() and ejbRemove() don’t have transaction or security context.
For each method in business interface of bean, there must be a matching method in business class.
References preserved during passivation – serializable objects, null, EB’s business interface or no-interface view, remote interface, remote home interface, entity bean’s local interface, local home interface, SessionContext, UserTransaction, Environmental Naming Context, Resource Manager Connection Factory,  Container managed Entity Manager object, EntityManagerFactory, Timer objects.
Recommended – declare all static fields in enterprise beans as final.
Any bean can directly access the database. Primary key is required for entities only. A separate process should clean up tables periodically based on DATETIMESTAMP of row.
Type-level DI needs to be put before class definition. Target of injection cannot be static or final.
References to other ejb’s home or component interfaces, even if they are not serializable are restored by container.
Embeddable usage requirements allow client code to instantiate an EJB container that runs within its own JVM and classloader.
No interface and local view – client should be packaged in same ejb-app. Same JVM is not enough.
Session EJB object is a persistent object.
To receive messages asynchronously-MDB, synchronously- Session Bean.
Initialization of resources occurs before any business methods are invoked on the bean instance and after the time the bean’s EJBContext is set.
Only stateful session beans can use a container managed entity manager with extended persistence context.
Interoperability – using 3.0 in 2.x business components – use @RemoteHome and @LocalHome to adapt 3.0 beans so that 2.x can lookup adapted home interfaces using JNDI.
For both horizontal and vertical clustering, business interfaces need both local and remote usage. Business methods are defined in common interface. It is extended by 2 interfaces, annotated with @Local and @Remote. Both interfaces are implemented by bean class.
Session beans with BMT can use transactional resources managed by container.

SessionSynchronization – container calls afterBegin, business methods, beforeCompletion and then afterCompletion.
Equals – two instances of same bean class/interface always equal/true for stateless and singleton, not equal/false for stateful.
A low quality container may choose to serialize multiple simultaneous client requests.
Only stateful beans with CMT may implement SessionSynchronization interface.
SessionSynchronization interface – afterBegin method notifies a session bean instance that a new transaction has started. beforeCompletion may not be called by container if transaction is marked for rollback.

Packaging

Names of env entries defined by an enterprise bean inside a .war can clash with names defined by other components in the same war.
A bean can’t change its environment. Env mechanism allows users of EB to customize business logic without modifying source code and allows EB to locate external information without prior knowledge of how the information is named and organized in target operational environment.

Timer

Timers cannot be created for stateful session beans or EJB 3.x entities. However, they can be created for 2.1 entity beans.
Conditional timer creation-programmatic- TimerService DI. Auto-deploy time- @Schedule.
2nd parameter of createTimer is just a data object and not a callback handle. Whichever method is annotated with @Timeout is invoked.
A timeout callback method can’t throw application exception.
Timeout method signature - void method() or void method(Timer timer). A bean that uses programmatic timers can have at most one timeout method even if it uses multiple Timers.
Signature of createTimer: public Timer createTimer(long duration, java.io.Serializable info) – if info is not serializable, bean will not compile.
Serializable TimerHandle may be persisted.
onMessage creates a Timer. @Timeout throws EJBException. If bean uses BMT and if the @Timeout method has started a transaction, container will roll it back, discard the bean instance and call timeout method again on a different instance.
getTimerService() in stateful – IllegalStateException.
Timeout callback method typically has transaction attributes – Required, Requires_New.
For calendar-based timers, expiration of the timer is expressed as a javax.ejb.ScheduleExpression object, passed as a parameter to the TimerService.createCalendarTimer method. ScheduleExpression schedule = new ScheduleExpression(); schedule.dayOfWeek(“Tue”); schedule.hour(“12-17,23”); Timer timer= timerService.createCalendarTimer(schedule);
@Schedule(dayOfWeek=”Sun”,hour=”0”)

Interceptors

One unique instance of interceptor is associated with one unique instance of a bean.
Lifecycle callback interceptors are allowed to throw system runtime exceptions but not application exceptions.
Interceptor allowed to throw those app exceptions that are listed in the throws clause of bean’s business methods or runtime exceptions.
Lifecycle callback interceptors are invoked in an unspecified security/transaction context, except for Singleton PostConstruct/PreDestroy methods.
Return type of interceptor method must match the return type of bean method on which interceptor is applied, otherwise a ClassCastException will be thrown.
AroundInvoke methods must have throws Exception.
Lifecycle call back interceptors – Method must not have parameters, must not thrown checked exception, return type must be void, method may be final, method must not be static except for the application client, method can be public, private, protected or package, if method throws unchecked exception, method must not be put into service except when EJB can handle them and recover.
AroundInvoke-allowed to catch and suppress exception – recover by calling proceed(), allowed to throw runtime or any checked exception the business method allows within its throw clause, can mark transaction for rollback by throwing a runtime exception or by calling setRollbackOnly().

Exceptions

Application exceptions - java.lang.Exception (java.io.IOException), not java.rmi.RemoteException or RuntimeException.
Operations dealing with JNDI – javax.naming.NamingException. Local-javax.ejb.NoSuchEJBException, Remote- java.rmi.NoSuchObjectException. java.lang.ClassNotFoundException – class instantiated using reflection API and JVM can’t find class. javax.ejb.ObjectNotFoundException – thrown by finder method to indicate EJB does not exist.
Finder, Create and Remove Exceptions are checked application exceptions & must be declared in throws clause of method.
If EJBTransactionRequiredException, subclass of EJBException is not caught upon receiving, it will be thrown out of bean to the container and container will discard the bean instance.
env-entry configured in DD. Without one, the values won’t be available in the NamingContext and lookup method will throw NameNotFoundException-Application Exception-rest will execute.
For unrecoverable checked exceptions, wrap it into EJBException and rethrow it.
System Exception – NoSuchEntityException. App Exceptions – ejb.DuplicateKeyException, ejb.ObjectNotFoundException, javax.naming.NamingException.
If client is outside rolled back transaction, it will get EJBException. The class that throws it gets discarded.
An app exception may be defined in the throws clause of a method of a web-service endpoint.
A system exception is a java.rmi.RemoteException or one of its subclasses or a RuntimeException that is not an application exception.
Container must throw java.lang.IllegalStateException if the EJBContext.getRollbackOnly method is invoked from a business method executing with the transaction attribute – Supports, Not_Supported or Never.
Application exception may be thrown by bean itself or by container while handling EJB’s create, find or remove methods.
App exceptions that are unchecked must be annotated or declared in DD.
Pre-defined application exceptions javax.ejb package (CreateException, FinderException, RemoveException, DuplicateKeyException, ObjectNotFoundException).
@AccessTimeout(value=”-1”)- client request will be blocked indefinitely until forward progress can be made. value=0 –>block concurrent access, throw javax.ejb.ConcurrentAccessException.
Never- javax.ejb.EJBException –local, java.rmi.RemoteException – remote.
NoSuchObjectException extends RemoteException.
Subclass of EJBException – javax.ejb.NoSuchObjectLocalException, NoSuchEntityException, TransactionRolledbackLocalException.
java.rmi.NoSuchObjectException –remote, javax.ejb.NoSuchObjectLocalException – local. – Client makes call to a session bean that has been removed. NoSuchEJBException – Stateful/Singleton.
java.lang.InvocationTargetException – thrown at runtime when a method is invoked by using Reflection API.
Responsibility of container to map the exception to the SOAP fault specified in the WSDL that describes the port type that the stateless bean implements.
javax.ejb.ObjectNotFound- subclass of javax.ejb.FinderException which is an application exception.

Transactions

If there is a transaction and a sys exception occurs, caller gets EJBTransactionRolledbackException, not EJBException.
Calling ut.commit when a transaction has been set for rollback will throw javax.transaction.RollbackException.
Transaction management type cannot be changed – immutable – set by bean provider. Transaction attribute values can be overriden by both deployer and app assembler.
BMT bean can’t run in the same transaction context as its caller.
<remove-method><retain-if-exception></…> If the bean is in a transaction when its remove method is called, it will throw RemoveException and the bean will not be discarded.
Entities execute within the transaction context of the caller.
A stateful session bean cannot be passivated if it is in a transaction.
Entities don’t manage their own transaction.
javax.transaction.UserTransaction has setTransactionTimeout(int secs).
To rollback conversational state to pre-transactional value if transaction rolls back, use afterCompletion method of SessionSynchronization interface.
TransactionRequiredException – remote. EJBTransactionRequiredException-local. Subclass of EJBException.
EB’s business methods, message listener methods, business interceptor methods, lifecycle callback interceptor methods, timeout callback method must not attempt to obtain or use the javax.transaction.UserTransaction interface.
RemoteException-Transaction Attribute – Never – if client is running with a transaction and invokes the method.
Transaction must be specified for onMessage() of MDB and remote interface methods of session beans.
UserTransaction – begin, commit, getStatus, rollback, setRollbackOnly.
In BMT, a bean that starts a transaction must complete the transaction before it starts a new transaction.

Async

For asynchronous method, regardless of kind of exception thrown by method, it gets java.util.concurrent.ExecutionException.
If the async method has return type void, then once control has returned from the client’s method call, no exceptions occurring during the processing of the invocation will be delivered to the client.
Return type of an async bean method must be void of Future<V>.
Required behaves like Requires_New for asynchronous calls.
If any one method has return type Future<V>, exception thrown from process of async method invocation is accessible to the client via getCause method of java.util.concurrent.ExecutionException thrown from Future.get() method.
EB architecture can use singleton, stateless(MD or Session) async service, stateful async service(stateful or stateless) and stateless sync service(stateless). JPA entities can be shared among clients.
Async methods with return type void must not declare app exceptions.
If a client calls cancel on its Future object, the container will attempt to cancel the associated asynchronous invocation if that invocation has not already been dispatched.
Caller security principal propagates with an asynchronous method invocation.

EJB Basics and Roles

App Assembler – declares <role-link> inside <security-role-ref>, <role-name> inside <security-role>, <security-identity>. Declares logical security roles, assigns method permissions and maps security role refs to security roles. Security view supplied by Application Assembler.
Bean Provider->declares logical security roles, declares roles using security-role-ref element and assigns method permissions.
Deployer->Assigns principal to security roles, creates app security policy descriptor, assigns security domain and principal realm. Deployer uses container tools to create or make available roles specified in <security-role> elements, maps app roles to the MySQL group tables. 
Sys admin- defines and configures the MySQL realm.
EJB profile supports: JMS, JTA, JavaMail, Java Connector Architecture, Web Services, JAX-RPC, JAX-WS, JAXB, JAXR, Management, JACC, JAS-PIC, WS Metadata, Common Annotation, JPA, Bean Validation, Managed Beans, Interceptor, Context and DI.
Resource manager – javax.sql.DataSource, javax.jms.QueueConnectionFactory/TopicConnectionFactory, javax.mail.Session, java.net.URL.
EJB 3.1  Embeddable API requires only EJB 3.1 Lite. EJBContainer ec=EJBContainer.createEJBContainer(properties); Context ctx=ec.getContext();
sctx.lookup doesn’t take a class parameter, it takes string parameter. java:global/appname/modulename/package.class!YLocal
A client retrieves a Context using the EJBContainer method: javax.naming.Context. EJBContainer.getContext().
For InitialContext, we must use full name and EJBContext/Session Context uses relative name.
sessionCtx.getBusinessObject obtains an object that can be used to invoke the current bean through a particular business interface or its no-interface view.
sctx.getBusinessObject(BeanRemote.class);
A type level dependency cannot be injected in a variable. It can only be made available in EJBContext and InitialContext and must be looked up by bean methods. Type-level dependency must have type parameter.
EJB’s are allowed to be socket clients. They cannot create a Socket server.
Entities don’t have EJBContext.
Annotations that cannot be overriden - @Stateless, @Stateful, @MessageDriven, @Service, @Consumer.
EJB Lite- No MDB, TimerService, CORBA interoperability, EJB 2.x support, Asynchronous invocation, Web Service interfaces, Remote interfaces.
Responsible for configuration and administration of enterprise’s computational and networking infrastructure that includes the EJB server and container. – Sys Admin.
Runtime support for deployed EB instances – EJB Container Provider.
Coarse grained transactions – JTA/JTS, Java CORBA services – JAVA IDL.
EB’s should not attempt to load a native library, create a new security manager, use java.lang.reflect, r/w nonfinal static fields, use java.awt, create/modify class loaders, redirect input/output/error streams, obtain security policy information, access/modify security configuration objects, create or manage threads, use thread sync primitives, stop JVM, listen on and accept connections or multicast from a network socket, change socket factories or change stream handler factory(java.net.URL), r/w a file descriptor, create/modify/delete files in a file system, use subclass and object substitution features of Java Serialization protocol.
Call to getEJBObject is valid when bean is remote, otherwise it throws IllegalStateException. Call to getMessageContext is used when bean is a web-service endpoint interface.
Transaction attribute for a CMT – specified by Bean Provider or Application Assembler.
Sys admin defines and configures LDAP realm.
Transaction, Security, Distribution and Concurrency Management are system level services.
Load balancing is not a guarantee for all EJB 3.0 containers.
APIs EJB container provides to EB at runtime – JNDI and JDBC API.
When a bean instance is discarded, resources held by instances acquired through the resource factories must be released by container. Responsibility – Container Provider.
Application assembler adds interceptor-binding (interceptor-order).
Responsibility of bean provider – For checked exceptions from which bean cannot recover, throw an EJBException that wraps the original exception. For app exception, ensure that if current transaction commits, there will be no loss of data integrity.

JNDI & Annotations

Container ensures enterprise bean instances have read-only access to their env variables. Throws javax.naming.OperationNotSupportedException from all methods of the javax.naming.Context interface.
JNDI requirements – EJB container must provide a JNDI namespace to bean instances. Following objects are available in the namespace:- UserTransaction, EJBContext, Resource Factories, EntityManagerFactory, ORB objects, TimerService objects, local business interfaces, remote business interfaces, references to no interface views, web service interfaces, home interfaces.
@Resource(lookup=””) should use global JNDI name and not relative name. @Resource(“”)=@Resource(name=””). Context iniContext=new InitialContext();
An env-entry needs to be defined in the ejb-jar.xml for a bean if the value is to be accessed using JNDI, but it should not contain env-entry-value element.
SessionContext is an interface that extends EJBContext interface.
InitialContext – lookup absolute. SessionContext – lookup relative. Lookup should use name and not beanName. Container binds name to beanName.
@Resource can decorate a class, a field or a method at runtime/init through injection. (name, type, authenticationType, shareable, mappedName, description)
Type- level env dependency on a Topic - @Resource(name=”topicRef”, type=Topic.class)

MDB

MDB – public class, cannot be abstract or final, must contain a public no-arg constructor, must not define finalize method.
MessageDrivenContext.isCallerInRole & getCallerPrincipal will return values as per the run-as config of bean.
Message durability can be set by calling queueSender.send(Message m, int deliveryMode, int priority, long timeToLine). createSession(boolean transactional, ack mode) True – Transactional.
onMessage() can throw app exceptions but not checked exceptions or remote exceptions(throw a subclass of RuntimeException and annotate it with @ApplicationException).
MDB CMT – sys exception – message gets redelivered. BMT – Container shouldn't acknowledge receipt.
MDB CMT - Message receipt part of transaction. BMT  – Message acknowledgement is auto-handled by container.
There is no need to close sessions, producers and consumers of a closed connection.
@MessageDriven(activationConfig={@ActivationConfigProperty{propertyName=”MessageSelector”, propertyValue=”JMS Type=’car’ AND color=’blue’ and weight>2500”)})
MDB- only Required and NotSupported allowed.
Where the bean fails to either rollback or commit a transaction, container throws EJBException only for session beans, not for MDBs. For MDBs, it always rolls back the transaction and discards the instance.
Poison message- CMT MDB throws a sys exception, transaction is rolled back and message receipt is never acknowledged. Container delivers message again and causes an infinite loop of delivering the message.
Topic/Queue data type can be Destination. Must not be static.
MessageDrivenBean interface has 2 methods- setMessageDrivenContext and ejbRemove.
createQueueSession(boolean transacted, Session.AUTO_ACKNOWLEDGE/CLIENT_ACKNOWLEDGE/DUPS_OK_ACKNOWLEDGE.
Sending a message is part of transaction and can be rolled back.
Administered objects are preconfigured  JMS objects created by an admin for the use of clients.
Use TopicSession.createDurableSubscriber method to create a durable topic subscriber.
A MDB/stateless instance must commit a transaction before a message listener method or timeout callback method returns.
<message-driven-destination><destination-type>javax.jms.Topic</…> <subscription-durability>Durable</…></…> – Durable outlasts a MDB container’s connection to JMS provider. Responsibility of JMS provider to store messages.
Each MDB instance will be invoked only one thread at a time.
Message m = consumer.receive(long timeout) – Timeout 0-never expires.
MDBs must not call security methods. Constructors cannot call security methods.
JMS – defines a set of message interfaces, doesnt define a wire protocol for messaging, doesnt define a repository for storing msgtype definitions, does not define an API for administering messaging products, defines error/advisory notification, does not address problem of load balancing/fault tolerance.

Singleton

Default concurrency management - @Lock(WRITE) – Container Managed – Singleton.
Singleton can be deployed in releases that support EJB3.1 Lite- Web Profile supports it.
Singleton supports reentrant calls. Stateless/stateful doesnt support loopback calls.
@ConcurrencyManagement(ConcurrencyManagementType.BEAN) allows full concurrent access to the Singleton bean.
One bean instance of the Singleton for each JVM will be created.
@DependsOn(“y.jar#Y”) @Singleton public class X{…}
PostConstruct and PreDestroy methods of singleton with CMT are transactional. They can have transaction attributes – Required, Requires_New(RequiresNew) or Not_Supported(NotSupported).
Singleton – new Instance(), dependency injection, PC callback, method ready, PD callback.
Singleton use- app startup, shutdown, shared state, single bean needs concurrent access, bean implementing a web-service.
Eager init of Singleton - @Startup.
@DependsOn ordering is not preserved at runtime.
Each interceptor class will be instantiated once per Singleton bean instance.
Singleton BMC – container allows full concurrent bean instance access and defers state sync responsibilities to bean developer.
It is legal to store Java EE objects that dont support concurrent access within Singleton bean instance state. – EntityManagers, stateful session beans but not Swing components.
With BMC in singleton, developers allowed to use sync primitives – synchronized and volatile.
If a Singleton invocation is rejected due to lock timeout, the ConcurrentAccessTimeoutException is throw to client.
EJB 2.1 Remote and Local client view is not supported for Singleton.
If singleton did not initialize successfully, attempted invocations – javax.ejb.NoSuchEJBException.

Security

If user-caller-identity is specified as the value of security-identity element, caller principal is propagated from the caller to the callee. Run-as element overrides this visibility in callee.
<security-identity> direct child element of <session> or <message-driven> elements. <security-identity><description>optional</…><user-caller-identity></…><run-as><role-name>..</…></run-as></…>.
user-caller-identity is forbidden for MDB.
<exclude-list> – child of <enterprise-beans> element – specified by App Assembler.
isCallerInRole can be called by EJBContext, WebServletContext and HttpServletRequest.
<run-as> identity applies to EB as a whole and doesn’t affect identity of bean’s callers.


This post first appeared on Night Without End, please read the originial post: here

Share the post

Important Parts of Specification - Oracle Certified Expert, Enterprise Java Beans Developer

×

Subscribe to Night Without End

Get updates delivered right to your inbox!

Thank you for your subscription

×