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.exist.security.realm.ldap.LdapContextFactory.java

public LdapContext getLdapContext(String username, final String password,
        final Map<String, Object> additionalEnv) throws NamingException {

    if (url == null) {
        throw new IllegalStateException("An LDAP URL must be specified of the form ldap://<hostname>:<port>");
    }//from w  w  w  . j av  a 2s .  c o  m

    if (StringUtils.isBlank(password)) {
        throw new IllegalStateException("Password for LDAP authentication may not be empty.");
    }

    if (username != null && principalPattern != null) {
        username = principalPatternFormat.format(new String[] { username });
    }

    final Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.SECURITY_AUTHENTICATION, authentication);
    if (ssl) {
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }

    if (username != null) {
        env.put(Context.SECURITY_PRINCIPAL, username);
    }

    if (password != null) {
        env.put(Context.SECURITY_CREDENTIALS, password);
    }

    env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactoryClassName);
    env.put(Context.PROVIDER_URL, url);

    //Absolutely nessecary for working with Active Directory
    env.put("java.naming.ldap.attributes.binary", "objectSid");

    // the following is helpful in debugging errors
    //env.put("com.sun.jndi.ldap.trace.ber", System.err);

    // Only pool connections for system contexts
    if (usePooling && username != null && username.equals(systemUsername)) {
        // Enable connection pooling
        env.put(SUN_CONNECTION_POOLING_PROPERTY, "true");
    }

    if (additionalEnv != null) {
        env.putAll(additionalEnv);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Initializing LDAP context using URL [" + url + "] and username [" + username + "] "
                + "with pooling [" + (usePooling ? "enabled" : "disabled") + "]");
    }

    return new InitialLdapContext(env, null);
}

From source file:org.jboss.test.security.test.SubjectContextUnitTestCase.java

