My web app constructed with SpringBoot 2.0.0.M3 and java8, deploy on outer tomcat/8.0.24 war.
My Exception handler:
#ControllerAdvice(annotations = RestController.class)
public class GlobalExceptionHandler extends
ResponseEntityExceptionHandler {
#ExceptionHandler(MyCustomException.class)
public ResponseEntity<String> handlerMyException(
MyCustomException rae) {
String msg = "MyCustomException";
return new ResponseEntity<>(msg ,
HttpStatus.OK);
}
}
I trow a MyCustomException in my Controller but it wasn't handled by handlerMyException() method:
ERROR 1 --- [ajp-nio-8009-exec-372] o.s.b.w.servlet.support.ErrorPageFilter : Forwarding to error page from request [/api/test] due to exception
Then I disable the ErrorPageFilter by:
setRegisterErrorPageFilter(false);
this time no error log occurred, but handlerMyException() still not triggered. Is anyone know this? TIA!
I'm needing to #Autowire a Spring Data Neo4J repository into a Spring MVC converter (in Spring Boot), but the MVC configuration gets started before the Data services get started. This results in an #Autowired not found problem. How do I get the Data Services to get started before the MVC so it finds an eligible bean?
I have a project I'm converting from XML Spring config to Spring Boot. Everything is working fine except for the MVC Converters. They are not able to #Autowire Neo4J Repository classes.
If remove the #Autowire of the Repository and hard code in a value, things work as expected with the hack. Other operations in services are using the Repositories just fine. It seems the MVC config is getting started before the Neo4J plumbing can get started and then can't find the right components to tie into. I've looked, but I can't figure out how to get the data config to start before the MVC config.
Here's my base config:
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Toyfiles {
public static void main(String[] args) throws Exception {
SpringApplication.run(Toyfiles.class, args);
}
}
My MVC Config:
#Configuration
public class MVCBeans extends WebMvcConfigurerAdapter {
#Autowired
private StringToBrand stringToBrand;
#Autowired
private BrandToString brandToString;
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(stringToBrand);
registry.addConverter(brandToString);
super.addFormatters(registry);
}
}
The offending Converter:
#Component
public class StringToBrand implements Converter<String, Brand> {
#Autowired
BrandRepository brandRepository;
#Override
public Brand convert(String s) {
return brandRepository.findBrandByName(s);
}
}
The Data config:
#Configuration
#Profile("localEmbeddedDBServer")
#EnableTransactionManagement
#EnableNeo4jRepositories(basePackages = "com.toyfiles.dataservices.")
public class LocalDBConfig extends Neo4jConfiguration {
public LocalDBConfig() {
setBasePackage("com.toyfiles");
}
#Bean
public GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory().newEmbeddedDatabase("target/graph.db");
}
}
And the Repository:
public interface BrandRepository extends GraphRepository<Brand> {
#Query(value = "MATCH (brand:Brand {name:{0}})-[:PART_OF]->line RETURN line")
public List<Line> getLinesForBrand(String name);
#Query(value = "MATCH (brand:Brand {name:{0}}) DELETE brand")
public void deleteBrandByName(String name);
public Brand findBrandByName(String name);
}
The "interesting" part of the Exception:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'brandRepository': Cannot resolve reference to bean 'neo4jTemplate' while setting bean property 'neo4jTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jTemplate' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.Neo4jTemplate org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jMappingContext' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4d49af10: startup date [Mon Sep 29 09:48:25 PDT 2014]; root of context hierarchy
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:336)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1457)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1198)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1021)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:964)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:862)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:481)
... 116 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jTemplate' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.Neo4jTemplate org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jMappingContext' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4d49af10: startup date [Mon Sep 29 09:48:25 PDT 2014]; root of context hierarchy
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:990)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
... 129 more
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.data.neo4j.support.Neo4jTemplate org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate() throws java.lang.Exception] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jMappingContext' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4d49af10: startup date [Mon Sep 29 09:48:25 PDT 2014]; root of context hierarchy
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
... 138 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'neo4jMappingContext' defined in class path resource [com/toyfiles/configuration/LocalDBConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4d49af10: startup date [Mon Sep 29 09:48:25 PDT 2014]; root of context hierarchy
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1554)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:288)
at com.toyfiles.configuration.LocalDBConfig$$EnhancerBySpringCGLIB$$321222c6.mappingInfrastructure(<generated>)
at org.springframework.data.neo4j.config.Neo4jConfiguration.neo4jTemplate(Neo4jConfiguration.java:135)
at com.toyfiles.configuration.LocalDBConfig$$EnhancerBySpringCGLIB$$321222c6.CGLIB$neo4jTemplate$23(<generated>)
at com.toyfiles.configuration.LocalDBConfig$$EnhancerBySpringCGLIB$$321222c6$$FastClassBySpringCGLIB$$12e74a61.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at com.toyfiles.configuration.LocalDBConfig$$EnhancerBySpringCGLIB$$321222c6.neo4jTemplate(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
... 139 more
Caused by: java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4d49af10: startup date [Mon Sep 29 09:48:25 PDT 2014]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:346)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:333)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:307)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:69)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:49)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:181)
at org.springframework.data.neo4j.mapping.RelationshipInfo.<init>(RelationshipInfo.java:65)
at org.springframework.data.neo4j.mapping.RelationshipInfo.fromField(RelationshipInfo.java:79)
at org.springframework.data.neo4j.support.mapping.Neo4jPersistentPropertyImpl.extractRelationshipInfo(Neo4JPersistentPropertyImpl.java:128)
at org.springframework.data.neo4j.support.mapping.Neo4jPersistentPropertyImpl.<init>(Neo4JPersistentPropertyImpl.java:80)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentProperty(Neo4jMappingContext.java:161)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentProperty(Neo4jMappingContext.java:49)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:449)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:427)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:606)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:295)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:69)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:49)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:181)
at org.springframework.data.neo4j.mapping.RelationshipInfo.<init>(RelationshipInfo.java:65)
at org.springframework.data.neo4j.mapping.RelationshipInfo.fromField(RelationshipInfo.java:79)
at org.springframework.data.neo4j.support.mapping.Neo4jPersistentPropertyImpl.extractRelationshipInfo(Neo4JPersistentPropertyImpl.java:128)
at org.springframework.data.neo4j.support.mapping.Neo4jPersistentPropertyImpl.<init>(Neo4JPersistentPropertyImpl.java:80)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentProperty(Neo4jMappingContext.java:161)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentProperty(Neo4jMappingContext.java:49)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:449)
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:427)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:606)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:295)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:69)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:49)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:257)
at org.springframework.data.mapping.context.AbstractMappingContext.initialize(AbstractMappingContext.java:373)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.initialize(Neo4jMappingContext.java:111)
at org.springframework.data.mapping.context.AbstractMappingContext.afterPropertiesSet(AbstractMappingContext.java:363)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1613)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1550)
... 160 more
I used an #Lazy annotation for the repository to delay the reference to the repository since the repository was getting started correctly later in the startup. This allowed the repository reference to be delayed until it was needed and available.
#Autowired
#Lazy
BrandRepository brandRepository;
I have few custom annotations defined on fields of an object like:
public class Person{
#Accountname
String email;
}
Implementation class of #Accountname:
#Autowired ValidationService service;
#Autowired ClientSession clientSession;
#Override
public boolean isValid(final String email, final ConstraintValidatorContext ctx) {
if(!service.isAccountValid(email, clientSession)){
return false;
}
}
I am trying to write junits for these annotations.
#Test
public void validEmailTest()
{
person.setEmail("abc#xyz.com");
Set<ConstraintViolation<Person>> violations = validatorInstance.getValidator().validateProperty(person, "email");
Assert.assertEquals(1, violations.size());
}
But its throwing this error when I execute the test:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.clientSession': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:343)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:34)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.getTarget(CglibAopProxy.java:663)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:614)
at org.hibernate.validator.internal.engine.ConstraintTree.validateSingleConstraint(ConstraintTree.java:308)
... 45 more
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
at org.springframework.web.context.request.SessionScope.get(SessionScope.java:90)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:329)
... 54 more
Any idea on how to write junits if a validator class has a dependency on services like session etc.?
This should be tested separately (units).
The real logic that validates is in your ValidationService, so test it there, in AccountnameValidator test only the logic that is in there, injecting your dependencies:
#Mock ValidationService service;
#Mock ClientSession clientSession;
#InjectMocks AccountnameValidator av = new AccountnameValidator()
//initialize mocks
//example test
when(service.isAccountValid(email, clientSession)).thenReturn(true);
boolean result = av.isValid(email, ctx);
assertTrue(result);
And finally if you want you can validate presence of the annotation in Person class on email field using reflection.
So I already learnt that integration of spring and jax-ws is not an easy thing.
I want to inject a spring bean into jax-ws service, but for some reason I get an exception during the deployment:
Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: java.lang.IllegalArgumentException: javax.servlet.ServletException: com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class org.springframework.web.context.ContextLoaderListener|#]
this is my jax-ws configuration:
<wss:binding url="/ws/users">
<wss:service>
<ws:service bean="#usersWs"/>
</wss:service>
</wss:binding>
<bean id="usersWs" class="love.service.endpoint.implementations.UserServiceImpl" />
And this is my service:
#WebService
public class UserServiceImpl implements UserService{
#EJB
private DBManager dbmanager;
#Override
#WebMethod
public boolean addUser(String name, String password, String email) {
return false;
}
#Override
#WebMethod
public boolean isUsernameAvailable(String username) {
return dbmanager.isLoginAvailable(username);
}
#Override
#WebMethod
public boolean isEmailAvailable(String email) {
return dbmanager.isEmailAvailable(email);
}
}
and finally my bean configuration:
<bean id="dbmanager" class="love.commons.database.DBManager" scope="request">
<aop:scoped-proxy/>
</bean>
I also tried injecting the bean into some controllers and then it works perfectly well.
If I replace #EJB with #Autowired, the application starts, but the service still doesn't work. When I tried sending a message to it, my only response was the following:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope">
<faultcode>S:Server</faultcode>
<faultstring>Error creating bean with name 'scopedTarget.dbmanager': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.</faultstring>
</S:Fault>
</S:Body>
</S:Envelope>
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.