February 9th, 2012
12:01 pm
EJB methods–returning status codes vs throwing exceptions

Posted under EJB
Tags , , ,

Exceptions are hotly debated on line, as is this issue as to whether to return status or throw an exception. There is no straight answer for all cases, but for the projects I am working on, I am adopting the following.

  1. Many EJB methods return data as lists of entities for example, and to return a status code as well is a nuisance as you need to build a wrapper class for this.
  2. My present way forward therefore is to throw exceptions in the EJB methods, for example when you attempt to delete a non existent row.
  3. Even though some methods like delete have no return and could return a status, others do return data and could not easily do it this way. I prefer to be consistent in my approach.
  4. Therefore, I will throw checked exceptions for these ‘important’ ones like non existant data, that the caller should check for.
  5. If I am using  a command pattern as per my post on this here, I will then catch these in the command objects,  and convert to one of the status enum values I have proposed for my Command Pattern implementation. This is an ideal place to do it, exceptions are not friendly to the command pattern mechanism if you want to continue from one, and I have already added the generic status enum idea.
  6. For cases when I do not use command patterns, a similar approach could be used by catching the exceptions in the model layer and converting to a status enum there. My model layer is stateful, and typically my fetch methods in the model populate result properties and then return void. These would be ideally placed to catch any exceptions from the service layer and return a status enum instead (or just return the enum status from a command if that was used).
  7. Coupling and isolation of the status enum needs to be considered. Where the enum is defined in the model, the view/controller layer has no dependency on the service layer. However, if the enum were to be defined in the service layer, the view then has a dependency on it as it uses that enum. This is (perhaps to a lesser extent) also true if the enum is defined in a command class, as these are also service layer classes. I may therefore decide to map them to a model specific enum (which may be similar).

No Comments »

July 19th, 2011
5:35 pm
Calling a utility POJO from a Session Bean

Posted under EJB
Tags , , , ,

Update 17/10/2013

This StackOverflow Post here is by David Blevins, EJB 3.1 expert group member among many other things. It confirms my original post below that plain CDI beans can be freely mixed with EJBs etc. and that you use what you need based on the features offered. It confirms that an @ApplicationScoped bean is pretty much an @Singleton but does not have the @Startup capability to run a method when the application starts. There is a javax.inject.Singleton as well as a javax.ejb.Singleton, however this post here points out that javax.inject.Singleton is not part of the official CDI spec. Therefore, it suggests (as does David Blevins in the above post) that you use @ApplicationScoped if you don’t need the special transactional/locking features of @Singleton (javax.ejb.Singleton that is), as it can be a lot faster.

In my case, there are a number of places where I may now end up replacing intermediate @Stateless beans with @Application scoped ones for simplicity and performance.

Original Post

A number of blog posts on this maintain that you need to create an EJB singleton for this, and set it to readonly, perhaps with Transactionattribute  set to unsupported to suspend the transaction whilst in the utility POJO/EJB.

Assuming the utility POJO did no database access and had no transaction involvement, I could see no reason for this. After all, an EJB can create and use an ArrayList for example without having to take any special actions. Why should my utility POJO be any different? In my case, the POJO was using the Apache Base64 encoder to encode an ID in Base64. When I subsequently read the CDI spec for info on this, it came to the rescue. CDI states that you can pretty much inject anything into anything else.

In particular, on P13 of the weld spec, Section 2.2.2 “SessionBeans” it states :-

“You can inject one session bean into another session bean, a managed bean into a session bean, a session bean into a managed bean, have a managed bean observe an event raised by a sessionbean, and so on.”

Therefore, if I just have a plain utility class which has nothing to do with session beans, the DB, or transactions, I can just inject it with CDI and call it from a session bean. I do not have to make it a singleton session bean/with readonly locking/transactions not supported etc.

The restriction would be that unlike session beans it could not be called remotely with all the clever EJB remote stuff, however this is absolutely not required in cases like this, I would just deploy it as a utility library in the local container along with the rest of the application. Each application server would therefore have its own copy.

This finally makes sense. In my case, it also works perfectly well when I inject an application scoped POJO into a stateless session bean.

No Comments »

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 »

November 26th, 2010
8:25 pm
Using container managed JPA 2.0 with CDI/EJB 3.1/Glassfish 3

Posted under JPA
Tags , , , , , ,

