Example usage for javax.naming Context INITIAL_CONTEXT_FACTORY

List of usage examples for javax.naming Context INITIAL_CONTEXT_FACTORY

Introduction

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

Prototype

String INITIAL_CONTEXT_FACTORY

To view the source code for javax.naming Context INITIAL_CONTEXT_FACTORY.

Click Source Link

Document

Constant that holds the name of the environment property for specifying the initial context factory to use.

Usage

From source file:it.openutils.mgnlaws.magnolia.init.ClasspathProviderImpl.java

/**
 * @see info.magnolia.repository.Provider#init(info.magnolia.repository.RepositoryMapping)
 *///from  w w w. j av a  2s .co m
public void init(RepositoryMapping repositoryMapping) throws RepositoryNotInitializedException {
    checkXmlSettings();

    this.repositoryMapping = repositoryMapping;
    /* connect to repository */
    Map params = this.repositoryMapping.getParameters();
    String configFile = (String) params.get(CONFIG_FILENAME_KEY);
    if (!StringUtils.startsWith(configFile, ClasspathPropertiesInitializer.CLASSPATH_PREFIX)) {
        configFile = Path.getAbsoluteFileSystemPath(configFile);
    }
    String repositoryHome = (String) params.get(REPOSITORY_HOME_KEY);
    repositoryHome = getRepositoryHome(repositoryHome);

    // cleanup the path, to remove eventual ../.. and make it absolute
    try {
        File repoHomeFile = new File(repositoryHome);
        repositoryHome = repoHomeFile.getCanonicalPath();
    } catch (IOException e1) {
        // should never happen and it's not a problem at this point, just pass it to jackrabbit and see
    }

    String clusterid = SystemProperty.getProperty(MAGNOLIA_CLUSTERID_PROPERTY);
    if (StringUtils.isNotBlank(clusterid)) {
        System.setProperty(JACKRABBIT_CLUSTER_ID_PROPERTY, clusterid);
    }

    // get it back from system properties, if it has been set elsewhere
    clusterid = System.getProperty(JACKRABBIT_CLUSTER_ID_PROPERTY);

    log.info("Loading repository at {} (config file: {}) - cluster id: \"{}\"",
            new Object[] { repositoryHome, configFile, StringUtils.defaultString(clusterid, "<unset>") });

    bindName = (String) params.get(BIND_NAME_KEY);
    jndiEnv = new Hashtable<String, Object>();
    jndiEnv.put(Context.INITIAL_CONTEXT_FACTORY, params.get(CONTEXT_FACTORY_CLASS_KEY));
    jndiEnv.put(Context.PROVIDER_URL, params.get(PROVIDER_URL_KEY));

    try {
        InitialContext ctx = new InitialContext(jndiEnv);
        // first try to find the existing object if any
        try {
            this.repository = (Repository) ctx.lookup(bindName);
        } catch (NameNotFoundException ne) {
            log.debug("No JNDI bound Repository found with name {}, trying to initialize a new Repository",
                    bindName);
            ClasspathRegistryHelper.registerRepository(ctx, bindName, configFile, repositoryHome, true);
            this.repository = (Repository) ctx.lookup(bindName);
        }
        this.validateWorkspaces();
    } catch (NamingException e) {
        log.error("Unable to initialize repository: " + e.getMessage(), e);
        throw new RepositoryNotInitializedException(e);
    } catch (RepositoryException e) {
        log.error("Unable to initialize repository: " + e.getMessage(), e);
        throw new RepositoryNotInitializedException(e);
    } catch (TransformerFactoryConfigurationError e) {
        log.error("Unable to initialize repository: " + e.getMessage(), e);
        throw new RepositoryNotInitializedException(e);
    }
}

From source file:com.redhat.lightblue.rest.crud.ITCaseCrudResourceRDBMSTest.java

