JBoss 7.1.1.Final - EJB Remote Call - java.lang.IllegalStateException: No EJB receiver available for handling - ejb

I do have 2 JBoss stanalon instance running. 1 act as Server and another 1 would client.
SERVER:
Remote Interface
package com.xyz.life.service.ejb;
import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.EJB;
import javax.ejb.Remote;
#Remote
public interface QuoteFacade extends Serializable{
public boolean isAlive() throws RemoteException;
}
EJB Impl
package com.xyz.life.common.component.ejb.services;
import java.rmi.RemoteException;
import javax.ejb.Remote;
import javax.ejb.Stateless;
#Stateless(mappedName = "QuoteFacadeEJB")
#Remote(QuoteFacade.class)
public class QuoteFacadeEJB extends CommonSessionBean implements QuoteFacade {
private static final long serialVersionUID = -8788783322280644881L;
#Override
public boolean isAlive() throws RemoteException {
return true;
}
}
server.log
16:40:25,012 INFO [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-4) JNDI bindings for session bean named QuoteFacadeEJB in deployment unit subdeployment "quote.jar" of deployment "quote.ear" are as follows:
java:global/quote/quote.jar/QuoteFacadeEJB!com.xyz.life.service.ejb.QuoteFacade
java:app/quote.jar/QuoteFacadeEJB!com.xyz.life.service.ejb.QuoteFacade
java:module/QuoteFacadeEJB!com.xyz.life.service.ejb.QuoteFacade
java:jboss/exported/quote/quote.jar/QuoteFacadeEJB!com.xyz.life.service.ejb.QuoteFacade
java:global/quote/quote.jar/QuoteFacadeEJB
java:app/quote.jar/QuoteFacadeEJB
java:module/QuoteFacadeEJB
Client
public void testClient() {
try {
Hashtable<String, Object> jndiProps = new Hashtable<String, Object>();
jndiProps.put(Context.URL_PKG_PREFIXES, JNDINames.JBOSS_CLIENT_NAMING_PREFIX);
jndiProps.put("jboss.naming.client.ejb.context", true);
Context ctx = new InitialContext(jndiProps);
String name = "ejb:global/quote/quote.jar/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade";
/*
"ejb:global/quote/quote.jar/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade",
"ejb:app/quote.jar/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade",
"ejb:jboss/exported/quote/quote.jar/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade"
*/
Object ref = ctx.lookup(name);
QuoteFacade quoteFacade = (QuoteFacade) ref;
LOGGER.debug("isAlive : " + quoteFacade.isAlive());
} catch (Exception e) {
LOGGER.error("Remote Client Exception : ", e);
}
}
No error/log on server side. Client side, it is failing with following error:
java.lang.IllegalStateException: No EJB receiver available for handling [appName:global,modulename:quote,distinctname:quote.jar] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext#200cae
at org.jboss.ejb.client.EJBClientContext.requireEJBReceiver(EJBClientContext.java:584)
at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:119)
at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:136)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:121)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:104)
at $Proxy10.isAlive(Unknown Source)
I tried without using Properties file:
private static QuoteFacade connectToStatelessBean(String name) throws NamingException {
Properties jndiProperties = new Properties();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
jndiProperties.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
jndiProperties.put(javax.naming.Context.PROVIDER_URL, "remote://localhost:4447");
jndiProperties.put(javax.naming.Context.SECURITY_PRINCIPAL, "admin");
jndiProperties.put(javax.naming.Context.SECURITY_CREDENTIALS, "Pass1234");
final Context context = new InitialContext(jndiProperties);
return (QuoteFacade) context.lookup(name);
}
public static void testLocal() {
String[] JNDINAME1 = {
"ejb:global/quote/quote.jar/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade",
"ejb:app/quote.jar/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade",
"ejb:module/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade",
"ejb:jboss/exported/quote/quote.jar/QuoteFacadeEJB!com.ge.life.annuity.service.ejb.QuoteFacade",
"ejb:global/quote/quote.jar/QuoteFacadeEJB",
"ejb:app/quote.jar/QuoteFacadeEJB",
"ejb:module/QuoteFacadeEJB"
};
for(int i=0;i<JNDINAME1.length;i++){
try {
QuoteFacade test1 = connectToStatelessBean(JNDINAME1[i]);
LOGGER.error("DSLKAJDLAS : " + test1.isAlive());
} catch (Exception e) {
LOGGER.error("DSLKAJDLAS : " , e);
}
}
LOGGER.info("Done - SANSSAN!!!!!!!!");
}
This time, different exception :
14.01.2013 17:40:37.627 [ERROR] - EJBClient - DSLKAJDLAS :
javax.naming.NamingException: JBAS011843: Failed instantiate InitialContextFactory org.jboss.naming.remote.client.InitialContextFactory from classloader ModuleClassLoader for Module "deployment.quote.war:main" from Service Module Loader
at org.jboss.as.naming.InitialContextFactoryBuilder.createInitialContextFactory(InitialContextFactoryBuilder.java:64)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:681)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307)
at javax.naming.InitialContext.init(InitialContext.java:242)
at javax.naming.InitialContext.><init>(InitialContext.java:216)
at com.xyz.life.test.EJBClient.connectToStatelessBean(EJBClient.java:208)
at com.xyz.life.test.EJBClient.testLocal(EJBClient.java:225)
at com.xyz.life.test.EJBClient.test(EJBClient.java:172)
at com.xyz.life.common.web.struts.plugin.FrameworkStartupPlugIn.init(FrameworkStartupPlugIn.java:99)
at org.apache.struts.action.ActionServlet.initModulePlugIns(ActionServlet.java:1158)
at org.apache.struts.action.ActionServlet.init(ActionServlet.java:473)
at javax.servlet.GenericServlet.init(GenericServlet.java:242)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1202)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1102)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3655)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:3873)
at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:90)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)

