java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp.BasicDataSource cannot be cast to org.apache.tomcat.jdbc.pool.DataSource - tomcat7

I'm running Tomcat 7.0.22 and I wrote a simple servlet that connects to a SQL Anywhere 12.0 database. When I run the servlet I get java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp.BasicDataSource cannot be cast to org.apache.tomcat.jdbc.pool.DataSource. My ./META-INF/content.xml file looks like the following:
<Context>
<Resource name="jdbc/FUDB"
auth="Container"
type="javax.sql.DataSource"
username="dba"
password="sql"
driverClassName="sybase.jdbc.sqlanywhere.IDriver"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
url="jdbc:sqlanywhere:uid=dba;pwd=sql;eng=BTH476331A_FedUtilization;"
accessToUnderlyingConnectionAllowed="true"
maxActive="8"
maxIdle="4" />
My webapp web.xml looks like this:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="true">
<display-name>FedUtilization</display-name>
<servlet>
<servlet-name>Report1</servlet-name>
<display-name>Report1</display-name>
<servlet-class>com.sapgss.ps.servlet.Report1</servlet-class>
Report1
/Report1
SQL Anywhere 12.0.1 server jdbc3
jdbc/FUDB
javax.sql.DataSource
Container
The servlet code is as follows:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import org.apache.catalina.core.StandardContext.*;
import org.apache.tomcat.jdbc.pool.*;
import com.sapgss.ps.dbutil.*;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
public class Report1 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println("Hello Elaine!");
out.println("");
out.println("");
out.println("Hello Elaine! ");
// This is how to code access to the database in Java Context
initCtx = new InitialContext(); Context envCtx = (Context)
initCtx.lookup("java:comp/env"); DataSource ds = (DataSource)
envCtx.lookup("jdbc/FUDB");
Connection conn = ds.getConnection(); .
.
.
}
}
The error happens when I try to get a DataSource at this line:
DataSource ds = (DataSource) envCtx.lookup("jdbc/FUDB");
Thanks in advance I'm pulling my hair out.

In my case I just forgot to put:
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
in my /tomcat7/conf/context.xml. Just added and all worked fine.
My context.xml:
<Context>
<Resource name="jdbc/gestrel" auth="Container"
type="javax.sql.DataSource"
driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://127.0.0.1:5432/g...."
username="postgres"
password="....." maxActive="20" maxIdle="10"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
maxWait="-1"/>
</Context>

Today I've spent a half of the day trying to deal with the similar issue. I have tomcat server.xml file defining context like this:
<Context docBase="app" path="/my_context_path">
</Context>
Then I tried to add jdbc pool support using org.apache.tomcat.jdbc.pool.DataSource.
Just added resource definition to my server.xml context definition (see above). And of cause I defined resource-ref in my web.xml.
But there was always org.apache.tomcat.dbcp.dbcp.BasicDataSource returned. I spent time debugging tomcat and finally got to the following:
If I define resource in server.xml context - tomcat does NOT pick that up.
If define in web archive's META-INF/context.xml works ok.
If define in server.xml GlobalNamingResources tag - tomcat does NOT pick that up.
If define in tomcat global context.xml file works ok.
If you specify resource-ref in web.xml for bad cases 1,3 - tomcat will return org.apache.tomcat.dbcp.dbcp.BasicDataSource, cause as I can see it is some kind of default. BUT using such data source returned will cause something like this:
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1452)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
If not specify resource-ref in web.xml then you will get an exception telling that resource with such name could not be find.
Also I noticed that for good cases 2,4 specifying resource-ref in web.xml is not necessary (works with and without resource-ref).
Try some of the cases I described. I hope something will help.
I would try to define resource in tomcat global context.xml file.
Good luck!
P.s. I run 7.0.22 version as well.

The solution is to import javax.sql.DataSource in your servlet as you define the resouce in context.xml of type="javax.sql.DataSource"

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.

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 Rest CXF [bean error] Tomcat

I´m doing a webservice in rest, spring, cxf and tomcat.
Link full project: http://www55.zippyshare.com/v/99585767/file.html
I´ve got this error on bean.
Can´t figure out why is this happening?
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restContainer': Cannot resolve reference to bean 'timeService' while setting bean property 'serviceBeans' with key [0]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'timeService' is defined
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
timeService.java
#Service("timeService")
#Path("/time")
public class TimeService {
#GET
#Produces("text/plain")
public String getDateTime()
{
DateFormatter formatter = new DateFormatter("dd/MM/yyyy hh:mm:ss");
return formatter.print(Calendar.getInstance().getTime(), Locale.getDefault());
}
}
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
<jaxrs:server id="restContainer" address="/">
<jaxrs:serviceBeans>
<ref bean="timeService"/>
</jaxrs:serviceBeans>
</jaxrs:server>
</beans>
These are my files and i can´t find out what is wrong. This is driving me nuts!
The Spring documentation says that you need to add an element to direct the finding of your #Service-annotated beans. For example, if your beans were in the package org.example or one of its sub-packages, you'd use a component scanner configuration in your beans.xml like this:
<context:component-scan base-package="org.example"/>
(As long as it's inside the <beans> element, it's fine whether it goes above or below the <jaxrs:server> element.)