public void testAllAuthMethod() throws Exception {
    log.debug("+++ testAllAuthMethod()");
    Properties env = new Properties();
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.security.jndi.JndiLoginInitialContextFactory");
    env.setProperty(Context.SECURITY_PRINCIPAL, "jduke");
    env.setProperty(Context.SECURITY_CREDENTIALS, "theduke");
    InitialContext ctx = new InitialContext(env);
    Object obj = ctx.lookup("jacc/Secured");
    obj = PortableRemoteObject.narrow(obj, SecuredServiceRemoteHome.class);
    SecuredServiceRemoteHome home = (SecuredServiceRemoteHome) obj;
    log.debug("Found SecuredServiceRemoteHome");
    SecuredServiceRemote bean = home.create();
    log.debug("Created SecuredServiceRemote");

    Principal callerIdentity = new SimplePrincipal("jduke");
    Principal runAsIdentity = new SimplePrincipal("runAsUser");
    HashSet expectedCallerRoles = new HashSet();
    expectedCallerRoles.add("groupMemberCaller");
    expectedCallerRoles.add("userCaller");
    expectedCallerRoles.add("allAuthCaller");
    expectedCallerRoles.add("webUser");
    HashSet expectedRunAsRoles = new HashSet();
    expectedRunAsRoles.add("identitySubstitutionCaller");
    expectedRunAsRoles.add("extraRunAsRole");
    CallerInfo info = new CallerInfo(callerIdentity, runAsIdentity, expectedCallerRoles, expectedRunAsRoles);
    bean.allAuthMethod(info);/*from  w  w w.j  ava  2  s  .co  m*/
    bean.remove();
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private DirContext initContext() throws NamingException {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    env.put(Context.PROVIDER_URL, this.connectionURL);
    env.put("java.naming.ldap.version", "3");
    if (this.connectionName != null) {
        env.put(Context.SECURITY_PRINCIPAL, this.connectionName);
        env.put(Context.SECURITY_CREDENTIALS, this.connectionPassword);
    }//from ww w.j  ava  2 s.  c  om
    return new InitialDirContext(env);
}

From source file:org.openiam.idm.srvc.synch.service.generic.LdapAdapterForGenericObject.java

private boolean connect(SynchConfig config) throws NamingException {

    Hashtable<String, String> envDC = new Hashtable();
    System.setProperty("javax.net.ssl.trustStore", keystore);

    String hostUrl = config.getSrcHost(); // managedSys.getHostUrl();
    log.debug("Directory host url:" + hostUrl);

    envDC.put(Context.PROVIDER_URL, hostUrl);
    envDC.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    envDC.put(Context.SECURITY_AUTHENTICATION, "simple"); // simple
    envDC.put(Context.SECURITY_PRINCIPAL, config.getSrcLoginId()); // "administrator@diamelle.local"
    envDC.put(Context.SECURITY_CREDENTIALS, config.getSrcPassword());

    if (hostUrl.contains("ldaps")) {

        envDC.put(Context.SECURITY_PROTOCOL, "SSL");
    }//from  ww w.  j  a va 2 s  . c o  m

    ctx = new InitialLdapContext(envDC, null);
    if (ctx != null) {
        return true;
    }

    return false;

}

From source file:nl.nn.adapterframework.jms.JNDIBase.java

protected Hashtable getJndiEnv() throws NamingException {
    Properties jndiEnv = new Properties();

    if (StringUtils.isNotEmpty(getJndiProperties())) {
        URL url = ClassUtils.getResourceURL(classLoader, getJndiProperties());
        if (url == null) {
            throw new NamingException("cannot find jndiProperties from [" + getJndiProperties() + "]");
        }/*from www.  ja v a  2  s.c o  m*/
        try {
            jndiEnv.load(url.openStream());
        } catch (IOException e) {
            throw new NamingException("cannot load jndiProperties [" + getJndiProperties() + "] from url ["
                    + url.toString() + "]");
        }
    }
    if (getInitialContextFactoryName() != null)
        jndiEnv.put(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactoryName());
    if (getProviderURL() != null)
        jndiEnv.put(Context.PROVIDER_URL, getProviderURL());
    if (getAuthentication() != null)
        jndiEnv.put(Context.SECURITY_AUTHENTICATION, getAuthentication());
    if (getPrincipal() != null || getCredentials() != null || getJndiAuthAlias() != null) {
        CredentialFactory jndiCf = new CredentialFactory(getJndiAuthAlias(), getPrincipal(), getCredentials());
        if (StringUtils.isNotEmpty(jndiCf.getUsername()))
            jndiEnv.put(Context.SECURITY_PRINCIPAL, jndiCf.getUsername());
        if (StringUtils.isNotEmpty(jndiCf.getPassword()))
            jndiEnv.put(Context.SECURITY_CREDENTIALS, jndiCf.getPassword());
    }
    if (getUrlPkgPrefixes() != null)
        jndiEnv.put(Context.URL_PKG_PREFIXES, getUrlPkgPrefixes());
    if (getSecurityProtocol() != null)
        jndiEnv.put(Context.SECURITY_PROTOCOL, getSecurityProtocol());

    if (log.isDebugEnabled()) {
        for (Iterator it = jndiEnv.keySet().iterator(); it.hasNext();) {
            String key = (String) it.next();
            String value = jndiEnv.getProperty(key);
            log.debug("jndiEnv [" + key + "] = [" + value + "]");
        }
    }
    return jndiEnv;
}

From source file:com.surevine.chat.auth.GroupAuthorisationFilter.java

protected InitialDirContext getLdapConnection() throws NamingException {
    Properties ldapEnv = new Properties();
    ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    ldapEnv.put(Context.PROVIDER_URL, "ldap://" + _host + "/" + _rootContext);
    ldapEnv.put(Context.SECURITY_PRINCIPAL, _rootDN);
    ldapEnv.put(Context.SECURITY_CREDENTIALS, _rootPW);
    return new InitialDirContext(ldapEnv);

}

From source file:org.apache.lens.server.user.LDAPBackedDatabaseUserConfigLoader.java

/**
 * Instantiates a new LDAP backed database user config loader.
 *
 * @param conf the conf/*from w  ww  . j  a  v  a 2  s  . c  om*/
 * @throws UserConfigLoaderException the user config loader exception
 */
public LDAPBackedDatabaseUserConfigLoader(final HiveConf conf) throws UserConfigLoaderException {
    super(conf);
    expiryHours = conf.getInt(LensConfConstants.USER_RESOLVER_CACHE_EXPIRY, 2);
    intermediateQuerySql = conf.get(LensConfConstants.USER_RESOLVER_LDAP_INTERMEDIATE_DB_QUERY);
    intermediateDeleteSql = conf.get(LensConfConstants.USER_RESOLVER_LDAP_INTERMEDIATE_DB_DELETE_SQL);
    intermediateInsertSql = conf.get(LensConfConstants.USER_RESOLVER_LDAP_INTERMEDIATE_DB_INSERT_SQL);
    ldapFields = conf.get(LensConfConstants.USER_RESOLVER_LDAP_FIELDS).split("\\s*,\\s*");
    searchBase = conf.get(LensConfConstants.USER_RESOLVER_LDAP_SEARCH_BASE);
    searchFilterPattern = conf.get(LensConfConstants.USER_RESOLVER_LDAP_SEARCH_FILTER);
    intermediateCache = CacheBuilder.newBuilder().expireAfterWrite(expiryHours, TimeUnit.HOURS)
            .maximumSize(conf.getInt(LensConfConstants.USER_RESOLVER_CACHE_MAX_SIZE, 100)).build();
    cache = CacheBuilder.newBuilder().expireAfterWrite(expiryHours, TimeUnit.HOURS)
            .maximumSize(conf.getInt(LensConfConstants.USER_RESOLVER_CACHE_MAX_SIZE, 100)).build();

    env = new Hashtable<String, Object>() {
        {
            put(Context.SECURITY_AUTHENTICATION, "simple");
            put(Context.SECURITY_PRINCIPAL, conf.get(LensConfConstants.USER_RESOLVER_LDAP_BIND_DN));
            put(Context.SECURITY_CREDENTIALS, conf.get(LensConfConstants.USER_RESOLVER_LDAP_BIND_PASSWORD));
            put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            put(Context.PROVIDER_URL, conf.get(LensConfConstants.USER_RESOLVER_LDAP_URL));
            put("java.naming.ldap.attributes.binary", "objectSID");
        }
    };
}

From source file:org.sonar.plugins.ldap.LdapContextFactory.java

private InitialDirContext createInitialDirContext(String principal, String credentials, boolean pooling)
        throws NamingException {
    final InitialLdapContext ctx;
    if (startTLS) {
        // Note that pooling is not enabled for such connections, because "Stop TLS" is not performed.
        Properties env = new Properties();
        env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
        env.put(Context.PROVIDER_URL, providerUrl);
        env.put(Context.REFERRAL, DEFAULT_REFERRAL);
        // At this point env should not contain properties SECURITY_AUTHENTICATION, SECURITY_PRINCIPAL and SECURITY_CREDENTIALS to avoid "bind" operation prior to StartTLS:
        ctx = new InitialLdapContext(env, null);
        // http://docs.oracle.com/javase/jndi/tutorial/ldap/ext/starttls.html
        StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
        try {//w w w .jav  a2s.co m
            tls.negotiate();
        } catch (IOException e) {
            NamingException ex = new NamingException("StartTLS failed");
            ex.initCause(e);
            throw ex;
        }
        // Explicitly initiate "bind" operation:
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, authentication);
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
        ctx.reconnect(null);
    } else {
        ctx = new InitialLdapContext(getEnvironment(principal, credentials, pooling), null);
    }
    return ctx;
}

