SCBCD‎ > ‎

02. General EJB 3.0 Enterprise Bean Knowledge

2.1 Identify correct and incorrect statements or examples about the lifecycle of all 3.0 Enterprise Bean instances, including the use of @PostConstruct and @PreDestroy callback method
2.2 Identify correct and correct statements or examples about interceptors, including implementing an interceptor class, the lifecycle of interceptor instances, @AroundInvoke methods, invocation order, exception handling, lifecycle callback methods, default and method level interceptors, and specifying interceptors in the DD
2.3 Identify correct and incorrect statements or examples about how enterprise beans declare dependencies on external resources using JNDI or dependency injection, including the general rules for using JNDI annotations and/or DD, EJB references, connection factories, resource environment entries, and persistence context and persistence unit references
2.4 Identify correct and incorrect statements or examples about Timer Services, including the bean provider’s view and responsibilities, the TimerService, Timer and TimerHandle interfaces, and @Timeout callback methods
2.5 Identify correct and incorrect statements or examples about EJB context objects that the container provides to 3.0 Session beans and 3.0 MDB, including the security, transaction, timer, and lookup services the context can provide
2.6 Identify correct and incorrect statements or examples about EJB 3.0 / EJB 2.x interoperability, including how to adapt an EJB 3.0 bean for use with clients written to the EJB 2.x API and how to access beans written to the EJb 2.x API from beans written to the EJB 3.0 API

----------------------
Enterprise Bean Instance’s Lifecycle (2.1)

(Reference: ejb-core 3.4.3, 4.4, 4.5, 5.3, 5.5)

Both Stateful and Stateless Session Bean
- Container manages the lifecycle of the bean instance.
- Client view: bean instance exists once the client has obtained a reference to its business interface

Stateful Session Bean
- Client view: instance is removed either by client explicitly invoking a “Remove” method, or by timing out
- An instance’s life starts when a client obtains a reference to a bean instance through dependency injection (@EJB), or JNDI, or create<METHOD> method on the home interface (EJB 2.x). Step 2 (Dependency injection) includes injecting SessionContext. Step 4 only applies if the session bean was written to the EJB 2.1 client view (yes, because @Init is meant to map ejbCreate method of home interface) ???
- An invocation of a transactional method causes the instance to be included in a transaction. While inside a transaction, any invocation of non-tx or different tx method will result in ERROR
- Instance has afterBegin, beforeCompletion, and afterCompletion methods if the session bean class implements, directly or indirectly, the SessionSynchronization interface

+ The afterBegin method is invoked on the instance before any business method or its interceptor method is executed as part of the transaction

+ The beforeCompletion method is invoked before the transaction is committed

+ The afterCompletion method is invoked after a transaction completed (either commit or rollback)

- When an instance is in a transaction, Remove method is not allowed to be invoked, or RemoveException is thrown. The transaction is NOT marked for rollback so that the client can recover.
- A session bean can be passivated only between transactions, and not within a transaction
- An instance can be removed in 3 ways:
+ Client invokes a Remove method (business method marked as Remove method, or a remove method on the home or component interface): If the Remove method completes successfully or if the Remove methods throws an application exception for which retainIfException is false
+ Time out (whether the instance is passivated or not)
+ Instance throws system exception
- If an instance has been removed, all object references and handles for the instance become invalid. Attempts by client to invoke a method will result in javax.ejb.NoSuchEJBExcception (or, for EJB 2.1, java.rmi.NoSuchObjectException, javax.ejb.NoSuchObjectLocalException)
- The container will invoke PreDestroy lifecyle callback method(s) after Remove method completes successfully or session instance timeout when instance is in “method-ready” state. However, if Remove method throws an application exception and retainIfException is true, the instance is not removed and PreDestroy method is not invoked

Stateless Session Bean
- Client view: Creation and removal of an instance is performed by the container, transparently to the client
- The container can perform the instance creation at any time - there is no direct relationship to a client’s invocation of a business method or the create method. Step 2 (Dependency injection) includes injecting SessionContext.
- A stateless session bean must not implement the javax.ejb.SessionSynchronization interface.

Message-driven Bean
- Client view: the existence of a MDB is completely hidden behind the destination or endpoint for which the MDB is the message listener
- Step 2 (Dependency injection) includes injecting SessionContext.

-------------------------
Interceptors (2.2)

(Reference: ejb-core 12)

Overview
- Interceptors are used to interpose on business method invocations and lifecycle events that occur on an enterprise bean instance.
- 3 types of interceptors: default interceptors, business method interceptors, lifecycle callback interceptors.
- Interceptor methods and interceptor classes are defined for a bean by means of metadata annotations or the DD or both. To apply interceptor to a class or individual method, use @Interceptors (type, method) annotation or interceptor-binding DD element.
- Invocation order:

+ Default interceptors > Class interceptors > Method interceptors > Bean’s interceptor methods

+ Within same group, invocation order is the same as order of specification. If DD is used to augment annotation, annotation > DD

