Example usage for javax.naming.directory InitialDirContext InitialDirContext

List of usage examples for javax.naming.directory InitialDirContext InitialDirContext

Introduction

In this page you can find the example usage for javax.naming.directory InitialDirContext InitialDirContext.

Prototype

public InitialDirContext(Hashtable<?, ?> environment) throws NamingException 

Source Link

Document

Constructs an initial DirContext using the supplied environment.

Usage

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

/**
 * @param args/*  w  ww  .ja va2 s .  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:es.udl.asic.user.OpenLdapDirectoryProvider.java

private boolean getUserInf(UserEdit edit, String filter) {

    String id = null;//  w ww . ja  v  a2 s  .c  o m
    String firstName = null;
    String lastName = null;
    String employeenumber = null;
    String email = null;
    try {
        DirContext ctx = new InitialDirContext(env);

        // Setup subtree scope to tell LDAP to recursively descend directory structure
        // during searches.
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // We want the user's id, first name and last name ...
        searchControls.setReturningAttributes(new String[] { "uid", "givenName", "sn" });

        // Execute the search, starting at the directory level of Users
        NamingEnumeration results = ctx.search(getBasePath(), filter, searchControls);

        while (results.hasMore()) {
            SearchResult result = (SearchResult) results.next();
            String dn = result.getName().toString() + "," + getBasePath();
            Attributes attrs = ctx.getAttributes(dn);
            id = attrs.get("uid").get().toString();
            String cn = attrs.get("cn").get().toString();
            firstName = cn.substring(0, cn.indexOf(" "));
            lastName = cn.substring(cn.indexOf(" "));
            email = attrs.get("mail").get().toString();
        }

        results.close();
        ctx.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }

    edit.setId(id);
    edit.setFirstName(firstName);
    edit.setLastName(lastName);
    edit.setEmail(email);
    return true;
}

From source file:org.openadaptor.auxil.connector.jndi.JNDIConnection.java

/**
 * Connect to a JNDI Service using the Alternate Provider URL.
 *
 * @return DirContext obtained./*from   w w  w  . j  ava2s. c  om*/
 * @throws NamingException
 */
public DirContext connectAlternate() throws NamingException {
    if (_alternateProviderUrl != null) {
        return new InitialDirContext(getAlternateConnectionProperties());
    } else {
        log.warn("Alternate Provider URL not Set. No alternative properties to try.");
        return null;
    }
}

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 w w w.  j  a  va2  s.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:org.pepstock.jem.gwt.server.security.ExtendedJndiLdapRealm.java

/**
 * Extract from LDAP all configured attributes.
 * //from   w  ww . j a v  a 2 s  .  c om
 * @param id user id
 * @param environment LDAP environment 
 * @return list of principal attributes
 */
public List<PrincipalAttribute> search(String id, Hashtable<String, String> environment) {
    // checks if attributes are set
    if (attributes != null && attributes.length > 0) {
        ctls.setReturningAttributes(attributes);
    }
    // if no attributes, uses UID by default
    if (ctls.getReturningAttributes() == null) {
        ctls.setReturningAttributes(new String[] { UID });
    }

    // uses useDN for searching
    String userDn = super.getUserDnTemplate();
    String ldapUserContext = StringUtils.substringAfter(userDn, ",");
    try {
        // gets initial context
        InitialDirContext ctx = new InitialDirContext(environment);

        // creates search string
        String filter = MessageFormat.format("(uid={0})", new Object[] { id });
        // searchs!
        Object obj = ctx.search(ldapUserContext, filter, ctls);
        // scans all attributes and load into a Principal Attribute
        @SuppressWarnings("rawtypes")
        NamingEnumeration userEnum = (NamingEnumeration) obj;
        if (userEnum != null && userEnum.hasMore()) {
            SearchResult result = (SearchResult) userEnum.next();
            return loadAttributes(id, result.getAttributes());
        }
    } catch (NamingException ne) {
        LogAppl.getInstance().emit(UserInterfaceMessage.JEMG031E, ne, id);
    }
    return new ArrayList<PrincipalAttribute>();
}

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

/**
 * Test to make sure that if anonymous binds are allowed a user may search
 * within a a partition./* w ww  .  ja  v  a2 s .c  om*/
 *
 * @throws Exception if anything goes wrong
 */
@Test
public void testAnonymousBindsEnabledBaseSearch() 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("dc=apache,dc=org", "(objectClass=*)", cons);
    SearchResult result = null;

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

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

    assertNotNull(result);
    assertNotNull(result.getAttributes().get("dc"));
}

From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java

/**
 * Retrieves the roles for the from the identity provider.
 *
 * @param username the user to get the roles for
 * @return the list of roles for the user
 * @throws PortalServiceException for any errors encountered
 *///w w  w.  j ava 2s  . co m
@SuppressWarnings("rawtypes")
public List<String> findRoles(String username) throws PortalServiceException {
    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);

        // Search for groups the user belongs to in order to get their names
        // Create the search controls
        SearchControls groupsSearchCtls = new SearchControls();

        // Specify the search scope
        groupsSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // Specify the attributes to return
        String groupsReturnedAtts[] = { "cn" };
        groupsSearchCtls.setReturningAttributes(groupsReturnedAtts);

        String userDn = MessageFormat.format(userDNPattern, username);
        // Search for objects using the filter
        NamingEnumeration groupsAnswer = ctx.search(groupsSearchBase,
                MessageFormat.format(groupsFilterPattern, userDn), groupsSearchCtls);

        List<String> groups = new ArrayList<String>();
        // Loop through the search results
        while (groupsAnswer.hasMoreElements()) {

            SearchResult sr = (SearchResult) groupsAnswer.next();
            Attributes attrs = sr.getAttributes();

            if (attrs != null) {
                groups.add((String) attrs.get("cn").get());
            }

            if (sr.getObject() instanceof Context) {
                closeContext((Context) sr.getObject());
            }
        }
        return groups;
    } catch (NamingException e) {
        throw new PortalServiceConfigurationException("Unable to get groups.", e);
    } finally {
        closeContext(ctx);
    }
}