From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java

private LdapContext getLdapContext() throws NamingException, AuthenticationException {
    if (config == null) {
        throw new NamingException("LDAP not configured");
    }//  w  w  w.j a va  2 s  .  c om
    if (StringUtils.isBlank(config.getProviderUrl())) {
        throw new NamingException("No LDAP server available");
    }
    if (StringUtils.isBlank(config.getUsername()) || StringUtils.isBlank(config.getPassword())) {
        throw new AuthenticationException("No LDAP credentials available");
    }
    String ctxFactory = config.getCtxFactory();
    if (StringUtils.isBlank(ctxFactory)) {
        ctxFactory = DEFAULT_CONTEXT_FACTORY;
    }
    String authentication = config.getAuthentication();
    if (StringUtils.isBlank(authentication)) {
        authentication = SIMPLE_AUTHENTICATION;
    }

    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, ctxFactory);
    env.put(Context.PROVIDER_URL, config.getProviderUrl());
    env.put(Context.SECURITY_PRINCIPAL, config.getUsername());
    env.put(Context.SECURITY_CREDENTIALS, config.getPassword());
    env.put(Context.SECURITY_AUTHENTICATION, authentication);
    if (StringUtils.isNotBlank(config.getReferral())) {
        env.put(Context.REFERRAL, config.getReferral());
    }
    if (config.getProviderUrl().startsWith(LDAPS_SCHEME)) {
        env.put(Context.SECURITY_PROTOCOL, "ssl"); //$NON-NLS-1$
        if (config.isSslNoVerify()) {
            env.put(JNDI_SOCKET_FACTORY, LDAPTrustAllSocketFactory.class.getName());
        }
    }
    // Gemini-specific properties
    env.put(JNDIConstants.BUNDLE_CONTEXT, FrameworkUtil.getBundle(LDAPClient.class).getBundleContext());

    // com.sun.jndi.ldap.LdapCtxFactory specific properties
    env.put(READ_TIMEOUT, DEFAULT_READ_TIMEOUT);
    env.put(USE_CONNECTION_POOLING, "true"); //$NON-NLS-1$

    // extremly ugly classloading workaround:
    // com.sun.jndi.ldap.LdapCtxFactory uses Class.forName() to load the socket factory, shame on them!
    InitialLdapContext ctx = null;
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(LDAPTrustAllSocketFactory.class.getClassLoader());
        ctx = new InitialLdapContext(env, null);
    } finally {
        if (classloader != null) {
            Thread.currentThread().setContextClassLoader(classloader);
        }
    }
    return ctx;
}

