Example usage for javax.naming Context bind

List of usage examples for javax.naming Context bind

Introduction

In this page you can find the example usage for javax.naming Context bind.

Prototype

public void bind(String name, Object obj) throws NamingException;

Source Link

Document

Binds a name to an object.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String url = "iiop://localhost/";
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.cosnaming.CNCtxFactory");
    env.put(Context.PROVIDER_URL, url);

    Context ctx = new InitialContext(env);
    // Add a binding.
    ctx.bind("Name", null);

    // Replace a binding.
    ctx.rebind("Name", null);

    // Remove a binding.
    ctx.unbind("Name");

    // Rename a binding.
    ctx.rename("Name", "NewSample");
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    // Set up the environment for creating the initial context
    Hashtable env = new Hashtable(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
    env.put(Context.PROVIDER_URL, "file:/jdbc");

    Context context = new InitialContext(env);
    NamingEnumeration list = context.list("jdbc");

    while (list.hasMore()) {
        NameClassPair nc = (NameClassPair) list.next();
        System.out.println(nc);/*w  w  w  .j av a2s. c  o m*/
    }

    OracleDataSource ods = new OracleDataSource();
    ods.setDriverType("thin");
    ods.setServerName("localhost");
    ods.setNetworkProtocol("tcp");
    ods.setDatabaseName("databaseName");
    ods.setPortNumber(1521);
    ods.setUser("userName");
    ods.setPassword("Password");

    Context ctx = new InitialContext();
    ctx.bind("file:/jdbc/mydb", ods);

    // Get the initial context of JNDI and lookup the datasource.
    InitialContext ic = new InitialContext();
    javax.sql.DataSource ds = (javax.sql.DataSource) ic.lookup("file:/jdbc/mydb");
    // Set the optional printwriter where the trace log is to be directed.
    ds.setLogWriter(new PrintWriter(new FileOutputStream("c:/datasource.log")));
    Connection con1 = ds.getConnection();
    Connection con2 = ds.getConnection("userName", "password");
    conn.close();

}

From source file:SerObj.java

public static void main(String[] args) {

    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {//www. j a  v  a  2s.c  o  m
        // Create the initial context
        Context ctx = new InitialContext(env);

        // Create object to be bound
        Button b = new Button("Push me");

        // Perform bind
        ctx.bind("cn=Button", b);

        // Check that it is bound
        Button b2 = (Button) ctx.lookup("cn=Button");
        System.out.println(b2);

        // Close the context when we're done
        ctx.close();
    } catch (NamingException e) {
        System.out.println("Operation failed: " + e);
    }
}

From source file:Bind.java

public static void main(String[] args) {

    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {/*from   ww  w . j  a  v a 2 s  . co m*/
        // Create the initial context
        Context ctx = new InitialContext(env);

        // Create the object to be bound
        Fruit fruit = new Fruit("orange");

        // Perform the bind
        ctx.bind("cn=Favorite Fruit", fruit);

        // Check that it is bound
        Object obj = ctx.lookup("cn=Favorite Fruit");
        System.out.println(obj);

        // Close the context when we're done
        ctx.close();
    } catch (NamingException e) {
        System.out.println("Operation failed: " + e);
    }
}

From source file:TestDSBind.java

public static void main(String args[]) throws SQLException, NamingException {

    // For this to work you will need to create the
    // directories /JNDI/JDBC on your file system first
    Context ctx = null;
    try {//from www.ja  va 2s  .  co m
        Properties prop = new Properties();
        prop.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
        prop.setProperty(Context.PROVIDER_URL, "file:/JNDI/JDBC");
        ctx = new InitialContext(prop);
    } catch (NamingException ne) {
        System.err.println(ne.getMessage());
    }

    OracleDataSource ds = new OracleDataSource();
    ds.setDriverType("thin");
    ds.setServerName("dssw2k01");
    ds.setPortNumber(1521);
    ds.setDatabaseName("orcl");
    ds.setUser("scott");
    ds.setPassword("tiger");

    ctx.bind("joe", ds);
}

From source file:Util.java

/**
 * Bind val to name in ctx, and make sure that all intermediate contexts exist
 * /*  w  w  w. j  a v a2  s .c o m*/
 * @param ctx
 *          the parent JNDI Context under which value will be bound
 * @param name
 *          the name relative to ctx where value will be bound
 * @param value
 *          the value to bind.
 * @throws NamingException
 *           for any error
 */
public static void bind(Context ctx, Name name, Object value) throws NamingException {
    int size = name.size();
    String atom = name.get(size - 1);
    Context parentCtx = createSubcontext(ctx, name.getPrefix(size - 1));
    parentCtx.bind(atom, value);
}

From source file:JNDIUtil.java

