Constant java:comp not bound in this context error tomcat6 - java

I keep getting this error and have tried a number of fixes rumoured online to no avail.
Here is the exception:
javax.naming.NameNotFoundException: Name java:comp is not bound in this Context
at org.apache.naming.NamingContext.lookup(NamingContext.java:770)
at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at my.app.database.DatabaseManager.connect(DatabaseManager.java:44)
at my.app.database.DatabaseManager.return(DatabaseManager.java:133)
at my.app.GenParse.GeneratePastPositions.updateSatHistory(GeneratePastPositions.java:89)
at my.app.updateHistory.run(SatelliteEclipseServer.java:72)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:351)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:178)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
My resource is declared in context.xml as this:
<?xml version='1.0' encoding='utf-8'?>
<!-- The contents of this file will be loaded for each web application -->
<Context reloadable="true">
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="myUsername" password="myPassword" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://mysql.myServer.com:3306/myUserName"/>
</Context>
And the connection in my java code:
public void connect() throws SQLException, NamingException{
initCtx = new InitialContext();
envCtx = (Context) initCtx.lookup("java:comp/env");
ds = (DataSource) envCtx.lookup("jdbc/TestDB");
}
I think also due to this its not closing the connection like it should. Other than the error message its all working, but I think this error compounds over time and uses up all the available connections.
I'd really appreciate some help with this as its been annoying me for weeks!

Related

porting web app to Tomcat: javax.naming.NameNotFoundException:

New user of Tomcat (8.5.9) on Linux CentOS 7 with Java SE 8. I must be making a simple mistake. This should be a textbook example how to configure a JDBC connection pool for tomcat.
I have this error:
javax.naming.NameNotFoundException: Name [jdbc/pool1] is not bound in this Context. Unable to find [jdbc]
Any idea what I could doing wrong? Tomcat states It is NOT recommended to place <Context> elements directly in the server.xml file. Thus, my setup:
$CATALINA_HOME/webapps/myapp/META-INF/context.xml is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/pool1"
auth="Container"
type="javax.sql.DataSource"
username="xx"
password="xx"
driverClassName="oracle.jdbc.OracleDriver"
url="xx"
maxTotal="256"
maxIdle="8"
initialSize="4"
removeAbandonedTimeout="7200"
removeAbandonedOnBorrow="true"/>
<Resource name="jdbc/pool2"
auth="Container"
type="javax.sql.DataSource"
username="xx"
password="xx"
driverClassName="oracle.jdbc.OracleDriver"
url="xx"
maxTotal="256"
maxIdle="8"
initialSize="4"
removeAbandonedTimeout="7200"
removeAbandonedOnBorrow="true"/>
<ResourceLink name="jdbc/pool1"
global="jdbc/pool1"
type="javax.sql.DataSource"/>
<ResourceLink name="jdbc/pool2"
global="jdbc/pool2"
type="javax.sql.DataSource"/>
</Context>
$CATALINA_HOME/webapps/myapp/WEB-INF/web.xml is as follows:
...
<resource-ref>
<description>xxx</description>
<res-ref-name>jdbc/pool1</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<resource-ref>
<description>xxx</description>
<res-ref-name>jdbc/pool1</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
...
The code causing the exception:
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("jdbc/pool1");
conn = ds.getConnection();
I have not modified $CATALINA_HOME/conf/server.xml at all. Did I configure something incorrectly, or am I missing setting another file up somewhere?
UPDATE 1
I tried adding the above ResourceLinks to the GlobalNamingResources tag in the $CATALINA_HOME/conf/server.xml file, then stopping/starting Tomcat, but I got the same error.
UPDATE 2
I then added the Resource tags from context.xml above also to the server.xml file (GlobalNamingResources tag), stopping/starting tomcat, and got same error.
UPDATE 3
I got everything working with Andreas' expert help (thanks!) by changing the way java calls the pool:
Context initCtx = new InitialContext();
Context context = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) context.lookup("jdbc/pool1");
conn = ds.getConnection();
Also, the ResourceLinks should not be in server.xml (they simply generate a warning in tomcat log).
Your $CATALINA_BASE/conf/server.xml file should contain the full <Resource> element. Remember to also add the JDBC driver jar file to Tomcat's $CATALINA_BASE/lib folder, since it is Tomcat, not your webapp, that needs it when the <Resource> is defined in server.xml.
Next, the META-INF/context.xml is a template that is used the first time your webapp is deployed. It gets copied to $CATALINA_BASE/conf/Catalina/localhost/myapp.xml, and is likely not updated/refreshed if you change META-INF/context.xml.
The .../Catalina/localhost/myapp.xml file should contain the <ResourceLink> element, mapping the name used by the webapp to the name used in server.xml. Keeping those two names the same is easiest, but not required.
Tomcat works fine without the <resource-ref> elements in WEB-INF/web.xml, but it's better if they are there, for compatibility with other Servlet containers.
Note: $CATALINA_BASE is usually the same as $CATALINA_HOME, i.e. the folder where Tomcat is installed, unless you explicitly configure it otherwise.
So, $CATALINA_BASE/conf/server.xml:
<?xml version='1.0' encoding='utf-8'?>
<Server ...>
...
<GlobalNamingResources>
...
<Resource name="jdbc/pool1" auth="Container" type="javax.sql.DataSource" ... />
<Resource name="jdbc/pool2" auth="Container" type="javax.sql.DataSource" ... />
...
</GlobalNamingResources>
...
</Server>
and $CATALINA_BASE/conf/Catalina/localhost/myapp.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<ResourceLink name="jdbc/pool1" global="jdbc/pool1" type="javax.sql.DataSource"/>
<ResourceLink name="jdbc/pool2" global="jdbc/pool2" type="javax.sql.DataSource"/>
</Context>
and place ojdbcXXX.jar in $CATALINA_BASE/lib.

