Example usage for javax.naming.directory SearchResult getName

List of usage examples for javax.naming.directory SearchResult getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Retrieves the name of this binding.

Usage

From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public List<String> getAllGroups(DirContext context) throws MappingException {

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {/*ww w .ja  v a 2  s .c  o m*/

        SearchControls searchControls = new SearchControls();

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

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

        if (!StringUtils.isEmpty(this.groupFilter)) {
            filter = "(&(" + filter + ")(" + this.groupFilter + "))";
        }

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

        List<String> allGroups = new ArrayList<String>();

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

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

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

            allGroups.add(groupName);

        }

        return allGroups;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    }

    finally {
        close(namingEnumeration);
    }
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

protected Organisation convertSearchResultToOrganization(final SearchResult sr)
        throws ExecutionException, NameNotFoundException {
    if (sr == null) {
        throw new ExecutionException("SearchResult sr == NULL", new NullPointerException());
    }//w  ww.  jav a2s .  c o  m
    Organisation vOrganisation = null;
    try {
        Attributes attributes = sr.getAttributes();

        Attribute attr;
        String vStr;
        String vOrgName = ((attr = attributes.get(Constants.ldap_ddbOrg_Id)) != null
                ? String.valueOf(attr.get())
                : null);
        String vName = sr.getName();
        String vNameInNamespace = sr.getNameInNamespace();
        // --- EntryDN
        String vEntryDN = ((attr = attributes.get(Constants.ldap_ddb_EntryDN)) != null
                ? String.valueOf(attr.get())
                : "");

        int idx;
        // -- Parent node detections:
        String vParent = null;
        //vParent = sr.getName();
        //LOG.log(Level.INFO, "getNameInNamespace() = '" + sr.getNameInNamespace() + "'");
        //LOG.log(Level.INFO, "getName() = '" + sr.getName() + "'");
        // -- getNameInNamespace() = 'o=99900711,o=00008125,o=00050350,ou=Organizations,dc=de'
        // -- getName() = 'o=99900711,o=00008125,o=00050350'

        //sr.getName(): 'o=00000116', 
        //sr.getNameInNamespace(): 'o=00000116,o=00050350,ou=Organizations,dc=de', 
        //vOrgEntryDN: 'o=00000116,o=00050350,ou=Organizations,dc=de'            
        vParent = sr.getNameInNamespace();
        if ((idx = vParent.indexOf(",ou=")) >= 0) {
            vParent = vParent.substring(0, idx);
        }
        vParent = vParent.replaceAll(Constants.ldap_ddbOrg_Id + "=", "");
        // -- 99900711,00008125,00050350'
        String[] vParents = vParent.split(",");

        if (vParents.length >= 2) {
            vParent = vParents[1];
        } else {
            vParent = null;
        }

        LOG.log(Level.INFO,
                "convertLdapOrganizationToOrganisation: o: '" + vOrgName + "', vParent: '" + vParent
                        + "', sr.getName(): '" + vName + "', sr.getNameInNamespace(): '" + vNameInNamespace
                        + "', vOrgEntryDN: '" + vEntryDN + "', sr.isRelative(): '" + sr.isRelative() + "'");
        /*
         * if ( (vOrgName != null)&&(!vOrgName.isEmpty()) ) { vOrganisation = new Organisation(vOrgName,
         * vDescription, vParent);
         */
        if ((vEntryDN != null) && (!vEntryDN.isEmpty())) {
            vOrganisation = new Organisation(vEntryDN,
                    (attr = sr.getAttributes().get(Constants.ldap_ddbOrg_PID)) != null
                            ? String.valueOf(attr.get())
                            : null);
            // Public-ID: (s.o.)
            // vOrganisation.setOrgPID( (attr = attributes.get(ddbOrg_PID)) != null ? String.valueOf(attr.get()) :
            // "");
            // Parent (s.o.)
            vOrganisation.setOrgParent(vParent);

            // Kurzbeschreibung der Einrichtung
            vOrganisation.setDescription((attr = attributes.get(Constants.ldap_ddbOrg_Description)) != null
                    ? String.valueOf(attr.get())
                    : null);

            // -- Rechtsform
            try {
                vOrganisation.setBusinessCategory(
                        (attr = attributes.get(Constants.ldap_ddbOrg_BusinessCategory)) != null
                                ? ConstEnumOrgSector.valueOf(String.valueOf(attr.get()))
                                : null);
            } catch (IllegalArgumentException ex) {
                LOG.log(Level.WARNING, "Organisation-Sector-Error: {0}", ex.getMessage());
                vOrganisation.setStatus(null);
            }

            // -- Sub-Sectors:
            if ((attr = attributes.get(Constants.ldap_ddbOrg_SubBusinessCategory)) != null) {
                ConstEnumOrgSubSector vSubSector;
                NamingEnumeration<?> allSubSectors = attr.getAll();
                while (allSubSectors.hasMore()) {
                    try {
                        vSubSector = ConstEnumOrgSubSector.valueOf((String) allSubSectors.next());
                        vOrganisation.addSubSectors(vSubSector);
                    } catch (IllegalArgumentException ex) {
                        LOG.log(Level.WARNING, "Organisation-SubSector-Error: {0}", ex.getMessage());
                    }
                }
            }

            // -- Funding Agency
            vOrganisation.setFundingAgency((attr = attributes.get(Constants.ldap_ddbOrg_FundingAgency)) != null
                    ? String.valueOf(attr.get())
                    : null);

            // Name der Einrichtung
            vOrganisation.setDisplayName((attr = attributes.get(Constants.ldap_ddbOrg_DisplayName)) != null
                    ? String.valueOf(attr.get())
                    : "");

            // E-Mail
            vOrganisation.setEmail(
                    (attr = attributes.get(Constants.ldap_ddbOrg_Email)) != null ? String.valueOf(attr.get())
                            : null);
            // Telefonnummer
            vOrganisation.setTel((attr = attributes.get(Constants.ldap_ddbOrg_TelephoneNumber)) != null
                    ? String.valueOf(attr.get())
                    : null);
            // -- FAX
            vOrganisation.setFax((attr = attributes.get(Constants.ldap_ddbOrg_FaxNumber)) != null
                    ? String.valueOf(attr.get())
                    : null);

            // -- PLZ
            vOrganisation.getAddress()
                    .setPostalCode((attr = attributes.get(Constants.ldap_ddbOrg_PostalCode)) != null
                            ? String.valueOf(attr.get())
                            : "");

            // -- City/Ortsname [l, localityName]
            if ((attr = attributes.get(Constants.ldap_ddbOrg_LocalityName)) != null) {
                vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get()));
            } else if ((attr = attributes.get("l")) != null) {
                vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get()));
            }

            // -- HouseIdentifier
            vOrganisation.getAddress()
                    .setHouseIdentifier((attr = attributes.get(Constants.ldap_ddbOrg_HouseIdentifier)) != null
                            ? String.valueOf(attr.get())
                            : "");
            // -- Strasse
            vOrganisation.getAddress()
                    .setStreet((attr = attributes.get(Constants.ldap_ddbOrg_Street)) != null
                            ? String.valueOf(attr.get())
                            : "");

            // -- Bundesland [stateOrProvinceName, st]
            if ((attr = attributes.get(Constants.ldap_ddbOrg_StateOrProvinceName)) != null) {
                vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get()));
            } else if ((attr = attributes.get("st")) != null) {
                vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get()));
            }

            // -- Land [countryName, c]
            if ((attr = attributes.get(Constants.ldap_ddbOrg_CountryName)) != null) {
                vOrganisation.getAddress().setCountryName(String.valueOf(attr.get()));
            }
            // -- AddressSuplement
            vOrganisation.getAddress()
                    .setAddressSuplement((attr = attributes.get(Constants.ldap_ddbOrg_AddressSuplement)) != null
                            ? String.valueOf(attr.get())
                            : "");

            // -- Geokoordinaten
            try {
                vOrganisation.getAddress()
                        .setLatitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLatitude)) != null
                                ? Double.valueOf(String.valueOf(attr.get()))
                                : 0.0);
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "GeoLatitude-Error: {0}", ex.getMessage());
            }
            try {
                vOrganisation.getAddress()
                        .setLongitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLongitude)) != null
                                ? Double.valueOf(String.valueOf(attr.get()))
                                : 0.0);
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "GeoLongitude-Error: {0}", ex.getMessage());
            }
            vOrganisation.getAddress().setLocationDisplayName(
                    (attr = attributes.get(Constants.ldap_ddbOrg_LocationDisplayName)) != null
                            ? String.valueOf(attr.get())
                            : null);

            vOrganisation.setAbbreviation((attr = attributes.get(Constants.ldap_ddbOrg_Abbreviation)) != null
                    ? String.valueOf(attr.get())
                    : null);

            vOrganisation.setLegalStatus((attr = attributes.get(Constants.ldap_ddbOrg_LegalStatus)) != null
                    ? String.valueOf(attr.get())
                    : null);

            if ((attr = attributes.get(Constants.ldap_ddbOrg_URL)) != null) {
                NamingEnumeration<?> allURLs = attr.getAll();
                while (allURLs.hasMore()) {
                    vOrganisation.addURLs((String) allURLs.next());
                }
            }

            vOrganisation.setLogo(
                    (attr = attributes.get(Constants.ldap_ddbOrg_Logo)) != null ? String.valueOf(attr.get())
                            : null);

            // -- org-Status:
            //vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null ? String
            //  .valueOf(attr.get()) : "");
            try {
                vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null
                        ? ConstEnumOrgStatus.valueOf(String.valueOf(attr.get()))
                        : ConstEnumOrgStatus.pending);
            } catch (IllegalArgumentException ex) {
                LOG.log(Level.WARNING, "Organisation-Status-Error: {0}", ex.getMessage());
                vOrganisation.setStatus(null);
            }

            vOrganisation.setCreatedBy((attr = attributes.get(Constants.ldap_ddb_CreatorsName)) != null
                    ? String.valueOf(attr.get())
                    : "");

            try { // createTimestamp-Error: For input string: "20120620142810Z"
                  // 1340205676692 - 20120620152116Z - 2012-06-20-15-21-16Z
                  // vOrganisation.setCreated( (attr = attributes.get(ddbOrg_CreateTimestamp)) != null ?
                  // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1));
                if ((attr = attributes.get(Constants.ldap_ddb_CreateTimestamp)) != null) {
                    vStr = String.valueOf(attr.get());
                    vOrganisation.setCreated(convertLdapDateToLong(vStr));
                }
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "createTimestamp-Error: {0}", ex.getMessage());
            }

            vOrganisation.setModifiedBy((attr = attributes.get(Constants.ldap_ddb_ModifiersName)) != null
                    ? String.valueOf(attr.get())
                    : "");
            try { // modifyTimestamp-Error: For input string: "20120620142810Z"
                  // vOrganisation.setModified( (attr = attributes.get(ddbOrg_ModifyTimestamp)) != null ?
                  // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1));
                if ((attr = attributes.get(Constants.ldap_ddb_ModifyTimestamp)) != null) {
                    vStr = String.valueOf(attr.get());
                    vOrganisation.setModified(convertLdapDateToLong(vStr));
                }
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "modifyTimestamp-Error: {0}", ex.getMessage());
            }

            if ((attr = attributes.get(Constants.ldap_ddbOrg_Properties)) != null
                    && attributes.get(Constants.ldap_ddbOrg_Properties).get() != null) {
                vOrganisation.setProperties(serializer.deserialize((String) attr.get()));
            }

        } else {
            throw new NameNotFoundException();
        }
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NameNotFoundException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw ex;
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, null, ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    }
    return vOrganisation;
}

