Example usage for javax.naming NamingEnumeration hasMore

List of usage examples for javax.naming NamingEnumeration hasMore

Introduction

In this page you can find the example usage for javax.naming NamingEnumeration hasMore.

Prototype

public boolean hasMore() throws NamingException;

Source Link

Document

Determines whether there are any more elements in the enumeration.

Usage

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * check if User already exists on system.
 *
 * @param inLogin//from   w w w . jav a  2 s  .c  o m
 *            String
 * @return path as string
 */
public boolean isUserAlreadyExists(String inLogin) {
    Hashtable<String, String> env = getLdapConnectionSettings();
    env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
    env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));
    DirContext ctx;
    boolean rueckgabe = false;
    try {
        ctx = new InitialDirContext(env);
        Attributes matchAttrs = new BasicAttributes(true);
        NamingEnumeration<SearchResult> answer = ctx.search("ou=users,dc=gdz,dc=sub,dc=uni-goettingen,dc=de",
                matchAttrs);
        rueckgabe = answer.hasMoreElements();

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            if (logger.isDebugEnabled()) {
                logger.debug(">>>" + sr.getName());
            }
            Attributes attrs = sr.getAttributes();
            String givenName = " ";
            String surName = " ";
            String mail = " ";
            String cn = " ";
            String hd = " ";
            try {
                givenName = attrs.get("givenName").toString();
            } catch (Exception err) {
                givenName = " ";
            }
            try {
                surName = attrs.get("sn").toString();
            } catch (Exception e2) {
                surName = " ";
            }
            try {
                mail = attrs.get("mail").toString();
            } catch (Exception e3) {
                mail = " ";
            }
            try {
                cn = attrs.get("cn").toString();
            } catch (Exception e4) {
                cn = " ";
            }
            try {
                hd = attrs.get("homeDirectory").toString();
            } catch (Exception e4) {
                hd = " ";
            }
            logger.debug(givenName);
            logger.debug(surName);
            logger.debug(mail);
            logger.debug(cn);
            logger.debug(hd);

        }

        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
    }
    return rueckgabe;
}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

private Attribute getChangePasswordAttribute(Attribute oldPasswordAttribute, Object oldCredential,
        Object newPassword) throws DirectoryServerManagerException {

    String passwordHashMethod = null;
    // when admin changes other user passwords he do not have to provide
    // the old password.
    if (oldCredential != null) {
        // here it is only possible to have one password, if there are more
        // every one should match with the given old password

        try {/* w ww .  ja v  a 2  s.  c  o m*/
            NamingEnumeration passwords = oldPasswordAttribute.getAll();

            if (passwords.hasMore()) {
                byte[] byteArray = (byte[]) passwords.next();
                String password = new String(byteArray, StandardCharsets.UTF_8);

                if (password.startsWith("{")) {
                    passwordHashMethod = password.substring(password.indexOf("{") + 1, password.indexOf("}"));
                }

                if (!password.equals(getPasswordToStore((String) oldCredential, passwordHashMethod))) {
                    throw new DirectoryServerManagerException("Old password does not match");
                }
            }
        } catch (NamingException e) {
            log.error("Unable to retrieve old password details.", e);
            throw new DirectoryServerManagerException("Could not find old password details");
        }
    }

    Attribute passwordAttribute = new BasicAttribute(LDAPServerManagerConstants.LDAP_PASSWORD);
    passwordAttribute.add(getPasswordToStore((String) newPassword, passwordHashMethod));

    return passwordAttribute;

}

From source file:org.easy.ldap.LdapDao.java

/**
 * @param rootDn/*ww w .j av  a  2 s.  co m*/
 * @param type
 * @return
 */
public List<String> findRdnValues(LdapName rootDn, Attributes attributesToMatch, RdnType returnType) {
    NamingEnumeration<SearchResult> result = null;
    List<String> out = new ArrayList<String>(0);

    DirContext ctx = null;

    try {
        ctx = contextFactory.createContext(rootDn.toString());
        result = ctx.search("", attributesToMatch);

        Attributes attributes;

        while (result.hasMore()) {
            attributes = result.next().getAttributes();
            out.add(attributes.get(returnType.toString()).get().toString());
        }

    } catch (NamingException e) {
        throw new RuntimeException(returnType.toString() + "," + rootDn.toString(), e);
    } finally {
        if (contextFactory != null)
            contextFactory.closeContext(ctx);
    }

    return out;
}

From source file:org.wso2.carbon.appfactory.s4.integration.DomainMappingManagementService.java

