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:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java

/**
 * {@inheritDoc}//from w ww. j a  v a2s. c om
 */
public Map<String, String> findByCommonNameStub(String stub, long maxCount) throws RepositoryException {
    Map<String, String> idNameMap = new LinkedHashMap<String, String>();
    String text = censorHumanoidSearchPhrase(stub);
    String filter = "(&(objectClass=" + getObjectClassName() + ")(cn=" + text + "*))";
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setCountLimit(maxCount);
    ctls.setReturningAttributes(new String[] { "cn", "uid" });

    try {
        NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls);
        while (resultEnum.hasMoreElements()) {
            SearchResult result = resultEnum.next();
            Attributes attrs = result.getAttributes();
            idNameMap.put((String) attrs.get("uid").get(), (String) attrs.get("cn").get());
        }
    } catch (NamingException e) {
        throw new RepositoryException(e);
    }
    return idNameMap;
}

From source file:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java

/**
 * Note that {@link User.getPassword()} will not give the password from the repository after 'unmarshalling'.
 * The user repository must be queried for this because the password is never retrieved from the repository 
 * and the User object does not contain it.  
 * //from  ww w. j  a va2 s . c  o  m
 */
public boolean isPasswordStored(String userId) throws RepositoryException {
    if (StringUtils.isBlank(userId)) {
        logger.debug("Insufficient data for getting user info.");
        throw new IllegalArgumentException();
    }
    String filter = "(&(objectClass=" + getObjectClassName() + ")(uid=" + userId + "))";

    final String PASSWD_ATTR_NAME = "userPassword";
    boolean passwordStored = false;
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setCountLimit(1);
    ctls.setReturningAttributes(new String[] { "uid", PASSWD_ATTR_NAME });

    try {
        NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls);
        while (resultEnum.hasMoreElements()) {
            SearchResult result = resultEnum.next();
            Attributes attrs = result.getAttributes();
            if (attrs.get(PASSWD_ATTR_NAME) != null)
                passwordStored = true;
        }
    } catch (NamingException e) {
        throw new RepositoryException(e);
    }

    return passwordStored;
}

From source file:org.acegisecurity.userdetails.ldap.LdapUserDetailsMapper.java

public Object mapAttributes(String dn, Attributes attributes) throws NamingException {
    LdapUserDetailsImpl.Essence essence = new LdapUserDetailsImpl.Essence();

    essence.setDn(dn);/* w  ww. ja  va2 s  .  c  o  m*/
    essence.setAttributes(attributes);

    Attribute passwordAttribute = attributes.get(passwordAttributeName);

    if (passwordAttribute != null) {
        essence.setPassword(mapPassword(passwordAttribute));
    }

    // Map the roles
    for (int i = 0; (roleAttributes != null) && (i < roleAttributes.length); i++) {
        Attribute roleAttribute = attributes.get(roleAttributes[i]);

        if (roleAttribute == null) {
            logger.debug("Couldn't read role attribute '" + roleAttributes[i] + "' for user " + dn);
            continue;
        }

        NamingEnumeration attributeRoles = roleAttribute.getAll();

        while (attributeRoles.hasMore()) {
            GrantedAuthority authority = createAuthority(attributeRoles.next());

            if (authority != null) {
                essence.addAuthority(authority);
            } else {
                logger.debug(
                        "Failed to create an authority value from attribute with Id: " + roleAttribute.getID());
            }
        }
    }

    return essence;
}

From source file:org.sonar.plugins.ldap.LdapAutodiscovery.java