@Before
public void setup() throws Exception {
    File folder = new File("/tmp");
    File[] files = folder.listFiles(new FilenameFilter() {
        @Override//from  ww  w .j  a  v a2 s .  co m
        public boolean accept(final File dir, final String name) {
            return name.startsWith("test.db");
        }
    });
    for (final File file : files) {
        if (!file.delete()) {
            System.out.println("Failed to remove " + file.getAbsolutePath());
        }
    }

    mongo.dropDatabase(DB_NAME);
    mongo.dropDatabase("local");
    mongo.dropDatabase("admin");
    mongo.dropDatabase("mongo");
    mongo.getDB(DB_NAME).dropDatabase();
    mongo.getDB("local").dropDatabase();
    mongo.getDB("admin").dropDatabase();
    mongo.getDB("mongo").dropDatabase();

    db.getCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION).remove(new BasicDBObject());
    mongo.getDB("mongo").getCollection("metadata").remove(new BasicDBObject());

    db.createCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION, null);
    BasicDBObject index = new BasicDBObject("name", 1);
    index.put("version.value", 1);
    db.getCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION).ensureIndex(index, "name", true);

    if (notRegistered) {
        notRegistered = false;
        try {
            // Create initial context
            System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
            System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
            // already tried System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.as.naming.InitialContextFactory");
            InitialContext ic = new InitialContext();

            ic.createSubcontext("java:");
            ic.createSubcontext("java:/comp");
            ic.createSubcontext("java:/comp/env");
            ic.createSubcontext("java:/comp/env/jdbc");

            JdbcConnectionPool ds = JdbcConnectionPool.create(
                    "jdbc:h2:file:/tmp/test.db;FILE_LOCK=NO;MVCC=TRUE;DB_CLOSE_ON_EXIT=TRUE", "sa", "sasasa");

            ic.bind("java:/mydatasource", ds);
        } catch (NamingException ex) {
            throw new IllegalStateException(ex);
        }
    } else {
        Context initCtx = new InitialContext();
        DataSource ds = (DataSource) initCtx.lookup("java:/mydatasource");
        Connection conn = ds.getConnection();
        Statement stmt = conn.createStatement();
        stmt.execute("DROP ALL OBJECTS ");
        stmt.close();
    }
}

From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java

/**
 * Connect to the LDAP server with System DN and Password
 * /* w  w w. j a  va2 s.c  o  m*/
 * Configuration: LDAP URL = ldapContext.xml (property=ldapURL) System DN =
 * ldapContext.xml (property=ldapSystemDN) System PW = ldapContext.xml
 * (property=ldapSystemPW)
 * 
 * @return The LDAP connection (LdapContext) or NULL if connect fails
 * 
 * @throws NamingException
 */
public LdapContext bindSystem() {
    // set LDAP connection attributes
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapLoginModule.getLdapUrl());
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, ldapLoginModule.getLdapSystemDN());
    env.put(Context.SECURITY_CREDENTIALS, ldapLoginModule.getLdapSystemPW());
    if (ldapLoginModule.getLdapConnectionTimeout() != null) {
        env.put(TIMEOUT_KEY, ldapLoginModule.getLdapConnectionTimeout().toString());
    }

    // check ssl
    if (ldapLoginModule.isSslEnabled()) {
        enableSSL(env);
    }

    try {
        InitialLdapContext ctx = new InitialLdapContext(env, new Control[] {});
        ctx.getConnectControls();
        return ctx;
    } catch (NamingException e) {
        log.error("NamingException when trying to bind system with DN::" + ldapLoginModule.getLdapSystemDN()
                + " and PW::" + ldapLoginModule.getLdapSystemPW() + " on URL::" + ldapLoginModule.getLdapUrl(),
                e);
        return null;
    } catch (Exception e) {
        log.error("Exception when trying to bind system with DN::" + ldapLoginModule.getLdapSystemDN()
                + " and PW::" + ldapLoginModule.getLdapSystemPW() + " on URL::" + ldapLoginModule.getLdapUrl(),
                e);
        return null;
    }

}

From source file:org.springframework.ldap.samples.article.dao.TraditionalPersonDaoImpl.java