Update

  • One issue to be aware of, which is not immediately obvious, is when populating a database from scripts. If the version column is left null (Eclipselink leaves it as nullable by default), then the null value causes an immediate OptimisticLockException to be thrown. This is because EclipseLink expects and checks for a zero as the initial value for a new record. If EclipseLink itself persists the record, then it writes a zero.
  • One good idea to resolve this would be to enforce version columns to be non null with a zero default – although it must be said that it would be helpful if EclipsLink did this automatically in response to the @Version annotation.
  • Population scripts should therefore set version to zero, unless it is set non null with a default of zero in JPA – this latter solution is cleaner and would be automatic for me because I create version columns in a mapped superclass used by all Entities. I have yet to test this out however.

 

Original Post

This follows on from a previous post relating to JPA 1.0/Glassfish 2.1, and contains a few notes and pointers relating to JPA 2.0 under Glassfish 3 with CDI/Weld.

Firstly, when using an EJB from a client, use CDI injection (@Inject) rather than the @EJB annotation, as CDI gives many additional benefits such as type safety.

In an EJB:-

  • You are using container managed transactions, and so simply have to inject an entity manager rather than create one from an entity manager factory.
  • The container managed entity manager can be injected with a simple @PersistenceContext annotation – the persistence unit name may be defaulted and is discovered automatically.
  • The container is responsible for entity manager lifetime/closing. Calling e.g. em.close at the end of a bean method is illegal and will make Glassfish angry. You do not want to make Glassfish angry – you end up with many long stack traces in the log which on the surface do not appear to relate to this trivial problem!

A major issue with container managed transactions is how to use optimistic locking and detect and handle optimistic lock exceptions correctly. This is detailed in Pro JPA 2, pages 355-357 (you can preview this in Google Books). The main problem is that in a server environment, the OptimisticLockException will simply be logged by the container which then throws an EJBException. Trying to catch an OptimisticLockException in the calling client is therefore doomed to failure – it will probably never be caught!

The solution is to call flush() on the entity manger (e.g. em.flush()) just before you are ready to complete the method. This forces a write to the database, locking resources at the end of the method so that the effects on concurrency are minimised. This allows us to handle an optimistic failure while we are still in control, without the container swallowing the exception. The ChangeCollisionException might contain the object which caused the exception, but it is not guarranteed to. If there were multiple objects in the transaction, we could have invoked getEntity() on the caught exception to see whether the offending object was included.

If we do get an exception from the flush() call, we can throw a domain specific application exception which the caller can recognise, i.e. convert an OptimisticLockException to our own ChangeCollisionException, avoiding coupling the caller to the internal semantics of JPA transactions. It is also desirable to factor out the code which calls flush() into our own method, e.g. flushChanges() to avoid the need for every method which needs to flush having to catch the optimistic lock exception and then throw our domain specific one – we can centralise the exception conversion in our own single method.

We must annotate the ChangeCollisionException class with @ApplicationException, which is an EJB container annotation, to indicate to the container that the exception is not really a system level one but should be thrown back to the client as-is. Normally defining an application exception will cause the container not to roll back the transaction, but this is an EJB 3 container notion. The persistence provider that threw the OptimisticLockException  (in this case Eclipselink) does not know about the special semantics of designated application exceptions and, seeing a runtime exception, will go ahead and mark the transaction for rollback. The client can now receive and handle the ChangeCollisionException and do something about it.

Here is an example of our exception class with the required annotation:-

@ApplicationException
public class ChangeCollisionException extends RunTimeException {
   public ChangeCollisionException() {super(); }
}

Here are code fragment examples from a stateless session bean showing the entity manager injection, and a client JSF model bean showing the CDI injection of the stateless session bean. Note that with EJB 3.1 it is not necessary to declare local or remote interfaces for an EJB as business interfaces are not a requirement. However, I always use an interface as it allows for example a mock version of a service layer to be easily swapped in for testing. CDI supports this conveniently via alternatives, whereby a mock version of a bean can be switched in via a setting in beans.xml for testing.

@Stateless
public class SentryServiceImpl implements SentryServiceLocal {

    @PersistenceContext
    private EntityManager em;

}

@Named
@Dependent
public class ModelBeanImpl implements ModelBean, Serializable {
    private static final long serialVersionUID = -366401344661990776L;
    private @Inject SentryServiceLocal sentryService;
… 
}

With container managed JPA and/or Glassfish your persistence.xml  can also be simplified, as you can define your data source in Glassfish rather than explicitly in persistence.xml, as described here.

