January 19th, 2011
7:39 pm
Using a Command Pattern for EJB method access

Posted under EJB
Tags , , , ,

Further Update 26/1/2012 – Return Status vs Exceptions in EJB methods

A further  design point has come up re the choice between returning a status enum or throwing exceptions in EJB methods. This also impacts the use of Command Patterns and in particular the status enum idea below. I have posted on this issue here.

 

Further Update 26/1/2012

  1. Another nice feature would be the ability to check the status of a command after it executed generically and then take a decision on whether to continue with the rest of a CommandList.
  2. If this check could be done in the CommandList execute() loop, it would avoid the need for custom initialisers just to abort after a status return. This would avoid the need for the anonymous inner initialiser classes, finals for all the Commands, and constructor injection for all the final Commands.
  3. The initialiser feature is a nice to have, but messy just for simple generic status checking.
  4. A flexible way to do this would be to add a status enum to each command, and then in the base results class, have an EnumSet of values from that status. Adding it to the base results ensures it gets copied back along with everything else.
  5. If a command succeeded with no issues, it would just return null for the status. If there were any ‘issues’ with the result, it return a status code from the enum saying what happened. This would be done in the actual command subclass, just after calling the actual SSB method, when building the results object to be returned.
  6. When using a Command in a list, you would then pass in an EnumSet of status codes for which execution is allowed to continue, to the actual command object generically (via a generic method of Command). Execution would continue either if the status was null, or if it was contained in the set. If non null and not in the set, then a CommandList would stop execution at that point and return what it had done so far.
  7. A further enhancement to 6. could be to also pass in a ‘default action’ enum value to indicate the default action (abort or continue) when a non null status is present. Then this enum value defines the default action, and the EnumSet defines the exceptions to the default, i.e. “abort on all non null statuses except  continue for any in this set” or “continue on all non null statuses except abort for any in this set”.
  8. If the feature was not needed, it could default to null status returns and a CommandList would always carry on (subject to what any Initialisers do)
  9. The feature adds flexible decision making for a CommandList about continuing, allowing checking for multiple status codes via the EnumSet, but in an entirely generic way which does not involve initialisers.
  10. An EnumSet is also efficient and compact, as it is implemented as  a bit mask, and typically a Command will only have a few statuses in its enum.

 

Update

  1. A better technique to fetching the results would be to do it automatically in the Invoker after the results are returned. This has the following advantages:-
  2. The caller has no work to do – for a command list, the results would be immediately available in the original passed in Command/CommandList. If a CommandList was passed, then the individual Commands used to build it would be populated and would be referred to directly so that the correct result subclass could be referenced.
  3. The best way would be for a Command/CommandList to do this generically by passing the original command list in rather than the current varargs mechanism. There is no point in just fetching some of the results as they will all be needed.
  4. Doing it this way presents even less risk of mismatching the command objects to their results – it is automatic and the caller cannot get it wrong. In particular it is not possible to fetch results into the ‘wrong’ command object.
  5. To do this, the fetching needs to be done in the caller’s context, not that of the Invoker (which is an SSB). This could be done by calling a static invoke method on the invoker and passing the invoker SSB and command/command list to it. The static method would then do the ‘real’ invoke, and then do the fetching directly afterwards, directly into the command/CommandList passed by the caller. This static method would therefore not return anything :-

Invoker.invoke(invoker, myCommandList);

Original Post

A command pattern provides a number of advantages for EJB method calling to stateless session beans, at the expense of having to wrap the EJB methods in command classes :-

  1. It provides a convenient and tidy way of performing a number of EJB method calls, specifically to stateless session beans, in a single transaction, by wrapping them in an outer Command List which is itself a command (a macro concept). This then means that only a single call is needed to the EJB container to establish transactional context, by calling a standard command invoker which is itself an EJB.
  2. When wrapping a number of EJB calls in this way, the interface is much cleaner than trying to roll your own higher level method call which calls all the others. When rolling your own, passing in parameters cleanly for a number of EJB calls can be complex, and packing the returned data for convenient retrieval is also a more complex issue. With a command list, each command in the list has its own call parameters, set up and stored in the command object when it is created. Each also has its own return object, retrieved using a convenient standard mechanism.
  3. Add hoc lists of commands can easily be created, as the list does not need to be hard coded.
  4. All the underlying EJB calls can of course still be used, so commands can be used on an as needed basis if it is deemed overly complex to use them throughout. However, there are advantages if they are used consistently, as other parts of a design can then rely on command usage.
  5. A command list can be used as a ‘drop box’ of commands, decoupling different client objects of the drop box from each other. This allows a single transactional context call to be used to execute all the commands, but the client objects need have no knowledge of each other or of the other commands in the drop box. An example of this might be different sub areas of a page which post commands into the drop box command list, and the list is executed by a submit button for the whole page. The sub areas of the page need have no knowledge of each other but can still share the same outer EJB call to the invoker of the command list, such that a single EJB container call results (indirectly) from the submit button.
  6. An initialisation mechanism allows initialiser objects to be attached to each command. This allows later commands in an ad hoc list to have inputs which depend on the output of earlier commands, but still having everything running as a result of a single EJB call to the container. The initialisers are typically anonymous inner classes passed in to a command object when it is set up. Each initialiser is called just prior to execution of the command it is attached to.
  7. The command objects will typically be called from a JSF model bean in a JSF environment.

