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:org.sonar.plugins.ldap.LdapContextFactory.java

private InitialDirContext createInitialDirContextUsingGssapi(String principal, String credentials)
        throws NamingException {
    Configuration.setConfiguration(new Krb5LoginConfiguration());
    InitialDirContext initialDirContext;
    try {/*w w  w .java2s .c  o  m*/
        LoginContext lc = new LoginContext(getClass().getName(),
                new CallbackHandlerImpl(principal, credentials));
        lc.login();
        initialDirContext = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<InitialDirContext>() {
            @Override
            public InitialDirContext run() throws NamingException {
                Properties env = new Properties();
                env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
                env.put(Context.PROVIDER_URL, providerUrl);
                env.put(Context.REFERRAL, DEFAULT_REFERRAL);
                return new InitialLdapContext(env, null);
            }
        });
    } catch (LoginException | PrivilegedActionException e) {
        NamingException namingException = new NamingException(e.getMessage());
        namingException.initCause(e);
        throw namingException;
    }
    return initialDirContext;
}

From source file:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java

/**
 * @throws NoSuchElementException if no user could be found with the given login
 * @throws AuthenticationException if the password does not match
 * @throws CommunicationException e.g. on server timeout
 * @throws NamingException on any other LDAP error
 *//*from ww  w .j  a  v  a  2s.c  o m*/
private HashMap<String, String> auth(String login, String password) throws NamingException {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put("com.sun.jndi.ldap.read.timeout", timeout);
    env.put("com.sun.jndi.ldap.connect.timeout", connectTimeout);
    if (binddn != null) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, binddn);
        env.put(Context.SECURITY_CREDENTIALS, bindpw);
    }

    HashMap<String, String> userAttrs = new HashMap<String, String>();
    String uid;

    DirContext ctx = new InitialDirContext(env);
    try {
        uid = searchUser(login, userAttrs, ctx);
    } finally {
        ctx.close();
    }

    if (passwordAttribute != null) {
        if (!userAttrs.containsKey("_pass"))
            throw new NoSuchElementException();
        String pass = userAttrs.get("_pass");
        if (pass == null || !pass.startsWith("{x-plain}"))
            throw new NoSuchElementException();
        log.debug("found password");
        pass = pass.substring(9);
        if (!pass.equals(password))
            throw new NoSuchElementException();
        userAttrs.remove("_pass");
    } else {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, uid + "," + base);
        env.put(Context.SECURITY_CREDENTIALS, password);
        DirContext ctx2 = new InitialDirContext(env);
        try {
            if (readAttributesAsSelf)
                searchUser(login, userAttrs, ctx2);
        } finally {
            ctx2.close();
        }
    }
    return userAttrs;
}

From source file:it.doqui.index.ecmengine.client.engine.EcmEngineDirectDelegateImpl.java

