Results 1 to 1 of 1
  1. #1
    Java Exam is offline Member
    Join Date
    Dec 2011
    Posts
    64
    Rep Power
    0

    Default Tutorial:Review of EJB Exception for the Component Developer Exam

    In this article we will look in depth at EJB Exception and EJB Exception Handling that a developer will need to know for the Component Developer Exam. We will first focus on both authentication and authorization as well as users, groups and roles and their function within EJB Exceptions. If you don't have a good understanding of EJBs, please review "Tutorial:Review of Session Bean for the Component Developer Exam" or "Tutorial: Review of the Message Driven Bean for the Component Developer Exam" for more information. Finally we will look at how to overlay security into the TudoList application.

    Introduction to EJB Exceptions

    As any good developer will attest to the best time to catch an error is at compile time well before you try to run the program. Unfortunately, we all know that it is impossible to catch all errors at compile time. Therefore the errors that are missed must be handled at run time through some means that allows the originator of the error to pass appropriate information to a recipient that can handle the error condition properly. Well designed error recovery is one of the best means to increase the robustness of your code. Error recovery is a fundamental concern for every written program but in Java is critical since one of Java’s goals is to create reusable components. Consequently, to create a robust system, each component must be robust. By providing a consistent error-reporting model using exceptions, in Java you can use components to communicate problems to client code. Java’s primary goals for exception handling are to optimize the creation of large, robust programs with minimal code as well as being confident that all errors are properly managed. Exceptions are one of those features that provide immediate and significant benefits to any project. This is equally true when working with EJB Exceptions.

    The Key Exception Types for EJBs

    Application exceptions are exceptions that are directly related to your business logic. System exceptions are exceptions of an unknown origin internal to the application. This doesn’t mean that you cannot have system exceptions thrown from a business method because during this happens quite frequently. Examples of this sort of error within a business method is if the database connection or messaging server is no longer available. Application exceptions imply that there is a business problem or failure, but not something that requires that you roll back or abort the business process. Let’s look in detail at each type.

    What are Application Exceptions

    Exception handling is the way for Java to reports errors. It is enforced by the Java compiler. This holds equally for Java Enterprise Edition components from the EJB specification. Any business interface could throw application exceptions. The exception should always be tied to the method and the business logic it is implementing. It indicates that there is a problem in the business logic. Any application exception will be propagated without modification to the client. You should remember to make any variables as serializable since they maybe streamed across the network to the client. Any business interface could throw application exceptions. The exception should always be tied to the method and the business logic it is implementing. It indicates that there is a problem in the business logic. The application exception should be relevant and informative to the client in identifying the error. The application exception should be relevant and informative to the client in identifying the error. Note that application exceptions are never wrapped in EJBExceptions but a propagated up directly to the client. When we want an application exception to force an automatic rollback of a transaction, we use the @ApplicationException annotation. An example of this is provided below:

    Java Code: Example of Application Exception
    /** 
    * Exception thrown when attempting to create a Todo 
    */
    @ApplicationException(rollback = true)
    public class TodoCreationException extends Exception
    {
    ...
    }
    In general we would roll back a transaction automatically but your business logic can be designed in such a way that the TodoCreationException can be caught and the transaction automatically retried by verifying the Todo values and references. This exception is related to a problem in the creation of the Todo. It could be related to insufficient data or if certain references (to say User or TodoList) are not presently set. You can use the @ApplicationException annotation on subclasses of java.lang.RuntimeException and java.rmi.RemoteException. If you want to avoid wrapping a RuntimeException in an EJBException, or to avoid rollback an exception from a subclass of RemoteException

    What are System Exceptions

    System exceptions are exceptions of an unknown origin. They are the exceptions which are not expected. The container will throw a system exception when it needs to abort a business process. System exceptions include java.lang.RuntimeExceptions, java.rmi.RemoteExceptions as well as the subclasses of both these exception classes. The difference between the RuntimeExceptions and RemoteException subclasses is that they can be transformed into applications exceptions by using @ApplicationException. System exceptions will always provoke a rollback of a transaction when they are thrown within the method of an enterprise bean. As long as a RuntimeException doesn’t have a @ApplicationException annotation, if the exception is thrown from a business method, it will automatically be handled by the container and will cause the transaction to rollback. RuntimeExceptions neither need to be declared in method signature’s throws clause nor does it need to be handled within a try/catch block. They will always be automatically thrown from the method.When an exception is handled automatically by the container it will do the following:
    1. Rollback the transaction
    2. Log the exception in order to inform the system administrator
    3. Discard the EJB instance

    When a system exception is thrown the EJB Container will automatically handle the exception and rollback the transaction. The only circumstance where this doesn’t apply is when a system exception is thrown from a callback method. If you have seen the previous article, Tutorial: Review of Session Beans for the Component Developer Exam, the you will remember there are a number of callbacks on the lifecycle of enterprise java beans. These are @PostConstruct, @PreDestroy, @PrePassivate and @PostActivate for stateful session beans, @PostConstruct and @PreDestroy for stateless session beans and message driven beans. When a system exception is thrown from one of these callback methods, it will be handled in exactly the same manner as if it was thrown from a normal business method. As for the logging of system exceptions, there is no specification for how the exceptions are logged nor for the format that must be used. This is left up to each system vendor.

    When a system exception happens, the container will discard the EJB instance because it has to assume that the EJB instance is somehow corrupted and unstable. This means that the EJB instance is dereferenced and can then be garbage collected. The impact of discarding a stateless session bean is relatively minor. This is because the client will use any stateless session bean which is in the method-ready pool. As they are swapped in and out of the method ready pool, the client will never know which stateless session bean instance it is using. The impact of using a stateful session bean is more significant. This is because each client will have a dedicated instance of a stateful session bean to serve the client’s requests. When a system exception causes an instance of a stateful session bean to be discarded, the next request from business methods of the stateful session bean will result in a NoSuchEJBException. This is a subclass of RuntimeException. The discarding of the instance of the session bean that takes place when a system exception is thrown is the same irrespective of whether the session bean is a remote or local invocation.

    Let’s look at some code from the previous article, “Tutorial: Review of EJB Transaction for the Component Developer Exam” where we showed the code for the createTodoList in the TodoListBusinessBean:
    Java Code: Example of use of @ApplicationException
    @Stateless
    @TransactionManagement(TransactionManagementType.CONTAINER) 
    public class TodoListsBusinessBean implements TodoListsBusiness {	
    @Resource	
    private SessionContext context;
    ...
    @TransactionAttribute(TransactionAttributeType.REQUIRED) 
    public void void createTodoList(TodoList todoList) 
       throws TodoListCreationException, DatabaseException {
            todoList.setLastUpdate(Calendar.getInstance().getTime());
            User user = userBusiness.getCurrentUser();
            todoList.getUsers().add(user);
            todoListEAO.saveTodoList(todoList);
            user.getTodoLists().add(todoList);
            userBusiness.updateUser(user);
    ...
    @ApplicationException(rollback=true)   
    public class TodoListCreationException extends Exception{
    ...
    @ApplicationException(rollback=false)   
    public class DatabaseException extends RuntimeException{
    ...
    We add the TodoListCreationException and DatabaseException has been added to the throws clause for the method declaration. Next we have used the @ApplicationException annotation to identify the TodoListCreationException as an application exception. The rollback element is set to true. This tells the container that it should roll back the transaction before the exception is passed to the client. The default setting for the rollback element is false which means that the application exception will not cause an automatic container-managed transaction rollback. The DatabaseException is by default a system exception but is transformed to an application exception through the use of @ApplicationException. This is because the exception doesn’t extend RuntimeException so the EJB container will treat this as an application exception. As we have set the rollback element to false, the transaction will not be rolled backed automatically.

    For a system exception that is within a transaction and propagated to the client from the EJB, it will be caught and re-thrown as a EJBTransactionRollbackException. This exception is a subtype of RuntimeException. It provides more explicit information to the client for the rollback. For a system exception that takes place when a client didn’t propagate a transaction to a session bean, the EJB container will wrap the exception in an EJBException. This means that a system exception that extends RuntimeException will be caught by the EJB Container and wrapped in EJBException. This is important for session beans in their interactions with entity beans. All the Java Persistence interfaces throw RuntimeExceptions. If you have any specific persistence exceptions, the way to make client code aware of these exceptions is by permitting the EJB container to wrap these exceptions into EJBException.

    For message driven beans, a system exception that is thrown on the callback methods or even the onMessage() method will cause the instance of the bean to be discarded. The message that was part of the method call will be redelivered only if the EJB container is acknowledging delivery. This is only valid if the message driven bean is part of the bean-managed transaction.

    Tutorial:Review of EJB Exception for the Component Developer Exam-a12-sessionbeanexceptions.jpg
    Table: Exceptions for Session Beans

    Next is the table showing the interaction types among the various exceptions and transactions in message-driven beans.

    Tutorial:Review of EJB Exception for the Component Developer Exam-a12-messagedrivenbeanexceptions.jpg
    Table: Exceptions for Message-Driven Beans

    Best Practices for EJB Exceptions

    Best practice for using application exceptions is to use CMT rollback carefully. Also use the setRollbackOnly in order to control the automated transaction management. But make sure that you understand fully the intricacies of exception handling in EJB. The key is to use all of the error-handling mechanisms that is available to you in the Java realm.

    OK. That's it for EJB Exceptions. Please remember to review our other articles on all the subjects for the component developer exam so that you are fully prepared to succeed on the exam.
    Last edited by Java Exam; 01-09-2012 at 08:00 PM.

Similar Threads

  1. Replies: 0
    Last Post: 01-09-2012, 07:25 PM
  2. Replies: 0
    Last Post: 01-06-2012, 11:51 AM
  3. Replies: 0
    Last Post: 12-21-2011, 03:56 PM
  4. Replies: 0
    Last Post: 12-20-2011, 06:02 PM
  5. Replies: 0
    Last Post: 12-13-2011, 07:42 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •