Exception creation stateless session bean - java

I'm trying to create an JaveEE project using EJB upon glassfish.
I have an Exception when trying to run it.
There is a entity bean:
User.java
#Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
EJB session:
package com.supinfo.courses.EJB;
import com.supinfo.courses.EJB.local.UserFacadeLocal;
import com.supinfo.courses.entities.User;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
#Stateless
public class UserFacade extends AbstractFacade<User> implements UserFacadeLocal {
#PersistenceContext(unitName = "4JVA-Courses-ejbPU")
private EntityManager em;
public UserFacade(EntityManager em, Class<User> entityClass) {
super(entityClass);
this.em = em;
}
#Override
protected EntityManager getEntityManager() {
return em;
}
public UserFacade() {
super(User.class);
}
#Override
public User findByCredentials(String email, String password) {
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery<User> cq = cb.createQuery(User.class);
Root<User> from = cq.from(User.class);
cq.where(cb.equal(from.get("email"), email));
cq.where(cb.equal(from.get("password"), hashPassword(password)));
TypedQuery<User> query = getEntityManager().createQuery(cq);
List<User> resultList = query.getResultList();
// return first user that match or null
return (resultList.isEmpty()) ? null : resultList.get(0);
}
#Override
public void create(User entity) {
// encrypt password (sha1)
entity.setPassword(hashPassword(entity.getPassword()));
super.create(entity);
}
public String hashPassword(String password) {
String sha1 = "";
try {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(password.getBytes("UTF-8"));
byte[] byteHash = crypt.digest();
try (Formatter formatter = new Formatter()) {
for (byte b : byteHash)
formatter.format("%02x", b);
sha1 = formatter.toString();
}
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
throw new Error("Unable to hash password");
}
return sha1;
}
}
And a service for using it:
#Stateless
public class UserService {
#EJB
public UserFacade userFacade;
public User registerUser(User user) {
userFacade.create(user);
return user;
}
public User loginUser(String email, String password) {
User foundUser = userFacade.findByCredentials(email, password);
return foundUser;
}
public boolean isValidEmailAddress(String email) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}
}
And finally the related servlet:
#WebServlet(name = "LoginServlet", urlPatterns = {"/login"})
public class LoginServlet extends AbstractServlet {
#EJB
UserService userService;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String error = null;
// Parse login informations
String email = request.getParameter("email");
String password = request.getParameter("password");
User user = null;
if (email == null || password == null) {
error = "Missing field";
} else if(!userService.isValidEmailAddress(email)) {
error = "Invalid email address";
} else if(password.length() < 7) {
error = "Password too short";
} else {
user = userService.loginUser(email, password);
if (user == null) {
error = "Bad Credentials";
}
}
if (error != null) {
//redirect with error data to jsp
request.setAttribute("error", error);
render("login", request, response);
} else {
request.getSession().setAttribute("user", user);
forward("/courses/list", request, response);
}
}
}
The stacktrace indicate:
Avertissement: Context path from ServletContext: /4JVA-Courses-war differs from path from bundle: 4JVA-Courses-war
Grave: EJB5070: Exception creating stateless session bean : [UserService]
Avertissement: EJB5184:A system exception occurred during an invocation on EJB UserService, method: public boolean com.supinfo.courses.services.UserService.isValidEmailAddress(java.lang.String)
Avertissement: javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:435)
at com.sun.ejb.containers.BaseContainer.getContext(BaseContainer.java:2516)
at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1906)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:210)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy447.isValidEmailAddress(Unknown Source)
at com.supinfo.courses.services.__EJB31_Generated__UserService__Intf____Bean__.isValidEmailAddress(Unknown Source)
at com.supinfo.courses.servlets.authentication.LoginServlet.doPost(LoginServlet.java:60)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
... 40 more
Caused by: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:700)
at com.sun.ejb.containers.util.pool.NonBlockingPool.getObject(NonBlockingPool.java:246)
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:430)
... 44 more
Caused by: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:514)
at com.sun.ejb.containers.StatelessSessionContainer.access$000(StatelessSessionContainer.java:97)
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:698)
... 46 more
Caused by: java.lang.IllegalStateException: Exception attempting to inject Remote ejb-ref name=com.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session into class com.supinfo.courses.services.UserService: Lookup failed for 'java:comp/env/com.supinfo.courses.services.UserService/userFacade' 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 org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:145)
at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:46)
at org.jboss.weld.injection.producer.DefaultInjector.inject(DefaultInjector.java:64)
at org.jboss.weld.injection.producer.BasicInjectionTarget.inject(BasicInjectionTarget.java:91)
at org.glassfish.weld.services.JCDIServiceImpl.injectEJBInstance(JCDIServiceImpl.java:257)
at com.sun.ejb.containers.BaseContainer.injectEjbInstance(BaseContainer.java:1683)
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:475)
... 48 more
Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting to inject Remote ejb-ref name=com.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session into class com.supinfo.courses.services.UserService: Lookup failed for 'java:comp/env/com.supinfo.courses.services.UserService/userFacade' 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:717)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.inject(InjectionManagerImpl.java:484)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:170)
at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:138)
... 54 more
Caused by: javax.naming.NamingException: Lookup failed for 'java:comp/env/com.supinfo.courses.services.UserService/userFacade' 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.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session' . Actual (possibly internal) Remote JNDI name used for lookup is 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' [Root exception is javax.naming.NamingException: Lookup failed for 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' 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.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found]]]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:491)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:613)
... 57 more
Caused by: javax.naming.NamingException: Exception resolving Ejb for 'Remote ejb-ref name=com.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session' . Actual (possibly internal) Remote JNDI name used for lookup is 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' [Root exception is javax.naming.NamingException: Lookup failed for 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' 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.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found]]
at com.sun.ejb.EjbNamingReferenceManagerImpl.resolveEjbReference(EjbNamingReferenceManagerImpl.java:188)
at com.sun.enterprise.container.common.impl.ComponentEnvManagerImpl$EjbReferenceProxy.create(ComponentEnvManagerImpl.java:1143)
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:745)
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:715)
at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:159)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:471)
... 61 more
Caused by: javax.naming.NamingException: Lookup failed for 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' 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.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:491)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at com.sun.ejb.EjbNamingReferenceManagerImpl.resolveEjbReference(EjbNamingReferenceManagerImpl.java:183)
... 66 more
Caused by: javax.naming.NameNotFoundException: com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found
at com.sun.enterprise.naming.impl.TransientContext.doLookup(TransientContext.java:237)
at com.sun.enterprise.naming.impl.TransientContext.lookup(TransientContext.java:204)
at com.sun.enterprise.naming.impl.SerialContextProviderImpl.lookup(SerialContextProviderImpl.java:66)
at com.sun.enterprise.naming.impl.LocalSerialContextProviderImpl.lookup(LocalSerialContextProviderImpl.java:114)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:478)
... 70 more
Avertissement: StandardWrapperValve[LoginServlet]: Servlet.service() for servlet LoginServlet threw exception
javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:435)
at com.sun.ejb.containers.BaseContainer.getContext(BaseContainer.java:2516)
at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1906)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:210)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy447.isValidEmailAddress(Unknown Source)
at com.supinfo.courses.services.__EJB31_Generated__UserService__Intf____Bean__.isValidEmailAddress(Unknown Source)
at com.supinfo.courses.servlets.authentication.LoginServlet.doPost(LoginServlet.java:60)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
... 42 more
Caused by: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:700)
at com.sun.ejb.containers.util.pool.NonBlockingPool.getObject(NonBlockingPool.java:246)
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:430)
... 44 more
Caused by: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:514)
at com.sun.ejb.containers.StatelessSessionContainer.access$000(StatelessSessionContainer.java:97)
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:698)
... 46 more
Caused by: java.lang.IllegalStateException: Exception attempting to inject Remote ejb-ref name=com.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session into class com.supinfo.courses.services.UserService: Lookup failed for 'java:comp/env/com.supinfo.courses.services.UserService/userFacade' 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 org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:145)
at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:46)
at org.jboss.weld.injection.producer.DefaultInjector.inject(DefaultInjector.java:64)
at org.jboss.weld.injection.producer.BasicInjectionTarget.inject(BasicInjectionTarget.java:91)
at org.glassfish.weld.services.JCDIServiceImpl.injectEJBInstance(JCDIServiceImpl.java:257)
at com.sun.ejb.containers.BaseContainer.injectEjbInstance(BaseContainer.java:1683)
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:475)
... 48 more
Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting to inject Remote ejb-ref name=com.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session into class com.supinfo.courses.services.UserService: Lookup failed for 'java:comp/env/com.supinfo.courses.services.UserService/userFacade' 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:717)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.inject(InjectionManagerImpl.java:484)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:170)
at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:138)
... 54 more
Caused by: javax.naming.NamingException: Lookup failed for 'java:comp/env/com.supinfo.courses.services.UserService/userFacade' 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.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session' . Actual (possibly internal) Remote JNDI name used for lookup is 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' [Root exception is javax.naming.NamingException: Lookup failed for 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' 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.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found]]]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:491)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:613)
... 57 more
Caused by: javax.naming.NamingException: Exception resolving Ejb for 'Remote ejb-ref name=com.supinfo.courses.services.UserService/userFacade,Remote 3.x interface =com.supinfo.courses.EJB.UserFacade,ejb-link=null,lookup=,mappedName=,jndi-name=com.supinfo.courses.EJB.UserFacade,refType=Session' . Actual (possibly internal) Remote JNDI name used for lookup is 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' [Root exception is javax.naming.NamingException: Lookup failed for 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' 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.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found]]
at com.sun.ejb.EjbNamingReferenceManagerImpl.resolveEjbReference(EjbNamingReferenceManagerImpl.java:188)
at com.sun.enterprise.container.common.impl.ComponentEnvManagerImpl$EjbReferenceProxy.create(ComponentEnvManagerImpl.java:1143)
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:745)
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:715)
at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:159)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:471)
... 61 more
Caused by: javax.naming.NamingException: Lookup failed for 'com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade' 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.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:491)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at com.sun.ejb.EjbNamingReferenceManagerImpl.resolveEjbReference(EjbNamingReferenceManagerImpl.java:183)
... 66 more
Caused by: javax.naming.NameNotFoundException: com.supinfo.courses.EJB.UserFacade#com.supinfo.courses.EJB.UserFacade not found
at com.sun.enterprise.naming.impl.TransientContext.doLookup(TransientContext.java:237)
at com.sun.enterprise.naming.impl.TransientContext.lookup(TransientContext.java:204)
at com.sun.enterprise.naming.impl.SerialContextProviderImpl.lookup(SerialContextProviderImpl.java:66)
at com.sun.enterprise.naming.impl.LocalSerialContextProviderImpl.lookup(LocalSerialContextProviderImpl.java:114)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:478)
... 70 more

Problem solved, also i didn't totally understood the logic.
From EJB Spec 3.1 - 4.9.2.1:
Session Bean Superclasses
A session bean class is permitted to have superclasses that are themselves session bean >classes. However, there are no special rules that apply to the processing of annotations or the deployment descriptor for this case. For the purposes of processing a particular session bean class, all superclass processing is identical regardless of whether the superclasses are themselves session bean classes. In this regard, the use of session bean classes as superclasses merely represents a convenient use of implementation inheritance, but does not have component inheritance semantics.
For example, the client views exposed by a particular session bean are not inherited by a subclass that also happens to define a session bean.
#Stateless
public class A implements Foo { ... }
#Stateless
public class B extends A implements Bar { ... }
Assuming Foo and Bar are local business interfaces and there is no associated deployment descriptor, session bean A exposes local business interface Foo and session bean B exposes local business interface Bar, but not Foo.
Session bean B would need to explicitly include Foo in its set of exposed views for that interface to apply. For example:
#Stateless
public class A implements Foo { ... }
#Stateless
public class B extends A implements Foo, Bar { ... }
I my case, refractoring project and removing Interfaces worked.

Related

How to check if a bean is injected or not in Spring

I'm injecting a bean as below which scope is Request.
#Autowired
private Optional<User> currentUser;
But when, bean is not injected for any reason, I'm trying to check currentUser.isPresent() and currentUser.isPresent(), Objects.nonNull( currentUser.get() ) both are giving true. But when try to access bean fields, it's giving Bean instantiation exception.
How can I check if the bean is successfully injected and available to use?
As asked by Thomas posting the stack trace.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.user' defined in class path resource [com/xxxx/spring/RequestScopeBeansConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.cl.xxxx.data.model.xxxxUser]: Factory method 'user' threw exception; nested exception is org.springframework.security.core.userdetails.UsernameNotFoundException: xxxxxxxxxxxxx
at deployment.xxxxx.war//org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
at deployment.xxxxx.war//org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:636)
at deployment.xxxxx.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
at deployment.xxxxx.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
at deployment.xxxxx.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at deployment.xxxxx.war//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at deployment.xxxxx.war//org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$1(AbstractBeanFactory.java:359)
at deployment.xxxxx.war//org.springframework.web.context.request.AbstractRequestAttributesScope.get(AbstractRequestAttributesScope.java:45)
at deployment.xxxxx.war//org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:356)
at deployment.xxxxx.war//org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at deployment.xxxxx.war//org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
at deployment.xxxxx.war//org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:675)
at deployment.xxxxx.war//com.cl.xxxx.data.model.xxxxUser$$EnhancerBySpringCGLIB$$48f26ffd.getId(<generated>)
at deployment.xxxxx.war//com.xxxx.spring.api.v1.service.UserService.createUser(UserService.java:355)
at deployment.xxxxx.war//com.xxxx.spring.api.v1.web.UserController.create(UserController.java:105)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at deployment.xxxxx.war//org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at deployment.xxxxx.war//org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at deployment.xxxxx.war//org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
at deployment.xxxxx.war//org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
at deployment.xxxxx.war//org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
at deployment.xxxxx.war//org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at deployment.xxxxx.war//org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at deployment.xxxxx.war//org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at deployment.xxxxx.war//org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at deployment.xxxxx.war//org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.api#2.0.0.Final//javax.servlet.http.HttpServlet.service(HttpServlet.java:523)
at deployment.xxxxx.war//org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.api#2.0.0.Final//javax.servlet.http.HttpServlet.service(HttpServlet.java:590)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at io.opentracing.contrib.opentracing-jaxrs2//io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter.doFilter(SpanFinishingFilter.java:52)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at deployment.xxxxx.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
at deployment.xxxxx.war//org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
at deployment.xxxxx.war//org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
at deployment.xxxxx.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at deployment.xxxxx.war//org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
at deployment.xxxxx.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at deployment.xxxxx.war//org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at deployment.xxxxx.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at deployment.xxxxx.war//org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at deployment.xxxxx.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at deployment.xxxxx.war//org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)
at deployment.xxxxx.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at deployment.xxxxx.war//org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at deployment.xxxxx.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at deployment.xxxxx.war//org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter.doFilterInternal(BearerTokenAuthenticationFilter.java:114)
at deployment.xxxxx.war//org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at deployment.xxxxx.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at deployment.xxxxx.war//org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter.doFilter(AbstractPreAuthenticatedProcessingFilter.java:124)
at deployment.xxxxx.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at deployment.xxxxx.war//org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at deployment.xxxxx.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at deployment.xxxxx.war//org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
at deployment.xxxxx.war//org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
at deployment.xxxxx.war//org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at deployment.xxxxx.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at deployment.xxxxx.war//org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at deployment.xxxxx.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at deployment.xxxxx.war//org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at deployment.xxxxx.war//org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at deployment.xxxxx.war//org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at deployment.xxxxx.war//org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at deployment.xxxxx.war//org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at deployment.xxxxx.war//org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
at deployment.xxxxx.war//org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow#20.0.1.Final//org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.core#2.1.3.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.core#2.1.3.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.core#2.1.3.Final//io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.core#2.1.3.Final//io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.core#2.1.3.Final//io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.core#2.1.3.Final//io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.core#2.1.3.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow#20.0.1.Final//org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.core#2.1.3.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow#20.0.1.Final//org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
at io.undertow.core#2.1.3.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:269)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:78)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:133)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:130)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at org.wildfly.extension.undertow#20.0.1.Final//org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
at org.wildfly.extension.undertow#20.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1530)
at org.wildfly.extension.undertow#20.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1530)
at org.wildfly.extension.undertow#20.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1530)
at org.wildfly.extension.undertow#20.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1530)
at org.wildfly.extension.undertow#20.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1530)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:249)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:78)
at io.undertow.servlet#2.1.3.Final//io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:99)
at io.undertow.core#2.1.3.Final//io.undertow.server.Connectors.executeRootHandler(Connectors.java:370)
at io.undertow.core#2.1.3.Final//io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
at org.jboss.threads#2.3.3.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads#2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
at org.jboss.threads#2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
at org.jboss.threads#2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1348)
at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.cl.xxxx.data.model.xxxxUser]: Factory method 'user' threw exception; nested exception is org.springframework.security.core.userdetails.UsernameNotFoundException: xxxxxxxxxxxxxxxxx
at deployment.xxxxx.war//org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at deployment.xxxxx.war//org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
... 115 more

