Cannot connect to Oracle DB through Java Context method. \Error: Name [comp/env] is not bound in this Context. Unable to find [comp] - oracle

I am learning Apache 9.0 web server and Oracle 11g DB within Eclipse EE environment.
When I simply connect using
conn = DriverManager.getConnection(url, "name", "pw");
I can connect to Oracle DB and send SQL and receive result. (everything works.)
But when I try to connect with this method below, I get error.
public class JdbcUtil {
public static Connection getConnection() {
Connection con = null;
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/OracleDB");
System.out.println("ds = " + ds);
con = ds.getConnection();
System.out.println("con = " + con);
con.setAutoCommit(false);
System.out.println("DB connect success! Util");
} catch (Exception e) {
System.out.println("DB connect failure! Util");
e.printStackTrace();
}
return con;
}
Error message is
javax.naming.NameNotFoundException: Name [comp/env] is not bound in this Context. Unable to find [comp].
at org.apache.naming.NamingContext.lookup(NamingContext.java:833)
at org.apache.naming.NamingContext.lookup(NamingContext.java:174)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:163)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at db.JdbcUtil.getConnection(JdbcUtil.java:14)
at service.mListService.memberList(mListService.java:15)
at controller.mListController.doProcess(mListController.java:45)
So the error is at Context envCtx = (Context) initCtx.lookup("java:comp/env");
But sometimes error is at DataSource ds = (DataSource) envCtx.lookup("jdbc/OracleDB");
This is my context.xml in META-INF (of my current project)
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource
name = "jdbc/OracleDB"
auth = "Container"
type = "javax.sql.DataSource"
username = "NAME"
password = "PW"
driverClassName = "oracle.jdbc.driver.OracleDriver"
factory = "org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
url = "jdbc:oracle:thin:#127.0.0.1:1521:xe"
maxActive ="500"
maxIdle = "100"
/>
</Context>
This is my web.xml in WEB-INF/lib (of my current project)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
<display-name>MemberBoard</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<resource-ref>
<description>Connection</description>
<res-ref-name>jdbc/OracleDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
I didn't touch xml files in my tomcat 9.0 server.

Related

Tomcat servlet configure JNDI

Good day, respective all!
My environment:
Tomcat 8.5 under windows 64-bit
All needed jars are placed into $CATALINA_HOME/lib
It is my first attempt to write servlet using ConnectionPool.
After "googling"I made an entry inside $CATALINA_HOME/conf/server.xml:
<context docbase="msgsend" path="/msgsend" reloadable="true">
<context docbase="ssr" path="/ssr" reloadable="true">
<Resource
name="jdbc/OrServlet"
auth="Container"
type="javax.sql.DataSource"
user="STERN"
username="STERN"
password="pwdxxx"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:STERN/pwdxxx#XEPDB1"
/>
</context>
I included following into WEb-INF/web.xml:
<resource-ref>
<description>just a test</description>
<res-ref-name>jdbc/OrServlet</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
When I try to connect to Oracle in traditional way:
try {
cn = DriverManager.getConnection(
"jdbc:oracle:thin:#XEPDB1", "STERN", "pwdxx");
}
catch (Exception e) { }
everything works fine.
But when I try to connect through context:
Connection cn = null;
DataSource ds = null;
try
{
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup("java:comp/env");
ds = (DataSource)envCtx.lookup("jdbc/OrServlet");
cn = ds.getConnection();
}
catch(NamingException n) {}
catch(SQLException s) {out.println(ds.getClass().getName()+" exception "+s);
;}
I get :
**exception java.sql.SQLException: Cannot create JDBC driver of class '' for connect URL 'null'**
and ds.getClass().getName() in exception handler returns:
org.apache.tomcat.dbcp.dbcp2.BasicDataSource
which is distinct from javax.sql.DataSource as declared in
and .
And it seems to me that ds = (DataSource)envCtx.lookup("jdbc/OrServlet")
doesn't wvwn try to look inside Resource section.
What I missed?
Any help will be very appreciated.
Regards,
Andrew.

Configuring JNDI JDBC for Web App in Tomcat