From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public List<String> getGroups(String username, DirContext context) throws MappingException {

    List<String> userGroups = new ArrayList<String>();

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {/* ww  w.  j  a  v a  2  s  .  c  om*/

        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String groupEntry = null;
        try {
            //try to look the user up
            User user = userManager.findUser(username);
            if (user instanceof LdapUser) {
                LdapUser ldapUser = LdapUser.class.cast(user);
                Attribute dnAttribute = ldapUser.getOriginalAttributes().get(getLdapDnAttribute());
                if (dnAttribute != null) {
                    groupEntry = String.class.cast(dnAttribute.get());
                }

            }
        } catch (UserNotFoundException e) {
            log.warn("Failed to look up user {}. Computing distinguished name manually", username, e);
        } catch (UserManagerException e) {
            log.warn("Failed to look up user {}. Computing distinguished name manually", username, e);
        }
        if (groupEntry == null) {
            //failed to look up the user's groupEntry directly
            StringBuilder builder = new StringBuilder();
            String posixGroup = "posixGroup";
            if (posixGroup.equals(getLdapGroupClass())) {
                builder.append(username);
            } else {
                builder.append(this.userIdAttribute).append("=").append(username).append(",")
                        .append(getBaseDn());
            }
            groupEntry = builder.toString();
        }

        String filter = new StringBuilder().append("(&").append("(objectClass=" + getLdapGroupClass() + ")")
                .append("(").append(getLdapGroupMember()).append("=").append(Rdn.escapeValue(groupEntry))
                .append(")").append(")").toString();

        log.debug("filter: {}", filter);

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

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

            List<String> allMembers = new ArrayList<String>();

            Attribute uniqueMemberAttr = searchResult.getAttributes().get(getLdapGroupMember());

            if (uniqueMemberAttr != null) {
                NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr
                        .getAll();
                while (allMembersEnum.hasMore()) {

                    String userName = allMembersEnum.next();
                    //the original dn
                    allMembers.add(userName);
                    // uid=blabla we only want bla bla
                    userName = StringUtils.substringAfter(userName, "=");
                    userName = StringUtils.substringBefore(userName, ",");
                    allMembers.add(userName);
                }
                close(allMembersEnum);
            }

            if (allMembers.contains(username)) {
                String groupName = searchResult.getName();
                // cn=blabla we only want bla bla
                groupName = StringUtils.substringAfter(groupName, "=");
                userGroups.add(groupName);

            } else if (allMembers.contains(groupEntry)) {
                String groupName = searchResult.getName();
                // cn=blabla we only want bla bla
                groupName = StringUtils.substringAfter(groupName, "=");
                userGroups.add(groupName);
            }

        }

        return userGroups;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    } finally {
        close(namingEnumeration);
    }
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private XmlBuilder searchResultsToXml(NamingEnumeration entries) throws NamingException {

    XmlBuilder entriesElem = new XmlBuilder("entries");
    int row = 0;//from www. j  a va2  s .c om
    while ((getMaxEntriesReturned() == 0 || row < getMaxEntriesReturned()) && entries.hasMore()) {
        SearchResult searchResult = (SearchResult) entries.next();
        XmlBuilder entryElem = new XmlBuilder("entry");

        entryElem.addAttribute("name", searchResult.getName());
        entryElem.addSubElement(attributesToXml(searchResult.getAttributes()));

        entriesElem.addSubElement(entryElem);
        row++;
    }
    return entriesElem;
}