List<LdapSrvRecord> getLdapServers(DirContext context, String domain) throws NamingException {
    Attributes lSrvAttrs = context.getAttributes("dns:/_ldap._tcp." + domain, new String[] { "srv" });
    Attribute serversAttribute = lSrvAttrs.get("srv");
    NamingEnumeration<?> lEnum = serversAttribute.getAll();
    SortedSet<LdapSrvRecord> result = new TreeSet<>();
    while (lEnum.hasMore()) {
        String srvRecord = (String) lEnum.next();
        // priority weight port target
        String[] srvData = srvRecord.split(" ");

        int priority = NumberUtils.toInt(srvData[0]);
        int weight = NumberUtils.toInt(srvData[1]);
        String port = srvData[2];
        String target = srvData[3];

        if (target.endsWith(".")) {
            target = target.substring(0, target.length() - 1);
        }/*from   w w w .  ja va 2  s  . c  o  m*/
        String server = "ldap://" + target + ":" + port;
        result.add(new LdapSrvRecord(server, priority, weight));
    }
    return new ArrayList<>(result);
}

From source file:se.vgregion.service.innovationsslussen.ldap.LdapService.java

AttributesMapper newAttributesMapper(final Class type) {
    return new AttributesMapper() {
        @Override/*from  w ww  .  j a  v a2  s  . c  o m*/
        public Object mapFromAttributes(Attributes attributes) throws NamingException {
            try {
                return mapFromAttributesImpl(attributes);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        public Object mapFromAttributesImpl(Attributes attributes)
                throws NamingException, IllegalAccessException, InstantiationException {
            Object result = type.newInstance();
            BeanMap bm = new BeanMap(result);
            NamingEnumeration<? extends Attribute> all = attributes.getAll();

            while (all.hasMore()) {
                Attribute attribute = all.next();

                String name = toBeanPropertyName(attribute.getID());
                if (bm.containsKey(name) && bm.getWriteMethod(name) != null) {
                    bm.put(name, attribute.get());
                }
            }
            return result;
        }
    };
}

From source file:org.beangle.security.ldap.connect.SimpleLdapUserStore.java

public String getUserDN(String uid) {
    DirContext ctx = getContext();
    if (ctx == null)
        return null;
    String result = null;//w ww.j a  v a2 s .com
    String condition = StrUtils.concat(uidName, "=", uid);
    try {
        String attrList[] = { uidName };
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(2);
        constraints.setReturningAttributes(attrList);
        NamingEnumeration<SearchResult> results = ctx.search(base, condition, constraints);
        if (results.hasMore()) {
            SearchResult si = results.next();
            result = StrUtils.concat(si.getName(), ",", base);
        }
        results.close();
        results = null;
    } catch (Throwable e) {
        logger.error("Ldap search error,uid=" + uid, e);
    }
    return result;
}

From source file:org.springframework.ldap.core.LdapAttributes.java

/**
 * Returns a string representation of the object in LDIF format.
 * // w w  w .  j  av  a  2 s  .c o  m
 * @return {@link java.lang.String} formated to RFC2849 LDIF specifications.
 */
public String toString() {
    StringBuilder sb = new StringBuilder();

    try {

        DistinguishedName dn = getDN();

        if (!dn.toString().matches(SAFE_INIT_CHAR + SAFE_CHAR + "*")) {
            sb.append("dn:: " + new BASE64Encoder().encode(dn.toString().getBytes()) + "\n");
        } else {
            sb.append("dn: " + getDN() + "\n");
        }

        NamingEnumeration<Attribute> attributes = getAll();

        while (attributes.hasMore()) {
            Attribute attribute = attributes.next();
            NamingEnumeration<?> values = attribute.getAll();

            while (values.hasMore()) {
                Object value = values.next();

                if (value instanceof String)
                    sb.append(attribute.getID() + ": " + (String) value + "\n");

                else if (value instanceof byte[])
                    sb.append(attribute.getID() + ":: " + new BASE64Encoder().encode((byte[]) value) + "\n");

                else if (value instanceof URI)
                    sb.append(attribute.getID() + ":< " + (URI) value + "\n");

                else {
                    sb.append(attribute.getID() + ": " + value + "\n");
                }
            }
        }

    } catch (NamingException e) {
        log.error("Error formating attributes for output.", e);
        sb = new StringBuilder();
    }

    return sb.toString();
}

From source file:io.apiman.tools.ldap.ApimanLdapServer.java

@Test
public void startLdapServer() throws Exception {
    DirContext ctx = createContext();
    Assert.assertNotNull(ctx);//from w  w w  . j a va 2  s.  co  m

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration<SearchResult> result = ctx.search("o=apiman", "(ObjectClass=*)", controls);

    int count = 0;
    while (result.hasMore()) {
        result.next();
        count++;
    }

    String url = "ldap://" + LDAP_SERVER + ":" + ldapServer.getPort();
    System.out.println("======================================================");
    System.out.println("LDAP server started successfully.");
    System.out.println("");
    System.out.println("  URL: " + url);
    System.out.println("  Node Count: " + count);
    System.out.println("  Direct Bind DN: cn=${username},ou=developers,ou=people,o=apiman");
    System.out.println("======================================================");
    System.out.println("");
    System.out.println("");
    System.out.println("Press Enter to stop the LDAP server.");
    new BufferedReader(new InputStreamReader(System.in)).readLine();
    System.out.println("Shutting down the LDAP server...");
}

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

public List<String> lookupMembershipGroups(DirContext dirContext, String userDn)
        throws javax.naming.NamingException {

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

    NamingEnumeration<SearchResult> searchResults = dirContext.search("",
            adConfiguration.getMembershipSearchFilter(), new String[] { userDn }, controls);

    List<String> roles = new LinkedList<String>();
    while (searchResults.hasMore()) {
        GroupDn groupDn = new GroupDn(searchResults.next().getNameInNamespace(),
                adConfiguration.getGroupsRdn());
        roles.add(groupDn.getAsGroupId());
    }/*  w ww . ja va 2 s. c  om*/

    return roles;
}

From source file:org.jasig.schedassist.impl.oraclecalendar.OracleCalendarResourceAccountAttributesMapper.java

@Override
public Object mapFromAttributes(Attributes attributes) throws NamingException {
    OracleCalendarResourceAccount user = new OracleCalendarResourceAccount(owner);

    NamingEnumeration<String> attributeNames = attributes.getIDs();
    Map<String, String> attributesMap = new HashMap<String, String>();
    while (attributeNames.hasMore()) {
        String attributeName = attributeNames.next();
        Attribute attribute = attributes.get(attributeName);
        String value = (String) attribute.get();
        if (null != value) {
            value = value.trim();/*from   w  w  w  .jav a 2 s.  c  o m*/
        }
        final String lcAttributeName = attributeName.toLowerCase();
        attributesMap.put(lcAttributeName, value);

        if (RESOURCE_OWNER_USERNAME.equals(lcAttributeName)) {
            user.setAccountOwnerUsername(value);
        } else if (AbstractOracleCalendarAccount.CTCALXITEMID.equals(lcAttributeName)) {
            user.setCtcalxitemid(value);
        } else if (OracleLdapCalendarResourceAccountDaoImpl.CN.equals(lcAttributeName)) {
            user.setResourceName(value);
        } else if (OracleLdapCalendarResourceAccountDaoImpl.POSTALADDRESS.equals(lcAttributeName)) {
            user.setLocation(value);
        } else if (AbstractOracleCalendarAccount.WISCEDUCALEMAIL.equals(lcAttributeName)) {
            user.setEmailAddress(value);
        }

    }
    user.setAttributes(attributesMap);

    String contactInfo = buildContactInformation(
            getAttributeValue(attributes, OracleLdapCalendarResourceAccountDaoImpl.GIVENNAME),
            getAttributeValue(attributes, OracleLdapCalendarResourceAccountDaoImpl.SN),
            getAttributeValue(attributes, OracleLdapCalendarResourceAccountDaoImpl.TELEPHONENUMBER));
    user.setContactInformation(contactInfo);

    String oracleGuid = this.oracleGUIDSource.getOracleGUID(user);
    user.setOracleGuid(oracleGuid);
    user.getAttributes().put(AbstractOracleCalendarAccount.ORACLE_GUID_ATTRIBUTE, oracleGuid);
    return user;
}