Error creating bean with name 'redisKeyValueAdapter': Bean instantiation via constructor failed

We have used Redis Caching in a project.
And we have implemented Mockito and we are mocking the repository layer but redisTemplate is being used to get the data from the cache at the service layer and we are trying to mock RedisTemplate but unable to do so
#MockBean
private RedisTemplate<Object, Object> redisTemplate;
#Test
public void testGetProductHappyPath() {
log.info(ApplicationConstantsTest.METHOD_ENTER_LABEL);
when(redisTemplate.keys(ArgumentMatchers.any())).thenReturn(null);
final RequestBuilder requestBuilder = MockMvcRequestBuilders.get(ApplicationConstantsTest.PRODUCT_WALLET_OF_PRODUCT, Integer.MAX_VALUE)
.accept(MediaType.APPLICATION_JSON);
try {
mockMvc.perform(requestBuilder).andExpect(status().isOk());
log.info(ApplicationConstantsTest.METHOD_EXIT_LABEL);
} catch (final Exception e) {
log.error(ApplicationConstantsTest.METHOD_EXCEPTION_LABEL, e);
}
}
But we are getting this:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.core.RedisKeyValueAdapter]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: ConnectionFactory must not be null!
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:217)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:309)
... 65 common frames omitted
Caused by: java.lang.IllegalArgumentException: ConnectionFactory must not be null!
at org.springframework.util.Assert.notNull(Assert.java:201)
at org.springframework.data.redis.listener.RedisMessageListenerContainer.setConnectionFactory(RedisMessageListenerContainer.java:311)
at org.springframework.data.redis.core.RedisKeyValueAdapter.initMessageListenerContainer(RedisKeyValueAdapter.java:712)
at org.springframework.data.redis.core.RedisKeyValueAdapter.<init>(RedisKeyValueAdapter.java:196)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:204)