From source file:no.feide.moria.directory.backend.JNDIBackend.java

/**
 * Does a subtree search for an element given a pattern. Only the first
 * element found is considered, and all references are searched in order
 * until either a match is found or no more references are left to search.
 * @param ldap/*from  w  w w. j av  a2  s  .  com*/
 *            A prepared LDAP context.
 * @param pattern
 *            The search pattern. Must not include the character '*' or the
 *            substring '\2a' to prevent possible LDAP exploits.
 * @return The element's relative DN, or <code>null</code> if none was
 *         found. <code>null</code> is also returned if the search pattern
 *         contains an illegal character or substring.
 * @throws BackendException
 *             If there was a problem accessing the backend. Typical causes
 *             include timeouts.
 */
private String ldapSearch(final InitialLdapContext ldap, final String pattern) throws BackendException {

    // Check pattern for illegal content.
    String[] illegals = { "*", "\\2a" };
    for (int i = 0; i < illegals.length; i++) {
        if (pattern.indexOf(illegals[i]) > -1)
            return null;
    }

    // The context provider URL, for later logging.
    String url = "unknown backend";

    // Start counting the (milli)seconds and prepare for timeouts.
    long searchStart = System.currentTimeMillis();
    JNDISearchInterruptor interruptTask = new JNDISearchInterruptor(ldap, mySessionTicket);
    NamingEnumeration results;
    try {

        // Remember the URL, for later logging.
        url = (String) ldap.getEnvironment().get(Context.PROVIDER_URL);
        interruptTask.setURL(url);

        // Start timeout interruptor and perform the search.
        Timer interruptTimer = new Timer();
        interruptTimer.schedule(interruptTask, (1000 * myTimeout));
        results = ldap.search("", pattern, new SearchControls(SearchControls.SUBTREE_SCOPE, 0, 1000 * myTimeout,
                new String[] {}, false, false));
        interruptTimer.cancel();
        if (!results.hasMore())
            return null;

    } catch (TimeLimitExceededException e) {

        // The search timed out.
        log.logWarn("Search on " + url + " for " + pattern + " timed out after ~"
                + (System.currentTimeMillis() - searchStart) + "ms", mySessionTicket);
        return null;

    } catch (SizeLimitExceededException e) {

        // The search returned too many results.
        log.logWarn("Search on " + url + " for " + pattern + " returned too many results", mySessionTicket);
        return null;

    } catch (NameNotFoundException e) {

        // Element not found. Possibly non-existing reference.
        log.logDebug("Could not find " + pattern + " on " + url, mySessionTicket); // Necessary?
        return null;

    } catch (AuthenticationException e) {

        // Search failed authentication; check non-anonymous search config.
        try {
            final String searchUser = (String) ldap.getEnvironment().get(Context.SECURITY_PRINCIPAL);
            final String errorMessage;
            if ((searchUser == null) || searchUser.equals(""))
                errorMessage = "Anonymous search failed authentication on " + url;
            else
                errorMessage = "Could not authenticate search user " + searchUser + " on " + url;
            log.logDebug(errorMessage, mySessionTicket);
            throw new BackendException(errorMessage, e);
        } catch (NamingException f) {

            // Should not happen!
            log.logCritical("Unable to read LDAP environment", mySessionTicket, f);
            throw new BackendException("Unable to read LDAP environment", f);

        }

    } catch (NamingException e) {

        // Did we interrupt the search ourselves?
        if (interruptTask.finished()) {
            final long elapsed = System.currentTimeMillis() - searchStart;
            log.logWarn("Search on " + url + " for " + pattern + " timed out after ~" + elapsed + "ms",
                    mySessionTicket);
            throw new BackendException("Search on " + url + " for " + pattern + " timed out after ~" + elapsed
                    + "ms; connection terminated");
        }

        // All other exceptions.
        log.logWarn("Search on " + url + " for " + pattern + " failed", mySessionTicket, e);
        return null;

    }

    // We just found at least one element. Did we get an ambigious result?
    SearchResult entry = null;
    try {
        entry = (SearchResult) results.next();
        String buffer = new String();
        while (results.hasMoreElements())
            buffer = buffer + ", " + ((SearchResult) results.next()).getName();
        if (!buffer.equals(""))
            log.logWarn("Search on " + url + " for " + pattern + " gave ambiguous result: [" + entry.getName()
                    + buffer + "]", mySessionTicket);
        // TODO: Throw BackendException, or a subclass, or just (as now)
        // pick the first and hope for the best?
        buffer = null;
    } catch (NamingException e) {
        throw new BackendException("Unable to read search results", e);
    }
    return entry.getName(); // Relative DN (to the reference).

}

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

