Configure DB Connection Pooling - Axis2 webservice - oracle

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

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

Liferay portlet non-liferay JNDI data source null

For a Liferay 6.2 custom portlet accessing a non liferay Oracle database we are running into an issue where the data source returned is null.
We have configured the tomcat/conf/context.xml
<!-- Adding custom New non liferay datasource -->
<Resource name="jdbc/NewPool"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:#(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = dbservernameorip)(PORT = 9999))
(CONNECT_DATA = (SERVER = DEDICATED)
(SERVICE_NAME = dbSIDorservicename)))"
username="user"
password="pwd"
maxActive="35"
maxIdle="10"
maxWait="20000"
removeAbandoned="true"
logAbandoned="true"
minEvictableIdleTimeMillis="3600000"
timeBetweenEvictionRunsMillis="1800000"
testOnBorrow="true"
testOnReturn="false"
/>
The portlet web.xml contains:
<resource-ref>
<description>Oracle Datasource example</description>
<res-ref-name>jdbc/NewPool</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
The code for lookup is:
String JNDI = "jdbc/NewPool"
_log.debug("JNDI Name is: " + JNDI);
_log.debug("dataSource in dbConnect is :" + dataSource);
Context context = new InitialContext();
Context envContext = (Context)context.lookup("java:/comp/env");
_log.debug("envContext in dbConnect is :" + envContext);
try {
DataSource ds = (DataSource)envContext.lookup(JNDI);
Liferay can use the context.xml resource with a similar data source for the Liferay Oracle database successfully.
Is some other wiring needed for Liferay portlet to establish a connection to another database?
The same portlet code works on weblogic without the web.xml change. Similar JNDI data source lookup code and configuration works on vanilla tomcat (without liferay) and a plain war (non liferay portlet) file.
Update:
I have checked db connections on the server with netstat -an|grep dbport. this does not show an established connection.
I have also tried setting the portal.security.manager.strategy=none in portal-ext.properties. This did not work either.
Any insight is much appreciated as we are kind of stuck here.
Thanks!
I just stumbled over this thread in the Liferay Forum which basically says. oput this in your tomcat/conf/server.xml
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
<Resource name="jdbc/XXX" auth="Container" type="javax.sql.DataSource"
maxActive="20" maxIdle="10" maxWait="5000"
removeAbandoned="true" removeAbandonedTimeout="250" validationQuery="SELECT 1"
username="user2" password="pwd2"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/myOtherDb"/>
and this in your context.xml:
<ResourceLink name="jdbc/XXX" global="jdbc/XXX" type="javax.sql.DataSource">
It should do the trick. If you really asking WHY Liferay can find the jndi resource, but not your portlet:
I have no clue...
We also had some problems using the resource and pools. Since we have very few requests to handle and performance were not a concern for our scenario we used a JDBC connection directly without a pool and it's working fine (we are connecting to a MS Sql server)
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String url = "jdbc:jtds:sqlserver://host/dbname";
String driver = "net.sourceforge.jtds.jdbc.Driver";
String db_userName = PropsUtil.get("jdbc.default.username");
String db_password = PropsUtil.get("jdbc.default.password");
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, db_userName, db_password);
String sql = "SELECT * FROM Users";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
// DO WHAT YOU WANT
return true;
}
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
And it's working fine. Username and password are configured in portal-ext.properties (We are using the same account used for liferay own db)
Hope this helps
I believe we found our issue. It seems like it was a typo.
All references to dataSource need to be changed to ds. There was a code changed. It turned out the the variable name was not changed to ds in code after the ds variable was declared during troubleshooting the issue.
String JNDI = "jdbc/NewPool"
_log.debug("JNDI Name is: " + JNDI);
_log.debug("dataSource in dbConnect is :" + ds);
Context context = new InitialContext();
Context envContext = (Context)context.lookup("java:/comp/env");
_log.debug("envContext in dbConnect is :" + envContext);
try {
DataSource ds = (DataSource)envContext.lookup(JNDI);
_log.debug("dataSource in dbConnect is :" + ds)
We need to test this out. I will post the results after the final test.

Getting "ORA-01017: invalid username/password; logon denied" when trying to create a data source in Tomcat 6

Been pulling my hair trying to set up a data source in in Tomcat for an application. The steps I've taken are
Create a META-INF/context.xml with the following content
<Context>
<Resource name="jdbc/mydb"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:#gpqa6.myserver.com:1526:gpqa6"
username="foo"
password="foobar"
maxActive="20"
maxIdle="30"
maxWait="-1" />
</Context>
Enter the following text in WEB-INF/web.xml
<resource-ref>
<description>Datasource</description>
<res-ref-name>jdbc/mydb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Using it in the code
public class MyServlet extends HttpServlet {
private DataSource ds;
public void init() {
try {
Context ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/mydb");
} catch (NamingException e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//this is where the exception is thrown
Connection conn = ds.getConnection();
//...do stuff with the connection
}
But keep on getting the following error
"Encounter exception during mapping. Error: Cannot create PoolableConnectionFactory (ORA-01017: invalid username/password; logon denied
)
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (ORA-01017: invalid username/password; logon denied"
I know that the username and password are correct. Because the following code works
Class.forName("oracle.jdbc.OracleDriver").newInstance();
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#gpqa6.myserver.com:1526:gpqa6", "foo", "foobar");
I've even tried to enter an invalid url but still get the same error. What's going on???
Also, does Tomcat have some way of testing the data source similar to WebLogic or Glassfish?
Now it's working. Seem like after I establish a connection with the following code
Class.forName("oracle.jdbc.OracleDriver").newInstance();
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#gpqa6.myserver.com:1526:gpqa6", "foo", "foobar");
then switching back to using the data source, it's fine. Maybe it's a caching issue?
--Update--
It is a caching issue. Ijust have to delete the \conf\Catalina folder.
This link really helped.
http://pwu-developer.blogspot.com/2010/02/why-isnt-my-datasource-configuration.html

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

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"

Resources