JDO - datanucleus - HSQL error - jdo

For my current project I have to use HSQL-JDO. I am writting sample application to check how this work. If I am using HSQL with jdbc (without any orm) my code run fine. But with JDO I am getting "socket creation error"
[Server#187a84e4]: [Thread[main,5,main]]: checkRunning(false) entered
[Server#187a84e4]: [Thread[main,5,main]]: checkRunning(false) exited
[Server#187a84e4]: [Thread[main,5,main]]: checkRunning(false) entered
[Server#187a84e4]: [Thread[main,5,main]]: checkRunning(false) exited
[Server#187a84e4]: [Thread[main,5,main]]: checkRunning(false) entered
[Server#187a84e4]: [Thread[main,5,main]]: checkRunning(false) exited
[Server#187a84e4]: [Thread[main,5,main]]: checkRunning(false) entered
[Server#187a84e4]: [Thread[main,5,main]]: checkRunning(false) exited
JdbcOdbcDriver class loaded
registerDriver: driver[className=sun.jdbc.odbc.JdbcOdbcDriver,sun.jdbc.odbc.JdbcOdbcDriver#a13f991]
DriverManager.initialize: jdbc.drivers = null
JDBC DriverManager initialized
registerDriver: driver[className=org.hsqldb.jdbcDriver,org.hsqldb.jdbcDriver#44e06940]
DriverManager.getConnection("jdbc:hsqldb:hsql://localhost:8974/test_db")
trying driver[className=sun.jdbc.odbc.JdbcOdbcDriver,sun.jdbc.odbc.JdbcOdbcDriver#a13f991]
*Driver.connect (jdbc:hsqldb:hsql://localhost:8974/test_db)
trying driver[className=org.hsqldb.jdbcDriver,org.hsqldb.jdbcDriver#44e06940]
SQLState(08000) vendor code(-80)
java.sql.SQLException: socket creation error
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.jdbcConnection.(Unknown Source)
at org.hsqldb.jdbcDriver.getConnection(Unknown Source)
at org.hsqldb.jdbcDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.apache.commons.dbcp.DriverManagerConnectionFactory.createConnection(DriverManagerConnectionFactory.java:78)
at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582)
at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1158)
at org.apache.commons.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:106)
at org.datanucleus.store.rdbms.ConnectionFactoryImpl$ManagedConnectionImpl.getConnection(ConnectionFactoryImpl.java:444)
at org.datanucleus.store.rdbms.RDBMSStoreManager.(RDBMSStoreManager.java:264)
Here is the code in main
Server server = new Server();
server.setAddress("localhost");
server.setDatabaseName(0, "test_db");
server.setDatabasePath(0, "test_db");
server.setPort(8974);
server.setTrace(true);
Properties properties = new Properties();
properties.setProperty("javax.jdo.PersistenceManagerFactoryClass","org.datanucleus.api.jdo.JDOPersistenceManagerFactory");
properties.setProperty("javax.jdo.option.ConnectionDriverName","org.hsqldb.jdbcDriver");
properties.setProperty("javax.jdo.option.ConnectionURL","jdbc:hsqldb:hsql://localhost:8974/test_db");
properties.setProperty("javax.jdo.option.ConnectionUserName","SA");
properties.setProperty("javax.jdo.option.ConnectionPassword","");
properties.setProperty("javax.jdo.option.ConnectionPassword","");
properties.setProperty("datanucleus.autoCreateSchema","true");
properties.setProperty("datanucleus.validateTables","false");
properties.setProperty("datanucleus.validateConstraints","false");
PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory(properties);
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx=pm.currentTransaction();
tx.begin();
pm.makePersistent(new Session("aniruddha"));
tx.commit();
Query q = pm.newQuery("SELECT FROM "+Session.class.getName());
List<Session> sessions = (List<Session>)q.execute();
//Iterator<Session> iter = sessions.iterator();
for(Session s : sessions){
System.out.println(s.getSESSION_ID()+" : "+s.getSESSION_USERNAME());
}
Here is the bean that I want to persist
#PersistenceCapable
public class Session {
private Session(){
// Default constructor required by jdo
}
public Session(String session_username){
SESSION_USERNAME = session_username;
}
public long getSESSION_ID() {
return SESSION_ID;
}
public String getSESSION_USERNAME() {
return SESSION_USERNAME;
}
public void setSESSION_ID(long sESSION_ID) {
SESSION_ID = sESSION_ID;
}
public void setSESSION_USERNAME(String sESSION_USERNAME) {
SESSION_USERNAME = sESSION_USERNAME;
}
#PrimaryKey
#Persistent(valueStrategy=IdGeneratorStrategy.INCREMENT)
private long SESSION_ID;
private String SESSION_USERNAME;
}

If server mode doesn't work then you haven't started the HSQLDB server. Works for me with either form, either URL or file. I start a server from the command line exactly as per the HSQLDB docs.
With your API calls for Server, you seem to be missing calling "server.start()". Either way the problem is in HSQLDB server startup, not DataNucleus access.

Related

Unable to throw exception by KafkaTemplate when topic is not available/ kafka broker is down

I am sending message to Kafka by Kafka Template but I wanted to test exception, So I have provided wrong topic name but When I run the code, it says " Error while fetching metadata with correlation id 2 : {ocf-oots-gr-outbound_123=LEADER_NOT_AVAILABLE" not available but the topic itself is created in Kafka that I can also see through Kafka tool and when broker is stopped, it is also not throwing exception.
Code:
KafkaTemplate<String, Object> kafkaTemplate = (KafkaTemplate<String, Object>) CommonAppContextProvider.getApplicationContext().getBean("kafkaTemplate");
//kafkaTemplate.send(CommonAppContextProvider.getApplicationContext().getEnvironment().getProperty("kafka.transalators.outbound.topic"), kafkaMessageFormat);
ListenableFuture listenableFuture = kafkaTemplate.send(CommonAppContextProvider.getApplicationContext().
getEnvironment().getProperty("kafka.transalators.outbound.topic"), kafkaMessageFormat);
listenableFuture.addCallback(new ListenableFutureCallback<SendResult<?, ?>>() {
#Override
public void onSuccess(SendResult<?, ?> result) {
System.out.println("Sent");
}
#Override
public void onFailure(Throwable ex) {
throw new KafkaException();
}
});
}
It should throw exception may be KafkaException, TimeOutException, Interrupted exception etc.
You have to call get(time, timeUnit) on the future to get the result (success or otherwise).

Unable to download file from firebase through android studio

i just want to download an image from Firebase storage,but i am having these issues.My google play service is up to date.I have an image "dog.jpg" in bucket and no other file.
Firebase bucket
My mainActivity code
public class MainActivity extends AppCompatActivity {
private StorageReference pathRef = FirebaseStorage.getInstance().getReference().child("dog.jpg");
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView) this.findViewById(R.id.imageView);
}
public void getImage(View v){
File localFile;
try {
localFile = File.createTempFile("images","jpg");
pathRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
//Local temp file has been created
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//handle error
Toast.makeText(MainActivity.this, e.getMessage()+"\n"+e.getCause(), Toast.LENGTH_LONG).show();
}
});
}catch (IOException exception){
Toast.makeText(this, "IOEXCEPTION", Toast.LENGTH_SHORT).show();
}
}
}
Errors i am getting.
W/GooglePlayServicesUtil: Google Play services out of date. Requires 11020000 but found 9683470
W/DynamiteModule: Local module descriptor class for com.google.android.gms.firebasestorage not found.
I/DynamiteModule: Considering local module com.google.android.gms.firebasestorage:0 and remote module com.google.android.gms.firebasestorage:0
E/NetworkRqFactoryProxy: NetworkRequestFactoryProxy failed with a RemoteException:
com.google.android.gms.dynamite.DynamiteModule$zzc: No acceptable module found. Local version is 0 and remote version is 0.
at com.google.android.gms.dynamite.DynamiteModule.zza(Unknown Source)
at com.google.android.gms.internal.ace.<init>(Unknown Source)
at com.google.android.gms.internal.ace.zzg(Unknown Source)
at com.google.firebase.storage.FileDownloadTask.run(Unknown Source)
at com.google.firebase.storage.zzr.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
E/FileDownloadTask: Unable to create firebase storage network request.
android.os.RemoteException
at com.google.android.gms.internal.ace.<init>(Unknown Source)
at com.google.android.gms.internal.ace.zzg(Unknown Source)
at com.google.firebase.storage.FileDownloadTask.run(Unknown Source)
at com.google.firebase.storage.zzr.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
E/StorageException: StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
Code: -13000 HttpResult: 0
E/StorageException: null
android.os.RemoteException
at com.google.android.gms.internal.ace.<init>(Unknown Source)
at com.google.android.gms.internal.ace.zzg(Unknown Source)
at com.google.firebase.storage.FileDownloadTask.run(Unknown Source)
at com.google.firebase.storage.zzr.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
E/StorageException: StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
Code: -13000 HttpResult: 0
E/StorageException: null
android.os.RemoteException
at com.google.android.gms.internal.ace.<init>(Unknown Source)
at com.google.android.gms.internal.ace.zzg(Unknown Source)
at com.google.firebase.storage.FileDownloadTask.run(Unknown Source)
at com.google.firebase.storage.zzr.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
whats wrong with my code...i even tried it on real device but still unable to download this file my storage rules are:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write:if true
}
}
}
Your Play services is not up to date as you suggest. This error message tells you what's going on:
W/GooglePlayServicesUtil: Google Play services out of date. Requires 11020000 but found 9683470
The message suggests that you're using client library version 11.0.2, but Play services 9.6.83 is installed on the device. The version of Play has to be greater than or equal to the version of the client library in order for things to work.

SpringBoot Async requests throwing 503 Service Unavailable

I was experimenting with springboots async controllers when I came around with this issue.
I set the number of threads for the servlet container to 10 by setting the following
#Bean
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory(#Value("${server.port:8080}") final String port,
#Value("${jetty.threadPool.maxThreads:10}") final String maxThreads,
#Value("${jetty.threadPool.minThreads:8}") final String minThreads,
#Value("${jetty.threadPool.idleTimeout:60000}") final String idleTimeout) {
final JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory(Integer.valueOf(port));
factory.addServerCustomizers(new JettyServerCustomizer() {
#Override
public void customize(final Server server) {
final QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class);
threadPool.setMaxThreads(Integer.valueOf(maxThreads));
threadPool.setMinThreads(Integer.valueOf(minThreads));
threadPool.setIdleTimeout(Integer.valueOf(idleTimeout));
}
});
return factory;
}
I then configured the async thread pool to also start with 10 but set the max thread poolsize to 200.
#Bean
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(200);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("asyncthread-");
executor.initialize();
return executor;
}
When I submit 20 concurrent requests I get the below error consistently on the client code. The server side doesn't seem to show any issues.
08:06:12.550 [pool-1-thread-1] DEBUG
org.springframework.web.client.RestTemplate - GET request for
"http://localhost:8080/time/basicasync" resulted in 503 (Service
Unavailable); invoking error handler
java.util.concurrent.ExecutionException:
org.springframework.web.client.HttpServerErrorException: 503 Service
Unavailable at
java.util.concurrent.FutureTask.report(FutureTask.java:122) at
java.util.concurrent.FutureTask.get(FutureTask.java:192) at
Main.main(Main.java:64) Caused by:
org.springframework.web.client.HttpServerErrorException: 503 Service
Unavailable at
org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94)
at
org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641)
at
org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597)
at
org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
at
org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:289)
at Main.lambda$main$1(Main.java:32) at
java.util.concurrent.FutureTask.run(FutureTask.java:266) at
java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)
My Client code hangs because I use CompletionService to submit all tasks. If I increase the async threadpool on the server to 50 the issue doesn't seem to occur. Can someone throw some light on this behavior ?

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

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

EJB JNDI with Glassfish

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

Resources