Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

connection

Status
Not open for further replies.

softjack

Programmer
Dec 4, 2005
44
0
0
IN
Hi,
I'm using tomcat 4.1. i connect to oracle database with a jsp or a servlet where the connection string is with in my code. if the connection is changed, i recomplile/change my code.

How can i save my connection information seperately and read it afterwards so that i don't have to recomplile/change my code again and again.

can someone throw some light on this???

thanks
softjack

 
Use a database connection pool.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Hi sedj,

Thanks for suggesting primrose. I downloaded all the required jars and followed the documentation.


This is my 'poolConfig.properties' file under tomcat/conf

Code:
#-----------------------------------------------------------------------------------------------
# poolConfig.properties INFORMATION
# -----------------------------------------------------------------------------------------------
#
#########################################
#### Information on - Admin settings ####
#########################################
#
# adminUser	   		: The user name for administering the pool via the web management interface
# adminPassword			: The user name for administering the pool via the web management interface
# adminWebManagementPort	: The port for which the web management too should run
# adminEmailAddresses		: Email address for the admin users to be notified of pool events
#				 	Multiple email addresses should be comma delimited - ie :
#					adminEmailAddresses=joe@bloggs.com,foo@bar.com
# adminEmailNotifcations	: Whether the pool should send emails for pool events (such as pools starting or stopping, and pool crisis information).
#					Value should be true/false
# adminEmailSMTPServer		: Your SMTP server if you want to recieve email notifications
# adminEmailCrisisAddress         : Crisis email address which will be used to send warnings to after the adminEmailMaxWarningNumber property has been exceeded
# adminEmailNotificationPeriod    : Time in milliseconds between warning emails
# adminEmailMaxWarningNumber      : The maximum number of emails to send about a specific problem before the crisis address is used
# adminEmailNotifications         : Boolean specifying whether the pool should send emails for pool events (such as pools starting or stopping, and pool crisis information)
# adminPoolControllerLogFile	  : The location of the PoolController log file (not pool instance logs, but general primrose logging)
#
# Note : If you enable email notifications, you must have activation.jar and mail.jar in common/lib or on the CLASSPATH. Both available from Sun
#	 via the JavaMail API home page on [URL unfurl="true"]http://www.java.sun.com,[/URL] or from [URL unfurl="true"]http://primrose.org.uk/download.jsp[/URL] (tomcat* support jar bundle)
#
# More info on these settings can be found at [URL unfurl="true"]http://www.primrose.org.uk/docs/mainPoolView.jsp[/URL]
#
##########################################
#### Information on - Pool Instances #####
##########################################
#
# poolName          : The name to use when calling the pool
# base              : The number of base connections to hold by default
# overflow          : How many connections to hold in the overflow pool
# user              : Username to connect to the database with
# password          : Which password to use with the specified username
# log               : Relative path to the log file (from the Tomcat bin directory)
# idleTime          : Number of milliseconds to keep a connection before releasing it when idle
# messageLogging    : Whether or not to log messages (such as SQL logging, connection gets() etc)
# sizeLogging       : Whether or not to log pool size data
# driverClass       : The class to load as the driver to the database
# driverURL         : The URL that is used to connect to the database (including host, port and db name/SID
# cycleConnections  : How many SQL transactions a connection should make before being refreshed, and creating a new one (-1 disables)
# killActiveConnectionsOverAge    : Number of milliseconds over which connections will be killed if still active (-1 disables)
# queueConnectionRequests	  : Whether or not connection requests should be queued when load is heavy and no connections are available (true == queue, false == do not queue (SQLException will be thrown)
# runPooledMode     : Whether the pool should return a pooled connection, or a the actual non-wrapped connection from the driver (true/false). If false, then it will effectively disable all pooling (ie close will actually close the physical connection, not return it to a pool).
# connectionAutoCommit : Whether when a connection is handed out, auto commit should be on or off. Default is 'true', options are 'true' or 'false'
# connectionTransactionIsolation : The transaction isolation level. See the website faq for more info. Default is to use the driver's default - omit the setting for this.
#
# More info on these settings can be found a [URL unfurl="true"]http://www.primrose.org.uk/docs/controllerView.jsp[/URL]
#
# -----------------------------------------------------------------------------------------------
#
# Example connection strings :
# -----------------------------------------------------------------------------------------------
# Oracle database connection details
#user=oracops
#password=dev
#driverClass=oracle.jdbc.driver.OracleDriver
#driverURL=jdbc:oracle:thin:@hostname:1521:SID
#
# MySQL database connection details
#driverClass=com.mysql.jdbc.Driver
#driverURL=jdbc:mysql://hostname:3306/db_name
#user=
#password=
# -----------------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------------