After new Controller created i'm getting "Injection of autowired dependencies failed" in Spring MVC , Hibernate

I have added a new controller in my spring mvc project and added all annotations as below ...but here while running the project i'm getting 404 exception and in the console i'm getting exception as below ...I'm confused to figure out the issue...
here is my controller:
#Controller
#RequestMapping("/escProjectProgStatusController")
public class ESCProjectProgStatusController {
#Autowired
ESCProjectProgStatusService escProjectProgStatusService;
#RequestMapping(value = "/fetchUnitNameDropDown")
public #ResponseBody String fetchUnitNameDropDown(HttpServletRequest request){
String strUnitNames = "";
String strProjectId = request.getParameter("projectId")==null?"":request.getParameter("projectId");
try {
strUnitNames = escProjectProgStatusService.fetchUnitNameFromProjectId(strProjectId);
} catch (Exception e) {
//logger.error(e);
throw e;
}
return strUnitNames.toString();
}
}
service Impl:
#Service("escProjectProgStatusServices")
#Transactional
public class ESCProjectProgStatusServiceImpl implements ESCProjectProgStatusService {
#Autowired
ESCProjectProgStatusDao escProjectProgStatusDao;
#Override
public String fetchUnitNameFromProjectId(String strProjectId){
JSONArray jsonArr = new JSONArray();
JSONObject jsonObj = null;
List<ProjectUnit> listProjectUnit = null;
try{
listProjectUnit = (List<ProjectUnit>)escProjectProgStatusDao.fetchUnitNameFromProjectId(strProjectId);
if(listProjectUnit!=null){
for(ProjectUnit projectUnit :listProjectUnit){
jsonObj = new JSONObject();
jsonObj.put("unitType", projectUnit.getUnitType());
jsonObj.put("unitName", projectUnit.getUnitName());
jsonArr.add(jsonObj);
}
}
}catch(Exception e){
//logger.error(e);
}
return jsonArr.toString();
}
}
Dao Impl:
#Repository("escProjectProgStatusDao")
public class ESCProjectProgStatusDaoImpl implements ESCProjectProgStatusDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public List<ProjectUnit> fetchUnitNameFromProjectId(String strProjectId){
List<ProjectUnit> listProjectUnit = null;
try {
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(ProjectUnit.class);
criteria.add(Restrictions.eq("merchantProductID", strProjectId));
listProjectUnit=criteria.list();
}catch(Exception e){
//logger.error(e);
}
return listProjectUnit;
}
}
Exception and Stack Trace:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ESCProjectProgStatusController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.interland.b2b.service.ESCProjectProgStatusService com.interland.b2b.controller.ESCProjectProgStatusController.escProjectProgStatusService; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'com.interland.b2b.service.ESCProjectProgStatusService'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.interland.b2b.service.ESCProjectProgStatusService]: no matching editors or conversion strategy found
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1208)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:759)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:434)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4973)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5467)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.interland.b2b.service.ESCProjectProgStatusService com.interland.b2b.controller.ESCProjectProgStatusController.escProjectProgStatusService; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'com.interland.b2b.service.ESCProjectProgStatusService'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.interland.b2b.service.ESCProjectProgStatusService]: no matching editors or conversion strategy found
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 22 more
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'com.interland.b2b.service.ESCProjectProgStatusService'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.interland.b2b.service.ESCProjectProgStatusService]: no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:74)
at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:54)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:961)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 24 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.interland.b2b.service.ESCProjectProgStatusService]: no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:287)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:124)
at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:61)
... 28 more
Can anyone please help me to get rid of this problem..Many thanks in advance....
In ESCProjectProgStatusServiceImpl class remove the String parameter of #Service annotation:
before:
#Service("escProjectProgStatusServices")
after:
#Service

