Why use Datasource & JNDI

HI
I am novice to the JNDI. I searched a few documents but did not find a right anwser. my question is , why do we need DataSource through JNDI. I think we need it to connect diffreent kind of resources. but think of a situation where my JDBC connetionpooling class resides on same JVM that of my application. in this case do I need to use datasource & JNDI name then bind it to the class or I can use the class directly by passing JNDI.
which one will be better & why

Hi,
The nice thing about JNDI is that you can write your application in a way that is independent of the details needed to setup and connect (user, passwd, URL, drivername etc) to the database.
In a typical J2EE server, the setup is done by a human administrator, using the appserver tools. This administrator needs to have little or no knowledge about your application, simply because the setup and the usage of the drivers are cleanly separated through JNDI in the middle.
In turn, your application can be perfectly portable across different servers, different databases with different drivers and user accounts, and you don't need to change your code in order to do that (at least not in principle).
Even if your application runs in the same VM, there are some virtues to this separation.
Best,
Guy
http://www.atomikos.com - JTA, JNDI and DataSource support for J2SE, J2EE and Tomcat

Similar Messages

  • How do I use a JNDI datasource in my application?

    Not sure how to access the JNDI datasource i setup in my config.xml. I tried to browse it at rmi://localhost:1099/ but it only shows jmxrmi in the tree.
    My config.xml looks like
    <n1:config xsi:schemaLocation="http://www.bea.com/ns/wlevs/config/server wlevs_server_config.xsd" xmlns:n1="http://www.bea.com/ns/wlevs/config/server" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <netio>
        <name>NetIO</name>
        <port>9002</port>
      </netio>
      <work-manager>
        <name>JettyWorkManager</name>
        <min-threads-constraint>5</min-threads-constraint>
        <max-threads-constraint>10</max-threads-constraint>
      </work-manager>
      <jetty>
        <name>JettyServer</name>
        <network-io-name>NetIO</network-io-name>
        <work-manager-name>JettyWorkManager</work-manager-name>
      </jetty>
      <rmi>
        <name>RMI</name>
        <http-service-name>JettyServer</http-service-name>
      </rmi>
      <jndi-context>
        <name>JNDI</name>
      </jndi-context>
      <exported-jndi-context>
        <name>exportedJndi</name>
        <rmi-service-name>RMI</rmi-service-name>
      </exported-jndi-context>
      <jmx>
        <jndi-service-name>JNDI</jndi-service-name>
        <rmi-service-name>RMI</rmi-service-name>
        <rmi-registry-port>1099</rmi-registry-port>
        <rmi-jrmp-port>9999</rmi-jrmp-port>
      </jmx>
      <transaction-manager>
          <name>transactionmanager</name>
          <!--max-resource-requests-on-server>1</max-resource-requests-on-server>
          <max-resource-unavailable-millis>1000</max-resource-unavailable-millis-->
      </transaction-manager>
      <data-source>   
          <name>hqsqlconn</name>   
          <driver-params>     
            <url>jdbc:hsqldb:hsql://localhost/wlevdb</url>
            <driver-name>org.hsqldb.jdbcDriver</driver-name>
            <properties>
              <element>
                <name>user</name>
                <value>sa</value>
              </element>
              <element>
                <name>password</name>
                <value></value>
              </element>
            </properties>
            <use-xa-data-source-interface>true</use-xa-data-source-interface>   
          </driver-params>   
          <connection-pool-params>     
            <initial-capacity>1</initial-capacity>     
            <max-capacity>5</max-capacity>     
            <test-table-name>test_table</test-table-name>   
          </connection-pool-params>   
          <data-source-params>     
            <jndi-names>
              <element>hqsqlconn</element>
            </jndi-names>
            <global-transactions-protocol>TwoPhaseCommit</global-transactions-protocol>
          </data-source-params> 
      </data-source>
    </n1:config>

    I see what you are saying.
    The JNDI approach should work-we will try to reproduce this internally.
    I would recommend leveraging the OSGi service registry, instead of using JNDI, however. The Event Server is a modular server based on OSGi, so one should use the OSGi service registry whenever possible instead of using the jndi registry. Jndi is primarily there to support legacy code that requires Jndi.
    Any data sources that you configure are automatically registered in the OSGi service registry. When there is more than one data source they can be distinguished using their name.
    There are a couple of options.
    If you want to inject a reference to your datasource into a Spring bean, you can use an annotation, @Service, to annotate a setter method on your bean (see my previous post). The container will then inject a reference to the data source into the bean.
    You can also put the following in your spring application context file
    <osgi:reference id="myDataSource"
    interface="javax.sql.DataSource"/>
    This creates a bean proxy that references the datasource by looking up the datasource in the OSGi service registry. It works similarly to JndiObjectFactoryBean, but it uses the OSGi service registry instead of the JNDI registry. You can read more about it here
    http://www.springframework.org/osgi/specification
    (Look in section 3.3)
    Hope that helps.
    Seth
    Edited by swhite at 08/01/2007 6:19 PM

  • 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

  • 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

  • Using Datasources with Weblogic 7.2

    Hi everyone,
    I am using Weblogic 7.2 with Db2 8.1 fp3(Type 4 Drivers). I am wanting
    to set up a Datasource that would allow my application to connect to
    DB2 using the JNDI lookup for that data-source.
    My question is: what additions/changes I need to make to config.xml in
    order to set this up.Looking at the Websphere Admin Doc, it seems to
    me that I need to atleast add 2 elements to my domain in config.xml:
    1. JDBCConnectionPool
    2. JDBCDataSource(and link it to the above pool)
    I have previously set-up datasources on WAS 5.0. What is confusing me
    w.r.t Weblogic is that there seems to be no way to specify the
    implementing class for the DataSource. e.g. WAS5.0 allows you to
    specify the implementationClassName of the
    datasource(com.ibm.db2.jcc.DB2ConnectionPoolDataSource in my case) while
    defining the DataSource.JDBCConnectionPool element in Weblogic does
    have an attribute called "DriverName" but per the documentation it
    should be set to an implementor of java.sql.Driver interface: there
    seems to be no way to set an implementor of javax.sql.DataSource
    anywhere.
    Could anyone please shed some light on how to set this up?
    Thanks much in advance,
    Sachin

    Mitesh,
    Many thanks for the reply. If you don't mind, I have a couple of follow-up questions
    for you.
    1> Does this mechanism work with Type 4 Pure Java Drivers?
    e.g. if I specified the connection pool as
    <JDBCConnectionPool DriverName="com.ibm.db2.jcc.DB2ConnectionPoolDataSource" Name="IBM-db2"
    Password="MYPASSWORD" Properties="user=USERNAME;DatabaseName=DATABASE" Targets="MYSERVER"
    TestTableName="SQL SELECT COUNT(*) FROM SYSIBM.SYSTABLES" URL="jdbc:db2:DATABASE"/>
    ==> I changed the DriverName to "com.ibm.db2.jcc.DB2ConnectionPoolDataSource"
    which
    is what I believe is the Type-4 version
    2> Setting the DriverName to a javax.sql.DataSource extension seems to suggest
    that the documentation in the "BEA Server Configuration Reference" guide is incorrect:
    -- For the DriverName attribute of the Connection Pool, the guide says that "DriverName
    must be the name of a class that implements the java.sql.Driver interface"
    Thanks again
    Sachin
    Mitesh Patel <[email protected]> wrote:
    <JDBCConnectionPool DriverName="COM.IBM.db2.jdbc.DB2XADataSource"
    Name="IBM-db2-xa"
    Password="MYPASSWORD"
    Properties="user=USERNAME;DatabaseName=DATABASE"
    Targets="MYSERVER"
    TestTableName="SQL SELECT COUNT(*) FROM SYSIBM.SYSTABLES"
    URL="jdbc:db2:DATABASE"/>
    <JDBCConnectionPool DriverName="COM.IBM.db2.jdbc.app.DB2Driver"
    Name="IBM-db2"
    Password="MYPASSWORD"
    Properties="user=USERNAME;DatabaseName=DATABASE"
    Targets="MYSERVER"
    TestTableName="SQL SELECT COUNT(*) FROM SYSIBM.SYSTABLES"
    URL="jdbc:db2:DATABASE"/>
    Then setup your datasource using one of this connection pools in your
    config.xml. Also, make sure your driver zip files are in the classpath.
    Thanks,
    Mitesh
    Sachin Arora wrote:
    Hi everyone,
    I am using Weblogic 7.2 with Db2 8.1 fp3(Type 4 Drivers). I am wanting
    to set up a Datasource that would allow my application to connect to
    DB2 using the JNDI lookup for that data-source.
    My question is: what additions/changes I need to make to config.xmlin
    order to set this up.Looking at the Websphere Admin Doc, it seems to
    me that I need to atleast add 2 elements to my domain in config.xml:
    1. JDBCConnectionPool
    2. JDBCDataSource(and link it to the above pool)
    I have previously set-up datasources on WAS 5.0. What is confusingme
    w.r.t Weblogic is that there seems to be no way to specify the
    implementing class for the DataSource. e.g. WAS5.0 allows you to
    specify the implementationClassName of the
    datasource(com.ibm.db2.jcc.DB2ConnectionPoolDataSource in my case)while
    defining the DataSource.JDBCConnectionPool element in Weblogic does
    have an attribute called "DriverName" but per the documentation it
    should be set to an implementor of java.sql.Driver interface: there
    seems to be no way to set an implementor of javax.sql.DataSource
    anywhere.
    Could anyone please shed some light on how to set this up?
    Thanks much in advance,
    Sachin

  • 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 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

  • Changing user password in Active Directory using the JNDI GSS-API/Kerberos5

    Hello,
    I am trying to the JNDI GSS-API to change a user password on an Active Directory Server 2003. I have seen a variation of this using SSL on the thread [*http://forums.sun.com/thread.jspa?threadID=592611&start=0&tstart=0*|http://forums.sun.com/thread.jspa?threadID=592611&start=0&tstart=0]
    but I can't seem to make this work using the GSS-API. I can successfully create a javax.security.auth.login.LoginContext.LoginContext and then call the login method on it to log in as a user. I then call the javax.security.auth.Subject.doAs() method which calls the run method in a class extending the javax.security.PrivilegedActionClass. But when I actually try to change the password using InitialDirContext.modifyAttributes(), I get the exception:
    *javax.naming.OperationNotSupportedException: [LDAP: error code 53 - 00002077: SvcErr: DSID-03190DC9, problem 5003 (WILL_NOT_PERFORM), data 0*
    *If anyone can help me figure out why it doesn't work, that would be great!*
    P.S: I know the error seems to suggest that there might be some active directory setting that is preventing this from working, but I've checked all relevant settings on the Windows 2003 server Active Directory that I can think of: In the User properties->Account->Account options, I've made sure the user can change password. Also, in the Group Policy->Computer Configuration->Windows Settings->Security Settings->Account Policies->Password Policy, Maximum password age is zero and so is minimum password age.
    Here's my java code:
    {code}import javax.naming.*;
    import javax.security.auth.*;
    import java.security.PrivilegedAction;
    import java.io.UnsupportedEncodingException;
    public void changeSecret((String uid, String oldPassword, String newPassword)
         throws NamingException, ACException{
    try {
         K5CallbackHandler cb = new K5CallbackHandler(uid, oldPassword);
         LoginContext lc = new LoginContext("marker", cb);
         lc.login();
         Subject.doAs(lc.getSubject(), new ChangePasswordAction(rz.getName(), oldPassword, newPassword));
         catch(LoginException e) {
         try {
              lc.logout();
         catch(LoginException e) {
    }ChangePasswordAction.java is:import javax.naming.*;
    import javax.naming.naming.directory.*;
    import java.io.UnsupportedEncodingException;
    private class ChangePasswordAction implements PrivilegedAction {
         private String uid;
         private String quotedOldPassword;
         private String quotedNewPassword;
         public ChangePasswordAction(String uid, String oldPassword, String newPassword) {
              this.uid = uid;
              quotedOldPassword = "\"" + oldPassword + "\"";
              quotedNewPassword = "\"" + newPassword + "\"";
         public Object run() {
              Hashtable env = new Hashtable(11);
              env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
              env.put(Context.PROVIDER_URL, "ldap://ad2k3:389");
              env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
              try {
                   DirContext ctx = new InitialDirContext(env);
                   ModificationItem[] mods = new ModificationItem[2];
                   byte[] oldPasswordUnicode = quotedOldPassword.getBytes("UTF-16LE");
                   byte[] newPasswordUnicode = quotedNewPassword.getBytes("UTF-16LE");
                   mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("unicodePwd", oldPasswordUnicode));
                   mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("unicodePwd", newPasswordUnicode));
                   ctx.modifyAttributes(uid, mods);
                   ctx.close();
              } catch (NamingException e) {
              } catch (UnsupportedEncodingException e) {
              return null;
    }K5CallbackHandler is:import javax.security.auth.callback.*;
    final class K5CallbackHandler
    implements CallbackHandler {
         private final String name;
         private final char[] passwd;
         public K5CallbackHandler(String nm, String pw) {
              name = nm;
              if(pw == null) {
                   passwd = new char[0];
              else {
                   passwd = pw.toCharArray();
         public void handle(Callback[] callbacks)
         throws java.io.IOException, UnsupportedCallbackException {
              for(int i = 0; i < callbacks.length; i++) {
                   if(callbacks[i] instanceof NameCallback) {
                        NameCallback cb = (NameCallback) callbacks;
                        cb.setName(name);
                   else {
                        if(callbacks[i] instanceof PasswordCallback) {
                             PasswordCallback cb = (PasswordCallback) callbacks[i];
                             cb.setPassword(passwd);
                        else {
                             throw new UnsupportedCallbackException(callbacks[i]);
    }The relevant entry in the JAAS.conf file that is referred to as "marker" in the LoginContext constructor is:
    marker {
    com.sun.security.auth.module.Krb5LoginModule required client=TRUE;

    This is one of the two Active Directory operations I have never solved using Java/JNDI. (FYI the other one is Cross Domain Move).
    My gut feel is that the underlying problem (which happens to be common to both Change Password & X-Domain Move) is that Java/JNDI/GSSAPI does not negotiate a sufficiently strong key length that allows Active Directory to change passwords or perform cross domain moves when using Kerberos & GSSAPI.
    Active Directory requires at a minimum, 128 bit key lengths for these security related operations.
    In more recent Kerberos suites and Java versions, support for RC4-HMAC & AES has been introduced, so it may be possible that you can negotiate a suitably string key length.
    Make sure that your Kerberos configuration is using either RC4-HMAC or AES and that Java is requesting a strong level of protection. (You can do this by adding //Specify the quality of protection
    //Eg. auth-conf; confidentiality, auth-int; integrity
    //confidentiality is required to set a password
    env.put("javax.security.sasl.qop","auth-conf");
    //require high strength 128 bit crypto
    env.put("javax.security.sasl.strength","high"); in your ChangePasswordAction class.
    You may also want to enable sasl logging in your app to see what exactly is going on and you may also want to check on the Java Security forum how to configure/enforce/check both RC4-HMAC or AES is used as the Kerbeos cipher suite and that a string key length is being used.
    Good luck.

  • Connect JBOSS to MySQL using datasource,both servers are on different machi

    HI,
    In my application, I use JBOSS server and MySQL database.JBOSS and MySQL server are on two different machines.I am using mysql datasource,not driver manager to get the connection. i configured mysql-ds.xml and put it in %JBOSS_HOME%\server\default\deploy directory.
    I have also put the mysql connector jar in the %JBOSS_HOME%\server\default\lib directory.
    mysql-ds.xml file
    <?xml version="1.0" encoding="UTF-8"?>
    <!-- $Id: mysql-ds.xml 41016 2006-02-07 14:23:00Z acoliver $ -->
    <!-- Datasource config for MySQL using 3.0.9 available from:
    http://www.mysql.com/downloads/api-jdbc-stable.html
    -->
    <datasources>
    <local-tx-datasource>
    <jndi-name>JBossAtWorkDS</jndi-name>
    <connection-url>jdbc:mysql://192.168.1.3:3306/JBossAtWorkDS</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>sa</user-name>
    <password></password>
    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
    <!-- should only be used on drivers after 3.22.1 with "ping" support
    <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
    -->
    <!-- sql to call when connection is created
    <new-connection-sql>some arbitrary sql</new-connection-sql>
    -->
    <!-- sql to call on an existing pooled connection when it is obtained from pool - MySQLValidConnectionChecker is preferred for newer drivers
    <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
    -->
    <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
    <metadata>
    <type-mapping>mySQL</type-mapping>
    </metadata>
    </local-tx-datasource>
    </datasources>
    code to make the connection is as follows...
    public class JDBCCarDAO implements CarDAO
    private List carList;
    private static final String DATA_SOURCE="java:comp/env/jdbc/JBossAtWorkDS";
    public JDBCCarDAO()
    public List findAll()
    List carList = new ArrayList();
    DataSource dataSource = null;
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try
    dataSource = ServiceLocator.getDataSource(DATA_SOURCE);
    conn = dataSource.getConnection();
    stmt = conn.createStatement();
    stmt.execute("select * from CAR");
         rs = stmt.getResultSet();
    while(rs.next())
    CarDTO car = new CarDTO();
    car.setMake(rs.getString("MAKE"));
    car.setModel(rs.getString("MODEL"));
    car.setModelYear(rs.getString("MODEL_YEAR"));
    carList.add(car);
    catch (Exception e)
    System.out.println("No SQL connection is made"+e);
    finally
    try
    if(rs != null){rs.close();}
    if(stmt != null){stmt.close();}
    if(conn != null){conn.close();}
    catch(Exception e)
    System.out.println(e);
    return carList;
    I am getting an error as follows...
    No SQL connection is made.
    org.Jboss.util.NestedSQLException:Could not create connection; -nested throwable: (java.sql.SQLException:Unable to connect to any host due to exception:java.net.ConnectException:Connection Time out:connect......
    how to get rid of this problem????plz...someone help me....

    If you have access to a copy of TimesTen 6.0 you can look in the AppServer Configuration Guide (appsrv.pdf) that was shipped with that release. This guide is currently being rewritten and so is not yet available for 7.0.
    If you can't get hold of a copy, e-mail me at [email protected] and I'll send it to you.
    Chris

  • 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

  • NameNotFoundException when looking up datasource jndi from standalone clien

    Hi,
    I'm trying to lookup datasource jndi from standalone client, but always get exceptions.
    I configured an oralce datasource with jndi name "oracleDataSource". When looking it up in servlet, I can get connection.
    In order to test it from standalone client, I created following code:
    public class DataSourceTest
    * Attempt to authenticate the user.
    public static void main(String[] args)
    String datasource = null;
    if (args.length == 1 ) {
    datasource = args[0];
    System.out.println("datasource = "+datasource);
    if(datasource == null)
    datasource = "oracleDataSource";
    try{
    Connection conn = null;
    Properties env = new Properties();
    env.put("java.naming.factory.initial","com.sun.jndi.cosnaming.CNCtxFactory");
    env.put("java.naming.provider.url", "iiop://localhost:3700");
    Context initial = new InitialContext(env);
    if(datasource != null){
    DataSource ds = (DataSource)initial.lookup(datasource);
    conn = ds.getConnection();
    if(conn != null){
    System.out.println("datasource is gotten.");
    conn.close();
    else
    System.out.println("datasource is error.");
    System.exit(0);
    } catch (Exception ex) {
    System.err.println("Caught an unexpected exception!");
    ex.printStackTrace();
    When running, I get following exception:
    [java] datasource = oracleDataSource
    [java] Caught an unexpected exception!
    [java] javax.naming.NameNotFoundException. Root exception is org.omg.CosNaming.NamingContextPackage.NotFound
    [java] at org.omg.CosNaming.NamingContextPackage.NotFoundHelper.read(NotFoundHelper.java:34)
    [java] at org.omg.CosNaming._NamingContextExtStub.resolve(_NamingContextExtStub.java:402)
    [java] at com.sun.jndi.cosnaming.CNCtx.callResolve(CNCtx.java:368)
    [java] at com.sun.jndi.cosnaming.CNCtx.lookup(CNCtx.java:417)
    [java] at com.sun.jndi.cosnaming.CNCtx.lookup(CNCtx.java:395)
    [java] at javax.naming.InitialContext.lookup(InitialContext.java:350)
    [java] at com.tbcn.ceap.test.cilent.DataSourceTest.main(DataSourceTest.java:42)
    I also tried many other methods but always got exceptions. What's wrong with it? How can I lookup the datasource jndi from standalone client?
    Thanks in advance!

    Thank Tuan!
    I tried. When running, the server will read security.properties and ejb.properties. But I didn't use ejb and I didn't know how to configure ejb.properties, so I let ejb.properties empty. The security.properties is as following:
    client.sendpassword=true
    server.trustedhosts=*
    interop.ssl.required=false
    interop.authRequired.enabled=false
    interop.nameservice.ssl.required=false
    The result is:
    [java] javax.naming.CommunicationException: Can't find SerialContextProvider
    [java] at com.sun.enterprise.naming.SerialContext.getProvider(SerialContext.java:63)
    [java] at com.sun.enterprise.naming.SerialContext.lookup(SerialContext.java:120)
    [java] at javax.naming.InitialContext.lookup(InitialContext.java:347)
    [java] at com.tbcn.ceap.test.cilent.DataSourceTest.main(DataSourceTest.java:42)
    Also, I tried it with ACC. In sun sample ConverterClient.java under rmi-iiop/simple, I added following code under with ACC and without ACC. With ACC, I can get connection. But without ACC, I can't get it.
    try{
              DataSource ds = (DataSource)initial.lookup("oracleDataSource");
              Connection conn = ds.getConnection();
              if(conn != null){
              System.out.println("datasource oracleDataSource gotten.");
              conn.close();
              else
              System.out.println("oracleDataSource is error.");
    Does it means that we must lookup datasource jndi with ACC?

  • 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.

  • Help me understand JDBC connections using DataSource objects

    I'm writing a simple Java server application that accepts connections from multiple clients via RMI, connects to a SQL Server 2000 database via Microsoft's SQL 2000 JDBC driver, gets some data, and returns it to the client. The server application will handle every SQL database connection. However, it must be able to establish multiple simultaneous connections, since multiple clients may connect at the same time and request data.
    Sounds like a simple multi-threaded server that utilizes a connection pool for database connectivity, right? Well, if I want to do that, I have to register a PooledDataSource object with JNDI. My server threads that are handling requests will simply grab connections out of the pool to retrieve data (presumably).
    This seems like a fairly simple server application; however, all the information and tutorials I've read on using DataSource objects for database connections rather than DriverManager.getConnection() mention XML config files, J2EE application servers, Tomcat, WebSphere, etc. I really don't want to have to deal with all that just to get connection pooling and not have to use the DriverManager.getConnection() method.
    Is there a simple way to use DataSource objects without installing a lot of extra junk on my server?

    Thanks, diazlara. Your response was exactly what I needed to know. All the information I've read prior to this suggested that I had to have a J2EE server running, and that I had to register the DataSource object with JNDI. If you ladies and gents could take a quick look at this and let me know if I'm doing it correctly, I'd appreciate it.
    As proflux suggested, I wrote a connection manager:
    import java.sql.*;
    import javax.sql.*;
    import com.microsoft.jdbcx.sqlserver.*;
    public class SQLConnectionManager {
       private static ConnectionPoolDataSource connectionPool;
       // Initialize the connection manager
       public SQLConnectionManager() {
          init();
       // Retrieve a connection from the connection pool and return it
       public static Connection getConnection() {
          Connection connection = null;
          try {
             connection = connectionPool.getPooledConnection("myUsername", "myPassword").getConnection();
          catch (SQLException ex) {
             System.err.println("A problem occurred while getting a connection from the pool.");
             ex.printStackTrace();
          return connection;
       // Initialize the datasource and connection pool
       private static void init() {
          SQLServerDataSource mds = new SQLServerDataSource();
          mds.setDescription("MS SQLServerDataSource");
          mds.setServerName("127.0.0.1");
          mds.setPortNumber(1433);
          mds.setDatabaseName("SomeTable");
          mds.setSelectMethod("cursor");
          connectionPool = (ConnectionPoolDataSource) mds;
    }As you can see, I'm hard-coding the username and password for testing purposes. I'll incorporate a login/authentication system for any production code that I use this in.
    Once the SQLConnectionManager is created, connections can be retrieved as follows:
          Connection connection = null;
          try {
             connection = SQLConnectionManager.getConnection();
             System.out.println("** Got a SQL database connection from the pool");
             DatabaseMetaData metaData = connection.getMetaData();
             ResultSet rs = metaData.getCatalogs();
             while (rs.next()) {
                System.out.println("\tcatalog: " + rs.getString(1));
             rs.close();
             connection.close();
          catch (SQLException ex) {
             System.out.println("An exception occurred while connecting to the SQL Database:");
             ex.printStackTrace();
          }So, how does that look? I tested it out, and it seems to work just fine. Using this code, I am getting a connection from a pool, correct? I want to make sure of that. Also, are there any inherent weaknesses or flaws with this method that I need to be aware of?
    Thanks so much for all the helpful responses.

  • Dynamically set database url using tomcat jndi

    By using Tomcat JNDI, database url information needs to be hardcoded in server.xml file according to the documentation. Is there a way to change the URL information in the code dynamically if necessary?
    And also we need multiple connection pools and the connection information about those pools are only known during run time. So the TOMCAT JNDI is still the right way to go???
    By the way, does anybody ever use tomcat DBCP package to get datasource and set url dynamically?
    Thanks in advance.

    By using Tomcat JNDI, database url information needs
    to be hardcoded in server.xml file according to the
    documentation. Is there a way to change the URL
    information in the code dynamically if necessary?
    Not that I know of.
    And also we need multiple connection pools and the
    connection information about those pools are only
    known during run time. So the TOMCAT JNDI is still the
    right way to go???
    I think so. Since it's just a JDNI lookup, perhaps you can set up multiple data sources and decide on the lookup name at the last minute, depending on circumstances. That might work. I haven't tried it myself. - MOD
    By the way, does anybody ever use tomcat DBCP package
    to get datasource and set url dynamically?
    Thanks in advance.

Maybe you are looking for

  • Report and Alert don't executed in the error handler with a JMS proxy service

    Hi, I'm working with OSB 11.1.1.4.0 and I'm facing a problem with the error handler of my JMS proxy service. My error handler contains two main elements : - a Report action - an Alert with a JMS destination defined When the business service failed th

  • HP Officejet Pro 8000 warm up time?

    I am interested in the HP Officejet Pro 8000 wireless.  However, many reviews for this printer mentions the long warm up time everytime they turn on their printer.  I contacted HP chat tech support and chat sales support many times and they kept sayi

  • Airport Extreme - Boosting signal?

    I just moved into a new apartment, and my Airport Extreme works great in the living room or office where I keep it. But when I go down a hallway (about 25 ft. away from the Extreme) and into the bedroom, I'm lucky if I get half a bar. Any way to get

  • Scheduling to File System BO4.0 without user/pass

    Hello all, I have a great deal of reports that I need to schedule to a network drive, which is mapped on the server running BO. However, I don't want to enter in a user and password on each instance. Obviously if the password changed for the account

  • Portal installation

    I've tried to install Oracle portal for the Oracle 8.1.6 database on the NT platform (nt 4.0 with Service Pack 6). Web Toolkit was installed properly under the SYS account; all sequences, synonyms are created well. But when I clicked on the "Finish"