protected EcmEngineSearchBusinessInterface createSearchService() throws Throwable {
    this.log.debug("[" + getClass().getSimpleName() + "::createSearchService] BEGIN ");

    Properties properties = new Properties();

    /* Caricamento del file contenenti le properties su cui fare il binding */
    rb = ResourceBundle.getBundle(ECMENGINE_PROPERTIES_FILE);

    /*// w w  w.  j a v a 2s.  c  o m
    * Caricamento delle proprieta' su cui fare il binding all'oggetto di business delle funzionalita'
    * implementate per la ricerca.
    */
    try {
        this.log.debug("[" + getClass().getSimpleName() + "::createSearchService] P-Delegata di search.");

        this.log.debug("[" + getClass().getSimpleName() + "::createSearchService] context factory vale : "
                + rb.getString(ECMENGINE_CONTEXT_FACTORY));
        properties.put(Context.INITIAL_CONTEXT_FACTORY, rb.getString(ECMENGINE_CONTEXT_FACTORY));
        this.log.debug("[" + getClass().getSimpleName() + "::createSearchService] url to connect vale : "
                + rb.getString(ECMENGINE_URL_TO_CONNECT));
        properties.put(Context.PROVIDER_URL, rb.getString(ECMENGINE_URL_TO_CONNECT));

        /* Controllo che la property cluster partition sia valorizzata per capire se
         * sto lavorando in una configurazione in cluster oppure no */
        String clusterPartition = rb.getString(ECMENGINE_CLUSTER_PARTITION);
        this.log.debug("[" + getClass().getSimpleName() + "::createSearchService] clusterPartition vale : "
                + clusterPartition);
        if (clusterPartition != null && clusterPartition.length() > 0) {
            properties.put("jnp.partitionName", clusterPartition);
            this.log.debug("[" + getClass().getSimpleName() + "::createSearchService] disable discovery vale : "
                    + rb.getString(ECMENGINE_DISABLE_DISCOVERY));
            properties.put("jnp.disableDiscovery", rb.getString(ECMENGINE_DISABLE_DISCOVERY));
        }

        // Get an initial context
        InitialContext jndiContext = new InitialContext(properties);
        log.debug("[" + getClass().getSimpleName() + "::createSearchService] context istanziato");

        // Get a reference to the Bean
        Object ref = jndiContext.lookup(ECMENGINE_SEARCH_JNDI_NAME);

        // Get a reference from this to the Bean's Home interface
        EcmEngineSearchHome home = (EcmEngineSearchHome) PortableRemoteObject.narrow(ref,
                EcmEngineSearchHome.class);

        // Create an Adder object from the Home interface
        return home.create();

    } catch (Throwable e) {
        this.log.error("[" + getClass().getSimpleName() + "::createSearchService] "
                + "Impossibile l'EJB di management: " + e.getMessage());
        throw e;
    } finally {
        this.log.debug("[" + getClass().getSimpleName() + "::createSearchService] END ");
    }
}

From source file:net.sf.ehcache.distribution.JNDIManualRMICacheManagerPeerProvider.java

/**
 * Register a new peer by looking it up in JNDI and storing
 * in a local cache the Context.//from w ww . j  a v a2 s . c  o m
 *
 * @param jndiProviderUrl
 */
private Context registerPeerToContext(String jndiProviderUrl) {
    String initialContextFactory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY);
    if (LOG.isDebugEnabled()) {
        LOG.debug("registerPeerToContext: " + jndiProviderUrl + " " + extractProviderUrl(jndiProviderUrl)
                + " with " + initialContextFactory);
    }
    Hashtable hashTable = new Hashtable(1);
    hashTable.put(Context.PROVIDER_URL, extractProviderUrl(jndiProviderUrl));
    Context initialContext = null;
    try {
        initialContext = new InitialContext(hashTable);
        registerPeerToContext(jndiProviderUrl, initialContext);

    } catch (NamingException e) {
        LOG.warn(jndiProviderUrl + " " + e.getMessage());
        registerPeerToContext(jndiProviderUrl, null);
    }
    return initialContext;
}

From source file:org.bonitasoft.engine.test.BonitaTestEngine.java

private void initializeEnvironment() {
    setSystemPropertyIfNotSet("sysprop.bonita.db.vendor", "h2");

    // Force these system properties
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
            "org.bonitasoft.engine.local.SimpleMemoryContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.bonitasoft.engine.local");

    final List<String> springConfigLocations = getSpringConfigLocations();
    springContext = new ClassPathXmlApplicationContext(
            springConfigLocations.toArray(new String[springConfigLocations.size()]));
}

From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java

private void createLdapContext() throws Throwable {
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUrl);
    if (ldapUrl.startsWith("ldaps")
            && (config.getSSLTrustStorePath() != null && !config.getSSLTrustStorePath().trim().isEmpty())) {
        env.put("java.naming.ldap.factory.socket",
                "org.apache.ranger.ldapusersync.process.CustomSSLSocketFactory");
    }//from  w  ww  . j a v  a 2s .  c o m

    ldapContext = new InitialLdapContext(env, null);
    if (!ldapUrl.startsWith("ldaps")) {
        if (config.isStartTlsEnabled()) {
            tls = (StartTlsResponse) ldapContext.extendedOperation(new StartTlsRequest());
            if (config.getSSLTrustStorePath() != null && !config.getSSLTrustStorePath().trim().isEmpty()) {
                tls.negotiate(CustomSSLSocketFactory.getDefault());
            } else {
                tls.negotiate();
            }
            LOG.info("Starting TLS session...");
        }
    }

    ldapContext.addToEnvironment(Context.SECURITY_PRINCIPAL, ldapBindDn);
    ldapContext.addToEnvironment(Context.SECURITY_CREDENTIALS, ldapBindPassword);
    ldapContext.addToEnvironment(Context.SECURITY_AUTHENTICATION, ldapAuthenticationMechanism);
    ldapContext.addToEnvironment(Context.REFERRAL, ldapReferral);
}

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