where do I put tomcat context.xml data in JBoss EAP 7.0.0?

I have an application on Tomcat. It uses mysql for persistence. I define the mysql connection related data in context.xml as follows:
<Context>
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
<Resource
auth="Container"
description="User database that can be updated and saved"
name="jdbc/VTREProto"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
removeAbandoned="true"
username="vtreapp"
password="vtre!##$%"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/developermodule"
/>
</Context>
I access this in my java code as:
InitialContext initCTX = new InitialContext();
// Lookup the DataSource, which will be backed by a pool
// that the application server provides.
pool = (DataSource)initCTX.lookup("java:comp/env/jdbc/VTREProto");
I want to migrate to JBoss EAP 7.0.0. how and where do I specify the above resource in JBoss EAP 7.0.0 without breaking my java code.
Thanx and regards
In JBoss you don't need a context.xml.
You only need to create a datasource in configuration file: (standalone.xml or domain.xml) accordingly to the mode you are running JBoss.
I suggest you change the jndi name as well to the default "java:jboss/datasources/VTREProto" for example. Instead of "java:comp/env/jdbc/VTREProto".
An example of mysql datasource :
<datasources>
<datasource jndi-name="java:jboss/datasources/VTREProto" pool-name="VTREProtoDS">
<connection-url>jdbc:mysql://localhost:3306/jbossdb</connection-url>
<driver>mysql</driver>
<security>
<user-name>admin</user-name>
<password>admin</password>
</security>
<validation>
<valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker"/>
<validate-on-match>true</validate-on-match>
<background-validation>false</background-validation>
<exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter"/>
</validation>
</datasource>
More details on official documentation.

I can't use JNDI in tomcat to connect MySQL

I did everything in this :
how to connect tomcat 7 and mysql
But it still isn't working..... why? What have I missed?
Enviroment
OS : Win7
Eclipse : J2EE Mars
Tomcat : tomcat 8.0
java : 1.8.0_73
db name : test
username: root
password: 123
controller:
writeDB testDB = new writeDB(tablename);
writeDB.java
....
Class.forName("com.mysql.jdbc.Driver");
try{
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
//-------error-------
dataSource = (DataSource) envContext.lookup("jdbc/test");
//-------error-------
}catch(NamingException ex)
{
throw new RuntimeException(ex);
}
web.xml (in my project)
<!-- MySQL JNDI -->
<resource-ref>
<description>MySQL DB</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
context.xml
(in TOMCAT_HOME/conf)
(Also in workspace\Servers\Tomcat v8.0 Server at localhost-config)
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/eatST">
<Resource
name="jdbc/test"
auth="Container"
type="javax.sql.DataSource"
maxActice="100"
maxIdle="30"
maxWait="10000"
username="root"
password="123"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test?
useUnicode=true&characterEncoding=UTF8"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
/>
</Context>
Logs
Servlet.service() for servlet [commentCtr] in context
with path [/eatST] threw exception
java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp2.BasicDataSource
cannot be cast to javax.activation.DataSource
at com.joe.db.writeDB.<init>(writeDB.java:58)
at com.joe.servlet.CommentCtr.doPost(CommentCtr.java:38)
at ............
You've imported (and presumable programmed to) an incorrect DataSource. Your exception (java.lang.ClassCastException ... cannot be cast to javax.activation.DataSource) is telling you that you have usedjavax.activation.DataSource, but you wanted javax.sql.DataSource. Modify com.joe.db.writeDB and change
import javax.activation.DataSource;
to
import javax.sql.DataSource;
Also, you don't need Class.forName("com.mysql.jdbc.Driver"); (it doesn't hurt anything, but JDBC drivers register themselves now).