selected bean is not in the same module or enterprise application

Just a shot in the dark, but do I need a local interface to call a remote stateless EJB?
when I try call the bean remotely through Netbeans:
Netbeans doesn't allow a remote call, or any call, on this bean. Why not?
Trying to do it manually, as below:
What is the jndi global remote name for the Remote EJB which is deployed on glassfish?
INFO: visiting unvisited references
INFO: visiting unvisited references
INFO: EJB5181:Portable JNDI names for EJB MyRemoteSessionClass: [java:global/RemoteSalutation-ejb/MyRemoteSessionClass!net.bounceme.dur.glassfish.MyRemoteSession, java:global/RemoteSalutation-ejb/MyRemoteSessionClass]
INFO: RemoteSalutation-ejb was successfully deployed in 941 milliseconds.
If possible, I would rather specify the class in the properties file rather than hard-coded. In any event, different variations result in a lookup failure. Here's the stack-trace:
run-deploy:
Copying 1 file to /home/thufir/NetBeansProjects/RemoteLookup/dist
Copying 2 files to /home/thufir/NetBeansProjects/RemoteLookup/dist/RemoteLookupClient
Warning: /home/thufir/NetBeansProjects/RemoteLookup/dist/gfdeploy/RemoteLookup does not exist.
Sep 13, 2014 1:35:41 AM net.bounceme.dur.remote.RemoteLookup run
INFO: java.naming.factory.initial com.sun.enterprise.naming.impl.SerialInitContextFactory
Sep 13, 2014 1:35:41 AM net.bounceme.dur.remote.RemoteLookup run
INFO: java.naming.factory.url.pkgs com.sun.enterprise.naming
Sep 13, 2014 1:35:41 AM net.bounceme.dur.remote.RemoteLookup run
INFO: java.naming.factory.state com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl
Sep 13, 2014 1:35:46 AM net.bounceme.dur.remote.RemoteLookup main
SEVERE: Lookup failed for ' java:comp/env//RemoteSalutation-ejb/MyRemoteSessionClass!net/bounceme/dur/glassfish/MyRemoteSession' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, remote=net.bounceme.ix.Foo, org.omg.CORBA.ORBInitialHost=localhost, java.naming.security.principal=user, org.omg.CORBA.ORBInitialPort=3700, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.provider.url=server.local:1199, java.naming.factory.url.pkgs=com.sun.enterprise.naming, java.naming.security.credentials=password}
javax.naming.NamingException: Lookup failed for ' java:comp/env//RemoteSalutation-ejb/MyRemoteSessionClass!net/bounceme/dur/glassfish/MyRemoteSession' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, remote=net.bounceme.ix.Foo, org.omg.CORBA.ORBInitialHost=localhost, java.naming.security.principal=user, org.omg.CORBA.ORBInitialPort=3700, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.provider.url=server.local:1199, java.naming.factory.url.pkgs=com.sun.enterprise.naming, java.naming.security.credentials=password} [Root exception is javax.naming.NameNotFoundException: java:comp]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:491)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:438)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at net.bounceme.dur.remote.RemoteLookup.run(RemoteLookup.java:34)
at net.bounceme.dur.remote.RemoteLookup.main(RemoteLookup.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.appclient.client.acc.AppClientContainer.launch(AppClientContainer.java:446)
at org.glassfish.appclient.client.AppClientFacade.main(AppClientFacade.java:166)
Caused by: javax.naming.NameNotFoundException: java:comp
at com.sun.enterprise.naming.impl.TransientContext.resolveContext(TransientContext.java:299)
at com.sun.enterprise.naming.impl.TransientContext.lookup(TransientContext.java:207)
at com.sun.enterprise.naming.impl.SerialContextProviderImpl.lookup(SerialContextProviderImpl.java:66)
at com.sun.enterprise.naming.impl.RemoteSerialContextProviderImpl.lookup(RemoteSerialContextProviderImpl.java:109)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie.dispatchToMethod(ReflectiveTie.java:143)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:173)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
run:
BUILD SUCCESSFUL (total time: 17 seconds)
client code:
package net.bounceme.dur.remote;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class RemoteLookup {
private static final Logger log = Logger.getLogger(RemoteLookup.class.getName());
private final MyProps p = new MyProps();
public static void main(String... args) {
try {
new RemoteLookup().run();
} catch (NamingException ex) {
Logger.getLogger(RemoteLookup.class.getName()).log(Level.SEVERE, ex.getExplanation(), ex);
}
}
private void run() throws NamingException {
Properties jndi = p.getJNDI();
Enumeration e = jndi.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String val = jndi.getProperty(key);
log.info(key + "\t" + val);
}
Context ic = new InitialContext();
// Object o = ic.lookup(" java:comp/env/RemoteSalutation-ejb/MyRemoteSessionClass");
Object o = ic.lookup(" java:comp/env//RemoteSalutation-ejb/MyRemoteSessionClass!net/bounceme/dur/glassfish/MyRemoteSession");
}
}
the remote EJB:
package net.bounceme.dur.glassfish;
import javax.ejb.Stateless;
//#LocalBean
#Stateless(mappedName = "salutationBean")
public class MyRemoteSessionClass implements MyRemoteSession {
#Override
public String SayHello() {
return "hello from glassfish..";
}
#Override
public String SayBye() {
return "goodbye..";
}
}
note that the interface is remote, ie: it's literally a Java class library. Correct? This makes the EJB remote.
referencing:
https://netbeans.org/kb/docs/javaee/entappclient.html
although I changed the names a bit..otherwise should be exactly as the tutorial.
Try Object o = ic.lookup("salutationBean");
Note that mappedName specifies the name to use in JNDI for a remote access.

