can't get DB Connection using JNDI datasource on JBoss - java

I'm studying how to build java webapps for JBossAS 5.1.0 and I'm trying to build a very basic jsp web app on JBossAS5 using a JNDI datasource for data access.
When trying to open a connection I get this exception:
21:42:52,834 ERROR [STDERR] Cannot get connection: org.jboss.util.NestedSQLException:
Unable to get managed connection for hedgehogDB; - nested throwable:
(javax.resource.ResourceException: Unable to get managed connection for hedgehogDB)
The datasource is deployed ok, I can see it in the jmx-console & the database files are getting created ok.
Java code in question where the exception is thrown:
static public Connection getHedgehogConnection()
{
Connection result = null;
try
{
String DS_Context = "java:comp/env/jdbc/hedgehogDB";
Context initialContext = new InitialContext();
if ( initialContext == null)
log("JNDI problem. Cannot get InitialContext.");
DataSource datasource = (DataSource)initialContext.lookup(DS_Context);
if (datasource != null)
result = datasource.getConnection();
else
log("Failed: datasource was null");
}
catch(Exception ex)
{
log("Cannot get connection: " + ex);
}
return result;
}
web.xml:
<web-app>
<resource-ref>
<res-ref-name>jdbc/hedgehogDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
jboss-web.xml:
<jboss-web>
<resource-ref>
<res-ref-name>jdbc/hedgehogDB</res-ref-name>
<jndi-name>java:/hedgehogDB</jndi-name>
</resource-ref>
</jboss-web>
hedgehogdb-ds.xml
<datasources>
<local-tx-datasource>
<jndi-name>hedgehogDB</jndi-name>
<connection-url>jdbc:hsqldb:${jboss.server.data.dir}${/}hypersonic${/}hedgehogDB</connection-url>
<driver-class>org.hsqldb.jdbcDriver</driver-class>
<user-name>sa</user-name>
<password></password>
<min-pool-size>5</min-pool-size>
<max-pool-size>20</max-pool-size>
<idle-timeout-minutes>0</idle-timeout-minutes>
<track-statements/>
<security-domain>HsqlDbRealm</security-domain>
<prepared-statement-cache-size>32</prepared-statement-cache-size>
<metadata>
<type-mapping>Hypersonic SQL</type-mapping>
</metadata>
<depends>jboss:service=Hypersonic,database=hedgehogDB</depends>
</local-tx-datasource>
<mbean code="org.jboss.jdbc.HypersonicDatabase"
name="jboss:service=Hypersonic,database=hedgehogDB">
<attribute name="Database">hedgehogDB</attribute>
<attribute name="InProcessMode">true</attribute>
</mbean>
</datasources>
This is my first time in this environment and I suspect that I'm missing something really basic.

it's also possible to in -ds.xml use < application-managed-security / > instead of < security-domain >, at lease in Jboss6

Looking at your code, it appears that you get the DataSource correctly -- otherwise it would be null. So the problem happens when you try to get the connection.
Looking at the HSQLDB docs, it seems that your URL needs a "file" component:
jdbc:hsqldb:file:${jboss.server.data.dir}${/}hypersonic${/}hedgehogDB
And, as a general coding comment, (1) use a standard logging package, rather than a homegrown "log" method, and (2) when logging an exception, use the logger call (supported by both Log4J and Commons Logging, probably others) that takes an exception as a paramter (so that you get the full stack trace).

Figured it out:
The culprit was this in hedgehogdb-ds.xml :
<security-domain>HsqlDbRealm</security-domain>
HsqlDbRealm was configured for a different DS & was causing the connection to fail.

Related

Murach's Java Servlets 3rd edition NullPointerException when writing to database from application