/**
 * Test to make sure anonymous binds are allowed on the RootDSE even when disabled
 * in general when going through the wire protocol.
 *
 * @throws Exception if anything goes wrong
 *///from  ww w . j  av a 2s  .c o m
@Test
public void testEnableAnonymousBindsOnRootDse() 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("", "(objectClass=*)", cons);

    SearchResult result = null;

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

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

    assertNotNull(result);
    assertEquals("", result.getName().trim());
}

From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

protected boolean authenticate(String username) throws Exception {
    DirContext context = open();//www.java  2  s  .  c om
    try {

        String filter = userSearchMatchingFormat.format(new String[] { username });
        SearchControls constraints = new SearchControls();
        if (userSearchSubtreeBool) {
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        } else {
            constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }

        // setup attributes
        String[] attribs;
        if (userRoleName == null) {
            attribs = new String[] {};
        } else {
            attribs = new String[] { userRoleName };
        }
        constraints.setReturningAttributes(attribs);

        NamingEnumeration results = context.search(userBase, filter, constraints);

        if (results == null || !results.hasMore()) {
            log.error("No roles associated with user " + username);
            loginSucceeded = false;
            throw new FailedLoginException();
        }

        SearchResult result = (SearchResult) results.next();

        if (results.hasMore()) {
            // ignore for now
        }
        NameParser parser = context.getNameParser("");
        Name contextName = parser.parse(context.getNameInNamespace());
        Name baseName = parser.parse(userBase);
        Name entryName = parser.parse(result.getName());
        Name name = contextName.addAll(baseName);
        name = name.addAll(entryName);
        String dn = name.toString();

        Attributes attrs = result.getAttributes();
        if (attrs == null) {
            return false;
        }
        ArrayList<String> roles = null;
        if (userRoleName != null) {
            roles = addAttributeValues(userRoleName, attrs, roles);
        }
        // check the credentials by binding to server
        // bindUser(context, dn);
        // if authenticated add more roles
        roles = getRoles(context, dn, username, roles);
        for (String role : roles) {
            groups.add(role);
        }
        if (groups.isEmpty()) {
            log.error("No roles associated with user " + username);
            loginSucceeded = false;
            throw new FailedLoginException();
        } else
            loginSucceeded = true;

    } catch (CommunicationException e) {
        close(context);
        throw (LoginException) new FailedLoginException().initCause(e);
    } catch (NamingException e) {
        close(context);
        throw (LoginException) new FailedLoginException().initCause(e);
    }
    return true;
}

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

