0

Hi I have a database connection class. This class is part of a dynamic web project I am running the web project on tomcat server locally and I am also trying to connect to a derby server. I have imported all the external files for derby and tomcat, both servers are running. When I run my application at this line I keep failing

ds = (DataSource) ctx.lookup("java:/comp/env");

These are the packages I have imported

import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

This is a snippet from the code

public DatabaseConnection() throws ServiceLocatorException{
try{
            ctx = new InitialContext();
            System.out.println("We are trying to connect to the Derby server: ");
            ds = (DataSource) ctx.lookup("java:/comp/env");
            logger.info("Database found:"+ds.toString());
        }catch(NamingException e){
            logger.severe("Cannot find context, throwing exception"+e.getMessage());
            e.printStackTrace();
            throw new ServiceLocatorException();
        }
}

The exception I am getting is this

java.lang.ClassCastException: org.apache.naming.NamingContext cannot be cast to javax.sql.DataSource

I am not sure what to do.

user3305018
  • 57
  • 4
  • 12
  • 1
    refer http://stackoverflow.com/questions/11631839/what-is-javacomp-env – bNd Apr 14 '14 at 05:04
  • see http://stackoverflow.com/questions/3327420/jdbc-jndi-problem-with-tomcat-6-0-26 –  Apr 14 '14 at 05:05
  • The JNDI name of your `DataSource` isn't `java:comp/env`. It's impossible. Something is missing from the end. – user207421 Aug 13 '20 at 02:07

2 Answers2

-1

I hope you have added resource-ref entries in web.xml.

Also, in your web application, you do have included META-INF/context.xml file.

Mahesh
  • 407
  • 5
  • 4
-1

I came cross this issue and search all around search engines and found no answer.

The issue is that the return object of ctx.lookup would be a NamingContext instead of DataSource if there is an empty databasename/resoucename being input as its parameter.

You might use

javax.naming.NamingEnumeration dsList = envCtx.list(""java:/comp/env"); 

to see what has been returned for this query.

SHOULD BE CORRECT:

ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/myDb"); //- make sure myDb exists

There is a long blog on this issue at -R/z2SU , hope this should be resolved by Apache Tomcat Dev team in future.

Wade Lau
  • 1
  • 1
  • -R/z2SU is a short url for http://ufqi.com/blog/tomcat-jdbc-mysql-namingcontext . – Wade Lau Jan 03 '19 at 07:18
  • The 'long issue' lnk is completely irrelevant, and certainly not a Tomcat bug log, and there is no reason why Tiomcat or anything else should support an 'empty databasename/resoucename '. Nothing for the Tomcat developers to fix here. – user207421 Aug 13 '20 at 02:10