Sonntag Jul 06, 2008

using JNDI MailSession in Glassfish

Today I played around a long time figuring out how to lookup a Java Mail Session out of a EJB from Glassfish. This is the link which finaly helps me through:

http://forums.java.net/jive/thread.jspa?messageID=260133&#260133

before I read a lot of pages like:

https://glassfish.dev.java.net/javaee5/docs/DG/beaow.html

http://forums.java.net/jive/thread.jspa?messageID=265263&#265263

The problem for me was the lookup like thisone:

 Context ic = new InitialContext();
Session session = (Session)ic.lookup("java:comp/env/mail/testSession");

 To avoid a :

javax.naming.NameNotFoundException: No object bound to name java:comp/env/mail/testSession

 it is importend to add the right name mapping to the ejb-jar.xml and also to the sun-ejb-jar.xml

to the ejb-jar.xml add the following code to that EJB which makes the lookup:        

    <resource-ref>
        <res-ref-name>mail/testSession</res-ref-name>
        <res-type>javax.mail.Session</res-type>
        <res-auth>Container</res-auth>
        <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>

And to the sun-ejb-jar.xml file add the following to the same EJB

 <resource-ref>
        <res-ref-name>mail/testSession</res-ref-name>
        <jndi-name>testSession</jndi-name>
 </resource-ref>

Notice that this is only necessary to perform a jndi lookup. I think you can save oneself this using dependency injection using annotations (@ressource)