The main disadvantages are as follows :-

  1. The EJB method calls need to be wrapped in Command classes, so extra coding is needed. However, this  is straightforward and follows a standard pattern.
  2. Some extra complexity arises when command lists are used, in order to unpack the results afterwards. However, this all follows a standard mechanism and importantly does not rely on any error prone use of hard coded list indexes to unpack results.
  3. If custom initialisers are used, the anonymous inner classes which are typically used make the code somewhat more complex. However, if certain lists of commands are commonly used they can and should be combined into a hard coded command list/macro. If this is done, the initialisation can be performed inline as the commands are called, rather than having to be passed in as in the case of an ad hoc list with initialisation.

A sample implementation of this may be found in the repository here.

Key design points for the implementation are as follows :-

  1. The command objects themselves are stateful (as they hold any passed parameters and results, and for a command list, the list of commands). They are not EJBs themselves, but they do refer to the actual EJBs being wrapped. The Invoker is an EJB, albeit a standard one, and is passed the commands to be invoked. Creation of the transactional context happens when the invoker is first invoked. All calls to the underlying EJBs (from the execute methods of the command objects being invoked) are then calls made within the same transactional context already established in the container, and so require much less overhead, and are of course part of the same transaction.
  2. CDI is used throughout for dependency injection, both on the EJBs and on all the commands. The commands must be injected with CDI as they themselves must also have EJB references injected into them – this will not happen correctly if a command object is just created via new, as it will not be properly under CDI control to allow the injection to take place. However, as Command Lists are purely containers for commands, and do not themselves have any CDI dependencies/any references injected, they can freely be created with new if desired. For example, A Command List may be created with new, have all its constituent commands passed into its constructor, and be created directly in the argument list of a call to the invoker, as in the code example above.
  3. A command list is literally a list of commands executed in list order.
  4. As a command list is also a command, lists may be nested – it is entirely possible for a command in a list to itself be another command list.
  5. When a command (or a command list, as it is also a command) is executed, it returns a new instance of its own class containing the results object as the return value. This is necessary as when calling into an EJB container, modifications to properties of parameter objects passed in are not normally visible on return from an EJB container. The only means of returning data is via the method return value. Whilst this behaviour can be overridden in some cases with EJB container settings, this was deemed highly undesirable, and is particularly an issue when the call is to a remote interface. It is important to understand the distinction between the methods of Command objects and Command lists which are called only in the client environment, and calls made into the EJB container (possibly remotely). Calls made in the client environment do allow changes to passed object properties – this is necessary for example to store the listIndex in a passed Command object when it is added to a Command List (see later in point 12), and also when fetching the results back via the fetch method after invoking a Command list (also in point 12). This behaviour is also used by a number of the Java APIs – for example, Collections.sort() sorts the passed list argument, but does not have a return value from the method. Conversely, when the Invoker object is used to invoke (execute) a passed command, the invoker is an EJB (stateless session bean), so the client is calling into the EJB container and establishing transactional context (the call may also be a remote one over RMI if a remote interface is used). In this case, the story is very different, and changes are only passed back via the method return value.
  6. Note that the client environment will often also be within an EJB container – Command objects will typically be invoked for example from a stateful JSF model bean, which may often be in the same Java EE container as the EJBs. However, they are not created in transactional EJB context, so whilst for example they may be created and hosted in Glassfish (which will also be responsible for providing CDI services among many other things), they are not created in its EJB container – they are passed into the EJB container via the Invoker which is itself an EJB (stateless session bean).
  7. Commands and Command lists are implemented using a Composite pattern based on an abstract Command class. This design choice was adopted as it became necessary for the Command base abstract class to have knowledge command lists. For example, a command must have a listIndex property which is used to hold its position in a command list if it is added to one, even though this has no relevance to a standalone command. Also, when command lists are themselves nested inside other command lists, the structure genuinely becomes composite so it is easier to be able to declare all member types generically using a standard abstract base Command class.
  8. A command class typically wraps all the overloaded method calls for an EJB method. This is convenient as a command must have a single return type, but allowing the overloaded methods with different call parameters to be encapsulated in the same command class reduces the number of command classes and eliminates unnecessary clutter. When implementing this, the command class has a set of method calls which mimic the method calls to the underlying EJB. The difference is that rather than calling the EJB, these method calls just store the parameters as properties of the command for later use when the command is invoked by the invoker. When implementing this, an enum (CallType) is used to define which overloaded method is being used. The enum value is set when a particular overloaded method is called. Later, when the command is invoked, the enum is used to determine which corresponding overloaded EJB method to call. This mechanism avoids arcane decoding of null parameters to try to decide which call is in use, and is completely transparent. When these methods on the command class are called, they typically return a reference to the command object as this is often useful. For example, the return reference might be used in a call to add the command to a new command list directly.
  9. When creating a fixed command list to be reused, it is easier and clearer just to extend Command and embed commands in a simple outer ‘macro’ command. Whilst it is possible to create a fixed list by either extending a CommandList or composing one, it turns out that this is slightly longer than just extending a Command, and the code is significantly more complex to understand. A comparison was done in an early version of the Command pattern implementation here. (Note that this is an old version and should only be used for reference. The link given further up is the latest version which is an EJB sample and should be used to base other code on.
  10. Each command has an inner class containing its results to be returned, together with a reference property to an instance of the inner class. The results are unique to the command class and are only used once, so the inner class avoids clutter. The inner class extends a base CommandResult inner class in the base Command class. This allows the results for a command to be reassigned polymorphically to the result property of another object – a trick which is used when accessing the results of commands from a command list. Note that a command class should use delegated property access to get the results – i.e. the command class itself will have property getters for all the result properties, but will get values directly from the result object members. This saves another level of nested reference by the client of the command object when accessing results. Note that when accessing result object members from within the command class, they are access directly without using getters. This saves code, and it is reasonable that the inner class result object is fully exposed to its parent command object.
  11. In the case of a command list, its result object contains a list of the results for its constituent commands, stored in the same sequence as the original command list.
  12. Each command, when inserted into the list, has its own internal listIndex property which stores its position in the list. After the command list has been executed, a fetch method is called on the returned result command list. The original command(s) stored in the list are passed to the fetch method. The fetch method uses the listIndex property from each command to fetch its results, as the results are stored in a list in the same sequence as the original command list. The result object from the list is then polymorphically assigned to the result property of the object passed in to the fetch method. The beauty of this is that the caller has no knowledge of the list index – they simply pass in the same object that they originally added to the command list when fetching the results, and this object holds its index in the list. This avoids errors which could easily occur if list indexes were explicitly hard coded. Refactoring for example could change the indexes of existing commands and break the code, which is completely avoided with this mechanism. Also, as the results are passed back into the original object, the original object may then be used to access the contents of the results as it knows the exact type of the results class – the results are its own! In this way, the results may be fetched polymorphically but accessed via the correct subclass.  At present, the error handling in the example is incomplete. Ideally a type check should be performed in fetch to confirm that the class passed into fetch really is an instance of the same type as the one in the command list. (If this is not the case, run time errors will happen when the result object is accessed as it will be the wrong result subclass.) One reason it may not be could be if the caller passes in a command object which was added to a different list, i.e. the command object is not for the list that is being accessed. A command object can be reused across multiple command lists, but can only be used with a new list after the results have been fetched into it (and accessed) from the list it was last added to and executed in. Another problem could arise if a caller passed a new instance of a command object into fetch – this would have a null listIndex and would therefore give an error. Error handling could also be improved by having a unique ID assigned to each command list, and storing this ID in each command object as well as the list Index. Then the fetch method could check this ID for a match as well. The ID could be reset if the command list is cleared for reuse a subsequent time. This kind of error cannot be detected at compile time with Generics as the list contains a mix of different Command subclasses. The polymorphic casting/assignment of the result object does not give any unchecked warning errors as Generics have not been used here. (Even with Java 5 and later, you won’t necessarily get unchecked warnings when you are using your own non-generic classes.)
  13. If an anonymous inner class is used as an initialiser, the anonymous inner class has access to the properties of its creator, i.e. the client object creating and invoking the commands. In particular, it can access the command object references which have been added to the command list. An initialiser is passed both the original command list and the results so far up to the point reached in the list. It can then use the standard fetch method on one of the object references added to the list in order to fetch details of previous results in the list, and use them to initialise the passed parameters for the command it is initialising (or indeed a later one in the list if required). Note that an anonymous inner class can only access final objects in its parent/creator, so this means that in this case any commands added to the list which are referenced in this way must be declared final. This is not the problem it might seem – for a final object, only the object reference cannot change – properties of the object can still be modified. Note that as CDI is normally used to inject all the object references, CDI constructor injection must be used to inject these object references in order to allow them to be final but still injectable by CDI. This is very straightforward (see the example code)– just define a constructor with all the required final objects as parameters, assign them in the constructor, and prefix the constructor with @Inject.
  14. Each initialiser returns a boolean. If true, the command and subsequent ones are executed normally. If an initialiser returns false, then all command execution is aborted at that point, and the results of any commands not executed are set to null. This would be convenient for example where subsequent commands depend on the result of an initial one, and the initial one returns null – the whole sequence can then be aborted as there is no point in executing all the dependant commands – they will all also return null.
  15. Each command has an enabled property which defaults to true. An initialiser can use this to disable any subsequent commands in the list (while leaving others enabled), as each initialiser is passed the original command list as well as the results so far. An initialiser is also passed the index of its own command in the command list so it is fully aware of the point reached in the list.

No Comments »

Trackback URI | Comments RSS

Leave a Reply

You must be logged in to post a comment.