Spring / Tomcat - Error in DataSource (NameNotFoundException)

I am trying to connect a Spring MVC 4 application to MY Sql local BBDD.
This is the files:
Spring MVCConfiguration File:
#Bean
public DataSource dataSource() throws Exception {
Context cts = new InitialContext();
DataSource dts = (DataSource) cts.lookup("java:/comp/env/jdbc/etielaBBDD");
return dts;
}
Tomcat Context.xml:
<ResourceLink name="jdbc/etielaBBDD"
global="jdbc/BBDD"
auth="Container"
type="javax.sql.DataSource" />
Tomcat Server XML:
<Resource name="jdbc/BBDD" global="jdbc/BBDD" auth="Container" type="javax.sql.DataSource"
username="XXXXXX"
password="XXXXXX"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/confluenceuseUnicode=true&characterEncoding=utf8"
maxActive="15"
maxIdle="7"
defaultTransactionIsolation="READ_COMMITTED"
validationQuery="Select 1" />
And, when I Start Tomcat, this error appears:
javax.naming.NameNotFoundException: Name jdbc/BBDD is not bound in this context
I am two days trying to solve this error with no solution. Any idea? Thanks.

Tomcat6 MySql JDBC Datasource configuration

I've always used Spring's dependency injection to get datasource objects and use them in my DAOs, but now, I have to write an app without that.
With Spring I can write something like this:
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1/app?characterEncoding=UTF-8" />
<property name="username" value="u" />
<property name="password" value="p" />
</bean>
But how can I use datasource in my DAOs without Spring or anything? I'm using servlets and JSPs only. Performance is very important factor.
Believe it or not, people were writing applications before Spring and some are still not using it :) In your case, you could use Tomcat connection pool (and there is a complete configuration example for MySQL in the documentation). Let me summarize it:
First, put your driver in $CATALINA_HOME/lib.
Then, configure a JNDI DataSource in Tomcat by adding a declaration for your resource to your Context:
<Context path="/DBTest" docBase="DBTest"
debug="5" reloadable="true" crossContext="true">
<!-- maxActive: Maximum number of dB connections in pool. Make sure you
configure your mysqld max_connections large enough to handle
all of your db connections. Set to -1 for no limit.
-->
<!-- maxIdle: Maximum number of idle dB connections to retain in pool.
Set to -1 for no limit. See also the DBCP documentation on this
and the minEvictableIdleTimeMillis configuration parameter.
-->
<!-- maxWait: Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->
<!-- username and password: MySQL dB username and password for dB connections -->
<!-- driverClassName: Class name for the old mm.mysql JDBC driver is
org.gjt.mm.mysql.Driver - we recommend using Connector/J though.
Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver.
-->
<!-- url: The JDBC connection url for connecting to your MySQL dB.
-->
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/javatest"/>
</Context>
Declare this resource in your web.xml:
<web-app 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"
version="2.4">
<description>MySQL Test App</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
And get the datasource with a JNDI lookup in your application:
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB");
Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();
Note that such lookup is usually coded in a ServiceLocator (when you can't have a a DI container or a framework inject it for you).
I used to get error with sybase, I had missing META-INF folder in WebContent folder. Putting context.xml in that fixed the error Cannot create JDBC driver of class '' for connect URL 'null'...
// www.abbulkmailer.com
My context.xml looks like
<Context path="/reports" docBase="reports" debug="5" reloadable="true" crossContext="true">
<Resource name='jdbc/ASCSybaseConnection'
auth='Container'
type='javax.sql.DataSource'
username='fdd'
password='555'
driverClassName='com.sybase.jdbc2.jdbc.SybDriver'
maxActive='100'
maxIdle='100'
minIdle='10'
removeAbandoned="true"
removeAbandonedTimeout="60"
testOnBorrow="true"
logAbandoned="true"
url='jdbc:sybase:Tds:1.3.4.5:654/DB'/>
</Context>
You can declare your data source as a JNDI object and retrieve a datasource via a JNDI lookup:
DataSource ds = (DataSource)
envCtx.lookup("jdbc/EmployeeDB");
as documented here and here.
That's as bare-bones as you can get, so from there on, performance is completely up to you.

Categories

Resources