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:ldap.SearchUtility.java

/**
 * This returns a list of all users that match the particular attribute value.
 * Often this will be a single user, in which case the list will only contain one value.  If
 * you know this is the case, use the 'getUser()' form of this method instead.
 * @param attrType/*from www .j av  a  2  s.  c  o m*/
 * @param attrValue
 * @return
 * @throws NamingException
 */
public List<Entry> getUsers(String attrType, String attrValue, DirContext context) throws NamingException {
    logger.info("getUsers(attrType,attrValue,context)");
    List<Entry> users = new ArrayList<Entry>();
    Attributes atts = new BasicAttributes();
    atts.put(attrType, attrValue);
    //NamingEnumeration<SearchResult> userResults = context.search(new LdapName(Config.SEARCH_BASE_DN), attrType + "={0}", new String[] {attrValue}, getSearchControls());
    NamingEnumeration<SearchResult> userResults = context.search(new LdapName(LdapConstants.ldapSearchBaseDn),
            attrType + "={0}", new String[] { attrValue }, getSearchControls());
    while (userResults.hasMore()) {
        SearchResult userResult = userResults.next();
        users.add(new Entry(userResult));
    }
    return users;
}

From source file:ldap.SearchUtility.java

/**
 * recursively walks the tree to depth 'depth', and returns
 * a list of all names found at that depth.
 * @param treeNode/*w  ww. jav a2  s . c  o m*/
 * @param depth
 * @return
 * @throws NamingException
 */

private List<LdapName> getElementNames(LdapName treeNode, int depth, DirContext context)
        throws NamingException {
    depth--;
    NamingEnumeration<NameClassPair> children = context.list(treeNode);
    List<LdapName> elementNames = new ArrayList<LdapName>();

    // cycle through all the children we've found.
    while (children.hasMore()) {
        NameClassPair child = children.next();
        LdapName childName = new LdapName(child.getNameInNamespace());
        if (depth == 0) // return value - these are what we're looking for!
            elementNames.add(childName);
        else
            elementNames.addAll(getElementNames(childName, depth, context)); // keep going down!
    }

    return elementNames;
}

From source file:org.kitodo.production.services.data.LdapServerService.java

/**
 * Check if User already exists on system.
 *
 * @param user/*from  w  w w  .j  a va 2s  .c  o  m*/
 *            The User.
 * @return result as boolean
 */
public boolean isUserAlreadyExists(User user) {
    Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(
            user.getLdapGroup().getLdapServer());
    DirContext ctx;
    boolean result = false;
    try {
        ctx = new InitialDirContext(ldapEnvironment);
        Attributes matchAttrs = new BasicAttributes(true);
        NamingEnumeration<SearchResult> answer = ctx.search(buildUserDN(user), matchAttrs);
        result = answer.hasMoreElements();

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            logger.debug(">>>{}", sr.getName());
            Attributes attrs = sr.getAttributes();
            String givenName = getStringForAttribute(attrs, "givenName");
            String surName = getStringForAttribute(attrs, "sn");
            String mail = getStringForAttribute(attrs, "mail");
            String cn = getStringForAttribute(attrs, "cn");
            String homeDirectory = getStringForAttribute(attrs, "homeDirectory");

            logger.debug(givenName);
            logger.debug(surName);
            logger.debug(mail);
            logger.debug(cn);
            logger.debug(homeDirectory);
        }

        ctx.close();
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }
    return result;
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