Try removing "global" from name:
String name =
"ejb:quote/quote.jar/QuoteFacadeEJB!com.xyz.life.service.ejb.QuoteFacade"
Also, your package name should be com.xyz.life.service.ejb (as seen on server log) and not com.ge.life.annuity.service.ejb.
Anyway, using remote-naming project for remote EJB invocations is discouraged as explained here.
... . So as you can see, we have managed to optimize certain operations by using the EJB client API for EJB lookup/invocation as against using the remote-naming project. There are other EJB client API implementation details (and probably more might be added) which are superior when it is used for remote EJB invocations in client applications as against remote-naming project which doesn't have the intelligence to carry out such optimizations for EJB invocations. That's why the remote-naming project for remote EJB invocations is considered "deprecated". ...
You can check how to do remote EJB invocations using the EJB client API here.

Found it....
The ones I used for Local machines only. Difference JBoss instances, should change the JNDI lookup name...
like
ejb:quote/quote.jar//QuoteFacadeEJB!com.xyz.life.service.ejb.QuoteFacade

Related

Why Stateful and Stateless beans behave in opposite way?

I created Stateful, Stateless and singleton bean classes and trying to access them two different servlet. And running project on JBoss server.
When I access Stateful bean from each servlet two different bean object will be created and different states(data) are preserved for them. But stateless bean object is shared between both servlet. Singleton bean also behaves same way as stateless bean.
My question is why stateful and stateless bean behaves in opposite way? Is lifecycle of session bean is same as lifecycle of servlet?
FirstServlet.java
#WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB
StatelessBean statelessBean;
#EJB
StateFullBean statefulBean;
#EJB
SingletonBean singletonBean;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String message = "Beans not injected.";
String beanType = request.getParameter("beanType");
if ("Stateless".equals(beanType)) {
if (statelessBean != null) {
message = statelessBean.getHits();
} else {
message = "Stateless bean not injected.";
}
}
if ("Stateful".equals(beanType)) {
if (statefulBean != null) {
message = statefulBean.getHits();
} else {
message = "Stateful bean not injected.";
}
}
if ("Singleton".equals(beanType)) {
if (singletonBean != null) {
message = singletonBean.getHits();
} else {
message = "Singleton bean not injected.";
}
}
response.setContentType("text/html");
response.getWriter().print("<h1>" + message + "</h1>");
}
}
Similarly, I created one more servlet DemoServlet.java.
StateFullBean.java
#Stateful
public class StateFullBean{
int hits=0;
public String getHits() {
hits++;
return "StateFullBean number of hits " + hits;
}
public StateFullBean() {
System.out.println("StateFullBean created.");
}
}
StatelessBean.java
#Stateless
public class StatelessBean{
int hits=0;
public String getHits() {
hits++;
return "StatelessBean number of hits " + hits;
}
public StatelessBean() {
System.out.println("StatelessBean created.");
}
}
SingletonBean.java
#Startup
#Singleton(name="SingletonBean")
public class SingletonBean {
int hits=0;
public SingletonBean() {
System.out.println("SingletonBean created.");
}
public String getHits() {
hits++;
return "Singleton bean number of hits " + hits;
}
}
Am I missed something in code?
Everything is behaving as specified.
A stateless EJB delegates the call further to currently available instance in the pool. Apparently there's only one which is not used concurrently (yet) and therefore all clients have the same chance to access the same instance in the pool. If you fire more HTTP requests concurrently on the servlet(s), then chances increase that there's no available instance anymore and the container will create a new instance in the pool.
A stateful EJB is tied to its client (in your case, the web servlet instance). In other words, each servlet has its own stateful EJB instance which is not shared elsewhere.
A singleton bean is application wide and shared across all clients. In other words, each servlet will share the same singleton EJB instance.
Do note that the terms "client" and "session" in EJB context are absolutely not the same as those in WAR context and this is where many starters fall over. The EJB client is not the webbrowser, but the instance of the class where the EJB is injected (in your case, the web servlet instance). The EJB session is not the HTTP session, but the EJB-client session.
See also:
#Inject stateless EJB contains data from previous request
Why Stateless session beans?
When using #EJB, does each managed bean get its own #EJB instance?