/**
 * Context.rebind() requires that all intermediate contexts and the target context (that named by
 * all but terminal atomic component of the name) must already exist, otherwise
 * NameNotFoundException is thrown. This method behaves similar to Context.rebind(), but creates
 * intermediate contexts, if necessary.//w  w  w  .j  a v a 2s  .co  m
 */
public static void rebind(Context c, String jndiName, Object o) throws NamingException {
    Context context = c;
    String name = jndiName;

    int idx = jndiName.lastIndexOf('/');
    if (idx != -1) {
        context = createContext(c, jndiName.substring(0, idx));
        name = jndiName.substring(idx + 1);
    }
    boolean failed = false;
    try {
        context.rebind(name, o);
    } catch (Exception ignored) {
        failed = true;
    }
    if (failed) {
        context.bind(name, o);
    }
}

From source file:com.joseflavio.iperoxo.IpeRoxo.java

/**
 * Inicia a {@link DataSource} e a {@link EntityManagerFactory}.
 *///ww w  .  j  a v a 2s. c  o m
private static void executarFonteDeDados() throws IOException, NamingException {

    if (Boolean.parseBoolean(getPropriedade("DataSource.Enable"))) {
        log.info(getMensagem(null, "Log.Iniciando.DataSource"));
    } else {
        return;
    }

    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");

    dataSource = new BasicDataSource();
    dataSource.setDriverClassName(getPropriedade("DataSource.Driver"));
    dataSource.setUrl(getPropriedade("DataSource.URL"));
    dataSource.setUsername(getPropriedade("DataSource.Username"));
    dataSource.setPassword(getPropriedade("DataSource.Password"));
    dataSource.setInitialSize(Integer.parseInt(getPropriedade("DataSource.InitialSize")));
    dataSource.setMaxTotal(Integer.parseInt(getPropriedade("DataSource.MaxTotal")));
    dataSource.setMinIdle(Integer.parseInt(getPropriedade("DataSource.MinIdle")));
    dataSource.setMaxIdle(Integer.parseInt(getPropriedade("DataSource.MaxIdle")));
    dataSource.setTestOnCreate(Boolean.parseBoolean(getPropriedade("DataSource.TestOnCreate")));
    dataSource.setTestWhileIdle(Boolean.parseBoolean(getPropriedade("DataSource.TestWhileIdle")));
    dataSource.setTestOnBorrow(Boolean.parseBoolean(getPropriedade("DataSource.TestOnBorrow")));
    dataSource.setTestOnReturn(Boolean.parseBoolean(getPropriedade("DataSource.TestOnReturn")));

    Context contexto = new InitialContext();
    try {
        contexto.bind("FONTE", dataSource);
    } finally {
        contexto.close();
    }

    while (true) {
        try (Connection con = getConnection()) {
            break;
        } catch (Exception e) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException f) {
            }
        }
    }

    if (Boolean.parseBoolean(getPropriedade("DataSource.JPA.Enable"))) {
        log.info(getMensagem(null, "Log.Iniciando.JPA"));
    } else {
        return;
    }

    emf = Persistence.createEntityManagerFactory("JPA");

    try {
        emf.createEntityManager().close();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

}

From source file:com.dattack.naming.loader.NamingLoader.java

private static void execBind(final Context context, final String key, final Object value)
        throws NamingException {

    Object obj = context.lookup(key);

    if (obj instanceof Context) {
        LOGGER.debug("Destroying context with name '{}'", key);
        context.destroySubcontext(key);/*from   w ww . ja v  a2  s .  c  om*/
        obj = null;
    }

    if (obj == null) {
        LOGGER.debug("Executing bind method for '{}'", key);
        context.bind(key, value);
    } else {
        LOGGER.debug("Executing rebind method for '{}'", key);
        context.rebind(key, value);
    }
}

From source file:ca.nrc.cadc.db.DBUtil.java

/**
 * Create a JNDI DataSOurce resource with the specified name and environment context.
 * /*w  ww  . j a v a 2  s . com*/
 * @param dataSourceName
 * @param envContextName
 * @param config
 * @throws NamingException 
 */
public static void createJNDIDataSource(String dataSourceName, String envContextName, ConnectionConfig config)
        throws NamingException {
    log.debug("createDataSource: " + dataSourceName + " START");
    StandaloneContextFactory.initJNDI();

    Context initContext = new InitialContext();
    Context envContext = (Context) initContext.lookup(envContextName);
    if (envContext == null) {
        envContext = initContext.createSubcontext(envContextName);
    }
    log.debug("env: " + envContext);

    DataSource ds = getDataSource(config);
    envContext.bind(dataSourceName, ds);
    log.debug("createDataSource: " + dataSourceName + " DONE");
}