Why this Spring application with java-based configuration don't work properly

I started recently a project with the Spring framework with the ojective to develop it without none XML config file, only Java code.
In this current moment, I add the follow files to my project:
WebAppConfig.java
#EnableWebMvc
#ComponentScan(value="org.webapp")
#Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(31556926);
registry.addResourceHandler("/css/**").addResourceLocations("/fonts/").setCachePeriod(31556926);
registry.addResourceHandler("/img/**").addResourceLocations("/image/").setCachePeriod(31556926);
registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
}
SecurityConfig.java
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("kleber").password("123").roles("USER");
}
}
SecurityWebApplicationInitializer.java
#Order(value=2)
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super(SecurityConfig.class);
}
}
In this state, when I run the application (in Eclipse) the browser shows the default login form from Spring Security, and an error 404 after I submit this form. If I try enter directly the url localhost:8080/spring/index, I can access the page which should appears afeter the login form.
If I add this class:
WebAppInitializer.java
#Order(value=1)
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(WebAppConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(DispatcherConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
In replacement to web.xml, following the instructions from official documentation, in this link:
http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/web/WebApplicationInitializer.html
I can't even access the login page. Same thing happens if I add to the class SecurityConfig the method:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**", "/fonts/**", "/image/**", "/js/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("spring/index").permitAll()
.failureUrl("spring/erro_login").permitAll()
.defaultSuccessUrl("spring/home")
.and()
.logout()
.logoutSuccessUrl("spring/logout")
.permitAll();
}
Someone can see what am I missing?
ps.:
My controler is this:
#Controller
#RequestMapping(value="spring")
public class SpringController {
#RequestMapping(value="index")
public ModelAndView index() {
ModelAndView mav = new ModelAndView();
mav.setViewName("index");
return mav;
}
#RequestMapping(value="home")
public ModelAndView home() {
ModelAndView mav = new ModelAndView();
mav.setViewName("home");
return mav;
}
#RequestMapping(value="erro_login")
public ModelAndView erro_login() {
ModelAndView mav = new ModelAndView();
mav.setViewName("erro_login");
return mav;
}
#RequestMapping(value="erro_nao_autorizado")
public ModelAndView erro_nao_autorizado() {
ModelAndView mav = new ModelAndView();
mav.setViewName("erro_nao_autorizado");
return mav;
}
#RequestMapping(value="logout")
public ModelAndView logout() {
ModelAndView mav = new ModelAndView();
mav.setViewName("index");
return mav;
}
}
UPDATE
This error is displayed in the console of Eclipse
Mar 29, 2014 1:28:02 PM org.apache.catalina.core.StandardContext listenerStart
Grave: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:265)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4937)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
After the answer given to this topic, I try remove one of two conflicting registration of ContextListeners, from SecurityWebApplicationInitializer or WebAppInitializer. In both cases, I get this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.servlet.Filter org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain() throws java.lang.Exception] threw exception; nested exception is java.lang.IllegalArgumentException: 'spring/index?error' is not a valid redirect URL
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:581)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1025)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:921)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4937)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.servlet.Filter org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain() throws java.lang.Exception] threw exception; nested exception is java.lang.IllegalArgumentException: 'spring/index?error' is not a valid redirect URL
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:181)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:570)
... 23 more
Caused by: java.lang.IllegalArgumentException: 'spring/index?error' is not a valid redirect URL
at org.springframework.util.Assert.isTrue(Assert.java:65)
at org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler.setDefaultFailureUrl(SimpleUrlAuthenticationFailureHandler.java:98)
at org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler.<init>(SimpleUrlAuthenticationFailureHandler.java:43)
at org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer.failureUrl(AbstractAuthenticationFilterConfigurer.java:199)
at org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer.updateAuthenticationDefaults(AbstractAuthenticationFilterConfigurer.java:345)
at org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer.loginPage(AbstractAuthenticationFilterConfigurer.java:285)
at org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer.loginPage(FormLoginConfigurer.java:181)
at org.webapp.security.SecurityConfig.configure(SecurityConfig.java:27)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:192)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:276)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:61)
at org.webapp.security.SecurityConfig$$EnhancerByCGLIB$$f93abbff.init(<generated>)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:369)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:322)
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:39)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:92)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerByCGLIB$$93d7a5f4.CGLIB$springSecurityFilterChain$0(<generated>)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerByCGLIB$$93d7a5f4$$FastClassByCGLIB$$eb934d27.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:286)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerByCGLIB$$93d7a5f4.springSecurityFilterChain(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:160)
... 24 more
Mar 29, 2014 4:18:30 PM org.apache.catalina.core.StandardContext listenerStart
Grave: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.servlet.Filter org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain() throws java.lang.Exception] threw exception; nested exception is java.lang.IllegalArgumentException: 'spring/index?error' is not a valid redirect URL
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:581)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1025)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:921)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4937)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.servlet.Filter org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain() throws java.lang.Exception] threw exception; nested exception is java.lang.IllegalArgumentException: 'spring/index?error' is not a valid redirect URL
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:181)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:570)
... 23 more
Caused by: java.lang.IllegalArgumentException: 'spring/index?error' is not a valid redirect URL
at org.springframework.util.Assert.isTrue(Assert.java:65)
at org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler.setDefaultFailureUrl(SimpleUrlAuthenticationFailureHandler.java:98)
at org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler.<init>(SimpleUrlAuthenticationFailureHandler.java:43)
at org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer.failureUrl(AbstractAuthenticationFilterConfigurer.java:199)
at org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer.updateAuthenticationDefaults(AbstractAuthenticationFilterConfigurer.java:345)
at org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer.loginPage(AbstractAuthenticationFilterConfigurer.java:285)
at org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer.loginPage(FormLoginConfigurer.java:181)
at org.webapp.security.SecurityConfig.configure(SecurityConfig.java:27)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:192)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:276)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:61)
at org.webapp.security.SecurityConfig$$EnhancerByCGLIB$$f93abbff.init(<generated>)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:369)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:322)
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:39)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:92)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerByCGLIB$$93d7a5f4.CGLIB$springSecurityFilterChain$0(<generated>)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerByCGLIB$$93d7a5f4$$FastClassByCGLIB$$eb934d27.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:286)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerByCGLIB$$93d7a5f4.springSecurityFilterChain(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:160)
... 24 more
java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!
In your WebAppInitializer, you are registering a ContextLoaderListener.
Because you are using AbstractSecurityWebApplicationInitializer with the super constructor that accepts a Class[]
Creates a new instance that will instantiate the ContextLoaderListener with the specified classes.
that also registers a ContextLoaderListener. Note the class javadoc
When used with AbstractSecurityWebApplicationInitializer(Class...), it
will also register a ContextLoaderListener. When used with
AbstractSecurityWebApplicationInitializer(), this class is typically
used in addition to a subclass of AbstractContextLoaderInitializer.
As the error states, you cannot have two ContextLoaderListener instances because they will both try to create and add a ApplicationContext to the ServletContext.
I think the problem is that this:
.loginPage("spring/index").permitAll()
should be this:
.loginPage("/spring/index").permitAll() //note the '/' at the beginning of the uri
Maybe there're some conflicting overlapping between your web.xml and java-based configuration class. That's the root cause when I met the same error as you. And my solution is to comment out the duplicated configuration in web.xml.
I had a class
MyContextLoaderListener extends ContextLoaderListener
somewhere in my code. It was unused. Spring boot apparently used reflection to find it. I deleted the file and the problem was gone

Categories