+ Within same class (bean or interceptor class), super-classes’ interceptor > current class’ interceptor. If an interceptor method is overridden by another method (regardless of whether that method is itself an interceptor method), it will not be invoked.

(http://docs.jboss.org/ejb3/app-server/tutorial/interceptor/interceptor.html)
  • External interceptors
    • Default interceptors, if present
    • Class interceptors, if present
    • Method interceptors, if present
  • Bean class interceptor method

Within each group (default, class, method) the order of the interceptors are from left to right as defined in the @Interceptors annotation, and then the xml interceptors.

- DD interceptor-order element can be used to override the default order specified in annotation. However, when used, developer must specify the total ordering of interceptors
- The binding of interceptors to classes is additive. If interceptors are bound at the class-level and/or default-level as well as at the method-level, both class-level and/or default-level as well as method-level interceptors will apply. (similar to log4j additive???) (Is it related to invocation order???)

Lifecycle
- The lifecycle of an interceptor instance is the same as that of the bean instance with which it is associated. For example (and thus):
+ Creation, Removal, Passivation, Activation
+ Both the bean and interceptor instances are created or activated (removed or passivated) before (after) any of the respective PostConstruct or PostActivate (PreDestroy or PrePassivate) callbacks are invoked
+ Extended persistence context is supported for only interceptors which are associated with stateful session beans
- Interceptor instance shares the same naming context with its associated enterprise bean
- Interceptor instance may use dependency injection, JNDI, JDBC, JMS, EJBContext, other enterprise beans, and the EntityManager
- Interceptor instance may hold state.  For what purpose??? if interceptor of Stateful SB ???
- Only a single instance of each interceptor class is created per bean instance

Common
- Interceptor methods may be defined in an enterprise bean class or in separate class(es) (called interceptor class) or in super-classes of the bean class or interceptor class. All types of interceptor method may be defined on a same class.
- A given class may not have more than one method for each type of interceptor (AroundInvoke, PostConstruct, Predestroy, PrePassivate, PostActivate) regardless of whether annotation, DD or some combination of DD and annotation are used to designate interceptor method.
- An interceptor class must have a public no-arg constructor
- Interceptor methods can have public, private, protected, or package level access. It must not be declared as final or static.
- The programming restrictions that apply to enterprise bean components apply to interceptors as well (See ejb-core 21.1.2 or SCBCD 1.3)
- Use context data of the InvocationContext object to carry state across multiple interceptor method invocations for a single event. Sharing between multiple events is not guaranteed.
- An interceptor method may catch an exception thrown by another interceptor method in the invocation chain, and clean up or recover before returning. Call InvocationContext.proceed() again with changed parameter/data???
- If a system exception escapes the interceptor chain, the bean instance and any associated interceptor instances are discarded. The PreDestroy callbacks are not invoked in this case: the interceptor methods in the chain should perform any necessary clean-up operations as the interceptor chain unwinds.

Default Interceptors
- Default interceptors may only be defined in DD
- Default interceptors are automatically applied to all components defined in the ejb-jar. Use  @ExcludeDefaultInterceptors annotation or exclude-default-interceptors DD element is to exclude the invocation of default interceptors for a bean or business method.
- The default interceptors are invoked before any other interceptors for a bean.
- If all beans derive from a common super class, can annotation be used to define pseudo- default interceptor???
-There is no specification of method signature for default interceptor. Does that mean there are 2 types of default interceptor: default ArroundInvoke interceptors and default lifecycle interceptors???

Business Method Interceptors (Session Bean, Message-driven Bean)
- Denoted by the @AroundInvoke (method) annotation or around-invoke DD element.
- An AroundInvoke method cannot be a business method of the bean.
- AroundInvoke methods have the following signature:

Object <METHOD>(InvocationContext) throws Exception

- An AroundInvoke method can invoke any component or resource that a business method can.
- Business method interceptor method invocations occur within the same transaction and security context as the business method for which they are invoked.
- Business method interceptor methods may be defined to apply the bean class or a business methods individually.
- The ExcludeClassInterceptors (method) annotation or exclude-class-interceptors DD element is used to exclude the invocation of the class-level interceptors
- Business method interceptor methods may throw runtime exceptions or application exceptions that are allowed in the throws clause of the business method.
- AroundInvoke methods can mark the transaction for rollback by throwing a runtime exception or by calling the EJBContext setRollbackOnly() method. AroundInvoke methods may cause this rollback before or after InvocationContext.proceed() is called.

Interceptors for Lifecycle Event Callback (Session Bean, Message-driven Bean)
- The @PostConstruct, @PreDestroy, @PostActivate, and @PrePassivate annotations (or corresponding DD elements post-construct, pre-destroy, post-activate, and pre-passivate ) are used to define an interceptor method for a lifecycle callback event
- Lifecycle callback interceptor methods are invoked in an unspecified transaction and security context.
- A single lifecycle callback interceptor method may be used to interpose on multiple callback events (e.g., PostConstruct and PostActivate).
- Lifecycle callback interceptor methods defined on an interceptor class have the following signature:

void <METHOD> (InvocationContext)

- Lifecycle callback interceptor methods defined on a bean class have the following signature:

void <METHOD>() //because they are invoked last in the chain?

- Lifecycle callback interceptor methods may throw system runtime exceptions, but NOT application exceptions. (because there is no throw clause?)

Invocation Context

public interface InvocationContext {

public Object getTarget();

public Method getMethod();

public Object[] getParameters();

public void setParameters(Object[] params);

public java.util.Map<String, Object> getContextData();

public Object proceed() throws Exception;

}

- The InvocationContext object provides metadata that enables interceptor methods to control the behavior of the invocation chain, including whether the next method in the chain is invoked and the values of its parameters and result. Same instance of InvocationContext is used for all interceptor method invocations in the invocation chain for a single event
- If interceptors are invoked as a result of the invocation on a web service endpoint, the map returned by getContextData will be the JAX-WS MessageContext.
- The lifecycle of the InvocationContext instance is otherwise unspecified.
- The getTarget method returns the bean instance.
- The getMethod method returns the business method on the bean class, or null if not applicable
- The getParameters method returns the parameters of the business method invocation.
- The setParameters method modifies the parameters used for the business method invocation. The new parameters must match the types and number of parameters of business method, or the IllegalArgumentException is thrown.
- The proceed() method causes the invocation of the next interceptor method in the chain, or, the business method. The proceed method returns the result of the next method invoked. If a method returns void, proceed returns null. For lifecycle callback interceptor methods, if there is no callback method defined on the bean class, the invocation of proceed in the last interceptor method in the chain is a no-op, and null is returned.

Specification of Interceptors in the Deployment Descriptor
- The DD can be used as an alternative or augmentation to annotations to specify interceptors and their binding to enterprise beans or to override the invocation order of interceptors as specified in annotations.
- To designate interceptor methods, use: around-invoke, pre-construct, post-destroy, pre-passivate, and post-activate elements.
- The interceptor-binding element is used to specify the binding of interceptor classes to enterprise beans and/or their business methods:

<ejb-jar metadata-complete=”false”>

<assembly-descriptor>

<interceptor-binding>

<ejb-name> // "*"  makes a default interceptor

<interceptor-class> * or <interceptor-order> +

<interceptor-class>+

<exclude-default-interceptors> ?

<exclude-class-interceptors> ?

<method> ? // ejb-name specified earlier must not be *

<method-name>

<method-params> ?

<method-param> *


- Explicitly listing an excluded higher-level interceptor at a lower level causes it to be applied at that level and below.
- If the interceptor-order element is used, the ordering specified at the given level must be a total order over ALL interceptor classes that have been defined at that level and above (unless they have been explicitly excluded).
- There are four possible styles of the interceptor element syntax:

Style 1: default interceptors
<interceptor-binding>

<ejb-name>*</ejb-name>

<interceptor-class>INTERCEPTOR</interceptor-class>

</interceptor-binding>

Style 2: class-level interceptors
<interceptor-binding>

<ejb-name>EJBNAME</ejb-name>

<interceptor-class>INTERCEPTOR</interceptor-class>

</interceptor-binding>

Style 3: method-level interceptors (inclusive of all overloaded methods)
<interceptor-binding>

<ejb-name>EJBNAME</ejb-name>

<interceptor-class>INTERCEPTOR</interceptor-class>

<method-name>METHOD</method-name>

</interceptor-binding>

Note that the wildcard value "*" cannot be used to specify method-level interceptors.

Style 4: method-level interceptors (exactly 1 method)
<interceptor-binding>

<ejb-name>EJBNAME</ejb-name>

<interceptor-class>INTERCEPTOR</interceptor-class>

<method-name>METHOD</method-name>

<method-params>

<method-param>PARAM-1</method-param>

<method-param>PARAM-2</method-param>

...

<method-param>PARAM-n</method-param>

</method-params>

<interceptor-binding>

The values PARAM-1 through PARAM-n are the fully-qualified Java types of the method’s input parameters (if the method has no input arguments, the method-params element contains no method-param elements). Arrays are specified by the array element’s type, followed by one or more pair of square brackets (e.g. int[][]).

If both styles 3 and 4 are used to define method-level interceptors for the same bean, the relative ordering of those method-level interceptors is undefined.

----------------------------------
Environment Entries and External Resources (2.3)

(Reference: ejb-core 16)

Enterprise Bean’s Environment as a JNDI Naming Context
- JNDI naming context: java:com/env
- Each enterprise bean defines its own private set of environment entries; all instances of an enterprise bean share the same environment entries. The environment entries are not shared with other enterprise beans; nor is name collision an issue.
- Enterprise bean instances are not allowed to modify the bean’s environment at runtime (i.e read-only access). The container must throw the javax.naming.OperationNotSupportedException from all the methods of the javax.naming.Context interface that modify the environment naming context and its subcontexts.
- The interceptor and web service handler classes for an enterprise bean share that bean’s environment and must be able to access the bean environment as well.
- In general, JNDI look-ups in java: context will return a new instance of the requested object every time; unless:

• The container knows the object is immutable (e.g. String), or knows that the application can’t change the state of the object.

• The object is defined to be a singleton

• The object is declared to be Shareable (via annotation or DD)

- In the case of resource adapter connection objects, it is the resource adapter’s ManagedConnectionFactory implementation that is responsible for satisfying this requirement.

- @javax.annotation.Resource
Resource.AuthenticationType
(APPLICATION, CONTAINER)
authentication
         The authentication type to use for this resource.
Stringdescription
StringmappedName
         A product specific name that this resource should be mapped to.
Stringname
         The JNDI name of the resource.
boolean
(true, false)
shareable
         Indicates whether this resource can be shared between this component and other components.
Classtype
         The Java type of the resource.


- @javax.ejb.EJB
ClassbeanInterface
         Holds one of the following interface types of the target EJB: Local/Remote business/home interfaces
StringbeanName
         The ejb-name of the Enterprise Java Bean to which this reference is mapped.
Stringdescription
StringmappedName
         The product specific name of the EJB component to which this ejb reference should be mapped.
Stringname
         The logical name of the ejb reference within the declaring component's (java:comp/env) environment.


- @javax.persistence.PersistenceUnit
Stringname
         The name by which the entity manager factory is to be accessed in the environment referencing context, and is not needed when dependency injection is used.
StringunitName
         The name of the persistence unit as defined in the persistence.xml file


- @javax.persistence.PersistenceContext
Stringname
         The name by which the entity manager is to be accessed in the environment referencing context, and is not needed when dependency injection is used.
PersistenceProperty[]properties
         Used to specify properties for the container or persistence provider.
PersistenceContextType
(EXTENDED, TRANSACTION)
type
         Specifies whether this is a transaction-scoped persistence context or an extended persistence context.
EXTENDED is valid only with Stateful Session Bean
StringunitName
         The name of the persistence unit.



Declare Environment Entries
- Either Annotation, or DD, or both. DD may be used to override annotation.
- Annotation:
    +  Must apply on class or any superclass. An annotation on any class in the inheritance hierarchy defines a resource needed by the bean.
+ JNDI name and entry type must be explicitly specified
- Rules on how DD overrides annotation:

+ JNDI name in DD must match that used in annotation (either defaulted or provided explicitly).

+ The type specified in the DD must be assignable to the type of the field or property or the type specified in the @Resource annotation (because only @Resource has a type element to identify the Java type of the environment entry)

+ The injection target, if specified, must name exactly the annotated field or property method.

+ The description, res-sharing-scope, res-auth element, if specified, overrides the corresponding values of the annotations. In general, res-sharing-scope, res-auth elements should never be changed, as doing so is likely to break the application.

- All JNDI name (both annotation & DD) is relative to java:comp/env context
- DD’s entry type is optional if injection target is specified. If both exists, must be assignable to the actual Java field/property

Access Environment Entries
- Dependency injection into bean’s fields or methods. Each injection of an object corresponds to a JNDI lookup
+ The field or method may have any access qualifier (public, private, etc.) but must NOT be final or static.

+ When annotation is declared on superclass, injection of such resources follows the Java language overriding rules. (Recall: a field can only be hidden, while a method can be overriden). An overriding method may request injection of a different resource, or no injection at all. Otherwise, a hidden field/method may still request for injection.

+ JNDI name may be specified explicitly in the annotation.

+ Else, by default, the name of the property is combined with the fully qualified name of the class to be used as the name in the naming context. E.g java:comp/env/com.acme.example.MySessionBean/myDatabase.

+ When a DD is used to specify injection, the JNDI name and the field/property name are both specified explicitly. Note that the JNDI name is always relative to the java:comp/env naming context.

- Perform EJBContext.lookup() or the JNDI lookup interfaces under java:comp/env context
- Invoking appropriate methods in EJBContext (e.g. getTimerService(), getUserTransaction()).

- Each resource may only be injected into a single field or method of the bean. Requesting injection into both field and set method is an error. Note, however, that either the field or the method could request injection of a resource of a different (non-default) name. By explicitly specifying the JNDI name of a resource, a single resource may be injected into multiple fields or methods of multiple classes.

Simple Environment Entries
- String, Character, Integer, Boolean, Double, Byte, Short, Long, and Float.
- @Resource: authenticationType and shareable elements of the must not be specified; simple environment entries are not shareable and do not require authentication.
- <env-entry>

<description>

<env-entry-name> //relative to java:comp/env

<env-entry-type> //required if no injection specified

<env-entry-value> //must be valid for the constructor of the specified type

<mapped-name>

<injection-target>

<injection-target-class>

<injection-target-name> //property name > field name


- If the env-entry-value element is not specified, no value will be injected (so that the default value in Java code can take effect). In addition, the named resource is not initialized in the naming context, and explicit lookups of the named resource will fail.

EJB References
- The EJB references corresponds to the enterprise bean business or home interfaces
- @EJB: The reference may be to a session bean’s business interface or to the remote/local home interface of a session bean or entity bean.
- <ejb-ref>, <ejb-local-ref>

<description>

<ejb-ref-name>

<ejb-ref-type> //either Entity or Session

<home> / <local-home> //required if reference to EJB 2.1

<remote> / <local> //business or component interface

<ejb-link> //to link a reference to a target enterprise bean

<mapped-name>, <injection-target>


- The EJB specification recommends that java:comp/env/ejb for all EJB references
- Recall that in EJB 2.1, all business interfaces must extends EJBObject or EJBLocalObject, and become component interfaces ???
- ejb-link may be a unique name of a enterprise bean in the same EAR. Or path-to-target-ejb-jar + ‘#’ + target-ejb-name. The path name is relative to the referencing application component jar file. Example: ../products/product.jar#ProductEJB.
- When specifying ejb-link, application assembler must ensure the target bean is type-compatible with the declared EJB reference.
- The Application Assembler may provides only the link to the target bean. Example:
<ejb-ref>
      <ejb-ref-name>ShoppingService/myCart</ejb-ref-name>
      <ejb-link>../products/product.jar#ShoppingCart</ejb-link>
</ejb-ref>

Web service references
- Web service references allow the Bean Provider to refer to external web services. The specification of web service references and their usage is defined in the Java API for XML Web Services (JAX-WS) and Web Services for Java EE specifications.
- The EJB specification recommends java:comp/env/service for all Web service references
- See 3.7: Web service client view

Resource manager connection factory
- A resource manager connection factory (e.g. javax.sql.DataSource) is an object that is used to create connections to a resource manager. Because resource manager connection factories allow the container to affect resource management, the connections acquired through the resource manager connection factory references are called managed resources (e.g., connection pooling, automatic enlistment of the connection with a transaction).
- @Resource: authenticationType (CONTAINER)  and shareable (true) elements may be used to control the type of authentication desired for the resource and the shareability of connections acquired from the factory.
- <resource-ref>

<description>

<res-ref-name> //relative to java:com/env context

<res-type> //optional if injection target is present

<res-auth> //either Application or Container

<res-sharing-scope> //either Shareable or Unshareable

<mapped-name>, <injection-target>


- The EJB specification recommends that all resource manager connection factory references be organized in the subcontexts of the bean’s environment, using a different subcontext for each resource manager type. Example: java:comp/env/jdbc,  java:comp/env/jms, java:comp/env/mail, java:comp/env/url (URL connection factory)
- The Bean Provider has two choices with respect to dealing with associating a principal with the resource manager access:
     + Allow the Deployer to set up principal mapping or resource manager sign-on information. In this case, the enterprise bean code invokes a resource manager connection factory method that has no security-related parameters. (CONTAINER)
      + Sign on to the resource manager from the bean code. In this case, the enterprise bean invokes the appropriate resource manager connection factory method that takes the sign-on information as method parameters. (APPLICATION)
- The Bean Provider must use the javax.sql.DataSource for JDBC connections; javax.jms.ConnectionFactory, javax.jms.QueueConnectionFactory, or javax.jms.TopicConnectionFactory for JMS connections; javax.mail.Session for JavaMail connections; java.net.URL for URLconnections.
- The Connector architecture allows an enterprise bean to use the API described in this section to obtain resource objects that provide access to additional back-end systems. ???

Resource Environment References
-  Resource environment references refer to administered objects that are associated with resources. Example: JMS Queue associated with JMS connection
- @Resource: authenticationType and shareable elements of the must not be specified; resource environment entries are not shareable and do not require authentication.
- <resource-env-ref>

<description>

<resource-env-ref-name>

<resource-env-ref-type>

<mapped-name>, <injection-target>


- The EJB specification recommends that all resource environment references be organized in the appropriate subcontext of the bean’s environment for the resource type.
- Example:
 <resource-env-ref>
     <resource-env-ref-name>jms/StockQueue </resource-env-ref-name>
     <resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>
 </resource-env-ref>

(WHAT really is a resource-env-ref: http://www.coderanch.com/t/157993/java-EJB-SCBCD/certification/Difference-between-resource-ref-resource) ==> probably this type of reference is replaced by Message Destination References

Message Destination References
- Message destination objects
- @Resource: authenticationType and shareable elements of the must not be specified
- <message-destination-ref>

<description>

<message-destination-ref-name>

<message-destination-type>

<message-destination-usage> //Consumes, Produces, ConsumesProduces

<message-destination-link> //similar to ejb-link

<mapped-name>, <injection-target>


- The EJB specification recommends java:comp/env/jms  for all message destination references
- The message-destination-usage element specifies whether messages are consumed from (Consumes) the message destination, produced for (Produces) the destination, or both (ConsumesProduces).
- Note that when using the @Resource to declare a message destination reference, it is not possible to link the reference to other references to the same message destination, or to specify whether the destination is used to produce or consume messages. A message destination reference declared via the @Resource is assumed to be used to both produce and consume messages.
- By means of linking message consumers and producers to one or more common logical destinations specified in the DD, the Application Assembler can specify the flow of messages within an application. The Application Assembler uses the message-destination element, the message-destination-link element (of the message-destination-ref element), and the message-destination-link element (of the message-driven element) to link message destination references to a common logical destination.
- <message-destination> //of assembly-descriptor

<message-destination-name>

<mapped-name> ?

- The Application Assembler specifies the link between message consumers and producers as follows:

+ Use the message-destination (of assembly-descriptor) to specify a logical message destination within the application.

+ Use the message-destination-link (of the message-destination-ref element) of an “producer” bean to link it to the target destination (defined in message-destination element above). Set the message-destination-usage element to Produces

   + If the consumer of messages from the common destination is a message-driven bean, use the message-destination-link element (of the message-driven element) to reference the logical destination. Should use message-destination-type element to specify the expected destination type (e.g. javax.jms.Queue)

+ Else, use the message-destination-link element (of the message-destination-ref element) of the “consumer” bean to link to the common destination. Set the message-destination-usage to Consumes.

- When linking message destinations, must ensure that the consumers and producers for the destination require a message destination of the same or compatible  type, as determined by the messaging system.
- The message-destination element can be in any module in the same Java EE application as the referencing component. The value of message-destination-link can follow the same syntax as ejb-link
- Example:
<enterprise-beans>
<session>
      <ejb-name>EmployeeService</ejb-name>
      <ejb-class>com.wombat.empl.EmployeeServiceBean</ejb-class>
      ...
      <message-destination-ref>
             <message-destination-ref-name>

jms/EmployeeReimbursements

             </message-destination-ref-name>
             <message-destination-type>javax.jms.Queue</message-destination-type>
             <message-destination-usage>Produces</message-destination-usage>
             <message-destination-link>ExpenseProcessingQueue</message-destination-link>
      </message-destination-ref>
</session>
...
<message-driven>
      <ejb-name>ExpenseProcessing</ejb-name>
      <ejb-class>com.wombat.empl.ExpenseProcessingBean</ejb-class>
      <messaging-type>javax.jms.MessageListener</messaging-type>
      ...
      <message-destination-type>javax.jms.Queue</message-destination-type>
      <message-destination-link>ExpenseProcessingQueue</message-destination-link>
      ...
</message-driven>
</enterprise-beans>
...
<assembly-descriptor>
      ...
      <message-destination>
             <message-destination-name>

     ExpenseProcessingQueue

             </message-destination-name>
      </message-destination>
      ...
</assembly-descriptor>

Persistence Unit References
- EntityManagerFactory for a persistence unit as defined in persistence.xml
- @PersistenceUnit
- <persistence-unit-ref>

<description>

<persistence-unit-ref-name> ?

<persistence-unit-name> //similar to ejb-link???

<mapped-name>, <injection-target>


- The EJB specification recommends java:comp/env/persistence for all persistence unit references
- When DD is used to override annotation, the persistence-unit-name overrides the unitName element of the annotation. Caution required as doing so is likely to break the application.

Persistence Context References
- Container-managed entity manager of a specified persistence context type
- @PersistenceContext:
- <persistence-context-ref>

<description>

<persistence-context-ref-name>

<persistence-unit-name> //similar to ejb-link???

<persistence-context-type> ? //either Transaction or Extended

<persistence-property> *

<name>

<value>

<mapped-name>, <injection-target>


- The EJB specification recommends java:comp/env/persistence for all all persistence context
- When DD is used to override annotation, the persistence-unit-name, persistence-context-type, persistence-property overrides or augment (persistence-property only) the unitName, type, properties elements of the annotation. Caution required as doing so is likely to break the application.

UserTransaction Interface
- @Resource: The authenticationType and shareable elements must not be specified
- JNDI java:comp/UserTransaction,
- EJBContext.getUserTransaction()       
- Only BMT session and message-driven beans are allow to access UserTransaction, all others’s attempt will result in  javax.naming.NameNotFoundException being thrown.
- A UserTransaction object reference may also be declared in a DD in the same way as a resource environment reference. Such a DD entry may be used to specify injection of a UserTransaction object.

ORB References
- Enterprise beans that need to make use of the CORBA ORB to perform certain operations can find an appropriate object implementing the ORB interface by requesting injection of an ORB object or by looking up the JNDI name java:comp/ORB. Consult ejb-core for more details

TimerService References
- @Resource: The authenticationType and shareable elements must not be specified
- JNDI java:comp/TimerService
- EJBContext.getTimerService()
- A TimerService  object reference may also be declared in a DD in the same way as a resource environment reference. Such a DD entry may be used to specify injection of a TimerService object.

EJBContext References
- @Resource: The authenticationType and shareable elements must not be specified
- JNDI java:comp/EJBContext
- SessionContext for session beans, MessageDrivenContext for message-driven beans.


---------------------------------
Timer Services

(Reference: ejb-core 18)

Overview
- The EJB timer service allows the Bean Provider to register enterprise beans for timer callbacks to occur at a specified time, after a specified elapsed time, or at specified intervals.
- An enterprise bean accesses this service by @Resource, EJBContext.getTimerService(), or through JNDI java:comp/TimerService
- The EJB Timer Service is a coarse-grained timer notification service. It is not intended for the modeling of real-time events.
- The timer service is intended for the modelling of long-lived business processes. Timers survive container crashes, server shutdown, and the activation/passivation and load/store cycles of the enterprise beans that are registered with them.

Bean Provider’s View
- javax.ejb.TimerService interface:       
TimercreateTimer(Date initialExpiration, long intervalDuration, Serializable info)
        Create an interval timer whose first expiration occurs at a given point in time and whose subsequent expirations occur after a specified interval.
TimercreateTimer(Date expiration, Serializable info)
        Create a single-action timer that expires at a given point in time.
TimercreateTimer(long initialDuration, long intervalDuration, Serializable info)
        Create an interval timer whose first expiration occurs after a specified duration, and whose subsequent expirations occur after a specified interval.
TimercreateTimer(long duration, Serializable info)
        Create a single-action timer that expires after a specified duration.
CollectiongetTimers()
        Get all the active timers associated with this bean.


- javax.ejb.Timer interface:   
voidcancel()
        Cause the timer and all its associated expiration notifications to be cancelled.
TimerHandlegetHandle()
        Get a serializable handle to the timer.
SerializablegetInfo()
        Get the information associated with the timer at the time of creation.
DategetNextTimeout()
        Get the point in time at which the next timer expiration is scheduled to occur.
longgetTimeRemaining()
        Get the number of milliseconds that will elapse before the next scheduled timer expiration.


- javax.ejb.TimedObject interface:
voidejbTimeout(Timer timer)
         Invoked by the EJB container upon timer expiration.


- javax.ejb.TimerHandle extends Serializable interface:
TimergetTimer()
         Obtain a reference to the timer represented by this handle.


- Timers can be created for stateless session beans, message-driven beans, and EJB 2.1 entity beans. A timer for Stateless SB or MDB can apply to all bean’s instances;  a timer for a 2.1 entity bean is associated with the entity bean’s identity; if an entity bean is removed, the container must remove the timers for that bean.
- The enterprise bean that uses the timer service must provide a timeout callback method, in the bean class or any superclass, either by annotating a method with the @Timeout, or by specifying timeout-method DD element, or by implementing javax.ejb.TimedObject interface. A bean can have at most ONE timeout method and DD cannot override annotation.
- A Timeout method can have public, private, protected, or package level access, and must NOT be final or static. Timeout callback methods must not throw application exceptions.
     void <METHOD>(Timer timer)

- The Bean Provider can use the Timer.getInfo() method to retrieve the information that was supplied when the timer was created.
- When the time specified at creation elapses, the container invokes the timeout callback method. A timer may be cancelled by a bean before its expiration and the timeout method will not be called.
- If a timer for an EJB 2.1 entity bean expires, and the bean has been passivated, the container must call the ejbActivate and ejbLoad methods on the entity bean class before calling the timeout callback method, as described in ejb-core 8.5.3 and 10.1.4.2.
- The container interleaves calls to the timeout method with the other business or lifecycle method calls. The invocation time of the timeout method is may therefore not correspond exactly to the time specified at timer creation. If multiple timers have been created for a bean and will expire at approximately the same times, out of sequence may occur.

-  If the timer is a single-action timer, the container removes the timer after the timeout callback method has been successfully invoked (e.g., when the transaction that has been started for the invocation of the timeout callback method commits). An invocation of Timer.cancel() method can also remove the timer. In both cases, if a method is subsequently invoked on the timer, the container must throw the javax.ejb.NoSuchObjectLocalException.

- Typically, creation, cancellation of timers and invocation of the timeout callback method are made within a transaction. The timeout callback method is typically has transaction attribute REQUIRED or REQUIRES_NEW. If the transaction is rolled back, the container rollback timer creation, rescind cancellation or retries the timeout at least once.
- Note that the container must start a new transaction if the REQUIRED (Required) transaction attribute is used. This transaction attribute value is allowed so that specification of a transaction attribute for the timeout callback method can be defaulted.???

- In general, the timeout callback method can perform the same operations as business methods from the component interface or methods from the message listener interface. See ejb-core Tables 2, 3, 4, and 10 for the specification of the operations that may be performed by the timeout callback method.  Since the timeout callback method is an internal method of the bean class, it has no client security context. When getCallerPrincipal is called from within the timeout callback method, it returns the container’s representation of the unauthenticated identity.

- The Bean Provider cannot rely on the == operator to compare timers for “object equality”. The Bean Provider must use the Timer.equals(Object obj) method.

- The javax.ejb.TimerHandle interface allows the Bean Provider to obtain a serializable timer       handle that may be persisted. Since timers are local objects, a TimerHandle must not be passed through a bean’s remote business interface, remote interface or web service interface. In addition, the specification requires that Timer instances must not be serializable.

- Timers are persistent objects. In the event of a container crash, any single-event timers that have expired during the intervening time before container restart must cause the timeout callback method to be invoked upon restart. Any interval timers that have expired during the intervening time must cause the  timeout callback method to be invoked at least once upon restart.
- If the transaction in which the timer cancellation occurs is rolled back, the container must restore the duration of the timer to the duration it would have had if it had not been cancelled. If the timer would have expired by the time that the transaction failed, the failure of the transaction should result in the expired timer providing an expiration notification after the transaction rolls back.


----------------------------------------
EJBContext (2.5)

(Referene: ejb-core 4.3.3, 5.4.4)

- @Resource: The authenticationType and shareable elements must not be specified
- JNDI java:comp/EJBContext
- SessionContext for session beans, MessageDrivenContext for message-driven beans.

- javax.ejb.EJBContext interface:
PrincipalgetCallerPrincipal()
         Obtain the java.security.Principal that identifies the caller.
EJBHomegetEJBHome()
         Obtain the enterprise bean's remote home interface.
EJBLocalHomegetEJBLocalHome()
         Obtain the enterprise bean's local home interface.
booleangetRollbackOnly()
         Test if the transaction has been marked for rollback only.
Only CMT bean can invoke this method
TimerServicegetTimerService()
         Get access to the EJB Timer Service.
Only Stateless SB and MDB can invoke this method
UserTransactiongetUserTransaction()
         Obtain the transaction demarcation interface.
Only BMT bean can invoke this method
booleanisCallerInRole(String roleName)
         Test if the caller has a given security role.
Objectlookup(String name)
         Lookup a resource within the component's private naming context.
voidsetRollbackOnly()
         Mark the current transaction for rollback.
Only CMT bean can invoke this method


- EJBContext is extended by the SessionContext, EntityContext, and MessageDrivenContext interfaces to provide additional methods specific to the enterprise interface Bean type

- javax.ejb.SessionContext interface:
<T> TgetBusinessObject(Class<T> businessInterface)
         Obtain an object that can be used to invoke the current bean through the given business interface.
         IllegalStateException - Thrown if this method is invoked with an invalid business interface for the current bean.
Only EJB 3.0 Session Bean can invoke this method
EJBLocalObjectgetEJBLocalObject()
         Obtain a reference to the EJB local object that is associated with the instance.
         IllegalStateException - Thrown if the instance invokes this method while the instance is in a state that does not allow the instance to invoke this method, or if the instance does not have a local interface.
EJBObjectgetEJBObject()
         Obtain a reference to the EJB object that is currently associated with the instance.
         IllegalStateException - Thrown if the instance invokes this method while the instance is in a state that does not allow the instance to invoke this method, or if the instance does not have a remote interface.
ClassgetInvokedBusinessInterface()
         Obtain the business interface through which the current business method invocation was made.
         IllegalStateException - Thrown if this method is called and the bean has not been invoked through a business interface.
MessageContextgetMessageContext()
         Obtain a reference to the JAX-RPC MessageContext.
         IllegalStateException - Thrown if this method is invoked while the instance is in a state that does not allow access to this method.
Only stateless session beans with web service endpoint interfaces can use this method


- javax.ejb.MessageDrivenContext interface: No extra method


------------------------------------
Compatibility & Migration (2.6)

(Reference: ejb-simplified)

- All EJB 3.0 implementations must support EJB 1.1, EJB 2.0, and EJB 2.1 DD for applications written to earlier versions of the EJB specification. Existing EJB 2.1 and earlier applications must be supported to run unchanged in EJB 3.0 containers.
- A client written to EJB 2.1 or earlier API can be client of EJB 3.0 components (including EJB 3.0 entities and/or EntityManager). No rewriting or recompiling is needed.
- A client written to EJB 3.0 can also be client of EJB 2.1 or earlier components (including Entity Bean) using EJB 2.1 (or earlier) client view home and component interfaces. The @EJB (or the ejb-ref and ejb-local-ref) may be used to specify the injection of home interfaces into the EJB 3.0 client
- In both cases, they can participate in a same transaction.

Adapting EJB 3.0 Session Beans to Earlier Client Views
- Clients written to the EJB 2.1 and earlier client view depend upon the existence of a home and component interface.
- A session bean written to the EJB 3.0 API may be adapted to such earlier preexisting client view interfaces by using the RemoteHome and/or LocalHome annotations (or equivalent deployment descriptor elements).
- @RemoteHome, @LocalHome:
- @Init: Designates a method of a session bean that corresponds to the create method of an adapted Home interface or an adapted Local Home interface. If no value is specified, the create matching is based on signature only. Stateful SB only
- The result type of such @Init method is required to be void, and its parameter types must be exactly the same as those of the referenced create<METHOD>() method.
Comments