Example usage for javax.naming NamingEnumeration next

List of usage examples for javax.naming NamingEnumeration next

Introduction

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

Prototype

public T next() throws NamingException;

Source Link

Document

Retrieves the next element in the enumeration.

Usage

From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java

private void parseMembers(String userDN, Set<GrantedAuthority> groups, NamingEnumeration<SearchResult> renum)
        throws NamingException {
    try {//  w w  w.  j ava 2  s .com
        while (renum.hasMore()) {
            Attributes a = renum.next().getAttributes();
            Attribute cn = a.get("cn");
            if (LOGGER.isLoggable(Level.FINE))
                LOGGER.fine(userDN + " is a member of " + cn);
            groups.add(new GrantedAuthorityImpl(cn.get().toString()));
        }
    } catch (PartialResultException e) {
        // See JENKINS-42687. Just log the exception. Sometimes all the groups are correctly
        // retrieved but this Exception is launched as a last element of the NamingEnumeration
        // Even if it is really a PartialResultException, I don't see why this should be a blocker
        // I think a better approach is to log the Exception and continue
        LOGGER.log(Level.WARNING, String.format("JENKINS-42687 Might be more members for user  %s", userDN), e);
    }
}

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "user.remove", required = { "userId" })
@SecuredMethod(constraints = "administrator.by_domain")
public HashMap<String, Object> removeUser(OperationContext opContext) throws NamingException {

    String userId = (String) opContext.getParams().get("userId");

    DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal();

    UserDn userDn = nameHelper.newUserDnFromId(userId);

    DomainDn domainDn = nameHelper.newDomainDnFromDomain(userDn.getDomain());

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<SearchResult> searchResults = userDirContext.search(
            nameHelper.getGroupsBaseDn(nameHelper.newDomainDnFromDomain(userDn.getDomain())),
            "(uniqueMember=" + userDn.toString() + ")", controls);

    while (searchResults.hasMore()) {
        SearchResult sr = searchResults.next();
        DirContextAdapter dca = (DirContextAdapter) userDirContext.lookup(sr.getNameInNamespace());
        dca.removeAttributeValue("uniqueMember", userDn.toString());
        userDirContext.modifyAttributes(sr.getNameInNamespace(), dca.getModificationItems());
    }/* w  w  w.  j a  v  a  2s .  c  o m*/

    userDirContext.unbind(userDn);

    HashMap<String, Object> response = new HashMap<String, Object>();
    response.put("success", true);

    return response;
}

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

/**
 * @param rootDn/*  w  w w . j ava 2s.  co m*/
 * @param type
 * @return
 */
public List<String> findRdnValue(LdapName rootDn, RdnType type) {
    NamingEnumeration<SearchResult> result = null;
    List<String> out = new ArrayList<String>(0);

    DirContext ctx = null;

    try {
        ctx = contextFactory.createContext(rootDn.toString());
        Attributes attributes = new BasicAttributes();
        attributes.put(new BasicAttribute(type.toString()));

        result = ctx.search("", attributes);

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

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

    return out;
}

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));
    }// ww w  . j a v  a 2  s.c o m
    return list;
}

From source file:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java

/**
 * @throws NamingException/*from w  ww.  j  a  v  a 2s  .c  o  m*/
 * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#validatePassword(java.lang.String,java.lang.String)
 */