I'm unable to figure out why JNDI JDBC data source is failing
context.xml in META-INF
<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true">
<Resource auth="Container"
name="jdbc/BigByte"
type="javax.sql.DataSource"
driverClassName="com.ibm.as400.access.AS400JDBCDriver"
url="jdbc:as400://****.****/****;prompt=false;sort=language;sort language=ENU;sort weight=shared"
username="****"
password="****"
maxIdle="10"
maxActive="200"
maxWait="5"
removeAbandoned="true"
removeAbandonedTimeout="1200" />
</Context>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
*
*
*
<resource-ref>
<description>Big Byte DB Connection</description>
<res-ref-name>jdbc/BigByte</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
</web-app>
my test
DataSource ds = null;
try {
Context initCtx = new InitialContext();
NamingEnumeration<NameClassPair> list = initCtx.list("");
while (list.hasMore()) {
System.out.println(list.next().getName());
}
Context envCtx = (Context)initCtx.lookup("java:comp/env");
ds = (DataSource)envCtx.lookup("jdbc/BigByte");
Connection con = ds.getConnection();
PreparedStatement ps = con.prepareStatement(
"select * from XAAQREV1 where AQABVN = ?");
ps.setString(1, "*****");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String uid = rs.getString("AQABVN");
System.out.println(uid);
}
} catch (NamingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
My console output
2017-09-28 10:13:26,482/: [http-nio-8080-exec-10/:ERROR] - Cannot find the class org/apache/naming/LocalStrings.class
2017-09-28 10:13:26,619/: [http-nio-8080-exec-10/:ERROR] - Cannot find the class org/apache/naming/LocalStrings_en.class
2017-09-28 10:13:26,775/: [http-nio-8080-exec-10/:ERROR] - Cannot find the class org/apache/naming/LocalStrings_en_US.class
2017-09-28 10:13:28,091/: [http-nio-8080-exec-10/:ERROR] - Cannot find the class org/apache/juli/JdkLoggerConfig.class
javax.naming.NameNotFoundException: Name [java:comp/env] is not bound in this Context. Unable to find [java:comp].
at org.apache.naming.NamingContext.lookup(NamingContext.java:824)
at org.apache.naming.NamingContext.lookup(NamingContext.java:172)
at javax.naming.InitialContext.lookup(Unknown Source)
at webx0001.XAC3DFR_ObFnc.ObRun(XAC3DFR_ObFnc.java:189)
...
When I step through my test, the NamingEnumeration list has no elements.
What are the console messages about missing classes about?
What am I missing?
I was not missing anything.
My project uses a Custom ClassLoader that breaks Tomcat JNDI.
I verified that with a simple servlet in a simple project.

org.h2.Driver version for embedded mode

My requirement is H2 database should get started while deploying my war file in embedded mode. For that I created class(DbSetup) in my java project. I mentioned the same class in web.xml . Then I implemented contextInitialized(ServletContextEvent sce) method. In that method I am making connection to h2 db to which I made connection while deploying war. While getting war file, I am getting exception like " No suitable class found for jdbc:h2:~/test1. Could you please how to approach this problem? I am binding h2-1.4.192.jar with my war. I also copied the same jar to class path.
web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>CEMDBWS</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.h2.server.web.DbStarter</listener-class>
</listener>
<context-param>
<param-name>db.url</param-name>
<param-value>"jdbc:h2:~/test1"</param-value>
</context-param>
<context-param>
<param-name>db.user</param-name>
<param-value>sa</param-value>
</context-param>
<context-param>
<param-name>db.password</param-name>
<param-value>sa</param-value>
</context-param>
<listener>
<listener-class>DbSetup</listener-class>
</listener>
<servlet>
<servlet-name>JSON TO SQL Rest API</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JSON TO SQL Rest API</servlet-name>
<url-pattern>/Request/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>-1</session-timeout>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
<mime-mapping>
<extension>json</extension>
<mime-type>application/json</mime-type>
</mime-mapping>
my class:
try
{
Connection connection = null;
final String DB_CONNECTION = "jdbc:h2:~/test1";
final String DB_USER = "sa";
Class.forName(org.h2.Driver);
final String DB_PASSWORD = "sa";
connection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
return connection;
} catch (SQLException e) {
LOGGER.error("Error while getting DB connection", e);
return connection;
} catch (ClassNotFoundException e) {
LOGGER.error("Error while loading Driver", e.getMessage());
}
return connection

Name is not bound in this Context... Datasource not found

Am building a small Jersey (1.9) REST Service and having a Java class as sub-resource where I connect to local database (Postgres 9.3).
For the datasource I have already add the entries in Context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/userProfile">
<Resource
auth="Container"
driverClassName="org.postgresql.Driver"
maxActive="100"
maxIdle="30"
maxWait="10000"
name="jdbc/apiUserProfile"
password="postgres"
type="javax.sql.DataSource"
url="jdbc:postgresql://localhost:5432/apiUserProfile"
username="postgres"/>
</Context>
When I run the application and call the following resource:
http://localhost:8084/userProfile/rest/user/conn
the page is blank - no content- and the tomcat (8.0) on netbeans (8.1) is throwing Error: Null Pointer Exception
javax.naming.NameNotFoundException: Name [jdbc/apiUserProfile] is not bound in this Context. Unable to find [jdbc].
at org.apache.naming.NamingContext.lookup(NamingContext.java:818)
at org.apache.naming.NamingContext.lookup(NamingContext.java:166)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:157)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at net.rest.dao.DbConn.apiUserProfileConn(DbConn.java:23)
at net.rest.service.userProfile.returnDatabaseStatus(userProfile.java:51)
I also already have the JAR files in the librairies:
lib/mysql-connector-java-5.1.39-bin.jar
lib/postgresql-9.3-1100-jdbc4.jar
and here is the sub-resource class for the datasource connection:
package net.rest.dao;
import javax.naming.*;
import javax.sql.*;
public class DbConn {
private static DataSource DbConn = null;
private static Context context = null;
public static DataSource apiUserProfileConn() throws Exception {
if(DbConn != null){
return DbConn;
}
try {
if(context == null){
context = new InitialContext();
}
DbConn = (DataSource) context.lookup("jdbc/apiUserProfile");
}
catch (Exception e) {
e.printStackTrace();
}
return DbConn;
}
}
Any Idea pls. how to fix this..
Many Thanks
a.kasbi
The issue is resolved now.. the Apache Tomcat Doc was very helpful:
http://localhost:8080/docs/jndi-datasource-examples-howto.html
http://localhost:8080/docs/jndi-datasource-examples-howto.html#PostgreSQL
The solution for me was adding the following into context.xml under: META-INF
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/apiRest">
<Resource name="jdbc/apiUserProfile" auth="Container"
type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://127.0.0.1:5432/apiUserProfile"
username="postgres" password="postgres" maxTotal="20" maxIdle="10"
maxWaitMillis="-1"/>
</Context>
and the following in web.xml:
<resource-ref>
<description>postgreSQL Datasource example</description>
<res-ref-name>jdbc/apiUserProfile</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
The lookup argument in the java Class for the Datasource connection:
...
DbConn = (DataSource) context.lookup("java:/comp/env/jdbc/apiUserProfile");
...
Thanks