From source file:fr.iphc.grid.jobmonitor.CeList.java

static public ArrayList<URL> AvailableLdapCe() throws Exception {
    ArrayList<URL> CeList = new ArrayList<URL>();
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://cclcgtopbdii01.in2p3.fr:2170");
    env.put("java.naming.ldap.attributes.binary", "objectSID");
    try {// w w  w. j av a  2 s. c  o m
        // Create initial context
        DirContext ctx = new InitialDirContext(env);
        SearchControls contraints = new SearchControls();
        contraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attributIDs = { "GlueCEUniqueID" };
        contraints.setReturningAttributes(attributIDs);
        String BASE_SEARCH = "Mds-Vo-name=local,o=grid";
        String filter = "(&(objectClass=GlueCE)(GlueCEImplementationName=CREAM)(GlueCEAccessControlBaseRule=VO:biomed))";
        NamingEnumeration<SearchResult> answer = ctx.search(BASE_SEARCH, filter, contraints);
        //         int index = 0;
        Random rand = new Random();
        while (answer.hasMore()) {
            //            index++;
            SearchResult result = answer.next();
            //            Attributes attrs = result.getAttributes();
            //            NamingEnumeration f = attrs.getAll();
            //            Attribute attr = (Attribute) f.next();
            String line = "cream://" + result.getAttributes().get("GlueCEUniqueID").get() + "?delegationId="
                    + rand.nextLong();
            URL serviceURL = URLFactory.createURL(line);
            CeList.add(serviceURL);
        }
        // Close the context when we're done
        ctx.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    ;
    return CeList;
}