I'm working with Murach's Java Servlets and JSP 3rd edition and have having difficulty with the ch12email project (which can be downloaded from murach.com). My issue is that when running the application and entering data into the form and submitting, I get the following HTTP Status 500 error:
java.lang.NullPointerException
murach.data.ConnectionPool.getConnection(ConnectionPool.java:32)
murach.data.UserDB.emailExists(UserDB.java:80)
murach.email.EmailListServlet.doPost(EmailListServlet.java:39)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Here is where the error is occurring:
public Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
System.out.println(e);
return null;
}
}
And that class's constructor:
private ConnectionPool() {
try {
InitialContext ic = new InitialContext();
dataSource = (DataSource) ic.lookup("java:/comp/env/jdbc/murach");
//dataSource = (DataSource) ic.lookup("jdbc/murach");
} catch (NamingException e) {
System.out.println(e);
}
}
However, I'm able to connect to the database in Netbeans and view or edit data in the database. This is the Resource tag in the context.xml file for the database user and password information:
<Resource name="jdbc/murach" auth="Container"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/murach"
username="root" password="67890"
maxActive="100" maxIdle="30" maxWait="10000"
logAbandoned="true" removeAbandoned="true"
removeAbandonedTimeout="60" type="javax.sql.DataSource" />
I'm not completely sure what information would be needed to thoroughly troubleshoot this problem, so please let me know whatever information would help and I'll be sure to supply it!
Do you have a resource ref defined in web.xml
<resource-ref>
<res-ref-name>jdbc/murach</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
I never found a solution, but was able to install it on a Windows 7 VM successfully following the steps in the book as normal. Afterwards I moved all of my files to an external and reinstalled Windows 10 on my laptop (the machine that was having the issue). After that I followed the book's instructions again and it worked. Thank you for anyone that took the time to try to help!

Understanding Apache Tomcat Connection Pooling

I am trying to implement Apache Tomcat's built-in JDBC connection pool. But I am confused with many things.
There are 2 methods mentioned in official page to initialize connection pool.
One using JNDI lookup and another by java PoolProperty class.
For JNDI lookup, we have to add entry to context.xmlor server.xml and initilize it in the java code. This require database connection details to be hardcoded.
For pool properties, we have to set various connection attributes in PoolProperty class using the datasource object. Does it require instantiating factory? (org.apache.tomcat.jdbc.pool.DataSourceFactory)
Whenever a try using pool properties, I am getting the error:
SEVERE: Unable to create initial connections of pool.
java.sql.SQLException: invalid arguments in call at
oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
I checked and confirmed all properties are correct. This error goes once I use the xml method. Can someone help me the correct way to configure pooling without xml?
This standalone java code gives me error:
PoolProperties p = new PoolProperties();
String dburl="jdbc:oracle:thin:#(DESCRIPTION=(LOAD_BALANCE=on)(ADDRESS=(PROTOCOL=TCP)(HOST=hostname) (PORT=1521))(ADDRESS=(PROTOCOL=TCP)(HOST=shostname2)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=Service)))";
p.setUrl(dburl);
p.setDriverClassName("oracle.jdbc.OracleDriver");
p.setUsername(username);
p.setPassword(pwd);
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1 from dual");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(10);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(600);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(10);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setJdbcInterceptors(
"org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
+ "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer;"
+ "org.apache.tomcat.jdbc.pool.interceptor.ResetAbandonedTimer");
p.setLogValidationErrors(true); datasource = new org.apache.tomcat.jdbc.pool.DataSource( );
datasource.setPoolProperties(p);
When I add A global Resource to Server.xml as below,it is working.
Resource auth="Container" description="User database that can be
updated and saved"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
name="jdbc/database" type="javax.sql.DataSource"/>
Please Help me to understand, what's the correct way of implementation.

Using datasource connection of weblogic server