Spring #Scheduled is executing task twice when using annotations

I have made task using Spring #Scheduled annotation, but for some reason it is executing task twice. My Spring Framework version is 3.0.2.
#Service
public class ReportService {
#Scheduled(fixedDelay=1000 * 60 * 60* 24)
#Transactional
public void dailyReportTask()
{
... code here ...
}
}
Here is my XML:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<task:scheduler id="taskScheduler" />
<task:executor id="taskExecutor" pool-size="1" />
<task:annotation-driven executor="taskExecutor"
scheduler="taskScheduler" />
</beans>
it is happening because of context listener
Just remove
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
from web.xml it should work.
I had this same problem, and I eventually found out that the problem was occurring as a result of the beans being created in the root context as well as the servlet context.
So, to fix this, you need to separate the creation of the beans into the appropriate contexts.
This answer explains really well how to that and was what fixed my problem.
According to this post: http://www.vodori.com/blog/spring3scheduler.html
Spring 3.0.0 Release had a bug where
web apps with a task scheduler would
end up executing scheduled methods
twice. This has been resolved in
Spring 3.0.1.
There has been another bug reported which affects Version/s: 3.0.2
https://jira.springsource.org/browse/SPR-7216
Which should be fixed in Version/s: 3.0.3.
I just had this problem recently and it was caused by my app being deployed twice in Tomcat by eclipse. The problem was that I had renamed my application in eclipse but the "wb-module deploy-name" specified in the "org.eclipse.wst.common.component" .settings file still had the old name.
In the tomcat manager, I could see that I had 2 apps running with different names.
Where are you actually running it? Your PC? Single server? 2 x load-balanced app servers?
Could be it's running on (a) your PC and (b) your server, so it just looks like it's running twice, if you see what I mean: it's correctly running once, just on two distinct locations.
Check if you have any manual scheduler config in your configuration files (through Java/XML). I'ved the same problem, and I discover that my config was loading my scheduler class twice:
In Java:
package com.mywork.br.myschuedulerpackage;
{...}
#Configuration
#EnableScheduling
public class SchedulerConfiguration {
#Bean
public CTXDataImporterScheduler ctxDataImporterScheduler() {
return new CTXDataImporterScheduler();
}
}
In XML applicationContext.xml:
<context:component-scan base-package="com.mywork.br.myschuedulerpackage" />
And in my scheduler class, I had #Component annotation thats was catch by the component scan and loaded a second time causing the #scheduler methods being executed twice.
I removed the Java config and then is working well now!
To solve twice-working of #Scheduled method just delete ContextLoaderListener from you web.xml (if you use web.xml-based application):
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Or if you use WebApplicationInitializer-based application just delete a string that adds ContextLoaderListener:
package com.dropbox.shortener.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class DropboxShortenerWebApplicationInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(AppConfig.class);
// (!) Delete the next string
// container.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
setupCharEncodingFilter(container);
}
private void setupCharEncodingFilter(ServletContext container) {
container.setInitParameter("defaultHtmlEscape", "true");
FilterRegistration charEncodingFilterReg = container.addFilter("CharacterEncodingFilter", CharacterEncodingFilter.class);
charEncodingFilterReg.setInitParameter("encoding", "UTF-8");
charEncodingFilterReg.setInitParameter("forceEncoding", "true");
charEncodingFilterReg.addMappingForUrlPatterns(null, false, "/*");
}
}
Use #Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE) on your bean
Disabling below will work.
<!-- <listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener> -->
One solution I would suggest is to do component scat like this
-In application context
<context:component-scan base-package="com.abc.cde.dao" />
In yourservlet-servlet.xml
<!-- package that had all the #Controller classes -->
I this way the servlet is only loaded if the web.xml is loaded
Similar can be done for task

Configure DB Connection Pooling - Axis2 webservice

I'd like to know how to modify the server.xml file so all my webservices built on axis2 can talk to the DB using Connection Pooling. Each webservice has a different data source, one points to one instance of the DB and the other to another DB server. How do I specify the context that should be used by each service?
Thanks in advance,
Pojo
If you want to use connection pool in your project , Ensure that you have the following code set up for the Tomcat connection pooling to work in context.xml file:
1)Create file with name "context.xml" if it's not exist under directory "WebContent/META-INF/context.xml" with the following content:
For My Project , Please modify it with appropriate value :
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/dbcp" docBase="dbcp">
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
removeAbandoned="true" removeAbandonedTimeout="30" maxActive="80"
maxIdle="30" maxWait="10000" username="sontn" password="nhantien"
driverClassName="org.postgresql.Driver"
url = "jdbc:postgresql://localhost/group8" useUnicode="true"
characterEncoding="utf-8" characterSetResults="utf8"/>
</Context>
Or you can copy file : context.xml into directory "$Catalian\webapps\axis2\META-INF"
How can you get connection pool?
In your webservice method : create method getConnection() with following content:
public Connection getConnection() {
Connection connection = null;
try {
Context envCtx = (Context) new InitialContext().lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB");
connection = ds.getConnection();
}
catch (Exception e) {
System.out.println("Connection error: " + e.getMessage());
}
return connection;
}
Thanks

Resources