/**
 * Resolve CNAME and A records for the given {@code hostname}.
 *
 * @param domain             hostname to be resolved.
 * @param environmentConfigs environment configuration
 * @return {@link com.google.common.collect.Multimap} of resolved dns entries. This {@link com.google.common.collect.Multimap} will contain the resolved
 * "CNAME" and "A" records from the given {@code hostname}
 * @throws AppFactoryException if error occurred while the operation
 *///from w w w  .j  a v  a 2 s. com
public Multimap<String, String> resolveDNS(String domain, Hashtable<String, String> environmentConfigs)
        throws AppFactoryException, DomainMappingVerificationException {
    // result mutimap of dns records. Contains the cname and records resolved by the given hostname
    // ex:  CNAME   => foo.com,bar.com
    //      A       => 192.1.2.3 , 192.3.4.5
    Multimap<String, String> dnsRecordsResult = ArrayListMultimap.create();
    Attributes dnsRecords;
    boolean isARecordFound = false;
    boolean isCNAMEFound = false;

    try {
        if (log.isDebugEnabled()) {
            log.debug("DNS validation: resolving DNS for " + domain + " " + "(A/CNAME)");
        }
        DirContext context = new InitialDirContext(environmentConfigs);
        String[] dnsRecordsToCheck = new String[] { DNS_A_RECORD, DNS_CNAME_RECORD };
        dnsRecords = context.getAttributes(domain, dnsRecordsToCheck);
    } catch (NamingException e) {
        String msg = "DNS validation: DNS query failed for: " + domain + ". Error occurred while configuring "
                + "directory context.";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    }

    try {
        // looking for for A records
        Attribute aRecords = dnsRecords.get(DNS_A_RECORD);
        if (aRecords != null && aRecords.size() > 0) { // if an A record exists
            NamingEnumeration aRecordHosts = aRecords.getAll(); // get all resolved A entries
            String aHost;
            while (aRecordHosts.hasMore()) {
                isARecordFound = true;
                aHost = (String) aRecordHosts.next();
                dnsRecordsResult.put(DNS_A_RECORD, aHost);
                if (log.isDebugEnabled()) {
                    log.debug("DNS validation: A record found: " + aHost);
                }
            }
        }

        // looking for CNAME records
        Attribute cnameRecords = dnsRecords.get(DNS_CNAME_RECORD);
        if (cnameRecords != null && cnameRecords.size() > 0) { // if CNAME record exists
            NamingEnumeration cnameRecordHosts = cnameRecords.getAll(); // get all resolved CNAME entries for hostname
            String cnameHost;
            while (cnameRecordHosts.hasMore()) {
                isCNAMEFound = true;
                cnameHost = (String) cnameRecordHosts.next();
                if (cnameHost.endsWith(".")) {
                    // Since DNS records are end with "." we are removing it.
                    // For example real dns entry for www.google.com is www.google.com.
                    cnameHost = cnameHost.substring(0, cnameHost.lastIndexOf('.'));
                }
                dnsRecordsResult.put(DNS_CNAME_RECORD, cnameHost);
                if (log.isDebugEnabled()) {
                    log.debug("DNS validation: recurring on CNAME record towards host " + cnameHost);
                }
                dnsRecordsResult.putAll(resolveDNS(cnameHost, environmentConfigs)); // recursively resolve cnameHost
            }
        }

        if (!isARecordFound && !isCNAMEFound && log.isDebugEnabled()) {
            log.debug("DNS validation: No CNAME or A record found for domain: '" + domain);
        }
        return dnsRecordsResult;
    } catch (NamingException ne) {
        String msg = "DNS validation: DNS query failed for: " + domain + ". Provided domain: " + domain
                + " might be a " + "non existing domain.";
        // we are logging this as warn messages since this is caused, due to an user error. For example if the
        // user entered a rubbish custom url(Or a url which is, CNAME record is not propagated at the
        // time of adding the url), then url validation will fail but it is not an system error
        log.warn(msg, ne);
        throw new DomainMappingVerificationException(msg, ne);
    }
}

From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java

/**
 * For a given name, this method makes ldap search in userBase with filter {@link #userIdAttribute}=name and objectClass={@link #userObjectClass}
 * and builds {@link User} based on search result.
 *
 * @param name/*from ww  w. jav  a  2  s . com*/
 *            The userId which should be value of the field {@link #userIdAttribute}
 * @return A {@link ReadOnlyLDAPUser} instance which is initialized with the
 *         userId of this user and ldap connection information with which
 *         the user was searched. Return null if such a user was not found.
 * @throws NamingException
 *             Propagated by the underlying LDAP communication layer.
 */
private ReadOnlyLDAPUser searchAndBuildUser(String name) throws NamingException {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { userIdAttribute });
    sc.setCountLimit(1);

    StringBuilder builderFilter = new StringBuilder("(&(");
    builderFilter.append(userIdAttribute).append("=").append(name).append(")").append("(objectClass=")
            .append(userObjectClass).append(")");

    if (StringUtils.isNotEmpty(filter)) {
        builderFilter.append(filter).append(")");
    } else {
        builderFilter.append(")");
    }

    NamingEnumeration<SearchResult> sr = ldapContext.search(userBase, builderFilter.toString(), sc);

    if (!sr.hasMore())
        return null;

    SearchResult r = sr.next();
    Attribute userName = r.getAttributes().get(userIdAttribute);

    if (!restriction.isActivated() || userInGroupsMembershipList(r.getNameInNamespace(),
            restriction.getGroupMembershipLists(ldapContext)))
        return new ReadOnlyLDAPUser(userName.get().toString(), r.getNameInNamespace(), ldapContext);

    return null;
}