From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java

/**
 * @see com.alfaariss.oa.api.idmapper.IIDMapper#start(com.alfaariss.oa.api.configuration.IConfigurationManager, org.w3c.dom.Element)
 *///  w  w  w  .  j  a  v  a 2  s  .  c  om
public void start(IConfigurationManager configManager, Element config) throws OAException {
    try {
        Element eResource = configManager.getSection(config, "resource");
        if (eResource == null) {
            _logger.error("No 'resource' section found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        Element eDN = configManager.getSection(eResource, "dn");
        if (eDN == null) {
            _logger.error("No 'dn' section found in 'resource' section in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        _sDNBase = configManager.getParam(eDN, "base");
        if (_sDNBase == null) {
            _logger.error("No 'dn' item found in 'base' section in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        Element eID = configManager.getSection(eDN, "id");
        if (eID == null) {
            _logger.warn("No 'id' section found in 'dn' section in configuration");
            _logger.info("Mapping from Distinguished Name (supplied id must be a Distinguished Name)");
            _sIDAttribute = null;
        } else {
            _sIDAttribute = configManager.getParam(eID, "attribute");
            if (_sIDAttribute == null) {
                _logger.error("No 'attribute' item found in 'id' section in configuration");
                throw new OAException(SystemErrors.ERROR_CONFIG_READ);
            }
        }

        Element eMapper = configManager.getSection(eDN, "mapper");
        if (eMapper == null) {
            if (_sIDAttribute == null) {
                _logger.error(
                        "Invalid id mapper configuration: No 'mapper' section and no 'id' section found in 'dn' section in configuration");
                throw new OAException(SystemErrors.ERROR_CONFIG_READ);
            }

            _logger.warn("No 'mapper' section found in 'dn' section in configuration");
            _logger.info("Mapping to Distinguished Name (the Distinguished Name of the searched attribute)");
            _sMapperAttribute = null;
        } else {
            _sMapperAttribute = configManager.getParam(eMapper, "attribute");
            if (_sMapperAttribute == null) {
                _logger.error("No 'attribute' item found in 'mapper' section in configuration");
                throw new OAException(SystemErrors.ERROR_CONFIG_READ);
            }
        }

        _htJNDIEnvironment = readJNDIContext(configManager, eResource);

        //test connection
        new InitialDirContext(_htJNDIEnvironment);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not initialize object", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:com.openkm.principal.LdapPrincipalAdapter.java

@SuppressWarnings("unchecked")
private List<String> ldapSearch(List<String> searchBases, String searchFilter, String attribute) {
    log.debug("ldapSearch({}, {}, {})", new Object[] { searchBases, searchFilter, attribute });
    List<String> al = new ArrayList<String>();
    DirContext ctx = null;/*from   w  w w  .j  a  v  a2s .co m*/
    Hashtable<String, String> env = getEnvironment();

    try {
        ctx = new InitialDirContext(env);
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        for (String searchBase : searchBases) {
            NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchCtls);

            while (results.hasMore()) {
                SearchResult searchResult = (SearchResult) results.next();
                Attributes attributes = searchResult.getAttributes();

                if (attribute.equals("")) {
                    StringBuilder sb = new StringBuilder();

                    for (NamingEnumeration<?> ne = attributes.getAll(); ne.hasMore();) {
                        Attribute attr = (Attribute) ne.nextElement();
                        sb.append(attr.toString());
                        sb.append("\n");
                    }

                    al.add(sb.toString());
                } else {
                    Attribute attrib = attributes.get(attribute);

                    if (attrib != null) {
                        // Handle multi-value attributes
                        for (NamingEnumeration<?> ne = attrib.getAll(); ne.hasMore();) {
                            String value = (String) ne.nextElement();

                            // If FQDN get only main part
                            if (value.startsWith("CN=") || value.startsWith("cn=")) {
                                String cn = value.substring(3, value.indexOf(','));
                                log.debug("FQDN: {}, CN: {}", value, cn);
                                al.add(cn);
                            } else {
                                al.add(value);
                            }
                        }
                    }
                }
            }
        }
    } catch (ReferralException e) {
        log.error("ReferralException: {}", e.getMessage());
        log.error("ReferralInfo: {}", e.getReferralInfo());
        log.error("ResolvedObj: {}", e.getResolvedObj());

        try {
            log.error("ReferralContext: {}", e.getReferralContext());
        } catch (NamingException e1) {
            log.error("NamingException logging context: {}", e1.getMessage());
        }
    } catch (NamingException e) {
        log.error("NamingException: {} (Base: {} - Filter: {} - Attribute: {})",
                new Object[] { e.getMessage(), searchBases, searchFilter, attribute });
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException e) {
            log.error("NamingException closing context: {}", e.getMessage());
        }
    }

    log.debug("ldapSearch: {}", al);
    return al;
}