Note that when defining a data source directly in persistence.xml,  some property names have been standardized for JPA 2.0, so have changed from e.g. eclipselink.jdbc.user to javax.persistence.jdbcuser. The following properties in persistence.xml are now standard:-

<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
<property name="javax.persistence.jdbc.user" value="sentry"/>
<property name="javax.persistence.jdbc.password" value="sentry"/>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>

An example persistence.xml used under JPA 2.0 follows:-

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

    <persistence-unit name="SentryPrototype" transaction-type="JTA">
      <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
      <jta-data-source>jdbc/SentryPool</jta-data-source>
      <properties>
       <property name="eclipselink.logging.level" value="INFO" />
       <property name="eclipselink.target-database" value="Oracle" />      
       <property name="eclipselink.ddl-generation.output-mode" value="database" />      
      </properties>
     </persistence-unit>
</persistence>

No Comments »

June 11th, 2010
12:44 pm
Further notes on EJB Lookups

Posted under Glassfish
Tags , ,

Much of this has already been covered here, but I am posting these somewhat raw notes from an earlier investigative email as they include one or two links and points not covered elsewhere. I don’t have the time or inclination at present to rework everything into an existing post :-

 

1/ For local beans, you can just use defaults in @Stateless (in the bean) and in @EJB (in the referring code)
Note that when you do not use all the defaults, you must declare both the beaninterface and the name attributes

@EJB(name=”ejb/JPAGlassFishIce/SimpleBean”, beanInterface=SimpleBeanLocal.class)
private SimpleBean simpleBean;
2/ For remote beans, you can use e.g.

@Stateless(mappedName=”ejb/JPAGlassFishIceEJB/SimpleBean”)

Then

@EJB(beanInterface=SimpleBeanRemote.class, mappedName=”ejb/JPAGlassFishIceEJB/SimpleBean”)
private SimpleBean simpleBean;

Note – you must pass the class of the remote interface as above or it will not work, and you just get name not found exception.

3/ The above methods work for both access from one bean to another, and from a JSF managed bean to a remote (or local) bean
It also works from any POJO called from e.g. a JSF manged bean.
Note that this ability is container specific – Glassfish does it, other containers may vary in what/if/how they support.

4/ If doing JNDI lookups yourself to a local bean (via context.lookup), you need to add <ejb-local-ref> to web.xml as follows :-

 <ejb-local-ref>
    <ejb-ref-name>ejb/JPAGlassFishIce/SimpleBean</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <local-home></local-home>
    <local>uk.co.salientsoft.jpaglassfishice.domain.SimpleBeanLocal</local>
</ejb-local-ref>

This would be used if using e.g. Spring or a custom EL resolver  to inject references into JSF managed beans (via JSF DI)

Note that the JNDI name for the above local reference would be
“java:comp/env/ejb/JPAGlassFishIce/SimpleBean”
i.e. this is picking up from the <ejb-ref-name> above, and is prefixed java:comp/env
java:comp/env is a reference to the JNDI “Environment” service provider for Java EE
you can also use this  to look up environment variables etc.
see here http://java.sun.com/developer/technicalArticles/xml/WebAppDev4/

The <ejb-local-ref> stuff is done for you automatically if you use @EJB

5/ Note that JNDI names are container specific at present (fixed in java ee6)
See here for a good SUN post on all the EJB reference stuff :-
https://glassfish.dev.java.net/javaee5/ejb/EJB_FAQ.html

No Comments »

May 8th, 2010
2:32 pm
New Java Stack ideas – articles on CDI, Weld, JSF2.0, Java EE6, Spring

Posted under Java
Tags , , , , ,

This is a collection of useful notes and post/article references on ideas for a suitable new Java stack:-

http://blogs.sun.com/enterprisetechtips/entry/using_cdi_and_dependency_injection

http://stackoverflow.com/questions/2270379/differences-between-java-ee-6-cdi-implementations

http://docs.jboss.org/weld/reference/1.0.0/en-US/html/environments.html#d0e4910

http://stackoverflow.com/questions/2499323/jee6-vs-spring-3-stack

No Comments »

December 3rd, 2009
3:14 pm
Create a JPA EJB using Eclipse/Eclipselink/Glassfish

Posted under Eclipse
Tags , , ,

This simple example was performed with Eclipse Galileo 3.5.1

1/ Project Creation Dialog