/**
 * Connect to the LDAP server with System DN and Password Configuration: LDAP URL = olatextconfig.xml (property=ldapURL) System DN = olatextconfig.xml
 * (property=ldapSystemDN) System PW = olatextconfig.xml (property=ldapSystemPW)
 * //from w w w  . j ava 2  s.c  om
 * @return The LDAP connection (LdapContext) or NULL if connect fails
 * @throws NamingException
 */
public LdapContext bindSystem() {
    // set LDAP connection attributes
    final 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());

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

    try {
        final InitialLdapContext ctx = new InitialLdapContext(env, new Control[] {});
        ctx.getConnectControls();
        return ctx;
    } catch (final NamingException e) {
        logError("NamingException when trying to bind system with DN::" + LDAPLoginModule.getLdapSystemDN()
                + " and PW::" + LDAPLoginModule.getLdapSystemPW() + " on URL::" + LDAPLoginModule.getLdapUrl(),
                e);
        return null;
    } catch (final Exception e) {
        logError("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.webterm.core.plugin.authentication.LdapAuthentication.java

@Override
public void init() {
    LOG.info("Initializing LDAP authentication..."); //$NON-NLS-1$

    try {//from   w  ww. j a  v a  2 s .co m
        final ConfigurationReader config = ConfigurationReader.getInstance();
        final String serverName = config.getApplicationProperty(CONFIG_SERVER_NAME);
        final String serverPort = config.getApplicationProperty(CONFIG_SERVER_PORT);
        final String bindDn = config.getApplicationProperty(CONFIG_BIND_DN);
        final String bindPwd = config.getApplicationProperty(CONFIG_BIND_PWD);
        this.baseDn = config.getApplicationProperty(CONFIG_BASE_DN);
        this.attrUser = config.getApplicationProperty(CONFIG_ATTR_USER);
        this.attrPwd = config.getApplicationProperty(CONFIG_ATTR_PWD);
        this.checkMethode = this.map.get(config.getApplicationProperty(CONFIG_PASSWORD_ENCODE));
        if (this.checkMethode == null) {
            LOG.fatal("unknown method: " + config.getApplicationProperty(CONFIG_PASSWORD_ENCODE)); //$NON-NLS-1$
        }

        final Hashtable<String, String> ldapEnv = new Hashtable<String, String>(); // NOPMD - HashTable is needed
        ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); //$NON-NLS-1$
        ldapEnv.put(Context.PROVIDER_URL, "ldap://" + serverName + ":" + serverPort); //$NON-NLS-1$ //$NON-NLS-2$
        ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");//$NON-NLS-1$
        ldapEnv.put(Context.SECURITY_PRINCIPAL, bindDn);
        ldapEnv.put(Context.SECURITY_CREDENTIALS, bindPwd);
        this.ldapContext = new InitialDirContext(ldapEnv);
    } catch (Exception ex) {
        LOG.error(ex, ex);
    }
}

From source file:org.apache.torque.JndiConfigurationTest.java

/**
 * Binds a DataSource to the jndi and checks that we have successfully
 * bound it. Then Torque is configured to lookup the DataSource in jndi,
 * and it is checked if Torque can read from the database. Finally,
 * the DataSource is closed and unbound.
 * @throws Exception if the test fails//from   ww  w.  j ava 2 s.  c o  m
 */
public void testTorqueBindTorqueLookup() throws Exception {
    // compose the correct configuration
    Configuration torqueConfiguration = getTorqueConfiguraton();
    String defaultDatabase = getDefaultDatabase(torqueConfiguration);

    // add the jndi configuration to the configuration
    torqueConfiguration.setProperty(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "."
            + defaultDatabase + "." + DataSourceFactory.FACTORY_KEY, JndiDataSourceFactory.class.getName());
    torqueConfiguration.setProperty(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "."
            + defaultDatabase + "." + JndiDataSourceFactory.JNDI_KEY + "." + JndiDataSourceFactory.PATH_KEY,
            JNDI_PATH);
    torqueConfiguration.setProperty(
            Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase + "."
                    + JndiDataSourceFactory.JNDI_KEY + "." + Context.INITIAL_CONTEXT_FACTORY,
            org.apache.naming.java.javaURLContextFactory.class.getName());

    // add the datasource configuration
    torqueConfiguration.setProperty(
            Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase + "."
                    + JndiDataSourceFactory.DATASOURCE_KEY + "." + JndiDataSourceFactory.CLASSNAME_KEY,
            BasicDataSource.class.getName());
    {
        Map tempStore = new HashMap();
        Configuration connectionConfiguration = torqueConfiguration
                .subset(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase + "."
                        + AbstractDataSourceFactory.CONNECTION_KEY);
        for (Iterator keyIt = connectionConfiguration.getKeys(); keyIt.hasNext();) {
            String key = (String) keyIt.next();
            String value = connectionConfiguration.getString(key);

            if ("user".equals(key)) {
                // setUser() in SharedPoolDataSouce corresponds to
                // setUsername() in BasicDataSourceFactory
                key = "username";
            } else if ("driver".equals(key)) {
                // setDriver() in SharedPoolDataSouce corresponds to
                // setDriverClassName() in BasicDataSourceFactory
                key = "driverClassName";
            }
            tempStore.put(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase
                    + "." + JndiDataSourceFactory.DATASOURCE_KEY + "." + key, value);
        }
        // add the new keys
        for (Iterator keyIt = tempStore.keySet().iterator(); keyIt.hasNext();) {
            String key = (String) keyIt.next();
            String value = (String) tempStore.get(key);
            torqueConfiguration.setProperty(key, value);
        }

        // remove the configuration for the original datasource
        connectionConfiguration.clear();
        Configuration poolConfiguration = torqueConfiguration
                .subset(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase + "."
                        + AbstractDataSourceFactory.POOL_KEY);
        poolConfiguration.clear();
    }

    //System.out.println("Configuration for testTorqueBindTorqueLookup:");
    //debugConfiguration(torqueConfiguration);
    //System.out.println();

    try {
        // initialize torque with the created configuration
        // and check that we can connect to the database.
        try {
            Torque.init(torqueConfiguration);
            torqueConnect();
        } finally {
            Torque.shutdown();
        }
    } finally {
        unbindDataSource();
    }
}

From source file:com.wfp.utils.LDAPUtils.java

/**
 * Overloaded method for getting the LDAP COntext based on the host,username, password
 * @param host/*from w  w  w.  j a  v a2  s .  c o m*/
 * @param adminName
 * @param adminPassword
 * @return
 * @throws NamingException
 */
@SuppressWarnings("unchecked")
public static LdapContext getLDAPContext(String host, String adminName, String adminPassword)
        throws NamingException {
    //Logger.info("Creating LDAP Context", LDAPUtils.class);
    Hashtable props = System.getProperties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.SECURITY_AUTHENTICATION, LDAP_SECURITY_AUTHENTICATION);
    props.put(Context.SECURITY_PRINCIPAL, adminName);
    props.put(Context.SECURITY_CREDENTIALS, adminPassword);
    props.put(Context.PROVIDER_URL, host);
    if (!StringUtils.isNull(LDAPConfigUtils.getTrustStorePath())) {
        System.setProperty("javax.net.ssl.trustStore", LDAPConfigUtils.getTrustStorePath());
        props.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    //Logger.info("Completed creating LDAP Context for host ["+host+"]", LDAPUtils.class);
    return (new InitialLdapContext(props, null));
}