Java – How to load files into session bean

ejb-3.0jakarta-eejava

I have a java EE application EE5 EJB3. I develop using NetBeans 6.7 and GlassFish 2.x
I need to have a configuration file (*.xsl, *.xml) that is deployment/client specific.

My questions are:

1) where do I put files that are external to the ear file?

2) How do I load the files into a session bean? can I use injection?

I manage to inject a @Resource for the file name using the ejb-jar.xml.

Many thanks in advance.
G.

Best Answer

I guess this is not what you are expecting but the right answer is that you shouldn't do it! According to the EJB specifications and more precisely the Programming Restrictions:

An enterprise bean must not use the java.io package to attempt to access files and directories in the file system.

And this statement is followed by this explanation:

The file system APIs are not well-suited for business components to access data. Business components should use a resource manager API, such as JDBC, to store data.

The reasons behind this statement are:

  1. Accessing the file system isn't transactional and would compromise component distributability.
  2. Accessing the file system from an EJB would compromise its deployability (the resource isn't under the EJB container's control and the EJB can't be moved easily in a cluster).
  3. Accessing the file system is a potential security hole.

Now that you know this, if you still want to do what you had in mind and if your EJB container doesn't restrict using classes from the java.io package, then I would put a read-only file on the classpath, preferably in a JAR, and access it using the getResource() or getResourceAsStream() methods of java.lang.Class. But really, you should keep the specification in mind, it's there to help you build portable applications.