From the menus in eclipse, select File/New/EJB project. On the resulting dialog, name the project. You can pick other options at this stage such as EAR membership but this can be done later if desired. Note that we are not amending the configuration section (via the modify button) at this stage to add JPA faceting (more on this later).

Click Finish and your EJB project will be created.

2/Project Facets

Right click your new project, and select Project Facets on the left. Tick the box marked Java Persistence in the middle pane, and you will be presented with the following screen :-

3/ JPA Facets

Now Click the “Further configuration available” link at the bottom. This will display the JPA Facet dialog as follows. On this screen you should do the following :-

  1. Select the correct platform version and library type – typically these will be Eclipselink 1.1 or later version if available.
  2. Untick the box marked “Include libraries with this application”.  The  latest Eclipselink.jar  library should be deployed separately to Glassfish, and stored in the $GLASSFISH_HOME/lib directory. To clarify, Eclipselink is available as a single jar, non-OSGI deployment, or split up into multiple jars for OSGI deployment. The OSGI jars have the long names with the OSGI packaging prefixes such as “org.eclipse.persistence.core” followed by name and version number information. They are a finer grained breakdown of the classes to allow more selectivity/flexibility in use. You can copy the OSGI jars to $GLASSFISH_HOME/lib directory – this will also work but is unnecessarily complex for non-OSGI use. This post here contains a brief overview of OSGI and links to detailed information about it.
  3. Select the database connection to be used. If it is not already present, click the Add connection link to create a new one. This also allows you to add a new JDBC provider for a given database type, and point to the jar file(s) for the provider. Note that you will also need to add the JDBC provider jar to GLASSFISH_HOME/lib. To clarify, this database connection is used by eclipse to validate the persistent entities and mappings in the project during development. It is not used by Glassfish at run time. The run time connection (data source) will be created in Glassfish, and persistence.xml will be configured to use the datasource that you created in Glassfish.
  4. Next, you can select whether your annotated persistent classes will be discovered automatically, or whether they must be listed explicitly in persistence.xml. To ensure portatbility, you should take the manual option as  automatic discovery is not guarrranteed to be portable.
  5. Finally you can select whether or not to create orm.xml. You can always create it later if you need it – if you are using annotations entirely you won’t. This post here describes how you can combine both annotations and orm.xml in order to both take advantage of features like sequences in Oracle whilst still retaining database independance.

Click OK on the JPA Facet dialog, and then OK on the project facets screen. This will complete the creation of your project.

Note that as already stated, it is possible to click the modify button in the configuration section of the dialog in stage 1, which will also display the project facet screen. However, this version of the project facet screen is different to the one displayed if you select Project Facets after creating the project. In particular it does not have the “Further configuration available” option, and so does not allow you to display the JPA Facet dialog to modfy the options there. It assumes defaults for these options instead.

It is possible to  reconfigure the project JPA Facet settings subsequently, by selecting the “Java Persistence” option which appears in the list on the left of the project properties dialog (this only appears for projects with the JPA facet selected). This displays the “Java Persistence” dialog which has the same options as the “JPA Facets” dialog. Instead, you can also untick Java Persistence on the Project Facets screen, applying the changes, and retick the option. This will reveal the “Further Configuration Available” option to allow access to the JPA Facet dialog as well. In the example above, we added the Java persistence facet after saving the project which gave us immediate access to the JPA Facets dialog.

No Comments »

December 3rd, 2009
10:30 am
Implementing Dual Interfaces on an EJB

Posted under EJB
Tags ,

Note that when implementing dual (both Local and Remote) interfaces on an EJB, you can extend a single underlying superinterface. In this case, SimpleBeanLocal and SimpleBeanRemote both extend SimpleBean. However, when you do this, the implementation code must explicitly implemement both subinterfaces SimpleBeanLocal and SimpleBeanRemote as in this example. Implementing the superinterface SimpleBean on its own will not work.

(Super)Interface SimpleBean

public interface SimpleBean {
   public void createUsers(); 
   public List fetchUsers();
}

 

 

(Sub)Interface SimpleBeanLocal

@Local()
public interface SimpleBeanLocal extends SimpleBean {}

 

(Sub)Interface SimpleBeanRemote

@Remote()
public interface SimpleBeanRemote extends SimpleBean {}

 

Implementation Class SimpleBeanImpl