#########################
#### Admin settings ####
#########################
adminUser=admin
adminPassword=password
adminWebManagementPort=8090
adminEmailAddresses=joe@bloggs.com,foo@bar.com
adminEmailNotifcations=true
adminEmailSMTPServer=my.smpt.server
adminEmailCrisisAddress=someone@important.com
adminEmailNotificationPeriod=10000
adminEmailMaxWarningNumber=10
adminPoolControllerLogFile=/var/log/PoolController.log


#################################
#### Example Pool Instances #####
#################################

##### webmap pool instance #####
poolName=webmap
base=5
overflow=1
log=/var/log/pools_${yyyy-MM-dd}.log
idleTime=120000
messageLogging=true
sizeLogging=true
driverClass=com.mysql.jdbc.Driver
driverURL=jdbc:mysql://localhost:3306/test
user=
password=
killActiveConnectionsOverAge=120000
cycleConnections=1000
queueConnectionRequests=true
runPooledMode=true
connectionAutoCommit=true
#connectionTransactionIsolation=TRANSACTION_READ_COMMITTED

##### LoginDB pool instance #####
poolName=LoginDB
base=5
overflow=1
log=/var/log/pools_${yyyy-MM-dd}.log
idleTime=120000
messageLogging=true
sizeLogging=true
driverClass=com.mysql.jdbc.Driver
driverURL=jdbc:mysql://localhost:3306/test
user=
password=
killActiveConnectionsOverAge=120000
cycleConnections=1000
queueConnectionRequests=true
runPooledMode=true
connectionAutoCommit=true
#connectionTransactionIsolation=TRANSACTION_READ_COMMITTED

poolName=OraConnect
base=5
overflow=1
log=/var/log/pools_${yyyy-MM-dd}.log
idleTime=120000
messageLogging=true
sizeLogging=true
driverClass=oracle.jdbc.driver.OracleDriver
driverURL=jdbc:oracle:thin:@192.168.0.1:1521:mysid
user=rsuser
password=passxyz
killActiveConnectionsOverAge=120000
cycleConnections=1000
queueConnectionRequests=true
runPooledMode=true
connectionAutoCommit=true
#connectionTransactionIsolation=TRANSACTION_READ_COMMITTED

Here i added a new pool called 'OraConnect'


Now this is edited server.xml

Code:
<Server port="8005" shutdown="SHUTDOWN" debug="0">



  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"
            debug="0"/>
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"
            debug="0"/>

  <!-- Global JNDI resources -->
  <GlobalNamingResources>

    <!-- Test entry for demonstration purposes -->
    <Environment name="simpleValue" type="java.lang.Integer" value="30"/>

    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users -->
    
	<Resource name="masterPool" auth="Container"
				  type="java.util.ArrayList"
		   description="Holds all the pools">
		</Resource>
		<ResourceParams name="masterPool">
		  <parameter>
			<name>factory</name>
			<value>uk.org.primrose.pool.datasource.MasterPoolDataSourceFactory</value>
		  </parameter>
		  <parameter>
			<name>configFile</name>
			<value>/usr/jakarta-tomcat-5.0.16/conf/poolConfig.properties</value>
		  </parameter>
		</ResourceParams>

<Resource name="OraConnect" auth="Container"
				  type="uk.org.primrose.pool.datasource.PoolDataSource"
		   description="The promapweb database pool">
		</Resource>
		<ResourceParams name="OraConnect">
		  <parameter>
			<name>factory</name>
			<value>uk.org.primrose.pool.datasource.PoolDataSourceFactory</value>
		  </parameter>
		  <parameter>
			<name>poolName</name>
			<value>OraConnect</value>
		  </parameter>
		</ResourceParams>

	
	<Resource name="webmap" auth="Container"
				  type="uk.org.primrose.pool.datasource.PoolDataSource"
		   description="The promapweb database pool">
		</Resource>
		<ResourceParams name="webmap">
		  <parameter>
			<name>factory</name>
			<value>uk.org.primrose.pool.datasource.PoolDataSourceFactory</value>
		  </parameter>
		  <parameter>
			<name>poolName</name>
			<value>webmap</value>
		  </parameter>
		</ResourceParams>