protected Set<Map<String, String>> buildGroup(Properties systemConfig, String filter) {
    Set<Map<String, String>> ret = new HashSet<Map<String, String>>();
    // Load our LDAP specific properties
    Properties env = getProperties(systemConfig);

    // Load the BaseDN
    String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN);

    // Load the LoginProperty
    String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty);
    if (loginProperty == null) {
        // Use the default
        loginProperty = "cn";
    }
    // Load any information we may need to bind
    String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN);
    String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW);
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }
    try {
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        SearchControls searchControls = getSearchControls();
        /*String filter = "(&(objectclass=groupOfUniqueNames)(uniqueMember=uid=" + userName
        + ",ou=People, dc=rhndev, dc=redhat, dc=com))";*/

        // Loop through each configured base DN.  It may be useful
        // in the future to allow for a filter to be configured for
        // each BaseDN, but for now the filter will apply to all.
        String[] baseDNs = baseDN.split(BASEDN_DELIMITER);

        for (int x = 0; x < baseDNs.length; x++) {
            NamingEnumeration<SearchResult> answer = ctx.search(baseDNs[x], filter, searchControls);
            boolean ldapApiEnumerationBugEncountered = false;
            while ((!ldapApiEnumerationBugEncountered) && answer.hasMoreElements()) {//BZ:582471- ldap api bug change
                // We use the first match
                SearchResult si = null;
                try {
                    si = answer.next();
                } catch (NullPointerException npe) {
                    ldapApiEnumerationBugEncountered = true;
                    break;
                }
                Map<String, String> entry = new HashMap<String, String>();
                String name = (String) si.getAttributes().get("cn").get();
                name = name.trim();
                Attribute desc = si.getAttributes().get("description");
                String description = desc != null ? (String) desc.get() : "";
                description = description.trim();
                entry.put("id", name);
                entry.put("name", name);
                entry.put("description", description);
                ret.add(entry);
            }
        }
    } catch (NamingException e) {
        if (e instanceof InvalidSearchFilterException) {
            InvalidSearchFilterException fException = (InvalidSearchFilterException) e;
            String message = "The ldap group filter defined is invalid ";
            log.error(message, fException);
            throw new LdapFilterException(message + " " + fException.getMessage());
        }
        //TODO: check for ldap connection/unavailable/etc. exceptions.
        else {
            log.error("LDAP communication error: " + e.getMessage(), e);
            throw new LdapCommunicationException(e);
        }
    }

    return ret;
}

From source file:net.officefloor.plugin.web.http.security.store.JndiLdapCredentialStoreTest.java

/**
 * Ensure correct roles./*from www  . j  av a  2s  .  c om*/
 */
@SuppressWarnings("unchecked")
public void testRoles() throws Exception {

    // Mocks
    final NamingEnumeration<SearchResult> searchResults = this.createMock(NamingEnumeration.class);
    final Attributes attributes = this.createMock(Attributes.class);
    final Attribute attribute = this.createMock(Attribute.class);

    // Objects
    final SearchResult searchResult = new SearchResult("uid=daniel", null, attributes);
    searchResult.setNameInNamespace("uid=daniel,ou=People,dc=officefloor,dc=net");

    // Record obtaining the Credential Entry
    this.recordReturn(this.context, this.context.search("ou=People,dc=officefloor,dc=net",
            "(&(objectClass=inetOrgPerson)(uid=daniel))", null), searchResults);
    this.recordReturn(searchResults, searchResults.hasMore(), true);
    this.recordReturn(searchResults, searchResults.next(), searchResult);

    // Record obtaining the Groups
    this.recordReturn(this.context, this.context.search("ou=Groups,dc=officefloor,dc=net",
            "(&(objectClass=groupOfNames)" + "(member=uid=daniel,ou=People,dc=officefloor,dc=net))", null),
            searchResults);
    this.recordReturn(searchResults, searchResults.hasMore(), true);
    this.recordReturn(searchResults, searchResults.next(), new SearchResult("cn=developers", null, attributes));
    this.recordReturn(attributes, attributes.get("ou"), attribute);
    this.recordReturn(attribute, attribute.get(), "developer");
    this.recordReturn(searchResults, searchResults.hasMore(), true);
    this.recordReturn(searchResults, searchResults.next(), new SearchResult("cn=founders", null, attributes));
    this.recordReturn(attributes, attributes.get("ou"), attribute);
    this.recordReturn(attribute, attribute.get(), "founder");
    this.recordReturn(searchResults, searchResults.hasMore(), false);

    // Test
    this.replayMockObjects();
    CredentialEntry entry = this.store.retrieveCredentialEntry("daniel", "REALM");
    Set<String> roles = entry.retrieveRoles();
    this.verifyMockObjects();

    // Ensure correct roles
    assertEquals("Incorrect number of roles", 2, roles.size());
    assertTrue("Must have developer role", roles.contains("developer"));
    assertTrue("Must have founder role", roles.contains("founder"));
}

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
 * //from  w w w  .  j a va 2  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.apache.syncope.fit.core.reference.GroupITCase.java