@Stateless(mappedName="ejb/JPAGlassFishIceEJB/SimpleBean")
public class SimpleBeanImpl implements SimpleBeanLocal, SimpleBeanRemote {
...class Code here...
}

No Comments »

December 1st, 2009
4:33 pm
Java EE Enterprise Naming Context

Posted under EJB
Tags , ,

This article on CodeIdol is a good detailed FAQ on the Enterprise Naming Context or ENC, also known as the Java EE Application Component Environment, accessed via the JNDI name “java:comp/env”.  The article details the use of the java ee annotations in @javax.annotation.EJB and the equivalent XML, including injection of bean references via XML using <injection-target> rather than annotations. 

Another article on redhat.com gives a good overview of this with some other helpful links.

No Comments »

December 1st, 2009
11:38 am
EJB referencing/JNDI mapping examples in JSF/Glassfish

Posted under Glassfish
Tags , , ,

Update

I have posted some further notes on this here. The notes are in raw form from an earlier investigative email – much of it is covered here, but some points and links are not, and I do not have the time or inclination at present to rework everything into a single post!

The following examples show typical scenarios which have been tested as working :-

1/ Local EJB Interface injected into JSF managed bean via @EJB

Note that when implementing a dual interface as here, you can extend a single underlying interface. In this case, SimpleBeanLocal and SimpleBeanRemote both extend SimpleBean. However, when you do this, the implementation code must explicitly implemement both SimpleBeanLocal and SimpleBeanRemote as in this example. Implementing the superinterface SimpleBean on its own will not work. This is also explained in this post.

JSF managed bean code

@EJB()
private SimpleBean simpleBean;

 

EJB Implementation Code

@Stateless()
public class SimpleBeanImpl implements SimpleBeanLocal, SimpleBeanRemote {

...class code here...

}

 

 

2/ Local EJB Interface looked up in JSF managed bean directly via JNDI 

JSF managed bean code

try {
  InitialContext ctx = new InitialContext();

  /* Note that the JNDI name consists of the Java EE Environment Naming Context (ENC) -
    "java:comp/env", followed by "/", followed by the <ejb-ref-name> used in web.xml.
    The extra /Local is just to make the name different to the remote example.
    Any name can be used providing web.xml matches, and multiple slashes can be present.
  */

  simpleBean = (SimpleBean) ctx.lookup("java:comp/env/ejb/JPAGlassFishIce/Local/SimpleBean");     
  userList = simpleBean.fetchUsers();
} catch (NamingException e1) {
  e1.printStackTrace();
}

 

web.xml

<!-- We define a reference for the bean here.
     If we were using @EJB this would do it for us,
     but in this case we are using an explicit JNDI lookup.
-->
<ejb-local-ref>
    <ejb-ref-name>ejb/JPAGlassFishIce/Local/SimpleBean</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <local-home></local-home>
    <local>uk.co.salientsoft.jpaglassfishice.domain.SimpleBeanLocal</local>
</ejb-local-ref>

 

EJB Implementation Code

@Stateless()
public class SimpleBeanImpl implements SimpleBeanLocal, SimpleBeanRemote {

...class code here...

}

 

 

3/ Remote EJB Interface injected into JSF managed bean via @EJB

JSF managed bean code

@EJB(name="ejb/JPAGlassFishIce/SimpleBean", beanInterface=SimpleBeanRemote.class)
private SimpleBean simpleBean;

 

EJB Implementation Code

@Stateless(mappedName="ejb/JPAGlassFishIceEJB/SimpleBean")
public class SimpleBeanImpl implements SimpleBeanLocal, SimpleBeanRemote {

...class code here...

}

 

 

4/ Remote EJB Interface looked up in JSF managed bean directly via JNDI 

JSF managed bean code

try {
  InitialContext ctx = new InitialContext();

  /* Note that the JNDI name here matches the mappedName given in the
     @Stateless annotation in the EJB implementation code.
     mappedName is only relevant for remote interfaces.
     It is not used for a local interface.
  */

  simpleBean = (SimpleBean) ctx.lookup=("ejb/JPAGlassFishIceEJB/SimpleBean");     
  userList = simpleBean.fetchUsers();
} catch (NamingException e1) {
  e1.printStackTrace();
}

 

EJB Implementation Code

@Stateless(mappedName="ejb/JPAGlassFishIceEJB/SimpleBean")
public class SimpleBeanImpl implements SimpleBeanLocal, SimpleBeanRemote {

...class code here...

}

No Comments »