Spring RESTful and Hibernate

I have a very simple database in postgres and i have used hibernate to "connect" to it. Everything works fine, i tested the database with hibernate and no problems so far.
Here is my DAO
#Repository("clientsBasicDao")
#Transactional
public class ClientsBasicDaoImpl implements ClientsBasicDao {
private Log log = LogFactory.getLog(ClientsBasicDaoImpl.class);
private SessionFactory sessionFactory;
private Session session;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
#Resource(name="sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
session = sessionFactory.openSession();
}
#SuppressWarnings("unchecked")
#Transactional(readOnly=true)
public List<ClientsBasic> findAllClients() throws HibernateException{
return session.createQuery("from ClientsBasic").list();
}
public ClientsBasic findClientById(int id) throws HibernateException {
return (ClientsBasic) session.
getNamedQuery("ClientsBasic.findById").setParameter("id", id).uniqueResult();
}
public ClientsBasic findClientByEmail(String email) throws HibernateException{
return (ClientsBasic) session.
getNamedQuery("ClientsBasic.findByEmail").setParameter("email", email).uniqueResult();
}
#SuppressWarnings("unchecked")
public List<ClientsBasic> findDirectClients() throws HibernateException{
return session.getNamedQuery("ClientsBasic.findDirectClients").list();
}
#SuppressWarnings("unchecked")
public List<ClientsBasic> findIndirectClients() throws HibernateException{
return session.getNamedQuery("ClientsBasic.findIndirectClients").list();
}
public ClientsBasic save(ClientsBasic client) throws HibernateException {
Transaction tx = null;
tx = session.beginTransaction();
session.saveOrUpdate(client);
tx.commit();
log.info("Client saved with id: " + client.getClientId());
return client;
}
public void delete(ClientsBasic client) throws HibernateException {
Transaction tx = null;
tx = session.beginTransaction();
Set<Resources> res = client.getClientResources();
if(res.size() > 0){ //there are client access resources for this client
Iterator<Resources> it = res.iterator();
while(it.hasNext()){
Resources resource = it.next();
resource.getClientsBasics().remove(client);
}
}
session.delete(client);
tx.commit();
log.info("Client deleted with id: " + client.getClientId());
}
}
Now, i am trying to learn restful web services so after some tutorials i tried my own implementation. It works, except when i try to use the method that connects to the database.
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
//http://localhost:8080/TestProject/greeting
// or
//http://localhost:8080/TestProject/greeting?name=stackoverflow
#RequestMapping("/greeting")
public #ResponseBody String greeting(
#RequestParam(value="name", required=false, defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name)).toString();
}
//http://localhost:8080/TestProject/testing
#RequestMapping("/testing")
public #ResponseBody String home(){
return "Welcome, the server is now up and running!";
}
//http://localhost:8080/TestProject/client?id=1
#RequestMapping("/client")
public #ResponseBody String client( //FAILS HERE
#RequestParam(value="id", required=true) String id){
ClientServiceBackend cb = new ClientServiceBackend();
return cb.findClient(Integer.parseInt(id));
}
}
and here is the error
HTTP Status 500 - Handler processing failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1284)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:965)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
My web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>test</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
and dispatcher:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.project.rest" />
<mvc:annotation-driven />
</beans>
like i said, i am trying to learn rest and this is my 2nd week with spring, so this is all kinda new to me, but i would expect this to work since the database is working fine!
NOTE: I am deploying this on Tomcat v7
can someone please give a hand here?
Thank you :-)
EDIT:
I added the hibernate jar to the tomcat classpath, and now the error is
The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'.

Resources