Aller au contenu | Aller au menu | Aller à la recherche


Monter (bind) une DataSource à chaud, la déclarer sur la JNDI, puis l'utiliser

Monter à chaud et utiliser une DataSource dans la JNDI

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
 
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
 
public class BindDataSourceMysql {
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
 
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setUser("monUser");
        mysqlDataSource.setPassword("monPass");
        mysqlDataSource.setServerName("monHost");
        mysqlDataSource.setPort(3306);
        mysqlDataSource.setDatabaseName("maBase");
//        mds.setUrl("jdbc:mysql://monHost:3306/maBase");
 
        System.out.println(mysqlDataSource.getUrl());
 
        DataSource dataSource = (DataSource) mysqlDataSource;
 
        PreparedStatement ps;
        ResultSet rs;
 
        System.out.println("---- Connexion à la DataSource - START");
        try {
			ps = dataSource.getConnection().prepareStatement("SELECT COUNT(*) AS nbr FROM maTable");
			rs = ps.executeQuery();
			while( rs.next() ) {
				System.out.println("Nombre d'enregistrement en base : " + rs.getInt("nbr"));
			}
 
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println("---- Connexion à la DataSource - STOP");
 
 
//    http://www.oracle.com/technology/sample_code/tech/java/codesnippet/j2ee/JNDI/index.html
//		
//    InitialContext()
//    This constructor creates a context  using the default context environment for the application as set by the OC4J container during start up.  This is typically used in JSP or servlet or an EJB code that runs in the server.
//
//    InitialContext(HashTable env) 
//    This constructor is used to create a context using the environment properties that are set in the Hashtable variable passed as parameter  to the constructor.  It is used in the client code where it is necessary to supply the JNDI properties to create initial context. Following are the environment properties that need to be supplied :
//
//    INITIAL_CONTEXT_FACTORY : Specifies which initial context factory to use when creating initial context.
//    PROVIDER_URL            : The URL that application client code uses to look up the objects on the server.
//    SECURITY_PRINCIPAL      : The username that will be used to authenticate the application client.
//    SECURITY_CREDENTIAL     : The password that will be used to authenticate the application client.		
 
		String urlObjetJndiName = "jdbc/mysqlDataSource";
 
		System.setProperty(Context.INITIAL_CONTEXT_FACTORY, InitialContextFactoryForTest.class.getName());	// public class InitialContextFactoryForTest implements InitialContextFactory
//		System.setProperty(Context.INITIAL_CONTEXT_FACTORY, BindDataSourceMysql.class.getName()); // javax.naming.NoInitialContextException: Cannot instantiate class: com.placeoweb.util.BindDataSourceMysql [Root exception is java.lang.ClassCastException: com.placeoweb.util.BindDataSourceMysql cannot be cast to javax.naming.spi.InitialContextFactory]
//		System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); // javax.naming.NoInitialContextException: Cannot instantiate class: com.sun.jndi.fscontext.RefFSContextFactory [Root exception is java.lang.ClassNotFoundException: com.sun.jndi.fscontext.RefFSContextFactory]
 
//		Properties props = new Properties();		
//		props.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
//		props.put("java.naming.factory.url.pkgs", "org.jboss.naming");		
//		System.out.println(props.getProperty("java.naming.factory.initial"));
//		System.setProperty(Context.INITIAL_CONTEXT_FACTORY, props.getProperty("java.naming.factory.initial"));
//		System.setProperty(Context.URL_PKG_PREFIXES, props.getProperty("java.naming.factory.url.pkgs"));
//				
		System.out.println(System.getProperty(Context.INITIAL_CONTEXT_FACTORY));	// com.placeoweb.util.InitialContextFactoryForTest
 
 
        // Déclare l'objet dans la JNDI avec bind
        InitialContextFactoryForTest.bind(urlObjetJndiName, dataSource);		
 
 
		System.out.println("---- Connexion à la DataSource déclarée dans la JNDI avec bind (" + urlObjetJndiName + ") - START");
		try {
			Context contextDeTest = new InitialContext();
			DataSource dataSourceBind = (DataSource) contextDeTest.lookup(urlObjetJndiName);
			ps = dataSourceBind.getConnection().prepareStatement("SELECT COUNT(*) AS nbr FROM maTable");
			rs = ps.executeQuery();
			while( rs.next() ) {
				System.out.println("Nombre d'enregistrement en base : " + rs.getInt("nbr"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("---- Connexion à la DataSource déclarée dans la JNDI avec bind (" + urlObjetJndiName + ") - STOP");
 
	}
 
}
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.spi.InitialContextFactory;
 
 
public class InitialContextFactoryForTest implements InitialContextFactory {
 
    private static Context context;
 
    static {
        try {
            context = new InitialContext(true) {
                Map<String, Object> bindings = new HashMap<String, Object>();
 
                @Override
                public void bind(String name, Object obj)
                        throws NamingException {
                    bindings.put(name, obj);
                }
 
                @Override
                public Object lookup(String name) throws NamingException {
                    return bindings.get(name);
                }
            };
        } catch (NamingException e) { // can't happen.
            throw new RuntimeException(e);
        }
    }
 
    public Context getInitialContext(Hashtable<?, ?> environment)
            throws NamingException {
        return context;
    }
 
    public static void bind(String name, Object obj) {
        try {
            context.bind(name, obj);
        } catch (NamingException e) { // can't happen.
            throw new RuntimeException(e);
        }
    }
}

Ajouter un commentaire

Le code HTML est affiché comme du texte et les adresses web sont automatiquement transformées.

Fil des commentaires de ce billet