I have wrote Java Client application (bean for Oracle form) to access the data through "jdbcdatasource" created on Weblogic 12c. It works fine when I am running on desktop, but when I am embedding on oracle forms as a bean, it gives following error:
java.lang.ClassNotFoundException: weblogic.jdbc.common.internal.RmiDataSource_12210_WLStub
java bean is an executable jar file includes all the dependency jar file, and it is executed independently by double click.
Here is a code:
Context ctx = null;
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3:" + url + ":7001");
if(sUser != null && sPwd != null){
ht.put(Context.SECURITY_PRINCIPAL, sUser);
ht.put(Context.SECURITY_CREDENTIALS, sPwd);
}
ctx = new InitialContext(ht);
System.out.println("!!! WebLogic Server Connection Done!");
javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("myDatasource");
java.sql.Connection conn = ds.getConnection();
System.out.println("!!! DataSource Connection Done!");
In the environment of Oracle forms it connect to the weblogic server but could not access the data source by displaying above error.
Any suggestion?
Just to make things clear to me.
When you say :
"to access the data through "jdbcdatasource" created on Weblogic 12c."
and you code shows:
"javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("myDatasource");"
The lookup parameter value shouldn't be exactly like "jdbcdatasource" instead of "myDataSource' as you stated before or it was just to explain your situation ?

Connect PostgreSQL to Java Dynamic Web Project

I'm trying to make my java dynamic web project work with postgresql database, but cannot figure out how to do that correctly.
What I did:
create Dynamic Web Project that runs on Tomcat v8.0
download postgresql jdbc driver
throw the postgresql-9.4-1205.jdbc4.jar file into my WEB-INF/lib
folder
create database java_lab2, create user lab2 with password qwerty, grant all privileges to user lab2 and create table users, all in psql
create META-INF/context.xml file
modify WEB-INF/web.xml file
here's my context.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/connectorDs" auth="Container"
type="javax.sql.DataSource" username="lab2" password="qwerty"
driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://localhost:8080/java_lab2"
maxTotal="10" maxIdle="4" />
</Context>
here's what I've added to web.xml:
<resource-ref>
<description>PostgreSQL data source</description>
<res-ref-name>jdbc/connectorDs</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
and now I cannot figure out how to actually start working with the database.
How do I connect to it? How do I query it in my servlets after the connection?
Update
I added the following function to my servlet:
private void attemptConnection() {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? "
+ "Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:8080/java_lab2", "lab2",
"qwerty");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
and run it in doGet method.
This gives me the following output:
PostgreSQL JDBC Driver Registered!
Connection Failed! Check output console
org.postgresql.util.PSQLException: The connection attempt
failed. at
org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:257)
at
org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:65)
......................
......................
Caused by:
java.io.EOFException at
org.postgresql.core.PGStream.ReceiveChar(PGStream.java:284) at
org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:405)
at
org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:203)
... 35 more

How to get resource from the context.xml file in tomcat webapp?

This is my context.xml file:
...
<Resource auth="Container"
driverClass="net.sourceforge.jtds.jdbc.Driver"
type="com.jolbox.bonecp.BoneCPDataSource"
idleMaxAge="240"
idleConnectionTestPeriod="60"
partitionCount="3"
acquireIncrement="1"
maxConnectionsPerPartition="10"
minConnectionsPerPartition="3"
statementsCacheSize="50"
releaseHelperThreads="4"
name="jdbc/MyDatasource"
username="my_username"
password="my_password"
factory="org.apache.naming.factory.BeanFactory"
jdbcUrl="jdbc:jtds:sqlserver://localhost:12345/my_database"
/>
...
I already tried using ServletContext.getResource(java.lang.String) with the name of the resource ("jdbc/MyDatasource"), but Tomcat complains that the name doesn't begin with a '/'. I also tried with "/jdbc/MyDatasource", but this time it returns null.
I mainly need the jdbcUrl to perform a connection check with the database server (see if the server is online and operational).
Keyword is: JNDI. The resources in the context.xml are not 'System Resources' but JNDI Resources.
Try this:
InitialContext ic = new InitialContext();
// that's everything from the context.xml and from the global configuration
Context xmlContext = (Context) ic.lookup("java:comp/env");
DataSource myDatasource = (DataSource) xmlContext.lookup("jdbc/MyDatasource");
// now get a connection to see if everything is fine.
Connection con = ds.getConnection();
// reaching this point means everything is fine.
con.close();
You should be able to access the datasource with the following code:
Context initialContext = new InitialContext();
Context envContext = (Context)initialContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/MyDatasource");

Categories

Resources