NoInitialContextException in simple EJB Project on Wildfly 8

I am trying to write a client for a simple EJB Project that I have deployed locally on my Wildfly 8 running in Eclipse.
My Interface:
package com.jwt.ejb.business;
import javax.ejb.Remote;
#Remote
public interface Hello {
public String sayHello();
}
My Implementation:
package com.jwt.ejb.businesslogic;
import javax.ejb.Stateless;
import com.jwt.ejb.business.Hello;
#Stateless
public class HelloBean implements Hello {
public HelloBean() {
}
public String sayHello() {
return "Hello Boss Welcome to EJB";
}
}
My client:
package com.jwt.ejb.test;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.jwt.ejb.business.Hello;
import com.jwt.ejb.businesslogic.HelloBean;
public class Client {
public static void main(String[] args) {
Hello bean = doLookup();
if (bean != null)
System.out.println(bean.sayHello());
}
private static Hello doLookup() {
Context context = null;
Hello bean = null;
try {
final Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
context = new InitialContext(jndiProperties);
bean = (Hello) context.lookup(getLookupString());
} catch (NamingException e) {
e.printStackTrace();
}
return bean;
}
private static String getLookupString() throws NamingException {
final String appName = "";
final String moduleName = "EJBTest";
final String distinctName = "";
final String beanName = HelloBean.class.getSimpleName();
final String viewClassName = Hello.class.getName();
return "ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName;
}
}
When I run it, I get this Exception:
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at com.jwt.ejb.test.Client.doLookup(Client.java:26)
at com.jwt.ejb.test.Client.main(Client.java:15)
Exception in thread "main" java.lang.NullPointerException
at com.jwt.ejb.test.Client.main(Client.java:16)
The official documentation does it like this too:
https://docs.jboss.org/author/display/AS71/EJB+invocations+from+a+remote+client+using+JNDI
Where is the problem ?
I came accross posts talking about boss-ejb-client.properties, but I am not sure what to put in it. As I understood it, I could either have this properties file, or declare the porperties programmatically, like I did.
Besides the fact that you are using Wildfly 8 and referencing JBoss AS 7.1's documentation, you're missing the InitialContextFactory on your JNDI properties.
Wildfly's documentation on EJB invocations via JNDI is here. Therefore you should do the following:
void doBeanLookup() {
Properties jndiProperties = new Properties();
jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
jndiProperties.put(Context.PROVIDER_URL, "http-remoting://localhost:8080");
// This is an important property to set if you want to do EJB invocations via the remote-naming project
jndiProps.put("jboss.naming.client.ejb.context", true);
// create a context passing these properties
Context ctx = new InitialContext(jndiProps);
// lookup the bean Hello
Hello bean = (Hello) ctx.lookup(getLookupString());
}
In your pom.xml you should have the following:
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-ejb-client-bom</artifactId>
<version>8.0.0.Final</version>
<type>pom</type>
</dependency>
If you want to use the http-remoting protocol, on your getLookupString method, you should remove the ejb: and have present that
http-remoting client assumes JNDI names in remote lookups are relative to java:jboss/exported namespace, a lookup of an absolute JNDI name will fail.
Further information can be found on Wildfly 8 Remote JNDI Reference Update Draft.

Weblogic 10.3.5 EJB3 local seesion bean lookup from java main class

I am using Weblogic 10.3.5 and EJB 3 for session bean
but I am not able to lookup jndi for local stateless session bean even though I am able to lookup
remote bean successfully
my code are for main class is
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
p.put(Context.PROVIDER_URL, "t3://localhost:7001");
try {
Context ctx = new InitialContext(p);
TheBeanRemote bean = (TheBeanRemote) ctx
.lookup("MrBean#com.bdc.TheBeanRemote");
System.out.println(bean.sayHello());
TheLocalLocal bean2 = (TheLocalLocal) ctx.lookup("TheLocalLocal");
Object obj = ctx.lookup("java:comp/env/ejb/MrBean2");
System.out.println(bean2.sayHello());
} catch (Exception e) {
e.printStackTrace();
}
Remote Bean
import javax.ejb.Remote;
#Remote
public interface TheBeanRemote {
public String sayHello();
}
Local Bean
import javax.ejb.Local;
#Local(TheLocalLocal.class)
public interface TheLocalLocal {
public String sayHello();
}
If you're running as a "client", that is a remote call, if that app is running on the server itself, that is a local call. It makes sense that one works but not the other.
The properties you're using indicate a remote call:
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
p.put(Context.PROVIDER_URL, "t3://localhost:7001");
Context ctx = new InitialContext(p);
A local call is:
Context context = new InitialContext();
See a similar question here: How to lookup JNDI resources on WebLogic?

