Techniques to use datasource efficiently

I am using datasource to get connections and everytime I want to get a connection I do this
Context initialcontext = new InitialContext();
DataSource datasource = (DataSource)initialcontext.lookup("java:comp/env/mydatasource");  
conn = datasource.getConnection();           
stmt = conn.createStatement();           
rs=..... etcThen I close connections..
          if(rs!=null)
          rs.close();
          if(stmt!=null)
          stmt.close();
conn.close(); //When I close them does it close the connection from the pool?If I want to reuse this connection on another page then how do I do that? Do I pass it in request or session ?

Hi!
On closing the connection it certainly goes back to the pool. Doesn't physically close one, which you seem to have known probably.
But certainly passing around a connection might not be such a good idea. It will certainly make it tougher to manage them across the code.
Regards
$ Carol.

Similar Messages

  • When is it appropriate to use DataSource (or Connection pooling)?

    Hello all,
    I'm having some design issues with my application and I'm starting to think that maybe using Connection pooling is not suited for my application. I'm using Tomcat 5.5.12 if it's any relevant..
    The architecture of our application looks like this:
    Servlets -> App Helper classes -> DB/Accessor classes
    looks like the three-tier architecture described in this document: http://www.subrahmanyam.com/articles/servlets/ServletIssues.html
    I have read on the Tomcat docs that said that using DataSource is good practice and improves efficiency since it recycles database connections. However, if the accessor/DB classes are not servlets, how can I use the DataSource facility that interacts with Tomcat?
    I would like to know whether it is a good idea to use DataSource in my case and if so, how? (since they are not servlets)
    Thanks in advance :)

    Hi. Thank you for replying.
    In the examples that I've seen that use JNDI for Database access, it seems that DataSource is always used--in other words, JNDI and DataSource always seem to be used together (in Servlets). I have not found a case where JNDI is used by itself to access the Database--perhaps I'm not looking in the right place. Could you point me to some documentation maybe?
    Thanks a lot!

  • How to use DataSource and External transaction in 9ias?

    I'm working on a project that the application server needs to connect to over 100 databases.
    I'd like to use connection pooling and external transaction service defined in OC4J's Datasources.
    I wonder if anyone has an example of using datasource and external transaction service for OC4J.
    Right now, I export toplink project to a java source and do the initialization there manually but I don't know how to use Datasource to get connections and how to use the external transaction service in the java code for OC4J.
    I really appreciate you help.
    Wei

    Here is a fill in the blank example on how you could set this up through code:
    Project project = new MyProject();
    // alternatively, use the XMLProjectReader
    server = project.createServerSession();
    server.getLogin().useExternalConnectionPooling();
    server.getLogin().setConnector(new JNDIConnector(new javax.naming.InitialContext(), "jdbc/DataSourceName"));
    // the next line depends on the type of driver you want to use.
    server.getLogin().useOracleThinJDBCDriver();
    server.getLogin().useOracle();
    server.getLogin().setUserName("username");
    server.getLogin().setPassword("password");
    server.getLogin().useExternalTransactionController();
    server.setExternalTransactionController(new Oracle9iJTSExternalTransactionController());
    server.logMessages();
    server.login();

  • Problem using datasource in netbeans to get connection

    The method initialContext.lookup("java:comp/env/myDatabase");
    generated the following exception
    javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:247)
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:284)
    at javax.naming.InitialContext.lookup(InitialContext.java:351)
    at enterprise.Test2.getMyDatabase2(Test2.java:54)
    at enterprise.Test2.doTest(Test2.java:36)
    at enterprise.Test2.main(Test2.java:46)
    How do i resolve this

    I t could be the right forum , since javamail uses DataSource.
    It could be you need to say
    javax.swing.Activation.DataSource at the variable declaration not simply import and assume.
    There are various "DataSource" classes in java.
    Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initialAs it is, it appears to be the server configuration file/application web.xml or a JNDI association/environment has not been constructed to point to the classes to load.
    Edited by: nicephotog on Oct 30, 2008 10:57 AM

  • How can i using datasource in toplink's map file

    In the TopLink map :
    <toplink:login xsi:type="toplink:database-login">
    <toplink:platform-class>oracle.toplink.platform.database.oracle.Oracle10Platform</toplink:platform-class>
    <toplink:user-name>test</toplink:user-name> <toplink:password>C23487CFA591952D44310804F3D591CB</toplink:password>
    <toplink:sequencing>
    <toplink:default-sequence xsi:type="toplink:native-sequence">
    <toplink:preallocation-size>1</toplink:preallocation-size>
    </toplink:default-sequence>
    </toplink:sequencing>
    <toplink:driver-class>oracle.jdbc.driver.OracleDriver</toplink:driver-class>
    <toplink:connection-url>jdbc:oracle:thin:@192.168.0.1:1521:testdb</toplink:connection-url>
    <toplink:bind-all-parameters>true</toplink:bind-all-parameters>
    </toplink:login>
    How can i modify it using datasource?

    The login information stored in the map file is good for direct connection and design time login information.
    For your runtime login information I would use the sessions configuration (sessions.xml). It provides complete deployment configuration:
       <session>
          <name>my-session</name>
          <!-- This references the ORM map XML file -->
          <project-xml>META-INF/employee-basic.xml</project-xml>
          <session-type>
             <server-session/>
          </session-type>
          <login>
             <datasource>jdbc/TopLinkDS</datasource>
             <uses-external-connection-pool>true</uses-external-connection-pool>
             <uses-external-transaction-controller>true</uses-external-transaction-controller>
          </login>
          <external-transaction-controller-class>oracle.toplink.essentials.transaction.oc4j.Oc4jTransactionController</external-transaction-controller-class>
          <enable-logging>true</enable-logging>
          <logging-options>
             <log-exceptions>true</log-exceptions>
             <print-thread>false</print-thread>
             <print-date>false</print-date>
          </logging-options>
       </session>Doug

  • How to use datasources to connect to database ?

    I have the following Problem
    I have two identical databases, one is the development database, the other one the production database.
    Now I need to find a way, how I can deploy an bc4j-application in local mode that way, that if the application is deployed to server 1 it connects to database 1 and if deployed to server 2 it connects to database 2.
    JDBC connection strings do not work as the connection is deployed with the application. So the application always connects to the same database.
    I thought datasources might be the solution. So I tried to define a datasource MyDS in the data-sources.xml file and specified it in the Configuration Wizard as the connection to use.
    But unfortunately this does not work and i do not know why:
    If I try to connect using the tester and using this datasource I get the following exception:
    Level #3: javax.naming.noInitialContextException
    Can anyone help me, what this means? How can I get around this using the BC4J Framework? Is there any "HowTo" Document which describes using datasources with BC4J?

    Frank,
    I've sorted this stuff out to some extent. Have a look at this thread:
    re:? How: multiple myAppWar.ear to use OC4J's data-sources.xml pooling?
    If this isn't all you need, then search on data-source.xml
    and read other threads also I may have posted helps on
    other threads so if you search on data-source.xml and my handle (curt504) it brings up all the threads that I posted to.
    Not to say I've solved all your problems, but I solved mine anyway. :)
    Good luck,
    curt

  • Urg Problem with using DataSources in Tomcat

    I am trying to use DataSource in Tomcat4.0
    I have a simple jsp file as shown below:=
    <html>
    <head>
    <title>DB Test using DataSource</title>
    </head>
    <body>
    <%
    foo.DBTest dbt = new foo.DBTest();
    dbt.init();
    %>
    <h2>Results</h2>
    Foo <%= dbt.getFoo() %>
    Bar <%= dbt.getBar() %>
    </body>
    </html>
    and a Servlet by the name of DBTest as shown below:-
    package foo;
    import javax.naming.*;
    import javax.sql.*;
    import java.sql.*;
    public class DBTest
    String foo = "Not Connected";
    int bar = -1;
    public void init()
    try
         System.out.println("Inside INIT of DBTest");
    Context ctx = new InitialContext();
    Context envCtx = (Context)ctx.lookup("java:comp/env");
    if(ctx == null )
    throw new Exception("Boom - No Context");
    //DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/TestDB");
    DataSource ds = (DataSource)envCtx.lookup("jdbc/TestDB");
    if (ds != null)
    Connection conn = ds.getConnection();
    if(conn != null)
    foo = "Got Connection "+conn.toString();
    Statement stmt = conn.createStatement();
    ResultSet rst = stmt.executeQuery("select id, foo, bar from testdata");
    if(rst.next())
    foo=rst.getString(2);
    bar=rst.getInt(3);
    conn.close();
    }catch(Exception e)
    e.printStackTrace();
    }//end of init
    public String getFoo() { return foo; }
    public int getBar() { return bar;}
    }//end of class
    I modified my server.xml file to include this:=
    <!-- Tomcat My DataSource Testing Context -->
    <Context path="/DBTest" docBase="C:\Program Files\Apache Tomcat 4.0\webapps\DBTest"
    debug="5" reloadable="true" crossContext="true">
    <Logger className="org.apache.catalina.logger.FileLogger"
    prefix="localhost_DBTest_log." suffix=".txt"
    timestamp="true"/>
    <Resource name="jdbc/TestDB"
    auth="Container"
    type="javax.sql.DataSource"/>
    <ResourceParams name="jdbc/TestDB">
    <parameter>
    <name>factory</name>
    <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
    </parameter>
    <parameter>
    <name>maxActive</name>
    <value>5</value>
    </parameter>
    <parameter>
    <name>maxIdle</name>
    <value>2</value>
    </parameter>
    <parameter>
    <name>maxWait</name>
    <value>10000</value>
    </parameter>
    <parameter>
    <name>username</name>
    <value>system</value>
    </parameter>
    <parameter>
    <name>password</name>
    <value>manager</value>
    </parameter>
    <parameter>
    <name>driverClassName</name>
    <value>oracle.jdbc.OracleDriver</value>
    </parameter>
    <parameter>
    <name>url</name>
    <value>jdbc:oracle:thin:@localhost:1521:Test2</value>
    </parameter>
    </ResourceParams>
    </Context>
    <!-- Tomcat My DataSource Testing Context -->
    and my web.xml file is as shown below:=
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE web-app PUBLIC
    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
    <description>Oracle DataSource 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>
    Now when i start Tomcat and try to access the jsp page i get this error in Tomcat Console:=
    Inside INIT of DBTest
    javax.naming.NamingException: Cannot create resource instance
    at org.apache.naming.NamingContext.lookup(NamingContext.java:837)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:181)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:822)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:194)
    at foo.DBTest.init(DBTest.java:25)
    at org.apache.jsp.test$jsp._jspService(test$jsp.java:60)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:107)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at org.apache.jasper.servlet.JspServlet$JspServletWrapper.service(JspSer
    vlet.java:202)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:3
    82)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:474)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
    icationFilterChain.java:247)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
    ilterChain.java:193)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperV
    alve.java:243)
    at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline
    .java:566)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.jav
    a:472)
    at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextV
    alve.java:201)
    at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline
    .java:566)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.jav
    a:472)
    at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
    at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:
    2344)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.j
    ava:164)
    at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline
    .java:566)
    at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatche
    rValve.java:170)
    at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline
    .java:564)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.j
    ava:170)
    at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline
    .java:564)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:
    462)
    at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline
    .java:564)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.jav
    a:472)
    at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineVal
    ve.java:163)
    at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline
    .java:566)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.jav
    a:472)
    at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
    at org.apache.catalina.connector.http.HttpProcessor.process(HttpProcesso
    r.java:1011)
    at org.apache.catalina.connector.http.HttpProcessor.run(HttpProcessor.ja
    va:1106)
    at java.lang.Thread.run(Unknown Source)
    Why is this happening .
    I am making sure the resource name in server.xml and web.xml are the same
    Any Help highly appreciated
    Thanks
    Raj

    Hi rajess_kr,
    Looks to me like you're pretty close.
    I'm assuming that you've got the JDBC driver JAR in TOMCAT_HOME/common/lib. The JAR containing your data source factory class org.apache.commons.dbcp.BasicDataSourceFactory should be in that directory, too. Since you're using Oracle, I'd also suggest that you repackage classes12.zip as a JAR file if it's not already a JAR.
    I think the JNDI lookup string should be "java:comp/env/jdbc/TestDB".
    I've got a working example on my desktop at work, but I don't seem to have one here at home. I'll give it a look on Monday and see if I can provide more details. It looks to me like you're not very far off. - MOD

  • Specialty of supply function and  how can we use it efficiently?

    Hi Experts,
    I have one question.
    What exactly the function of “Supply function” for a node.
    Some says when ever lead change happens the “Supply function” triggers.
    I put a break point in Supply function say “ZSupply” written code to populate the table.
    It triggered only once to populate the table. If this is the functionality then I can write code in method and call it in modify view my checking it for first time why “supply function”.   I want to know what is its specialty, how can we use it efficiently?
    Thanks
    Gopal

    Hi Gopal,
    You are correct even without supply function you can achieve the same functionality i.e when ever there is a change in HEADER the corresponding ITEM for the HEADER can be displayed.
    But the idea of using SUPPLY Function is - the code written in the node i.e assume HEADER and ITEM relation gets executed as and when the node is instantiated in the run time where in there is no need us to handle it explicitly.
    If not used SUPPLY Function then we need to handle the complete HEADER and ITEM relation explicitly.
    Regards,
    Mohammed

  • Using DataSource in Websphere

    We are using websphere WAS and informix data base and while using DataSource for connection pooling we are getting a Forwarding exception and Illegal state exception apparently thrown by WAS and we tried getting over that by switching to Driver Manager instead of data source but that started giving a corba.rollback exception ! our whole implementation is running on WCS 5.1 using WAS and informix database. Any suggestions on why we are getting forwarding exceptions on using data source with WAS? we have registered the look up in the administrative console and there seems to be no problems with that. please let me know if there are any opinions regarding this. Thanks for your time.

    we are getting the error using the data source in a jsp/ejb . the error is actually printed out to a log file and this happens only when multiple users hit the server at the sam time and not when the server is interacting with a single user. we are somewhat stumped by this right now. i am pasting the actual error message in the log file below this. pls pardon me if that is too verbose ! you may see a writer stream not obtained message in it, but that does not seem to be the root cause , that comes since we had not set the printwriter object in the datasource and hence it is redirecting the actual message to screen rather than log file. Thanks for your time.
    An error has occurred: Error Code Message Target Servlet Name
    500 ERROR: Cannot forward. Writer or Stream already obtained. null
    Stack Trace:
    java.lang.IllegalStateException: ERROR: Cannot forward. Writer or Stream already obtained. at com.ibm.servlet.engine.webapp.WebAppRequestDispatcher.handleOutputStreamPrinterWriterObtained(WebAppRequestDispatcher.java:595) at com.ibm.servlet.engine.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:112) at com.ibm.commerce.command.HttpForwardViewCommandImpl.forwardDocument(HttpForwardViewCommandImpl.java) at com.ibm.commerce.command.HttpForwardViewCommandImpl.performExecute(HttpForwardViewCommandImpl.java(Compiled Code)) at com.ibm.commerce.command.ECCommandImpl.execute(ECCommandImpl.java) at com.ibm.commerce.webcontroller.ErrorCmdExecUnit.execute(ErrorCmdExecUnit.java) at com.ibm.commerce.webcontroller.WebController.executeTransaction(WebController.java(Compiled Code)) at com.ibm.commerce.webcontroller.WebController.processRequest(WebController.java) at com.ibm.commerce.adapter.HttpAdapterImpl.processRequest(HttpAdapterImpl.java) at com.ibm.commerce.server.RequestServlet.service(RequestServlet.java) at javax.servlet.http.HttpServlet.service(HttpServlet.java:853) at com.ibm.servlet.engine.webapp.StrictServletInstance.doService(ServletManager.java:626) at com.ibm.servlet.engine.webapp.StrictLifecycleServlet._service(StrictLifecycleServlet.java:160) at com.ibm.servlet.engine.webapp.IdleServletState.service(StrictLifecycleServlet.java:287) at com.ibm.servlet.engine.webapp.StrictLifecycleServlet.service(StrictLifecycleServlet.java:105) at com.ibm.servlet.engine.webapp.ServletInstance.service(ServletManager.java:360) at com.ibm.servlet.engine.webapp.ValidServletReferenceState.dispatch(ServletManager.java:775) at com.ibm.servlet.engine.webapp.ServletInstanceReference.dispatch(ServletManager.java:701) at com.ibm.servlet.engine.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:478) at com.ibm.servlet.engine.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:234) at com.ibm.servlet.engine.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:138) at com.ibm.servlet.engine.srt.WebAppInvoker.handleInvocationHook(WebAppInvoker.java:77) at com.ibm.servlet.engine.invocation.CachedInvocation.handleInvocation(CachedInvocation.java:67) at com.ibm.servlet.engine.srp.ServletRequestProcessor.dispatchByURI(ServletRequestProcessor.java:155) at com.ibm.servlet.engine.oselistener.OSEListenerDispatcher.service(OSEListener.java:300) at com.ibm.servlet.engine.oselistener.SQEventListenerImp$ServiceRunnable.run(SQEventListenerImp.java:230) at com.ibm.servlet.engine.oselistener.SQEventListenerImp.notifySQEvent(SQEventListenerImp.java:104) at com.ibm.servlet.engine.oselistener.serverqueue.SQEventSource.notifyEvent(SQEventSource.java:212) at com.ibm.servlet.engine.oselistener.serverqueue.SQWrapperEventSource$SelectRunnable.notifyService(SQWrapperEventSource.java:353) at com.ibm.servlet.engine.oselistener.serverqueue.SQWrapperEventSource$SelectRunnable.run(SQWrapperEventSource.java:220) at com.ibm.servlet.engine.oselistener.outofproc.OutOfProcThread$CtlRunnable.run(OutOfProcThread.java(Compiled Code)) at java.lang.Thread.run(Thread.java:481)
    Root Cause: java.lang.IllegalStateException: ERROR: Cannot forward. Writer or Stream already obtained.
    **************************************************************

  • Help! use DataSource in Tomcat

    I configure server.xml and web.xml in tomcat to use DataSource
    server.xml is
    <Resource name="jdbc/jsptest" auth="Container"
                   type="javax.sql.DataSource"/>
                   <ResourceParams name="jdbc/jsptest">                    
    <parameter><name>user</name><value>aa</value></parameter>
    <parameter><name>password</name><value>aa</value></parameter>
    <parameter><name>driverClassName</name>
    <value>sun.jdbc.odbc.JdbcOdbcDriver</value></parameter>
    <parameter><name>driverName</name>
    <value>jdbc:odbc:ejbtest</value></parameter>
    </ResourceParams>
    and the web.xml is
    <web-app>
    <resource-ref>
    <description>Resource reference to a factory for java.sql.Connection instances that may be used for talking to a particular database that is configured in the server.xml file.</description>
    <res-ref-name>jdbc/jsptest</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Sharable</res-sharing-scope>
    </resource-ref>
    </web-app>
    but ,when I run my jsp ,it always throws
    TyrexDataSourceFactory: Cannot create DataSource, Exception
    java.lang.ClassNotFoundException: org.hsql.jdbcDriver
    I didn't use org.hsql.jdbcDriver ,so I change other jdbc Drivers and receive same
    result,why?
    Thank everyone ,it drives me crazy!

    Dear kbpv43a
    here iam facing the same problem as "ClassNotFoundException: org.hsql.JDBCDriver" even after iam using thin driver for oracle database. i already commented as i dont know where i missed to close
    the /> end tag. but still its throwing the same exception.
    can u please help me by just going through my program and suggest me
    where i committed mistake..??
    here are my server.xml,web.xml and servletApplication for gettting conection from the pool using thin driver for oracle using Tomcat4.0.4
    version.
    thanx.
    server.xml
    <Server port="8005" shutdown="SHUTDOWN" debug="0">
              <!-- Tomcat Stand-Alone Service -->
    <Service name="Tomcat-Standalone">
         <!-- Non-SSL HTTP/1.1 Connector on port 8080 -->
    <Connector className="org.apache.catalina.connector.http.HttpConnector"
    port="8080" minProcessors="5" maxProcessors="75"
    enableLookups="true" redirectPort="8443"
    acceptCount="10" debug="0" connectionTimeout="60000"/>
              <!-- AJP 1.3 Connector on port 8009 -->
    <Connector className="org.apache.ajp.tomcat4.Ajp13Connector"
    port="8009" minProcessors="5" maxProcessors="75"
    acceptCount="10" debug="0"/>
              <!-- 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"/>
         <!-- Because this Realm is here, an instance will be shared globally
              <Realm className="org.apache.catalina.realm.MemoryRealm" /> -->
    <Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
              driverName="oracle.jdbc.driver.OracleDriver"
                   connectionURL="jdbc:oracle:thin:@oracle:1521:ORCL"
    connectionName = "mail"
    connectionPassword = "mail"
              userTable="users" userNameCol="user_name" userCredCol="user_pass"
                   userRoleTable="user_roles" roleNameCol="role_name" />
                   <!-- Define the default virtual host -->
    <Host name="localhost" debug="1" appBase="webapps" unpackWARs="true">
         <Valve className="org.apache.catalina.valves.AccessLogValve"
         directory="logs" prefix="localhost_access_log." suffix=".txt"
         pattern="common"/>
    <Logger className="org.apache.catalina.logger.FileLogger"
    directory="logs" prefix="localhost_log." suffix=".txt"
         timestamp="true"/>
                   <!-- Tomcat Root Context -->
                   <!-- Tomcat Manager Context -->
    <Context path="/manager" docBase="manager" debug="0" privileged="true"/>
    <!-- My context, username=good and password=bad for my oracle to connect -->
         <Context path="/localhost" docBase="localhost" debug="0" reloadable="false" override="true">
              <Resource name="jdbc/myConnection" auth="Container" type="javax.sql.DataSource"/>
              <ResourceParams name="jdbc/myConnection">
                   <parameter><name>user</name><value>good</value></parameter>
                   <parameter><name>password</name><value>bad</value></parameter>
                   <parameter><name>driverClassName</name><value>oracle.jdbc.driver.OracleDriver</value></parameter>
                   <parameter>
                        <name>url</name>
                        <value>jdbc:oracle:thin:@oracle:1521:ORCL</value>
                   </parameter>
                   <parameter>
                        <name>maxActive</name>
                        <value>32</value>
                   </parameter>
                   <parameter>
                        <name>maxIdle</name>
                        <value>10</value>
                   </parameter>
              </ResourceParams>
    <!-- end of MY Context -->
                   <!-- Tomcat Examples Context
    <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>user</name><value>sa</value></parameter>
    <parameter><name>password</name><value></value></parameter>
    <parameter><name>driverClassName</name><value>org.hsql.jdbcDriver</value></parameter>
    <parameter><name>driverName</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>
    -->
    </Context>
    </Host>
    </Engine>
    </Service>
         <!-- Define an Apache-Connector Service -->
    <Service name="Tomcat-Apache">
    <Connector className="org.apache.catalina.connector.warp.WarpConnector"
    port="8008" minProcessors="5" maxProcessors="75"
    enableLookups="true" appBase="webapps"
    acceptCount="10" debug="0"/>
    <Engine className="org.apache.catalina.connector.warp.WarpEngine"
    name="Apache" debug="0">
    <Logger className="org.apache.catalina.logger.FileLogger"
    prefix="apache_log." suffix=".txt"
    timestamp="true"/>
              <Realm className="org.apache.catalina.realm.MemoryRealm" />
    </Engine>
    </Service>
    </Server>
    web.xml
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
    <servlet>
    <servlet-name>conServlet</servlet-name>
    <servlet-class>conServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>conServlet</servlet-name>
    <url-pattern> /conServlet </url-pattern>
    </servlet-mapping>
    <resource-ref>
    <description> Resource reference to java.sql.Connection
    factory defined in server.xml
    </description>
    <res-ref-name>jdbc/myConnection</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>
    </web-app>
    Servlet Application:
    public void service(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
         res.setContentType("text/html");
         PrintWriter out = res.getWriter();
    //Ordinary jdbc connection      
                   //DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                   //con=DriverManager.getConnection("jdbc:oracle:thin:@oracle:1521:ORCL","mail","mail");
                   //out.println("Your con=="+con);
    try
    // jdbc connection from pool
         Context initCtx = new InitialContext();
    Context envCtx = (Context)initCtx.lookup("java:/comp/env");
    DataSource ds = (DataSource)envCtx.lookup("jdbc/myConnection");
    conn = ds.getConnection();
         out.println("conn : " + conn);
    conn.close();
         catch (Exception e)
         out.println("conn failed : " + e);
    Note: my oralce username is "good" and password is "bad"
    here

  • Using Datasource with Toplink

    Hi,
    I am using toplink 10.1.3 .We are using the datasource to connect to weblogic connection pool.
    My session.xml is like this:
    - <login xsi:type="database-login">
    <platform-class>oracle.toplink.platform.database.oracle.Oracle10Platform</platform-class>
    <user-name />
    <datasource>jdbc/ds</datasource>
    </login>
    In the java DAO part,I need a physical database connection to get the ArrayDescriptor.The part of java code is below
    java.sql.Connection dbconnection=null;
    DatabaseLogin login = serverSession.getLogin();
    dbconnection=(java.sql.Connection)login.connectToDatasource(null);
    Questions:
    1.Is the above correct way to get the Physical JDBC connection from a weblogic connection pool(configured using datasource).
    2.How will the Connection released to the pool?Should i use dbconnection.close() or clientSession.release().
    Thanks

    Thanks doug for your reply.
    I am using datasource to connect to the weblogic 9.2 connection pool.
    My specific use case is this.
    I am executing a Stored procedure which will takes a Oracle user defined data type as an Input paramater.
    some steps we use in the java code for the above use case.
    --Getting the  toplink session
    ServerSession serverSession = TopLinkGenericDAO.getSession();
    clientSession = serverSession.acquireClientSession();
    --For getting the oracle user defined array
    java.sql.Connection dbconnection=null;
    DatabaseLogin login = serverSession.getLogin();
    dbconnection=(java.sql.Connection)login.connectToDatasource(null);
    oracle.sql.ArrayDescriptor descriptor = new oracle.sql.ArrayDescriptor(
    "STRING_ARRAY", dbconnection);
    oracle.sql.ARRAY arr_ORCL = new oracle.sql.ARRAY(descriptor,
    dbconnection, aIncl_Vin);
    --for executing stored procedure
    StoredProcedureCall call = new StoredProcedureCall();
    DataReadQuery dbquery = new DataReadQuery();
    call.setProcedureName(CVeITDAOConstants.INSERT_PING);
    call.addNamedArgumentValue("para1", arr_ORCL );
    dbquery.setCall(call);
    --release connection in the finally block
    finally
    clientSession.release();
    dbconnection.close();
    The above code fails when we execute it for 150 concurrent connection(using JMeter) with connection fail exception.
    Please let me know how do i release the physical jdbc connection(dbconnection) in the finally block.
    do we need to give dbconnection.close() or just by giving clientSession.release() will also release the jdbc connection.
    Thanks.

  • How can i use connectionfactory efficiently?

    i am wondering about the connection factory Object in jms.it may be used by one or more client.So how can i use it efficiently, each client have a connection factory or all of clients use the only one. pls tell me the truth,and thanks a lot !

    Connection Factory is an administered Object and ideally should be shared between n number of users. (1<=n<=Total Number of users).
    There are some connection factory which are used for administrative purposes. Only the administrators of the JMS server can access them.
    JMS server can run on different protocols or more than one transport protocol (HTTP , TCP, HTTPS etc). So client can use the connection factory depending upon the protocol with which it can communicate.
    Also the connect URL in the connection factory can be different. So one connection factory may be responsible for connections on JMS server1 and other may be responsible for connections on JMS server2.
    Also check out your vendors documentation to know more about the power of Connection factories.

  • Using Datasource in OC4J  to connect to 9iDb(ArrayIndexOutOfBoundsException

    Hi all,
    I've been encountering a certain ArrayIndexOutOfBoundsException when attempting to connect to Oracle 9i
    via a defined datasource.
    I've taken the following troubleshooting steps but to no avail:
    1. Verified username and password
    2. Verified URL by having a test class to establish a direct connection using this URL
    3. Verified that both classes12.jar and ocrs12.jar are defined in the classpath
    3. Updated classes12.jar and ocrs12.jar from the OTN to copies stipulated to be compliant with 9.2.0.1
    (this was based on a post on the net with reference to similar error messages:http://www.orafaq.net/msgboard/java/messages/1488.htm)
    It would be great if anyone could have some input on this problem.
    Thanks!
    WK
    My development environment:
    Oracle Database 9.2.0.1
    oc4j
    The following configuration and code snippets are provided for reference:
    data-sources.xml
         <data-source
              class="com.evermind.sql.DriverManagerDataSource"
              name="OraclePool"
              location="jdbc/OracleCoreDS"
              xa-location="jdbc/xa/OracleXADS"
              ejb-location="jdbc/OracleDS"
              connection-driver="oracle.jdbc.driver.OracleDriver"
              username="USER"
              password="PASSWORD"
              inactivity-timeout="30"
              url="jdbc:oracle:thin:@localhost:1521:OracleDb"
    />
    Client Code:
    InitialContext ic = new InitialContext();
    DataSource ds = (DataSource)ic.lookup("jdbc/OracleDS");
    Connection conn = ds.getConnection();
    Statement stmt = conn.createStatement();
    String strQuery = "SELECT id FROM TBL_PART";
    ResultSet rset = stmt.executeQuery (strQuery);
    Error:
    java.lang.ArrayIndexOutOfBoundsException
         at oracle.security.o3logon.C1.r(C1)
         at oracle.security.o3logon.C1.l(C1)
         at oracle.security.o3logon.C0.c(C0)
         at oracle.security.o3logon.O3LoginClientHelper.getEPasswd(O3LoginClientHelper)
         at oracle.jdbc.ttc7.O3log.<init>(O3log.java:290)
         at oracle.jdbc.ttc7.TTC7Protocol.logon(TTC7Protocol.java:251)
         at oracle.jdbc.driver.OracleConnection.<init>(OracleConnection.java:252)
         at oracle.jdbc.driver.OracleDriver.getConnectionInstance(OracleDriver.java:365)
         at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:260)
         at com.evermind[Oracle9iAS (1.0.2.2) Containers for J2EE].sql.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:118)
         at com.evermind[Oracle9iAS (1.0.2.2) Containers for J2EE].sql.DriverManagerConnectionPoolDataSource.getPooledConnection(DriverManagerConnectionPoolDataSource.java:24)
         at com.evermind[Oracle9iAS (1.0.2.2) Containers for J2EE].sql.OrionPooledDataSource.getPooledConnection(OrionPooledDataSource.java:273)
         at com.evermind[Oracle9iAS (1.0.2.2) Containers for J2EE].sql.PooledConnectionUsage.getPooledConnection(PooledConnectionUsage.java:21)
         at com.evermind[Oracle9iAS (1.0.2.2) Containers for J2EE].sql.OrionPooledDataSource.getConnection(OrionPooledDataSource.java:145)
         at com.evermind[Oracle9iAS (1.0.2.2) Containers for J2EE].sql.DriverManagerXADataSource.getAutoCommitConnection(DriverManagerXADataSource.java:226)
         at com.evermind[Oracle9iAS (1.0.2.2) Containers for J2EE].sql.LogicalDriverManagerXAConnection.intercept(LogicalDriverManagerXAConnection.java:88)
         at com.evermind[Oracle9iAS (1.0.2.2) Containers for J2EE].sql.FilterConnection.createStatement(FilterConnection.java:324)
         at com.evermind[Oracle9iAS (1.0.2.2) Containers for J2EE].sql.FilterConnection.createStatement(FilterConnection.java:325)

    Hi WK,
    According to your stack trace, you are using a very old version of OC4J. I suggest updating to the latest, production version: 9.0.3
    Also, I seem to recall reading somewhere (I think it was in this forum), that "DataSource" is not serializable, and therefore cannot be transferred to the client.
    I use "DataSource" in my BMP entity beans to interact with the database -- this works fine. I have not tried getting a "DataSource" from a remote client, though.
    And also you may need to pass some "properties" to your "InitialContext" constructor -- depending on the type of client you are using (which I could not ascertain from your post).
    Hope this has helped you.
    Good Luck,
    Avi.

  • How to improve the load performance while using Datasources for the Invoice

    HI All,
    How to improve the  load performance while using Datasources for the Invoice . Actually my invoice load (Appx. 0.4 M records) is taking very long time nearly ~16 to 18 hrs  to update data from R/3 to 0ASA_DS01.
    If I load through flat file it will load with in ~20 Min for the same amount of data.
    Please suggest how to improve load performance.
    PS: I have done the Inpo package settings as per the OSS note.
    Regads
    Srininivasarao.Namburi.

    Hi Srinivas,
    Please refer to my blog posting [/people/divyesh.jain/blog/2010/07/20/package-size-in-spend-performance-management-extraction|/people/divyesh.jain/blog/2010/07/20/package-size-in-spend-performance-management-extraction] which gives the details about the package size setting for extractors. I am sure that will be helpful in your case.
    Thanks,
    Divyesh
    Edited by: Divyesh Jain on Jul 20, 2010 8:47 PM

  • Retrieve db connection using datasource object

    The problem is: i can't retrieve the connection to database
    using datasource object in jsp.
    my jsp was build by Oracle9i Report Builder,then deployed
    to OC4J jsp container,
    i define the datasource at container level,
    but an error "log on not specified" arise.
    is it possible to use datasource object in such a way or not?
    thanks you for your help.

    What is the full Java and os versions you are using to compile and to run. Note that with JDEV the platform used for your code may be different than the platform used by JDEV itself.
    Please modify all of your exception handlers to print the stack trace. Add this as the first line in each handler.
    ex.printStackTrace();The stacktrace contains important information about where the problem really occured.
    See the Java docs for NamingException - http://docs.oracle.com/javase/6/docs/api/javax/naming/NamingException.html
    >
    This is the superclass of all exceptions thrown by operations in the Context and DirContext interfaces. The nature of the failure is described by the name of the subclass. This exception captures the information pinpointing where the operation failed, such as where resolution last proceeded to.
    •Resolved Name. Portion of name that has been resolved.
    •Resolved Object. Object to which resolution of name proceeded.
    •Remaining Name. Portion of name that has not been resolved.
    •Explanation. Detail explaining why name resolution failed.
    •Root Exception. The exception that caused this naming exception to be thrown.

Maybe you are looking for