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.olat.ldap.manager.LDAPLoginManagerImpl.java

/**
 * Connect to the LDAP server with System DN and Password
 * /*from   w  w w.java 2 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;/*  w  w w .j a  v a  2  s .  co  m*/
    try {
        ctx = new InitialDirContext(env);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
    return ctx;
}

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);
    }//  w  w  w.ja va  2 s  . com

    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.wso2.carbon.user.core.ldap.LDAPConnectionContext.java

public DirContext getContext() throws UserStoreException {
    DirContext context = null;//w w w  .  j  a  va 2 s.  c  o m
    //if dcMap is not populated, it is not DNS case
    if (dcMap == null) {
        try {
            context = new InitialDirContext(environment);

        } catch (NamingException e) {
            log.error("Error obtaining connection. " + e.getMessage(), e);
            log.error("Trying again to get connection.");

            try {
                context = new InitialDirContext(environment);
            } catch (Exception e1) {
                log.error("Error obtaining connection for the second time" + e.getMessage(), e);
                throw new UserStoreException("Error obtaining connection. " + e.getMessage(), e);
            }

        }
    } else if (dcMap != null && dcMap.size() != 0) {
        try {
            //first try the first entry in dcMap, if it fails, try iteratively
            Integer firstKey = dcMap.firstKey();
            SRVRecord firstRecord = dcMap.get(firstKey);
            //compose the connection URL
            environment.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(firstRecord));
            context = new InitialDirContext(environment);

        } catch (NamingException e) {
            log.error("Error obtaining connection to first Domain Controller." + e.getMessage(), e);
            log.info("Trying to connect with other Domain Controllers");

            for (Integer integer : dcMap.keySet()) {
                try {
                    SRVRecord srv = dcMap.get(integer);
                    environment.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(srv));
                    context = new InitialDirContext(environment);
                    break;
                } catch (NamingException e1) {
                    if (integer == (dcMap.lastKey())) {
                        log.error("Error obtaining connection for all " + integer + " Domain Controllers."
                                + e.getMessage(), e);
                        throw new UserStoreException("Error obtaining connection. " + e.getMessage(), e);
                    }
                }
            }
        }
    }
    return (context);

}

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

/**
 * @param args//from  w w  w  .  j av  a2s  .c  o 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.jboss.additional.testsuite.jdkall.present.elytron.sasl.OtpSaslTestCase.java

/**
 * Check correct user attribute values in the LDAP when using OTP algorithm.
 *///from www  .jav  a 2s . c  om
private void assertSequenceAndHash(Integer expectedSequence, byte[] expectedHash) throws NamingException {
    final Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAP_URL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    final LdapContext ctx = new InitialLdapContext(env, null);
    NamingEnumeration<?> namingEnum = ctx.search("dc=wildfly,dc=org", new BasicAttributes("cn", "jduke"));
    if (namingEnum.hasMore()) {
        SearchResult sr = (SearchResult) namingEnum.next();
        Attributes attrs = sr.getAttributes();
        assertEquals("Unexpected sequence number in LDAP attribute", expectedSequence,
                new Integer(attrs.get("telephoneNumber").get().toString()));
        assertEquals("Unexpected hash value in LDAP attribute",
                Base64.getEncoder().encodeToString(expectedHash), attrs.get("title").get().toString());
    } else {
        fail("User not found in LDAP");
    }

    namingEnum.close();
    ctx.close();
}

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 . ja v  a2s. c om
    try {
        ctx = new InitialDirContext(env);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
    return ctx;
}

From source file:org.nuxeo.ecm.directory.ldap.MockLdapServer.java

public void startLdapServer() {
    cfg = new MutableStartupConfiguration();
    cfg.setWorkingDirectory(workingDir);

    log.debug("Working directory is " + workingDir.getAbsolutePath());

    Properties env = new Properties();

    env.setProperty(Context.PROVIDER_URL, BASE_DN);
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
    env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    env.setProperty(Context.SECURITY_PRINCIPAL, PartitionNexus.ADMIN_PRINCIPAL);
    env.setProperty(Context.SECURITY_CREDENTIALS, PartitionNexus.ADMIN_PASSWORD);

    try {//from   ww w  .  j a  va  2s  .c o  m
        initConfiguration();
        env.putAll(cfg.toJndiEnvironment());
        serverContext = new InitialDirContext(env);
    } catch (NamingException e) {
        log.error("Failed to start Apache DS: ", e);
    }
}

From source file:com.communote.server.test.ldap.AbstractApacheDSServer.java

/**
 * Common code to get an initial context via a simple bind to the server over the wire using the
 * SUN JNDI LDAP provider. Do not use this method until after the setUp() method is called to
 * start the server otherwise it will fail.
 *
 * @param bindPrincipalDn//from w ww.ja va2  s  .  co m
 *            the DN of the principal to bind as
 * @param password
 *            the password of the bind principal
 * @return an LDAP context as the the administrator to the rootDSE
 * @throws Exception
 *             if the server cannot be contacted
 */
protected LdapContext getWiredContext(String bindPrincipalDn, String password) throws Exception {
    // if ( ! apacheDS.isStarted() )
    // {
    // throw new ConfigurationException( "The server is not online! Cannot connect to it." );
    // }

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, CTX_FACTORY);
    env.put(Context.PROVIDER_URL, "ldap://localhost:" + getPort());
    env.put(Context.SECURITY_PRINCIPAL, bindPrincipalDn);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    return new InitialLdapContext(env, null);
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Opens a connection to Active Directory by establishing an initial LDAP
 * context.  The security principal and credentials are assigned the
 * account name and password parameters.
 *
 * @param anAcountDN Active Directory account name (DN format).
 * @param anAccountPassword Active Directory account password.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *///ww  w.ja  v  a 2s. co  m
@SuppressWarnings("unchecked")
public void open(String anAcountDN, String anAccountPassword) throws NSException {
    Logger appLogger = mAppMgr.getLogger(this, "open");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    // LDAP Reference - http://docs.oracle.com/javase/1.5.0/docs/guide/jndi/jndi-ldap-gl.html

    Hashtable<String, String> environmentalVariables = new Hashtable<String, String>();
    environmentalVariables.put("com.sun.jndi.ldap.connect.pool", StrUtl.STRING_TRUE);
    environmentalVariables.put(Context.PROVIDER_URL, getPropertyValue("domain_url", null));
    environmentalVariables.put("java.naming.ldap.attributes.binary", "tokenGroups objectSid");
    environmentalVariables.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environmentalVariables.put(Context.SECURITY_PRINCIPAL, anAcountDN);
    environmentalVariables.put(Context.SECURITY_CREDENTIALS, anAccountPassword);

    // Referral options: follow, throw, ignore (default)

    environmentalVariables.put(Context.REFERRAL, getPropertyValue("referral_handling", "ignore"));

    // Authentication options: simple, DIGEST-MD5 CRAM-MD5

    environmentalVariables.put(Context.SECURITY_AUTHENTICATION, getPropertyValue("authentication", "simple"));

    try {
        mLdapContext = new InitialLdapContext(environmentalVariables, null);
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Context Error: %s", e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}