private boolean bindSearchX(String username, String password, Hashtable<String, String> env, boolean bind)
        throws AuthenticationException, NamingException {

    env.put(Context.SECURITY_PRINCIPAL, ldapSecurityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, ldapSecurityCredentials);

    DirContext ctx = null;//from   ww w.  j  av  a 2  s  .  com
    try {
        ctx = new InitialDirContext(env);
    } catch (NamingException ne) {
        log.error("Failed to bind as: {}", ldapSecurityPrincipal);
    }

    // ensure we have the userPassword attribute at a minimum
    String[] attributeList = new String[] { "userPassword" };

    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(attributeList);
    sc.setDerefLinkFlag(true);
    sc.setReturningObjFlag(false);
    sc.setTimeLimit(5000);

    String filter = "(" + filterPrefix + idAttr + "=" + username + filterSuffix + ")";
    // Do the search
    NamingEnumeration<SearchResult> results = ctx.search(baseDn, filter, sc);
    if (!results.hasMore()) {
        log.warn("no valid user found.");
        return false;
    }

    SearchResult result = results.next();
    log.debug("authenticating user: {}", result.getNameInNamespace());

    if (bind) {
        // setup user context for binding
        Hashtable<String, String> userEnv = new Hashtable<String, String>();
        userEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        userEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
        userEnv.put(Context.PROVIDER_URL, baseUrl);
        userEnv.put(Context.SECURITY_PRINCIPAL, result.getNameInNamespace());
        userEnv.put(Context.SECURITY_CREDENTIALS, password);

        try {
            new InitialDirContext(userEnv);
        } catch (NamingException ne) {
            log.error("failed to authenticate user: " + result.getNameInNamespace());
            throw ne;
        }
    } else {
        // get userPassword attribute
        Attribute up = result.getAttributes().get("userPassword");
        if (up == null) {
            log.error("unable to read userPassword attribute for: {}", result.getNameInNamespace());
            return false;
        }

        byte[] userPasswordBytes = (byte[]) up.get();
        String userPassword = new String(userPasswordBytes);

        // compare passwords - also handles encodings
        if (!passwordsMatch(password, userPassword)) {
            return false;
        }
    }

    return true;
}

From source file:ru.efo.security.ADUserDetailsService.java

private void describeRoles(DirContext context, Attribute memberOf, Set<String> groups, Set<String> roles)
        throws NamingException {
    if (memberOf != null) {
        for (int i = 0; i < memberOf.size(); i++) {
            Attribute attr = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" }).get("CN");
            if (attr != null) {
                final String role = attr.get().toString();
                if (rolesMapping != null) {
                    for (String key : rolesMapping.keySet()) {
                        if (role.matches(rolesMapping.get(key))) {
                            if (logger.isLoggable(Level.FINE)) {
                                if (!roles.contains(key)) {
                                    logger.log(Level.FINE, "Role: " + key);
                                }// ww w  .  j  a  va 2  s . c  o  m
                            }
                            roles.add(key);
                        }
                    }
                } else {
                    final String roleWithPrefix = (rolePrefix == null ? "" : rolePrefix)
                            + role.toUpperCase().replaceAll("(\\s|-)+", "_");
                    if (logger.isLoggable(Level.FINE)) {
                        if (!roles.contains(role)) {
                            logger.log(Level.FINE, "Role: " + roleWithPrefix);
                        }
                    }
                    roles.add(roleWithPrefix);
                }
                groups.add(role);

                if (recursiveRoleSearch) {
                    SearchControls controls = new SearchControls();
                    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                    NamingEnumeration<SearchResult> renum = context.search(
                            groupSearchBase != null ? groupSearchBase : userSearchBase, "(CN=" + role + ")",
                            controls);
                    if (renum.hasMore()) {
                        SearchResult searchResult = renum.next();
                        attr = searchResult.getAttributes().get("memberOf");
                        describeRoles(context, attr, groups, roles);
                    }
                }
            }
        }
    }
}

From source file:com.evolveum.midpoint.model.common.expression.functions.BasicExpressionFunctions.java

public String determineLdapSingleAttributeValue(String dn, String attributeName, Collection<?> values)
        throws NamingException {
    if (values == null || values.isEmpty()) {
        return null;
    }//from   w w w.  ja  v a 2  s  . co  m

    Collection<String> stringValues = null;
    // Determine item type, try to convert to strings
    Object firstElement = values.iterator().next();
    if (firstElement instanceof String) {
        stringValues = (Collection) values;
    } else if (firstElement instanceof Element) {
        stringValues = new ArrayList<String>(values.size());
        for (Object value : values) {
            Element element = (Element) value;
            stringValues.add(element.getTextContent());
        }
    } else {
        throw new IllegalArgumentException("Unexpected value type " + firstElement.getClass());
    }

    if (stringValues.size() == 1) {
        return stringValues.iterator().next();
    }

    if (StringUtils.isBlank(dn)) {
        throw new IllegalArgumentException(
                "No dn argument specified, cannot determine which of " + values.size() + " values to use");
    }

    LdapName parsedDn = new LdapName(dn);
    for (int i = 0; i < parsedDn.size(); i++) {
        Rdn rdn = parsedDn.getRdn(i);
        Attributes rdnAttributes = rdn.toAttributes();
        NamingEnumeration<String> rdnIDs = rdnAttributes.getIDs();
        while (rdnIDs.hasMore()) {
            String rdnID = rdnIDs.next();
            Attribute attribute = rdnAttributes.get(rdnID);
            if (attributeName.equals(attribute.getID())) {
                for (int j = 0; j < attribute.size(); j++) {
                    Object value = attribute.get(j);
                    if (stringValues.contains(value)) {
                        return (String) value;
                    }
                }
            }
        }
    }

    // Fallback. No values in DN. Just return the first alphabetically-wise value.
    return Collections.min(stringValues);
}

