Example usage for javax.naming Context PROVIDER_URL

List of usage examples for javax.naming Context PROVIDER_URL

Introduction

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

Prototype

String PROVIDER_URL

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

Click Source Link

Document

Constant that holds the name of the environment property for specifying configuration information for the service provider 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  ww  w.j av  a2s  . c  om*/

    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.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   www . ja  v  a2 s.co  m*/
    return new InitialDirContext(env);
}

From source file:org.seedstack.seed.ws.internal.jms.SoapJmsUri.java

static Context getContext(SoapJmsUri soapJmsUri) throws NamingException {
    Properties properties = new Properties();

    String jndiInitialContextFactory = soapJmsUri.getParameter("jndiInitialContextFactory");
    if (!StringUtils.isEmpty(jndiInitialContextFactory)) {
        properties.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, jndiInitialContextFactory);
    }/*from   w  ww .ja v  a 2s .c  o  m*/

    String jndiURL = soapJmsUri.getParameter("jndiURL");
    if (!StringUtils.isEmpty(jndiURL)) {
        properties.setProperty(javax.naming.Context.PROVIDER_URL, jndiURL);
    }

    return new InitialContext(properties);
}

From source file:com.mirth.connect.connectors.jms.JmsClient.java

private ConnectionFactory lookupConnectionFactoryWithJndi() throws Exception {
    String channelId = connector.getChannelId();
    String channelName = connector.getChannel().getName();

    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

    try {//  w w  w.  jav a 2 s  .c  o m
        MirthContextFactory contextFactory = contextFactoryController.getContextFactory(resourceIds);
        Thread.currentThread().setContextClassLoader(contextFactory.getApplicationClassLoader());

        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.PROVIDER_URL,
                replacer.replaceValues(connectorProperties.getJndiProviderUrl(), channelId, channelName));
        env.put(Context.INITIAL_CONTEXT_FACTORY, replacer
                .replaceValues(connectorProperties.getJndiInitialContextFactory(), channelId, channelName));
        env.put(Context.SECURITY_PRINCIPAL,
                replacer.replaceValues(connectorProperties.getUsername(), channelId, channelName));
        env.put(Context.SECURITY_CREDENTIALS,
                replacer.replaceValues(connectorProperties.getPassword(), channelId, channelName));

        initialContext = new InitialContext(env);
        String connectionFactoryName = replacer
                .replaceValues(connectorProperties.getJndiConnectionFactoryName(), channelId, channelName);
        return (ConnectionFactory) initialContext.lookup(connectionFactoryName);
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

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: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 w  w  w.j  a  va 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: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 a 2 s  .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");
    }//from   ww w  . j a v  a 2  s  . c  o  m
    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:org.apache.lens.server.user.LDAPBackedDatabaseUserConfigLoader.java

/**
 * Instantiates a new LDAP backed database user config loader.
 *
 * @param conf the conf//from  w  w w  . j a  v  a 2s  .c o m
 * @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: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 {/* ww  w  . j a  va  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;
}