<Resource name="LoginDB" auth="Container"
				  type="uk.org.primrose.pool.datasource.PoolDataSource"
		   description="The login database pool">
		</Resource>
		<ResourceParams name="LoginDB">
		  <parameter>
			<name>factory</name>
			<value>uk.org.primrose.pool.datasource.PoolDataSourceFactory</value>
		  </parameter>
		  <parameter>
			<name>poolName</name>
			<value>LoginDB</value>
		  </parameter>
		</ResourceParams>
	
	
	
	<Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
       description="User database that can be updated and saved">
    </Resource>
    <ResourceParams name="UserDatabase">
      <parameter>
        <name>factory</name>
        <value>org.apache.catalina.users.MemoryUserDatabaseFactory</value>
      </parameter>
      <parameter>
        <name>pathname</name>
        <value>conf/tomcat-users.xml</value>
      </parameter>
    </ResourceParams>

  </GlobalNamingResources>



  <!-- Define the Tomcat Stand-Alone Service -->
  <Service name="Tomcat-Standalone">

  

    <!-- Define a non-SSL Coyote HTTP/1.1 Connector on port 8080 -->
    <Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
               port="8080" minProcessors="5" maxProcessors="75"
               enableLookups="true" redirectPort="8443"
               acceptCount="100" debug="0" connectionTimeout="20000"
               useURIValidationHack="false" disableUploadTimeout="true" />
 

    <!-- Define a Coyote/JK2 AJP 1.3 Connector on port 8009 -->
    <Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
               port="8009" minProcessors="5" maxProcessors="75"
               enableLookups="true" redirectPort="8443"
               acceptCount="10" debug="0" connectionTimeout="0"
               useURIValidationHack="false"
               protocolHandlerClassName="org.apache.jk.server.JkCoyoteHandler"/>

  
    <!-- Define the top level container in our container hierarchy -->
    <Engine name="Standalone" defaultHost="localhost" debug="0">

    

      <!-- Global logger unless overridden at lower levels -->
      <Logger className="org.apache.catalina.logger.FileLogger"
              prefix="catalina_log." suffix=".txt"
              timestamp="true"/>

      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
                 debug="0" resourceName="UserDatabase"/>

    

      <!-- Define the default virtual host -->
      <Host name="localhost" debug="0" appBase="webapps"
       unpackWARs="true" autoDeploy="true">

   
        <Logger className="org.apache.catalina.logger.FileLogger"
                 directory="logs"  prefix="localhost_log." suffix=".txt"
            timestamp="true"/>

        
		
		
		<Context path="/examples" docBase="examples" debug="0"
                 reloadable="true" crossContext="true">
          <Logger className="org.apache.catalina.logger.FileLogger"
                     prefix="localhost_examples_log." suffix=".txt"
              timestamp="true"/>
          <Ejb   name="ejb/EmplRecord" type="Entity"
                 home="com.wombat.empl.EmployeeRecordHome"
               remote="com.wombat.empl.EmployeeRecord"/>

         
          <Environment name="maxExemptions" type="java.lang.Integer"
                      value="15"/>
          <Parameter name="context.param.name" value="context.param.value"
                     override="false"/>
          <Resource name="jdbc/EmployeeAppDb" auth="SERVLET"
                    type="javax.sql.DataSource"/>
          <ResourceParams name="jdbc/EmployeeAppDb">
            <parameter><name>username</name><value>sa</value></parameter>
            <parameter><name>password</name><value></value></parameter>
            <parameter><name>driverClassName</name>
              <value>org.hsql.jdbcDriver</value></parameter>
            <parameter><name>url</name>
              <value>jdbc:HypersonicSQL:database</value></parameter>
          </ResourceParams>
          <Resource name="mail/Session" auth="Container"
                    type="javax.mail.Session"/>
          <ResourceParams name="mail/Session">
            <parameter>
              <name>mail.smtp.host</name>
              <value>localhost</value>
            </parameter>
          </ResourceParams>
          <ResourceLink name="linkToGlobalResource"
                    global="simpleValue"
                    type="java.lang.Integer"/>

		    <ResourceLink
			global="OraConnect"
			name="OraConnect"
			type="javax.sql.DataSource"/>
		    <ResourceLink
			global="masterPool"
			name="masterPool"
			type="java.util.ArrayList"/>




        </Context>



      </Host>

    </Engine>

  </Service>


</Server>


This is the connect.jsp page through which i'm trying to establish the connection