@Test
public void issueSYNCOPE632() {
    GroupTO groupTO = null;/*from   w  w w  . java2s  .c o  m*/
    try {
        // 1. create new LDAP resource having ConnObjectKey mapped to a derived attribute
        ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP);
        newLDAP.setKey("new-ldap");
        newLDAP.setPropagationPrimary(true);

        MappingTO mapping = newLDAP.getProvision(AnyTypeKind.GROUP.name()).getMapping();

        MappingItemTO connObjectKey = mapping.getConnObjectKeyItem();
        connObjectKey.setIntMappingType(IntMappingType.GroupDerivedSchema);
        connObjectKey.setIntAttrName("displayProperty");
        mapping.setConnObjectKeyItem(connObjectKey);
        mapping.setConnObjectLink("'cn=' + displayProperty + ',ou=groups,o=isp'");

        MappingItemTO description = new MappingItemTO();
        description.setIntMappingType(IntMappingType.GroupKey);
        description.setExtAttrName("description");
        description.setPurpose(MappingPurpose.BOTH);
        mapping.add(description);

        newLDAP = createResource(newLDAP);
        assertNotNull(newLDAP);

        // 2. create a group and give the resource created above
        groupTO = getSampleTO("lastGroup" + getUUIDString());
        groupTO.getPlainAttrs().add(attrTO("icon", "anIcon"));
        groupTO.getPlainAttrs().add(attrTO("show", "true"));
        groupTO.getDerAttrs().add(attrTO("displayProperty", null));
        groupTO.getResources().clear();
        groupTO.getResources().add("new-ldap");

        groupTO = createGroup(groupTO);
        assertNotNull(groupTO);

        // 3. update the group
        GroupMod groupMod = new GroupMod();
        groupMod.setKey(groupTO.getKey());
        groupMod.getPlainAttrsToRemove().add("icon");
        groupMod.getPlainAttrsToUpdate().add(attrMod("icon", "anotherIcon"));

        groupTO = updateGroup(groupMod);
        assertNotNull(groupTO);

        // 4. check that a single group exists in LDAP for the group created and updated above
        int entries = 0;
        DirContext ctx = null;
        try {
            ctx = getLdapResourceDirContext(null, null);

            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(new String[] { "*", "+" });
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp",
                    "(description=" + groupTO.getKey() + ")", ctls);
            while (result.hasMore()) {
                result.next();
                entries++;
            }
        } catch (Exception e) {
            // ignore
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {
                    // ignore
                }
            }
        }

        assertEquals(1, entries);
    } finally {
        if (groupTO != null) {
            groupService.delete(groupTO.getKey());
        }
        resourceService.delete("new-ldap");
    }
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private List searchFromUsers(DirContext context, Map filters) throws NamingException {

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration searchResultEnum;

    String filter = buildFilter(filters);
    if (log.isInfoEnabled())
        log.info("Search User from " + userBase + " by " + filter);
    searchResultEnum = context.search(userBase, filter, searchControls);
    //roop of retrieval result

    List users = new ArrayList();
    while (searchResultEnum.hasMore()) {
        SearchResult searchResult = (SearchResult) searchResultEnum.next();
        String dn = searchResult.getName() + "," + userBase;
        LDAPAccount user = createLDAPUser(dn, searchResult.getAttributes());
        users.add(user);/*from w ww . j  ava 2 s  .  co m*/
    }
    return users;
}

From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java

public Map<String, Collection<String>> findUsersWithRoles(DirContext dirContext)
        throws LdapControllerException {
    Map<String, Collection<String>> usersWithRoles = new HashMap<String, Collection<String>>();

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {//from  w w w.ja  v  a2 s  . c o  m

        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String filter = "objectClass=" + getLdapGroupClass();

        namingEnumeration = dirContext.search(getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();

            String groupName = searchResult.getName();
            // cn=blabla we only want bla bla
            groupName = StringUtils.substringAfter(groupName, "=");

            Attribute uniqueMemberAttr = searchResult.getAttributes().get("uniquemember");

            if (uniqueMemberAttr != null) {
                NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr
                        .getAll();
                while (allMembersEnum.hasMore()) {
                    String userName = allMembersEnum.next();
                    // uid=blabla we only want bla bla
                    userName = StringUtils.substringAfter(userName, "=");
                    userName = StringUtils.substringBefore(userName, ",");
                    Collection<String> roles = usersWithRoles.get(userName);
                    if (roles == null) {
                        roles = new HashSet<String>();
                    }

                    roles.add(groupName);

                    usersWithRoles.put(userName, roles);

                }
            }

            log.debug("found groupName: '{}' with users: {}", groupName);

        }

        return usersWithRoles;
    } catch (NamingException e) {
        throw new LdapControllerException(e.getMessage(), e);
    }

    finally {

        if (namingEnumeration != null) {
            try {
                namingEnumeration.close();
            } catch (NamingException e) {
                log.warn("failed to close search results", e);
            }
        }
    }
}