private DirContext createContext(Hashtable env) {
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    String tempUrl = createUrl();
    env.put(Context.PROVIDER_URL, tempUrl);
    DirContext ctx;/*from  w w w. j  a v  a 2  s.c  o  m*/
    try {
        ctx = new InitialDirContext(env);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
    return ctx;
}

From source file:org.mule.providers.ldap.util.DSManager.java

/**
 * Sets the contexts for this base class. Values of user and password used
 * to set the respective JNDI properties. These values can be overriden by
 * the overrides properties.//ww  w.  j a  v a  2  s .c  o  m
 * 
 * @param user
 *            the username for authenticating as this user
 * @param passwd
 *            the password of the user
 * @throws NamingException
 *             if there is a failure of any kind
 */
protected void setContexts(String user, String passwd) throws NamingException {
    Hashtable env = new Hashtable(configuration.toJndiEnvironment());
    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, passwd);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.INITIAL_CONTEXT_FACTORY, ServerContextFactory.class.getName());
    setContexts(env);
}

From source file:iplatform.admin.ui.server.auth.ad.ActiveDirectoryLdapAuthenticationProvider.java

private DirContext bindAsUser(String username, String password) {
    // TODO. add DNS lookup based on domain
    final String bindUrl = url;

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    String bindPrincipal = createBindPrincipal(username);
    env.put(Context.SECURITY_PRINCIPAL, bindPrincipal);
    env.put(Context.PROVIDER_URL, bindUrl);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.OBJECT_FACTORIES, DefaultDirObjectFactory.class.getName());

    try {//from   w  ww  . j  a  va 2s. c  om
        return contextFactory.createContext(env);
    } catch (NamingException e) {
        if ((e instanceof AuthenticationException) || (e instanceof OperationNotSupportedException)) {
            handleBindException(bindPrincipal, e);
            throw badCredentials(e);
        } else {
            throw LdapUtils.convertLdapException(e);
        }
    }
}

From source file:org.keycloak.testsuite.federation.kerberos.AbstractKerberosTest.java

protected String invokeLdap(GSSCredential gssCredential, String username) throws NamingException {
    Hashtable env = new Hashtable(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:10389");

    if (gssCredential != null) {
        env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
        env.put(Sasl.CREDENTIALS, gssCredential);
    }//from  ww w. ja v a2 s. c o m

    DirContext ctx = new InitialDirContext(env);
    try {
        Attributes attrs = ctx.getAttributes("uid=" + username + ",ou=People,dc=keycloak,dc=org");
        String cn = (String) attrs.get("cn").get();
        String sn = (String) attrs.get("sn").get();
        return cn + " " + sn;
    } finally {
        ctx.close();
    }
}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Test to make sure anonymous binds are allowed on the RootDSE even when disabled
 * in general when going through the wire protocol.
 *
 * @throws Exception if anything goes wrong
 *///  w  w w.j a  va2 s . c om
@Test
public void testEnableAnonymousBindsOnRootDse() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous
    Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put(Context.SECURITY_AUTHENTICATION, "none");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    InitialDirContext ctx = new InitialDirContext(env);
    SearchControls cons = new SearchControls();
    cons.setSearchScope(SearchControls.OBJECT_SCOPE);
    NamingEnumeration<SearchResult> list = ctx.search("", "(objectClass=*)", cons);

    SearchResult result = null;

    if (list.hasMore()) {
        result = list.next();
    }

    assertFalse(list.hasMore());
    list.close();

    assertNotNull(result);
    assertEquals("", result.getName().trim());
}

From source file:it.webappcommon.lib.LDAPHelper.java

/**
 * @param args/*ww  w.jav  a2 s  .co m*/
 *            the command line arguments
 */