Code:
<%@ page import = "java.sql.*" %>
<%@ page import = "javax.sql.*"%>
<%@ page import = "java.io.*" %>
<%@ page import = "java.util.*" %>
<%@ page import = "javax.naming.*"%>
<%

// Obtain a JNDI javax.naming.Context object
  Context ctx = new InitialContext();
  // Retrieve a DataSource object using JNDI
  DataSource ds = (DataSource)ctx.lookup("java:comp/env/???");
  // Extract a connection from the datasource
  Connection con = ds.getConnection();
%>

What path should be given in (DataSource)ctx.lookup("?????????");

I am getting an error message
javax.servlet.ServletException: Name ??? is not bound in this Context

Please enlight me on this. Am I doing something wrong??

regards,

softjack
 
You would use :

DataSource ds = (DataSource)ctx.lookup("java:comp/env/OraConnect");

BTW, you don't need the sections that reference "LoginDB" or "webmap" in poolConfig or server.xml - they are just examples (but you do need the masterPool stuff in server.xml).

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Hi,

I removed the sections that reference "LoginDB" or "webmap" in poolConfig and server.xml

Then after using the following line in my code

Code:
DataSource ds = (DataSource)ctx.lookup("java:comp/env/OraConnect");

i'm getting this error message:

javax.servlet.ServletException: Name OraConnect is not bound in this Context

This happend before also...what could be the problem??

regards,

Softjack


 
Is the JSP under the "examples" webapp ?

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Hi,

yes there was a name conflict it was 'example' rather than 'examples'....corrected that!!!

Now i'm getting a different error message i.e.

"Error retrieving list of pools available, or extracting valid connection - so cannot return"

I can successfully connect with the following jsp code without using connection pooling
Code:
<%@ page import = "java.sql.*" %>
<%@ page import = "javax.sql.*"%>
<%@ page import = "java.io.*" %>
<%@ page import = "java.util.*" %>
<%@ page import = "javax.naming.*"%>
<% Connection con=null;
try
   {
	Class.forName("oracle.jdbc.driver.OracleDriver"); 
	con = DriverManager.getConnection ("jdbc:oracle:thin:@192.168.0.1:1521:mysid", "rsuser", "passxyz");


   }

   catch(SQLException e)
   {
      out.println("SQLException: " + e.getMessage() + "<BR>");
      while((e = e.getNextException()) != null)
         out.println(e.getMessage() + "<BR>");
   }
   catch(ClassNotFoundException e)
   {
      out.println("ClassNotFoundException: " + e.getMessage() + "<BR>");
   }
%>

so there is no problem in the connection string or oracle connection.

what do you think???

regards,
Softjack

 
Also i cannot open my web management page at port 8090 using the url

where 192.168.0.4 is my server ip address.

I also tried to change the port to 9090 in poolConfig.properties but still it didn't work...changed it back to 8090.

How can i access the web management page.

regards,
softjack
 
Sounds like the pool is failing to initialise correctly.
Check all tomcat log files for errors relating to primrose.

Your poolConfig.propertied also indicates that you have all the log files going to a directory called '/var/log/*' - are you sure this directory exists, and that the tomcat user can write to it ?
You also have email notification on, but have not altered the MX server or email addresses.

You should go through the settings carefully and check they are set to correct values.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
hey sedj,

It worked!!!!
Actually the problem was with the path specified for the configfile in masterPool.

Corrected it and it is working fine now!!!
web management page is also working.

There is one more thing i would like to ask...
i have a xml file under web_inf which takes
url,driver,username & password to connect to a database.

Can i somehow use the information stored in poolConfig.properties in this xml file???


Thanks for your help and support

regards,
Softjack
 
Not sure what you mean ... could you elaborate ?

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Hi,

My app can now connect to Oracle easily using Primrose(connection pooling)

In a part of my application...
I am using a third party tool (for some purpose) which connects to the database reading connection information from an xml file located under WEB_INF/aserver.

This is one portion of that xml file

Code:
<database user="rsuser" password="passxyz" url="jdbc:oracle:thin:@192.168.0.1:1521:mysid" driver="oracle.jdbc.driver.OracleDriver" server="Oracle"/>

As i cannot edit the code for this third party tool, Is there a way to take connection info in this xml file from poolConfig.properties file located at /conf??
...or i have to edit this xml file everytime, whenever some changes are made in the connection??

regards,
Softjack
 
The only way I can think of you doing that is by running a job when you build the webapp that creates your xml file on the fly based on the content of the primrose config file.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top