JNDI object creation in standalone application

2019-05-30 04:08发布

问题:

Is is possible to create JNDI llookup and it's reference in standalone application means without any application server.

java:comp/env/jdbc

Regards,

Chaitu

回答1:

JNDI is a service which is provided by Java platform. Refer to below link

http://www.javaworld.com/javaworld/jw-04-2002/jw-0419-jndi.html



回答2:

You can use the class org.springframework.mock.jndi.SimpleNamingContextBuilder of Spring, either the dependency or the file spring-mock-1.0.2.jar. e.g.:

  • Setup:

    SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
    builder.bind("jdbc/Oracle", ods);
    builder.activate();
    
  • Use:

    DataSource ds = InitialContext.doLookup("jdbc/Oracle");
    


回答3:

I found a better solution courtesy of Injecting JNDI datasources (https://web.archive.org/web/20140530014804/https://blogs.oracle.com/randystuph/entry/injecting_jndi_datasources_for_junit)

NEW SOLUTION

How to Run JUnit Tests that require "java:/comp/env/jdbc/keyofsomethingegdatabase"

Add the following Jar's to the JUnit test-case's CLASSPATH:

    TOMCAT_HOME/bin/tomcat-juli.jar (required by catalina.jar)
    TOMCAT_HOME/lib/catalina.jar (contains the actual factory)

Create the binding that you require in the static "for-all-tests" method:

    @BeforeClass
    public static void setUpClass() throws Exception {
        ...
        // Use Apache Tomcat's Directory
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
        // Standard hook
        InitialContext initialContext = new InitialContext();
        // Create binding
        initialContext.createSubcontext("java:");
        initialContext.createSubcontext("java:comp");
        initialContext.createSubcontext("java:comp/env");
        initialContext.createSubcontext("java:comp/env/jdbc");
        // Construct DataSource
        OracleConnectionPoolDataSource dataSource = new OracleConnectionPoolDataSource();
        dataSource.setURL("jdbc:oracle:thin:@myserver:1521:MYSID");
        dataSource.setUser("username");
        dataSource.setPassword("password");

        initialContext.bind("java:comp/env/jdbc/mydatabase", dataSource);
        ...
    }


Then you can create this method in your Singleton class (either lookup method works):

    public Connection getConnection() throws NamingException, SQLException {
        if (dataSource == null) {
            Context initialContext = new InitialContext();
            boolean bLooksLikeChangeDirectory = false;
            if (bLooksLikeChangeDirectory) {
                Context context = (Context) initialContext.lookup("java:comp/env");
                dataSource = (DataSource) context.lookup("jdbc/mydatabase");
            } else {
                dataSource = (DataSource) initialContext.lookup("java:comp/env/jdbc/mydatabase");
            }
        }
        Connection result = dataSource.getConnection();
        return result;
    }

OLD SOLUTION FOLLOWS

This is how you can use a stand-alone JNDI (file-based) for running tests involving: "new InitialContext() ... "lookup". This also describes how to use BoneCP (Connection Pool) with JNDI.

You can use the "com.sun.jndi.fscontext.RefFSContextFactory" (fscontext.jar and providerutil.jar).

I wanted "lookup" to be runnable from inside an application server as well, so it would be useful if someone could tell me for sure if one has to use lookup("java:comp/env/jdbc/mydbnickname") instead of lookup("jdbc/mydbnickname") when running inside an application server.

The latter is preferable, because "java:comp/env" does not exist in the stand-alone RefFSContextFactory directory, so you'd have to have a System property that specifies the JNDI lookup parameter.

Overview You can use "jdbc/mydbnickname" as the argument to "lookup" and to "rebind" (i.e. no "scheme:"). In this case, "RefFSContextFactory" uses the "default scheme", whatever that is ("file:" or "jndi:"). With the following in "jndi.properties" (on the CLASSPATH)

 java.naming.factory.initial=com.sun.jndi.fscontext.RefFSContextFactory
        java.naming.provider.url=file:///u:/workdirectory
    and this in "persistence.xml" (JTA setup)
        <jta-data-source>jdbc/mydbnickname</jta-data-source>
    When you use:
        ...rebind("jdbc/mydbnickname", ...)
    and
        ...lookup("jdbc/mydbnickname")
    then the ".bindings" file (created by "rebind") is
        "u:/workdirectory/.bindings"
    and it looks like this (I have sorted it and tested it with just "lookup"):
        #This file is used by the JNDI FSContext.
        #Thu Jan 09 16:02:17 EST 2014
        jdbc/mydbnickname/ClassName=com.jolbox.bonecp.BoneCPDataSource
        jdbc/mydbnickname/FactoryName=com.jolbox.bonecp.BoneCPDataSource
        jdbc/mydbnickname/RefAddr/0/Content=oracle.jdbc.OracleDriver
        jdbc/mydbnickname/RefAddr/0/Encoding=String
        jdbc/mydbnickname/RefAddr/0/Type=driverClassName
        jdbc/mydbnickname/RefAddr/1/Content=jdbc\:oracle\:thin\:@myserver\:1521\:mysid
        jdbc/mydbnickname/RefAddr/1/Encoding=String
        jdbc/mydbnickname/RefAddr/1/Type=jdbcUrl
        jdbc/mydbnickname/RefAddr/2/Content=myusername
        jdbc/mydbnickname/RefAddr/2/Encoding=String
        jdbc/mydbnickname/RefAddr/2/Type=username
        jdbc/mydbnickname/RefAddr/3/Content=mypassword
        jdbc/mydbnickname/RefAddr/3/Encoding=String
        jdbc/mydbnickname/RefAddr/3/Type=password
    If you use
        "jndi:jdbc/mydbnickname"
    instead of
        "jdbc/mydbnickname",
    then the file created is
        u:/workdirectory/jdbc/.bindings
    and it looks like this:
        mydbnickname/ClassName=com.jolbox.bonecp.BoneCPDataSource
        mydbnickname/FactoryName=com.jolbox.bonecp.BoneCPDataSource
        mydbnickname/RefAddr/0/Content=oracle.jdbc.OracleDriver
        mydbnickname/RefAddr/0/Encoding=String
        mydbnickname/RefAddr/0/Type=driverClassName
        mydbnickname/RefAddr/1/Content=jdbc\:oracle\:thin\:@myserver\:1521\:mysid
        mydbnickname/RefAddr/1/Encoding=String
        mydbnickname/RefAddr/1/Type=jdbcUrl
        mydbnickname/RefAddr/2/Content=myusername
        mydbnickname/RefAddr/2/Encoding=String
        mydbnickname/RefAddr/2/Type=username
        mydbnickname/RefAddr/3/Content=mypassword
        mydbnickname/RefAddr/3/Encoding=String
        mydbnickname/RefAddr/3/Type=password
Rebind (in a JUnit Test)
    @BeforeClass
    public static void setUpClass() throws Throwable {
        final String sMyName = "setUpClass";
        try {
            if (Boolean.parseBoolean(System.getProperty("test.initialcontext.rebind", "true"))) {
                final InitialContext initialContext = new InitialContext();
                final String contextName = "jdbc/mydbnickname";
                final Reference contextValue = new Reference("com.jolbox.bonecp.BoneCPDataSource", "com.jolbox.bonecp.BoneCPDataSource", null);
                contextValue.add(new StringRefAddr("driverClassName", "oracle.jdbc.OracleDriver"));
                contextValue.add(new StringRefAddr("jdbcUrl", "jdbc:oracle:thin:@myserver:1521:mysid"));
                contextValue.add(new StringRefAddr("username", "myusername"));
                contextValue.add(new StringRefAddr("password", "mypassword"));
                initialContext.rebind(contextName, contextValue);
            }
        } catch (final Throwable exception) {
            Utils.getInstance().logExceptionStack(logger, Level.ERROR, sMyName, exception);
            throw exception;
        }
    }
Lookup (in production code)
    protected Connection getConnection() throws Exception {
        Connection result = null;
        // "An InitialContext instance is not synchronized against concurrent access by multiple threads"
        synchronized (this) {
            if (context == null) {
                context = new InitialContext();
            }
            final BoneCPDataSource connectionPool = (BoneCPDataSource) context.lookup("jdbc/mydbnickname"); 
            result = connectionPool.getConnection();
        }
        return result;
    }
CLASSPATH
    BoneCP Connection Pool
        <classpathentry kind="var" path="JAVA_LIB/bonecp-0.8.0.RELEASE.jar" sourcepath="/JAVA_LIB/bonecp-0.8.0.RELEASE-sources.jar"/>
        <classpathentry kind="var" path="JAVA_LIB/slf4j-api-1.7.5.jar" sourcepath="/JAVA_LIB/slf4j-api-1.7.5-sources.jar"/>
        <classpathentry kind="var" path="JAVA_LIB/guava-15.0.jar" sourcepath="/JAVA_LIB/guava-15.0-sources.jar"/>
        <classpathentry kind="var" path="JAVA_LIB/slf4j-simple-1.7.5.jar" sourcepath="/JAVA_LIB/slf4j-simple-1.7.5-sources.jar"/>
    Eclipse JPA (2.5.1)
        <classpathentry kind="var" path="JAVA_LIB/javax.persistence-2.1.0.jar"/>
        <classpathentry kind="var" path="JAVA_LIB/eclipselink-2.5.1.jar"/>
    JNDI
        <classpathentry kind="var" path="JAVA_LIB/fscontext.jar"/>
        <classpathentry kind="var" path="JAVA_LIB/providerutil.jar"/>


标签: java jndi