From source file:org.projectforge.business.ldap.LdapDao.java

public List<T> findAll(final DirContext ctx, final String organizationalUnit) throws NamingException {
    final LinkedList<T> list = new LinkedList<T>();
    NamingEnumeration<?> results = null;
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final String searchBase = getSearchBase(organizationalUnit);
    results = ctx.search(searchBase, "(objectclass=" + getObjectClass() + ")", controls);
    while (results.hasMore()) {
        final SearchResult searchResult = (SearchResult) results.next();
        final String dn = searchResult.getName();
        final Attributes attributes = searchResult.getAttributes();
        list.add(mapToObject(dn, searchBase, attributes));
    }/* w  w  w  .j  a  v a 2  s.c  o  m*/
    return list;
}

From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java

/**
 * Gets all the user entities taken from the LDAP server, as taken from the
 * search-context given by the value of the attribute {@link #userBase}.
 *
 * @return A set containing all the relevant users found in the LDAP
 *         directory./*from  ww w .j  a v  a  2s.  co m*/
 * @throws NamingException
 *             Propagated from the LDAP communication layer.
 */
private Set<String> getAllUsersFromLDAP() throws NamingException {
    Set<String> result = new HashSet<String>();

    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { "distinguishedName" });
    NamingEnumeration<SearchResult> sr = ldapContext.search(userBase, "(objectClass=" + userObjectClass + ")",
            sc);
    while (sr.hasMore()) {
        SearchResult r = sr.next();
        result.add(r.getNameInNamespace());
    }

    return result;
}

From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java

private String findPrincipalDN(String normalizedPrincipal) throws NamingException, KerberosOperationException {
    String dn = null;/* w w w  .  j  av a2  s  .  c o  m*/

    if (normalizedPrincipal != null) {
        NamingEnumeration<SearchResult> results = null;

        try {
            results = ldapContext.search(principalContainerDn,
                    String.format("(userPrincipalName=%s)", normalizedPrincipal), searchControls);

            if ((results != null) && results.hasMore()) {
                SearchResult result = results.next();
                dn = result.getNameInNamespace();
            }
        } finally {
            try {
                if (results != null) {
                    results.close();
                }
            } catch (NamingException ne) {
                // ignore, we can not do anything about it
            }
        }
    }

    return dn;
}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public boolean isExistingServiceUid(String uid) throws DirectoryServerManagerException {

    DirContext dirContext;// w ww .  j  av a 2s.  c o m
    try {
        dirContext = this.connectionSource.getContext();
    } catch (UserStoreException e) {
        log.error("Unable to retrieve directory context.", e);
        throw new DirectoryServerManagerException("Unable to retrieve directory context.", e);
    }

    //first search the existing user entry.
    String searchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    String filter = "(&(" + LDAPServerManagerConstants.LDAP_UID + "=" + uid + ")"
            + getServerPrincipleIncludeString() + ")";

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_UID });

    try {
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, filter,
                searchControls);
        return namingEnumeration.hasMore();

    } catch (NamingException e) {
        log.error("Unable to check whether service exists in directory server. UID - " + uid, e);
        throw new DirectoryServerManagerException("Can not access the directory service", e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }
}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public boolean isExistingServicePrinciple(String servicePrinciple) throws DirectoryServerManagerException {

    DirContext dirContext;//from  w  w w .  j  a v  a2 s .  c om
    try {
        dirContext = this.connectionSource.getContext();
    } catch (UserStoreException e) {
        log.error("Unable to retrieve directory context.", e);
        throw new DirectoryServerManagerException("Unable to retrieve directory context.", e);
    }

    //first search the existing user entry.
    String searchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    String filter = getServicePrincipleFilter(servicePrinciple);

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_UID });

    try {
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, filter,
                searchControls);
        return namingEnumeration.hasMore();

    } catch (NamingException e) {
        String message = "Unable to search entry with search base " + searchBase + ", filter -" + filter;
        log.error(message, e);
        throw new DirectoryServerManagerException("Can not access the directory service", e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }
}