From source file:org.viafirma.nucleo.validacion.CRLUtil.java

/**
 * Se conecta a la url indicada y se descarga las crls. No se esta usando
 * *******************!!! En desarrollo, no funciona
 * //  w  ww.j a  v  a2 s .  c  o  m
 * @param hostURL
 * @return
 * @throws CRLException
 *             No se ha podido recuperar el listado
 * @throws CertificateParsingException
 */
@SuppressWarnings("unchecked")
private InputStream getIoCrlFromFNMTLDAP(X509Certificate certificadoX509)
        throws CRLException, CertificateParsingException {
    // ************************
    // recupero las propiedades para realizar la busqueda en LDAP.
    // EJ :[CN=CRL1, OU=FNMT Clase 2 CA, O=FNMT, C=ES] {2.5.4.11=FNMT Clase
    // 2 CA, 2.5.4.10=FNMT, 2.5.4.6=ES, 2.5.4.3=CRL1}
    Map<String, String> propiedades = new HashMap<String, String>();
    try {
        log.debug("Recuperando puntos de distribucin CRL del certificado FNMT: "
                + certificadoX509.getIssuerDN());
        // recupero la extensin OID 2.5.29.31 ( id-ce-cRLDistributionPoinds
        // segun el RFC 3280 seccin 4.2.1.14)
        byte[] val1 = certificadoX509.getExtensionValue(OID_CRLS);
        if (val1 == null) {
            log.debug("   El certificado NO tiene punto de distribucin de CRL ");
        } else {
            ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1));
            DERObject derObj = oAsnInStream.readObject();
            DEROctetString dos = (DEROctetString) derObj;
            byte[] val2 = dos.getOctets();
            ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2));
            DERObject derObj2 = oAsnInStream2.readObject();

            X509Handler.getCurrentInstance().readPropiedadesOid(OID_CRLS, derObj2, propiedades);

        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new CertificateParsingException(e.toString());
    }

    // comprobamos la configuracin
    if (isSomeFNMTValorNull()) {
        throw new CRLException(
                "Para el acceso a las CRLs de la FNMT es necesario las credenciales. Indique el parametro de configuracin :"
                        + Constantes.CONEXION_LDAP_CRL_FNMT);
    }

    String CN = "CN=" + propiedades.get(FNMT_CN_IDENTIFICADOR) + "," + certificadoX509.getIssuerDN();
    log.debug("Buscando en el LDAP " + CN);

    // **********************************************
    // Nos conectamos al LDAP para recuperar la CRLs.

    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, fnmtLDAPHostURL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, fnmtPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, fnmtCredencial);
    env.put(Context.REFERRAL, "follow");

    try {
        DirContext ctx = new InitialDirContext(env);
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration namings = (ctx.search(CN, "(objectclass=*)", searchControls));

        log.debug("Se ha logrado conectar al LDAP");

        if (namings.hasMore()) {
            log.debug("Recuperando el contenido de la CRLs");
            // recupero el resultado
            SearchResult resultado = ((SearchResult) namings.next());

            // recupero todos los atributos del resultado
            Attributes avals = resultado.getAttributes();

            // recupero los bytes.
            byte[] bytes;
            if ((avals.get("certificateRevocationList;binary")) != null) {
                log.debug("Atributos deben estar en binario");
                Attribute atributo = (avals.get("certificateRevocationList;binary"));
                bytes = ((byte[]) atributo.get());
            } else {
                log.debug("Atributos en exadecimal En Hexadecimal");
                Attribute atributo = (avals.get("certificateRevocationList"));
                bytes = ((byte[]) atributo.get());
                log.debug("Por implementar");
            }

            if (bytes != null) {
                ByteArrayInputStream io = new ByteArrayInputStream(bytes);
                return io;
            }
        }
    } catch (NamingException e) {
        log.error("No se puede conectar al LDAP!!", e);
    }
    return null;
}

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