private void writeSearchResult(final SearchResult sr, final XMLBuffer xmlb) throws NamingException {
    final Attributes attrs = sr.getAttributes();
    final int size = attrs.size();
    final ArrayList<Attribute> sortedAttrs = new ArrayList<>(size);

    xmlb.openTag("searchresult"); // $NON-NLS-1$
    xmlb.tag("dn", sr.getName()); // $NON-NLS-1$
    xmlb.tag("returnedattr", Integer.toString(size)); // $NON-NLS-1$
    xmlb.openTag("attributes"); // $NON-NLS-1$

    try {//from w  ww.  j a va 2s.  co m
        for (NamingEnumeration<? extends Attribute> en = attrs.getAll(); en.hasMore();) {
            final Attribute attr = en.next();
            sortedAttrs.add(attr);
        }
        sortAttributes(sortedAttrs);
        for (final Attribute attr : sortedAttrs) {
            StringBuilder sb = new StringBuilder();
            if (attr.size() == 1) {
                sb.append(getWriteValue(attr.get()));
            } else {
                final ArrayList<String> sortedVals = new ArrayList<>(attr.size());
                boolean first = true;

                for (NamingEnumeration<?> ven = attr.getAll(); ven.hasMore();) {
                    final Object value = getWriteValue(ven.next());
                    sortedVals.add(value.toString());
                }

                Collections.sort(sortedVals);

                for (final String value : sortedVals) {
                    if (first) {
                        first = false;
                    } else {
                        sb.append(", "); // $NON-NLS-1$
                    }
                    sb.append(value);
                }
            }
            xmlb.tag(attr.getID(), sb);
        }
    } finally {
        xmlb.closeTag("attributes"); // $NON-NLS-1$
        xmlb.closeTag("searchresult"); // $NON-NLS-1$
    }
}

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