// public static void main(String[] args) {
private List<UserInfo> search(String filter) throws NamingException {
    DirContext ctx = null;
    SearchControls ctls = null;
    Properties env = new Properties();
    List<UserInfo> res = new ArrayList<UserInfo>();
    boolean trovatiRisultati = false;

    env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT);

    env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port);

    env.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (org.apache.commons.lang3.StringUtils.isEmpty(loginDomain)) {
        env.put(Context.SECURITY_PRINCIPAL, loginUserName);
    } else {
        env.put(Context.SECURITY_PRINCIPAL, loginDomain + "\\" + loginUserName);
    }
    env.put(Context.SECURITY_CREDENTIALS, loginPassword);

    try {
        ctx = new InitialDirContext(env);

        ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // String filter = "";
        // // filter = "(&(objectClass=inetOrgPerson)(objectClass=person))";
        // filter = FILTER_USERS_ACTIVE;

        // Tutti i membri di un gruppo
        // (objectCategory=user)(memberOf=CN=QA Users,OU=Help
        // Desk,DC=dpetri,DC=net)

        // ESEMPI
        // http://www.petri.co.il/ldap_search_samples_for_windows_2003_and_exchange.htm

        // Account disabled
        // (UserAccountControl:1.2.840.113556.1.4.803:=2)

        NamingEnumeration<SearchResult> answer = ctx.search(areaWhereSearch, filter, ctls);

        UserInfo userInfo = null;
        while (answer.hasMoreElements()) {
            trovatiRisultati = true;

            SearchResult a = answer.nextElement();
            // logger.debug(a.getNameInNamespace());

            Attributes result = a.getAttributes();

            if (result == null) {
                // System.out.print("Attributi non presenti");
            } else {
                NamingEnumeration<? extends Attribute> attributi = result.getAll();

                userInfo = new UserInfo();
                while (attributi.hasMoreElements()) {
                    Attribute att = attributi.nextElement();
                    // logger.debug(att.getID());

                    String value = "";
                    // for (NamingEnumeration vals = att.getAll();
                    // vals.hasMoreElements(); logger.debug("\t" +
                    // vals.nextElement()))
                    // ;
                    NamingEnumeration<?> vals = att.getAll();
                    while (vals.hasMoreElements()) {
                        Object val = vals.nextElement();

                        // logger.debug("\t" + val);
                        value = (value.isEmpty()) ? value + val.toString() : value + ";" + val.toString();
                    }

                    if (att.getID().equalsIgnoreCase(FIELD_ACCOUNT_NAME)) {
                        // userInfo.setFIELD_ACCOUNT_NAME(value);
                        userInfo.setAccount(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_COGNOME)) {
                        // userInfo.setFIELD_COGNOME(value);
                        userInfo.setCognome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_EMAIL)) {
                        // userInfo.setFIELD_EMAIL(value);
                        userInfo.setEmail(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_GROUPS)) {
                        // userInfo.setFIELD_GROUPS(value);
                        userInfo.setGruppi(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME)) {
                        // userInfo.setFIELD_NOME(value);
                        userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_COMPLETO)) {
                        // userInfo.setFIELD_NOME_COMPLETO(value);
                        userInfo.setNomeCompleto(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_VISUALIZZATO)) {
                        // userInfo.setFIELD_NOME_VISUALIZZATO(value);
                        // userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_TEL)) {
                        // userInfo.setFIELD_TEL(value);
                        userInfo.setTel(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_UFFICIO)) {
                        // userInfo.setFIELD_UFFICIO(value);
                        userInfo.setUfficio(value);
                    }
                    // res.put(att.getID(), value);
                }

                // Attribute attr = result.get("cn");
                // if (attr != null) {
                // logger.debug("cn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("sn");
                // if (attr != null) {
                // logger.debug("sn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("mail");
                // if (attr != null) {
                // logger.debug("mail:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // // attr = result.get("uid");
                // // if (attr != null) {
                // // logger.debug("uid:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }
                // //
                // // attr = result.get("userPassword");
                // // if (attr != null) {
                // // logger.debug("userPassword:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }

                if (userInfo != null) {
                    res.add(userInfo);
                }
            }
        }
    } catch (NamingException ne) {
        // ne.printStackTrace();
        logger.error(ne);
        throw ne;
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (Exception e) {
        }
    }

    // Azzero l'hash map
    if (!trovatiRisultati) {
        res = null;
    }

    return res;
}

From source file:org.springframework.ldap.demo.dao.PersonDaoImpl.java

private DirContext createContext(Hashtable<String, String> env) {
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    String tempUrl = createUrl();
    env.put(Context.PROVIDER_URL, tempUrl);
    DirContext ctx;/*from w  w  w.j a v  a2s  .c o  m*/
    try {
        ctx = new InitialDirContext(env);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
    return ctx;
}