@Override
public List<LdapUser> findAllUsers(String tenantId, LdapUser example) {

    NamingEnumeration<SearchResult> result = null;
    List<LdapUser> out = new ArrayList<LdapUser>();

    LdapName rootDn = namingFactory.createUsersDn(tenantId);
    result = ldapDao.findAll(rootDn, LdapDao.toAttributes(example));

    try {//w ww.j av a 2s . c  om
        while (result.hasMore()) {
            out.add(LdapDao.toModel(tenantId, result.next().getAttributes()));
        }
    } catch (NamingException e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }

    return out;
}

From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java

protected void updateGroups(DirContext dirContext, SearchControls controls) {
    String ldapSuffix = getLDAPSuffix();
    String ldapGroups = getLDAPGroups();
    NamingEnumeration<SearchResult> namingEnum = null;
    try {//from ww  w  .j  a va 2s .  c om
        boolean schemaExists = false;
        try {
            namingEnum = dirContext.search(ldapSuffix, ldapGroups, controls);
            schemaExists = namingEnum.hasMore();
        } catch (NamingException ex) {
            throw new RuntimeException("Could find groups schema", ex);
        }
        if (schemaExists) {
            logger.info("LDAP schema for " + ldapGroups + " already exists");
        } else {
            String dn = ldapGroups + "," + ldapSuffix;
            Attributes attributes = new BasicAttributes();
            Attribute objclass = new BasicAttribute("objectclass");
            objclass.add("organizationalUnit");
            attributes.put(objclass);
            attributes.put(ldapGroups.substring(0, ldapGroups.indexOf("=")),
                    ldapGroups.substring(ldapGroups.indexOf("=") + 1));
            try {
                dirContext.createSubcontext(dn, attributes);
            } catch (NamingException ex) {
                throw new RuntimeException("Could not create groups schema", ex);
            }
            logger.info("Created LDAP schema for " + ldapGroups);
        }
    } finally {
        if (namingEnum != null) {
            try {
                namingEnum.close();
            } catch (NamingException ex) {
                throw new RuntimeException("Could not close the naming enumeration for the ldap groups schema",
                        ex);
            }
        }
    }
}

From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java

protected void updatePeople(DirContext dirContext, SearchControls controls) {
    String ldapSuffix = getLDAPSuffix();
    String ldapPeople = getLDAPPeople();
    NamingEnumeration<SearchResult> namingEnum = null;
    try {/* w  w  w  .ja va2s .  co m*/
        boolean schemaExists = false;
        try {
            namingEnum = dirContext.search(ldapSuffix, ldapPeople, controls);
            schemaExists = namingEnum.hasMore();
        } catch (NamingException ex) {
            throw new RuntimeException("Could find people schema", ex);
        }
        if (schemaExists) {
            logger.info("LDAP schema for " + ldapPeople + " already exists");
        } else {
            String dn = ldapPeople + "," + ldapSuffix;
            Attributes attributes = new BasicAttributes();
            Attribute objclass = new BasicAttribute("objectclass");
            objclass.add("organizationalUnit");
            attributes.put(objclass);
            attributes.put(ldapPeople.substring(0, ldapPeople.indexOf("=")),
                    ldapPeople.substring(ldapPeople.indexOf("=") + 1));
            try {
                dirContext.createSubcontext(dn, attributes);
            } catch (NamingException ex) {
                throw new RuntimeException("Could not create people schema", ex);
            }
            logger.info("Created LDAP schema for " + ldapPeople);
        }
    } finally {
        if (namingEnum != null) {
            try {
                namingEnum.close();
            } catch (NamingException ex) {
                throw new RuntimeException("Could not close the naming enumeration for the ldap people schema",
                        ex);
            }
        }
    }
}