private void sortResults(final List<SearchResult> sortedResults) {
    Collections.sort(sortedResults, new Comparator<SearchResult>() {
        private int compareToReverse(final String s1, final String s2) {
            int len1 = s1.length();
            int len2 = s2.length();
            int s1i = len1 - 1;
            int s2i = len2 - 1;

            for (; (s1i >= 0) && (s2i >= 0); s1i--, s2i--) {
                char c1 = s1.charAt(s1i);
                char c2 = s2.charAt(s2i);

                if (c1 != c2) {
                    return c1 - c2;
                }//from w  ww.j  ava 2 s .c o  m
            }
            return len1 - len2;
        }

        @Override
        public int compare(SearchResult o1, SearchResult o2) {
            String nm1 = o1.getName();
            String nm2 = o2.getName();

            if (nm1 == null) {
                nm1 = "";
            }
            if (nm2 == null) {
                nm2 = "";
            }
            return compareToReverse(nm1, nm2);
        }
    });
}

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

private String normaliseSearchDN(final SearchResult sr, final String searchBase, final String rootDn) {
    String srName = sr.getName();

    if (!srName.endsWith(searchBase)) {
        if (srName.length() > 0) {
            srName = srName + ',';
        }/*from   w w  w  . ja  v a  2 s  .com*/
        srName = srName + searchBase;
    }
    if ((rootDn.length() > 0) && !srName.endsWith(rootDn)) {
        if (srName.length() > 0) {
            srName = srName + ',';
        }
        srName = srName + rootDn;
    }
    sr.setName(srName);
    return srName;
}