EJB JNDI with Glassfish

I'm trying to get EJB to work with Glassfish v3. I'm working on a Java EE Web application with Servlets.
When I deploy this web app to Glassfish, it registers the EJB class into the
java:global JNDI tree. But, when I try to inject an instance of this into my
Servlet I got a NameNotFoundException.
When I look at the logs of my server, the Servlet tries to do the look up in java:comp/env.
Can someone help me to solve this?
Relevant code for the login part:
UserDao.java
#Local
public interface UserDao {
public User find(Long id);
public List<User> findAll();
public List<User> paginate(int offset, int nbentry) throws IllegalArgumentException, IllegalStateException;
public User findUserByUsernameAndPassword(String username, String password);
public User create(User user) throws UserException;
public User update(User user) throws UserException;
public Boolean delete(User user) throws UserException;
public int count();
}
JpaUserDao.java
#Stateless
public class JpaUserDao implements UserDao {
private Logger log = Logger.getLogger(JpaUserDao.class.getSimpleName());
#PersistenceContext(unitName = "YouFood-PU")
private EntityManager em;
#Override
public User create(User user) throws UserException {
try {
em.persist(user);
} catch (Exception e) {
throw new UserException("Creation of the user: " + user
+ " failed, please try later or contact the webmaster");
}
return user;
}
#Override
public User update(User user) throws UserException {
try {
em.persist(em.merge(user));
} catch (Exception e) {
throw new UserException("Update of the user: " + user
+ " failed, please try later or contact the webmaster");
}
return user;
}
#Override
public Boolean delete(User user) throws UserException {
try {
em.remove(em.merge(user));
return true;
} catch (Exception e) {
throw new UserException("Deletion of the user: " + user
+ " failed, please try later or contact the webmaster");
}
}
#Override
public User find(Long id) {
User user = new User();
try {
user = em.find(User.class, id);
return user;
} catch (Exception e) {
return null;
}
}
#Override
public User findUserByUsernameAndPassword(String username, String password) {
User user = null;
try {
log.info("findUserByUsernameAndPassword");
user = (User) em
.createQuery(
"SELECT u FROM User AS u where u.username = :username AND u.password = :password ")
.setParameter("username", username)
.setParameter("password", password).getSingleResult();
return user;
} catch (Exception e) {
e.printStackTrace();
log.severe(e.getStackTrace().toString());
return null;
}
}
#SuppressWarnings("unchecked")
#Override
public List<User> findAll() {
List<User> users = null;
try {
users = (List<User>) em.createQuery("SELECT u FROM User u")
.getResultList();
return users;
} catch (Exception e) {
return null;
}
}
#SuppressWarnings("unchecked")
#Override
public List<User> paginate(int offset, int nbentry)
throws IllegalArgumentException, IllegalStateException {
List<User> users = null;
users = (List<User>) em.createQuery("FROM User").setFirstResult(offset)
.setMaxResults(nbentry).getResultList();
return users;
}
#Override
public int count() {
Number count;
count = (Number) em.createQuery("SELECT COUNT(u.id) FROM User")
.getSingleResult();
return count.intValue();
}
}
Authenticator.java
#Stateless
public class Authenticator {
private String userFullName;
private Long userId;
#EJB
private JpaUserDao userDao;
public Authenticator() {}
public AuthenticationError connect(String username, String password)
throws Exception {
String hashed_password = Authenticator.hash(password, "UTF-8");
User user = null;
user = userDao.findUserByUsernameAndPassword(username,
hashed_password);
if (user == null) {
return AuthenticationError.UserNotFound;
}
this.userFullName = user.toString();
this.userId = user.getId();
return AuthenticationError.Success;
}
public Boolean disconnect(HttpSession session) throws Exception {
try {
session.invalidate();
return true;
} catch (Exception e) {
return false;
}
}
public String getUserFullName() {
return this.userFullName;
}
public Long getUserId() {
return this.userId;
}
/**
*
* Static method
*
* #throws Exception
*
*/
public static String hash(String data, String charset) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(data.getBytes(charset), 0, data.length());
String hash = new BigInteger(1, md.digest()).toString(16);
return hash;
}
}
LoginServlet.java
#WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Logger log = Logger.getLogger(LoginServlet.class.getSimpleName());
#EJB
private Authenticator auth;
/**
* #see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
log.info("LoginServlet.deGet() call");
request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//auth = new Authenticator();
log.info("LoginServlet.dePost() call");
String message = null;
String username = request.getParameter("username");
String password = request.getParameter("password");
log.info("username: " + username);
log.info("password: " + password);
try {
AuthenticationError status = auth.connect(username, password);
System.out.println(status);
switch (status) {
case PasswordMissMatch:
message = "Password missmatch";
log.info(message);
request.setAttribute("error", message);
request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
break;
case Success:
message = "Your are successfully logged in";
log.info(message);
request.setAttribute("success", message);
request.getSession().setAttribute("loggedIn", true);
request.getSession().setAttribute("full_name", auth.getUserFullName());
request.getSession().setAttribute("user_id", auth.getUserId());
break;
case UserNotFound:
message = "Username provided not found in our record";
log.info(message);
request.setAttribute("error", message);
request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
break;
}
} catch (GeneralSecurityException e) {
message = e.getMessage();
request.setAttribute("error", message);
} catch (Exception e) {
message = e.getMessage();
request.setAttribute("error", message);
}
request.getRequestDispatcher("/home").forward(request, response);
}
}
Glassfish Deploy log
INFO: closing
ATTENTION: DPL8027: Ignore WEB-INF/sun-web.xml in archive
/Users/guillaume/Documents/workspace/Supinfo/YouFood/nbbuild/web/, as GlassFish
counterpart runtime xml WEB-INF/glassfish-web.xml is present in the same
archive.
INFO: Processing PersistenceUnitInfo [
name: YouFood-PU
...]
INFO: Binding entity from annotated class: com.youfood.entity.Menu
INFO: Bind entity com.youfood.entity.Menu on table Menu
INFO: Binding entity from annotated class: com.youfood.entity.DinningRoom
INFO: Bind entity com.youfood.entity.DinningRoom on table DinningRoom
INFO: Binding entity from annotated class: com.youfood.entity.Item
INFO: Bind entity com.youfood.entity.Item on table Item
INFO: Binding entity from annotated class: com.youfood.entity.TTable
INFO: Bind entity com.youfood.entity.TTable on table TTable
INFO: Binding entity from annotated class: com.youfood.entity.Zone
INFO: Bind entity com.youfood.entity.Zone on table Zone
INFO: Binding entity from annotated class: com.youfood.entity.Country
INFO: Bind entity com.youfood.entity.Country on table Country
INFO: Binding entity from annotated class: com.youfood.entity.User
INFO: Bind entity com.youfood.entity.User on table User
INFO: Binding entity from annotated class: com.youfood.entity.Order
INFO: Bind entity com.youfood.entity.Order on table OrderTable
INFO: Binding entity from annotated class: com.youfood.entity.Restaurant
INFO: Bind entity com.youfood.entity.Restaurant on table Restaurant
INFO: Mapping collection: com.youfood.entity.DinningRoom.zones -> Zone
INFO: Mapping collection: com.youfood.entity.Zone.tables -> TTable
INFO: Mapping collection: com.youfood.entity.Country.restaurants -> Restaurant
INFO: Mapping collection: com.youfood.entity.Restaurant.dinningRoom -> DinningRoom
INFO: Hibernate Validator not found: ignoring
INFO: Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
INFO: Initializing connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
INFO: Using provided datasource
INFO: RDBMS: MySQL, version: 5.1.54
INFO: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.13 ( Revision: ${bzr.revision-id} )
INFO: Using dialect: org.hibernate.dialect.MySQLDialect
INFO: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
INFO: Transaction strategy: org.hibernate.ejb.transaction.JoinableCMTTransactionFactory
INFO: instantiating TransactionManagerLookup: org.hibernate.transaction.SunONETransactionManagerLookup
INFO: instantiated TransactionManagerLookup
INFO: Automatic flush during beforeCompletion(): disabled
INFO: Automatic session close at end of transaction: disabled
INFO: JDBC batch size: 15
INFO: JDBC batch updates for versioned data: disabled
INFO: Scrollable result sets: enabled
INFO: JDBC3 getGeneratedKeys(): enabled
INFO: Connection release mode: auto
INFO: Maximum outer join fetch depth: 2
INFO: Default batch fetch size: 1
INFO: Generate SQL with comments: disabled
INFO: Order SQL updates by primary key: disabled
INFO: Order SQL inserts for batching: disabled
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
INFO: Using ASTQueryTranslatorFactory
INFO: Query language substitutions: {}
INFO: JPA-QL strict compliance: enabled
INFO: Second-level cache: enabled
INFO: Query cache: disabled
INFO: Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
INFO: Optimize cache for minimal puts: disabled
INFO: Structured second-level cache entries: disabled
INFO: Statistics: disabled
INFO: Deleted entity synthetic identifier rollback: disabled
INFO: Default entity-mode: pojo
INFO: Named query checking : enabled
INFO: Check Nullability in Core (should be disabled when Bean Validation is on): disabled
INFO: building session factory
INFO: Not binding factory to JNDI, no JNDI name configured
INFO: JNDI InitialContext properties:{}
INFO: EJB5181:Portable JNDI names for EJB JpaUserDao: [java:global/YouFood/JpaUserDao, java:global/YouFood/JpaUserDao!com.youfood.dao.UserDao]
INFO: EJB5181:Portable JNDI names for EJB Authenticator: [java:global/YouFood/Authenticator!com.youfood.backoffice.utils.Authenticator, java:global/YouFood/Authenticator]
INFO: WEB0671: Loading application [YouFood] at [/web]
INFO: YouFood a été déployé en 1 279 ms.
Server Log Exception
GRAVE: EJB5070: Exception creating stateless session bean : [Authenticator]
ATTENTION: EJB5184:A system exception occurred during an invocation on EJB Authenticator, method: public com.youfood.backoffice.utils.AuthenticationError com.youfood.backoffice.utils.Authenticator.connect(java.lang.String,java.lang.String) throws java.lang.Exception
ATTENTION: javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:454)
at com.sun.ejb.containers.BaseContainer.getContext(BaseContainer.java:2547)
at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1899)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at $Proxy150.connect(Unknown Source)
at com.youfood.backoffice.utils.__EJB31_Generated__Authenticator__Intf____Bean__.connect(Unknown Source)
at com.youfood.backoffice.servlet.LoginServlet.doPost(LoginServlet.java:61)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:688)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1542)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(SiteMeshFilter.java:129)
at com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:77)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:680)
Caused by: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:726)
at com.sun.ejb.containers.util.pool.NonBlockingPool.getObject(NonBlockingPool.java:247)
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:449)
... 39 more
Caused by: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:534)
at com.sun.ejb.containers.StatelessSessionContainer.access$000(StatelessSessionContainer.java:95)
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:724)
... 41 more
Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Exception lors de la tentative d'injection de l'élément Remote ejb-ref name=com.youfood.backoffice.utils.Authenticator/userDao,Remote 3.x interface =com.youfood.dao.jpa.JpaUserDao,ejb-link=null,lookup=,mappedName=,jndi-name=com.youfood.dao.jpa.JpaUserDao,refType=Session dans class com.youfood.backoffice.utils.Authenticator : Lookup failed for 'java:comp/env/com.youfood.backoffice.utils.Authenticator/userDao' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming}
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:703)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.inject(InjectionManagerImpl.java:470)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:171)
at com.sun.ejb.containers.BaseContainer.injectEjbInstance(BaseContainer.java:1694)
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:494)
... 43 more
Caused by: javax.naming.NamingException: Lookup failed for 'java:comp/env/com.youfood.backoffice.utils.Authenticator/userDao' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NamingException: Exception resolving Ejb for 'Remote ejb-ref name=com.youfood.backoffice.utils.Authenticator/userDao,Remote 3.x interface =com.youfood.dao.jpa.JpaUserDao,ejb-link=null,lookup=,mappedName=,jndi-name=com.youfood.dao.jpa.JpaUserDao,refType=Session' . Actual (possibly internal) Remote JNDI name used for lookup is 'com.youfood.dao.jpa.JpaUserDao#com.youfood.dao.jpa.JpaUserDao' [Root exception is javax.naming.NamingException: Lookup failed for 'com.youfood.dao.jpa.JpaUserDao#com.youfood.dao.jpa.JpaUserDao' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: com.youfood.dao.jpa.JpaUserDao#com.youfood.dao.jpa.JpaUserDao not found]]]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:518)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:599)
... 47 more
Caused by: javax.naming.NamingException: Exception resolving Ejb for 'Remote ejb-ref name=com.youfood.backoffice.utils.Authenticator/userDao,Remote 3.x interface =com.youfood.dao.jpa.JpaUserDao,ejb-link=null,lookup=,mappedName=,jndi-name=com.youfood.dao.jpa.JpaUserDao,refType=Session' . Actual (possibly internal) Remote JNDI name used for lookup is 'com.youfood.dao.jpa.JpaUserDao#com.youfood.dao.jpa.JpaUserDao' [Root exception is javax.naming.NamingException: Lookup failed for 'com.youfood.dao.jpa.JpaUserDao#com.youfood.dao.jpa.JpaUserDao' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: com.youfood.dao.jpa.JpaUserDao#com.youfood.dao.jpa.JpaUserDao not found]]
at com.sun.ejb.EjbNamingReferenceManagerImpl.resolveEjbReference(EjbNamingReferenceManagerImpl.java:191)
at com.sun.enterprise.container.common.impl.ComponentEnvManagerImpl$EjbReferenceProxy.create(ComponentEnvManagerImpl.java:1109)
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:776)
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:744)
at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:169)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:498)
... 51 more
Caused by: javax.naming.NamingException: Lookup failed for 'com.youfood.dao.jpa.JpaUserDao#com.youfood.dao.jpa.JpaUserDao' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: com.youfood.dao.jpa.JpaUserDao#com.youfood.dao.jpa.JpaUserDao not found]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:518)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at com.sun.ejb.EjbNamingReferenceManagerImpl.resolveEjbReference(EjbNamingReferenceManagerImpl.java:186)
... 56 more
Caused by: javax.naming.NameNotFoundException: com.youfood.dao.jpa.JpaUserDao#com.youfood.dao.jpa.JpaUserDao not found
at com.sun.enterprise.naming.impl.TransientContext.doLookup(TransientContext.java:248)
at com.sun.enterprise.naming.impl.TransientContext.lookup(TransientContext.java:215)
at com.sun.enterprise.naming.impl.SerialContextProviderImpl.lookup(SerialContextProviderImpl.java:77)
at com.sun.enterprise.naming.impl.LocalSerialContextProviderImpl.lookup(LocalSerialContextProviderImpl.java:119)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:505)
... 60 more
My guess is that you specified names, mapped names and what have you. This is not needed.
Something like the following should work:
EJB:
#Stateless
public class MyBean {
// ...
}
Servlet:
#WebServlet(urlPatterns="/someurl")
public class MyServlet extends HttpServlet {
#EJB
private MyBean myBean;
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ...
}
}
UPDATE:
After seeing your code, the problem is not the injection of the EJB into the Servlet, but the injection of JpaUserDao in Authenticator.
You are injecting it by class, but this will not work since JpaUserDao implements a business interface: UserDao. Because it implements such an interface, there will be no local-view created. As a result, you have to inject using the interface:
#Stateless
public class Authenticator {
private String userFullName;
private Long userId;
#EJB
private UserDao userDao;
// ...
}
As an extra note, the concept of your Authenticator bean is not going to work. It's a stateless bean and its instance variables will have no meaning to the outside world. Thus, getUserFullName() is not guaranteed to return the result you think it will return. It may happen to work momentarily for you in a test when the container happens to select the same bean instance, but this will not work in general.
Even when you hold on to the reference of an Authenticator, it will still not work. The thing is you get a proxy, and the container will potentially direct every call to it to another instance. Think of it as a URL to servers in a web farm where a browser does a call to. You have no guarantee that two successive will go to the exact same physical server.
The authentication that you're trying to do there should be handled by a bean in the web layer and the authentication details put in the HTTP session (additionally, you should maybe use container authentication as well, but that's a whole other thing that's too off-topic here)
There are several ways for injecting a EJB. The most common and simplest solution would be via Dependency Injection as mentioned Arjan Tijms answer.
Another way would be to get a reference via InitialContext.lookup().
In this approach you can choose which lookup name you pass:
Use the class-name of the declaring Bean-Interface:
String jindiName = BeanInterface.class.getName();
InitialContext ctx = new InitialContext();
BeanInterface bi = ctx.lookup(jndiName);
This also works for a remote lookup from any stand-alone client because the interface is public.
Use the JINDI name of the component naming environment:
String jndiName = "java:comp/env/yourejb"
// same as shown above
This will only work inside the same container because the "outside world" do not have access to to the component naming environment.
For a better understanding of jndi names have a look at this.
I hope this helpes, have Fun!
How do I access a Remote EJB component from a stand-alone java client?
Step 1. Use the no-arg InitialContext() constructor in your code.
The most common problem developers run into is passing specific JNDI bootstrapping properties to InitialContext(args). Some other vendors require this step but GlassFish does not. Instead, use the no-arg InitialContext() constructor.
Step 2. Pass the global JNDI name of the Remote EJB to InitialContext.lookup()
Stand-alone java clients do not have access to a component naming environment (java:comp/env) or to the #EJB annotation, so they must explicitly use the global JNDI name to lookup the Remote EJB. (See here for more information on how global JNDI names are assigned to EJB components) Assuming the global JNDI name of the Remote EJB is "FooEJB" :
For Beans with a 3.x Remote Business interface :
Foo foo = (Foo) new InitialContext().lookup("FooEJB");
Note that in the EJB 3.x case the result of the lookup can be directly cast to the remote business interface type without using PortableRemoteObject.narrow().
For EJB 2.1 and earlier session/entity beans :
Object homeObj = new InitialContext().lookup("FooEJB");
FooHome fooHome = (FooHome)
PortableRemoteObject.narrow(homeObj,FooHome.class);
Foo foo = fooHome.create(...)
Step 3. Include the appropriate GlassFish .jars in the java client's classpath.
For GlassFish 3.
Include $GLASSFISH_HOME/glassfish/lib/gf-client.jar in the client's classpath.
E.g., assuming the application classes are in /home/user1/myclasses and the main client class is acme.MyClient :
java -classpath $GLASSFISH_HOME/glassfish/lib/gf-client.jar:/home/user1/myclasses acme.MyClient
Note that the Java EE 6 API classes are automatically included by gf-client.jar so there is no need to explicitly add javaee.jar to the classpath. gf-client.jar refers to many other .jars from the GlassFish installation directory so it is best to refer to it from within the installation directory itself rather than copying it(and all the other .jars) to another location.
Note: gf-client.jar is located in $GLASSFISH_HOME/modules/gf-client.jar in GlassFish v3.

Injecting jms resource in servlet & best practice for MDB

using ejb 3.1, servlet 3.0 (glassfish server v3)
Scenario:
I have MDB that listen to jms messages and give processing to some other session bean (Stateless).
Servelet injecting jms resource.
Question 1: Why servlet can`t inject jms resources when they use static declaration ?
#Resource(mappedName = "jms/Tarturus")
private static ConnectionFactory connectionFactory;
#Resource(mappedName = "jms/StyxMDB")
private static Queue queue;
private Connection connection;
and
#PostConstruct
public void postConstruct() {
try {
connection = connectionFactory.createConnection();
} catch (JMSException e) {
e.printStackTrace();
}
}
#PreDestroy
public void preDestroy() {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
The error that I get is :
[#|2010-05-03T15:18:17.118+0300|WARNING|glassfish3.0|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=35;_ThreadName=Thread-1;|StandardWrapperValve[WorkerServlet]:
PWC1382: Allocate exception for
servlet WorkerServlet
com.sun.enterprise.container.common.spi.util.InjectionException:
Error creating managed object for
class
ua.co.rufous.server.services.WorkerServiceImpl
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.createManagedObject(InjectionManagerImpl.java:312)
at
com.sun.enterprise.web.WebContainer.createServletInstance(WebContainer.java:709)
at
com.sun.enterprise.web.WebModule.createServletInstance(WebModule.java:1937)
at
org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1252)
Caused by:
com.sun.enterprise.container.common.spi.util.InjectionException:
Exception attempting to inject
Unresolved Message-Destination-Ref
ua.co.rufous.server.services.WorkerServiceImpl/queue#java.lang.String#null
into class
ua.co.rufous.server.services.WorkerServiceImpl
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:614) at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.inject(InjectionManagerImpl.java:384)
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:141)
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:127)
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.createManagedObject(InjectionManagerImpl.java:306)
... 27 more Caused by:
com.sun.enterprise.container.common.spi.util.InjectionException:
Illegal use of static field private
static javax.jms.Queue
ua.co.rufous.server.services.WorkerServiceImpl.queue
on class that only supports
instance-based injection at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:532) ... 31 more |#]
my MDB :
/**
* asadmin commands
* asadmin create-jms-resource --restype javax.jms.ConnectionFactory jms/Tarturus
* asadmin create-jms-resource --restype javax.jms.Queue jms/StyxMDB
* asadmin list-jms-resources
*/
#MessageDriven(mappedName = "jms/StyxMDB", activationConfig =
{
#ActivationConfigProperty(propertyName = "connectionFactoryJndiName", propertyValue = "jms/Tarturus"),
#ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class StyxMDB implements MessageListener {
#EJB
private ActivationProcessingLocal aProcessing;
public StyxMDB() {
}
public void onMessage(Message message) {
try {
TextMessage msg = (TextMessage) message;
String hash = msg.getText();
GluttonyLogger.getInstance().writeInfoLog("geted jms message hash = " + hash);
} catch (JMSException e) {
}
}
}
everything work good without static declaration:
#Resource(mappedName = "jms/Tarturus")
private ConnectionFactory connectionFactory;
#Resource(mappedName = "jms/StyxMDB")
private Queue queue;
private Connection connection;
Question 2:
what is the best practice for working with MDB : processing full request in onMessage() or calling another bean(Stateless bean in my case) in onMessage() method that would process it.
Processing including few calls to soap services, so the full processing time could be for a 3 seconds.
Thank you.
Answers:
1. You cannot inject a resource into a static field. Injection into member fields occurs during object construction, static fields are not part of the object (only part of the class). In addition EJBs and servlets are threaded objects so this could possibly be dangerous to do.
2. If splitting the processing up into multiple EJB(s) makes sense do it that way, otherwise processing in onMessage() is perfectly valid.
One additional suggestion that I can give, is that you should take a look at CDI which is a new addition to the EE 6 specification and provides rich dependency injection.
Are you using an MDB to perform asynchronous operations, Servlet 3.0 has some neat asynchronous capabilities. I suggest you watch the entire presentation if you are not familiar with Servlet 3.0.

Resources