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:jp.ikedam.jenkins.plugins.ldap_sasl.SearchUserDnResolver.java

/**
 * Resolve the user DN by querying the LDAP directory.
 * //from  www.  j  a va  2  s  .c o m
 * @param ctx LDAP context, already authenticated.
 * @param username the username the user authenticated with.
 * 
 * @return the DN of the user.
 * @see jp.ikedam.jenkins.plugins.ldap_sasl.UserDnResolver#getUserDn(javax.naming.ldap.LdapContext, java.lang.String)
 */
@Override
public String getUserDn(LdapContext ctx, String username) {
    Logger logger = getLogger();
    if (StringUtils.isBlank(getSearchQueryTemplate())) {
        // not configured.
        logger.severe("Not configured.");

        return null;
    }

    try {
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        logger.fine(String.format("Searching users base=%s, username=%s", getSearchBase(), username));
        String query = expandUsername(getSearchQueryTemplate(), username);
        NamingEnumeration<SearchResult> entries = ctx.search((getSearchBase() != null) ? getSearchBase() : "",
                query, searchControls);
        if (!entries.hasMore()) {
            // no entry.
            logger.severe(String.format("User not found: %s", username));
            return null;
        }

        String userDn = entries.next().getNameInNamespace();

        if (entries.hasMore()) {
            // more than one entry.
            logger.severe(String.format("User found more than one: %s", username));
            return null;
        }
        entries.close();

        return userDn;
    } catch (NamingException e) {
        logger.log(Level.SEVERE, "Failed to search a user", e);
        return null;
    }
}

From source file:de.tuttas.util.LDAPUtil.java

/**
 * Benutzer aus der LDAP Abfragen/*from  w w w .j  a  va2  s.c o  m*/
 *
 * @param username Benutzername
 * @param password Kennwort
 * @return der Benutzer
 * @throws Exception Wenn etwas schief ging
 */
public LDAPUser authenticateJndi(String username, String password) throws Exception {
    // Anbindung ans LDAP
    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost);
    props.put(Context.SECURITY_PRINCIPAL, Config.getInstance().bindUser);//adminuser - User with special priviledge, dn user
    props.put(Context.SECURITY_CREDENTIALS, Config.getInstance().bindPassword);//dn user password
    try {
        context = new InitialDirContext(props);
        ctrls = new SearchControls();
        ctrls.setReturningAttributes(new String[] { "description", "mail", "sn", "initials", "givenName",
                "memberOf", "userPrincipalName", "distinguishedName" });
        ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    } catch (NamingException ex) {
        Logger.getLogger(LDAPUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
    NamingEnumeration<javax.naming.directory.SearchResult> answers = context
            .search(Config.getInstance().userContext, "(cn=" + username + ")", ctrls);
    Log.d("answers=" + answers);
    Log.d("answers=" + answers.hasMore());

    if (!answers.hasMore()) {
        return null;
    }

    javax.naming.directory.SearchResult result = answers.nextElement();

    try {
        for (NamingEnumeration ae = result.getAttributes().getAll(); ae.hasMore();) {
            Attribute attr = (Attribute) ae.next();
            Log.d("attribute: " + attr.getID());

            /* print each value */
            for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println("value: " + e.next()))
                ;
        }
    } catch (NamingException e) {
        e.printStackTrace();
    }

    String inititials = "";
    if (result.getAttributes().get("initials") != null) {
        inititials = result.getAttributes().get("initials").getAll().next().toString();
    }
    LDAPUser u;
    if (result.getAttributes().get("mail") == null) {
        u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(),
                result.getAttributes().get("givenName").getAll().next().toString(), "", inititials);
    } else {
        u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(),
                result.getAttributes().get("givenName").getAll().next().toString(),
                result.getAttributes().get("mail").getAll().next().toString(), inititials);
    }

    String dName = result.getAttributes().get("distinguishedName").getAll().next().toString();
    Log.d("dName=" + dName);
    if (dName.contains("OU=Lehrer")) {
        Log.d("Ich bin ein Lehrer");
        u.setRole(Roles.toString(Roles.LEHRER));
    } else {
        Log.d("Ich bin ein Schler");
        u.setRole(Roles.toString(Roles.SCHUELER));
        if (result.getAttributes().get("memberOf") != null) {
            String memberOf = result.getAttributes().get("memberOf").getAll().next().toString();
            String courseName = memberOf.split(",")[0];
            courseName = courseName.substring(courseName.indexOf("=") + 1);
            Log.d("Name der Klasse ist " + courseName);
            u.setCourse(courseName);
        }
    }

    String user = result.getNameInNamespace();

    try {

        props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost);
        props.put(Context.SECURITY_PRINCIPAL, user);
        props.put(Context.SECURITY_CREDENTIALS, password);

        context = new InitialDirContext(props);
    } catch (Exception e) {
        return null;
    }
    return u;
}

From source file:LDAPTest.java

/**
     * Constructs the data panel./*  w  ww  . jav  a2  s. co m*/
     * @param attributes the attributes of the given entry
     */
    public DataPanel(Attributes attrs) throws NamingException {
        setLayout(new java.awt.GridLayout(0, 2, 3, 1));

        NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
        while (attrEnum.hasMore()) {
            Attribute attr = attrEnum.next();
            String id = attr.getID();

            NamingEnumeration<?> valueEnum = attr.getAll();
            while (valueEnum.hasMore()) {
                Object value = valueEnum.next();
                if (id.equals("userPassword"))
                    value = new String((byte[]) value);

                JLabel idLabel = new JLabel(id, SwingConstants.RIGHT);
                JTextField valueField = new JTextField("" + value);
                if (id.equals("objectClass"))
                    valueField.setEditable(false);
                if (!id.equals("uid")) {
                    add(idLabel);
                    add(valueField);
                }
            }
        }
    }

From source file:com.teklabs.throng.integration.ldap.Ldap.java

private String getPrincipal(String login) throws NamingException {
    if (baseDN == null) {
        throw new IllegalArgumentException("LDAP BaseDN is not set");
    }/*  w w w  .  ja  v a2  s. c  om*/
    InitialDirContext context = null;
    String principal;
    try {
        if (LdapHelper.LOG.isDebugEnabled()) {
            LdapHelper.LOG.debug("Search principal: " + login);
        }

        context = ldapContextFactory.getInitialDirContext();
        String request = "(&(objectClass=" + userObjectClass + ")(" + loginAttribute + "={0}))";
        if (LdapHelper.LOG.isDebugEnabled()) {
            LdapHelper.LOG.debug("LDAP request: " + request);
        }

        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        controls.setReturningAttributes(new String[] {});
        controls.setReturningObjFlag(true);
        NamingEnumeration result = context.search(baseDN, request, new String[] { login }, controls);
        String found = null;
        if (result.hasMore()) {
            SearchResult obj = (SearchResult) result.next();
            found = obj.getNameInNamespace();
            if (found != null && result.hasMore()) {
                found = null;
                LdapHelper.LOG.error(
                        "Login \'" + login + "\' is not unique in LDAP (see attribute " + loginAttribute + ")");
            }
        }

        principal = found;
    } finally {
        LdapHelper.closeContext(context);
    }

    return principal;
}

From source file:org.apache.zeppelin.rest.GetUserList.java

/**
 * function to extract users from LDAP//from  w  w  w. j a  va2 s.  c  om
 */
public List<String> getUserList(JndiLdapRealm r, String searchText) {
    List<String> userList = new ArrayList<>();
    String userDnTemplate = r.getUserDnTemplate();
    String userDn[] = userDnTemplate.split(",", 2);
    String userDnPrefix = userDn[0].split("=")[0];
    String userDnSuffix = userDn[1];
    JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory();
    try {
        LdapContext ctx = CF.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { userDnPrefix };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userDnPrefix) != null) {
                String currentUser = attrs.get(userDnPrefix).toString();
                userList.add(currentUser.split(":")[1].trim());
            }
        }
    } catch (Exception e) {
        LOG.error("Error retrieving User list from Ldap Realm", e);
    }
    LOG.info("UserList: " + userList);
    return userList;
}

From source file:com.photon.phresco.ldap.impl.LDAPManagerImpl.java

private User getUser(Credentials credentials, DirContext ctx) throws PhrescoException {
    if (isDebugEnabled) {
        S_LOGGER.debug("Entering Method LDAPManagerImpl.getUserInfo(String userName, DirContext ctx)");
    }/*from w  w  w. j a v a2s . c  om*/
    User user = new User();
    try {
        String userName = credentials.getUsername();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { "*" };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration<SearchResult> ne = ctx.search(ldapConfig.getLdapBaseDn(),
                ldapConfig.getLdapLoginAttribute() + Constants.STR_EQUALS + userName, constraints);
        if (ne.hasMore()) {
            Attributes attrs = ne.next().getAttributes();

            user.setName(userName);
            //      userInfo.setCredentials(credentials);
            user.setDisplayName(getDisplayName(attrs));
            user.setEmail(getMailId(attrs));
            user.setPhrescoEnabled(isPhrescoEnabled(attrs));
            //      userInfo.setCustomerNames(getCustomerNames(attrs));

        }

    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return user;
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static LDAPUser getUser(String cn) {
    LDAPUser user = null;/*  ww w.j av  a  2  s. c o  m*/
    NamingEnumeration results = null;
    DirContext ctx = null;
    try {
        ctx = getContext();
        SearchControls controls = new SearchControls();
        String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf",
                "createTimestamp" };
        controls.setReturningAttributes(retAttrs);
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls);
        if (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            user = new LDAPUser();

            if (attributes.get("cn") != null)
                user.setUsername((String) attributes.get("cn").get());
            if (attributes.get("sn") != null)
                user.setSurname((String) attributes.get("sn").get());
            if (attributes.get("givenName") != null)
                user.setGivenname((String) attributes.get("givenName").get());
            if (attributes.get("title") != null)
                user.setTitle((String) attributes.get("title").get());
            if (attributes.get("registeredAddress") != null)
                user.setPreferredMail((String) attributes.get("registeredAddress").get(0));
            if (attributes.get("mail") != null) {
                String mails = "";
                for (int i = 0; i < attributes.get("mail").size(); i++) {
                    if (i != 0)
                        mails = mails + ", ";
                    mails = mails + (String) attributes.get("mail").get(i);
                }
                user.setAdditionalMails(mails);
            }
            if (attributes.get("memberOf") != null) {
                for (int i = 0; i < attributes.get("memberOf").size(); i++) {
                    user.addGroup((String) attributes.get("memberOf").get(i));
                }
            }

            if (attributes.get("createTimestamp") != null) {
                String time = (String) attributes.get("createTimestamp").get();
                DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss");
                user.setCreationTime(ldapData.parse(time));
            }

        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        _log.error(e);
    } catch (ParseException ex) {
        _log.error(ex);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }

    return user;
}

From source file:ddf.security.sts.SecurityAttributesClaimsHandler.java

private Claim buildClaim(ClaimsParameters parameters, Entry<String, String> claimAttr, Attribute attr)
        throws URISyntaxException {
    Claim c = new Claim();
    c.setClaimType(new URI(claimAttr.getKey()));
    c.setPrincipal(parameters.getPrincipal());

    StringBuilder claimValue = new StringBuilder();
    try {// w w  w . j  av  a 2  s .  co m
        NamingEnumeration<?> list = (NamingEnumeration<?>) attr.getAll();
        while (list.hasMore()) {
            Object obj = list.next();
            if (!(obj instanceof String)) {
                LOGGER.warn("LDAP attribute '{}' has an unsupported value type", claimAttr.getValue());
                break;
            }
            claimValue.append((String) obj);
            if (list.hasMore()) {
                claimValue.append(ATTRIBUTE_DELIMITER);
            }
        }
    } catch (NamingException ex) {
        LOGGER.warn("Failed to read value of LDAP attribute '{}'", claimAttr.getValue());
    }

    c.setValue(claimValue.toString());
    return c;
}

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

@Override
public CredentialEntry retrieveCredentialEntry(String userId, String realm) throws IOException {
    try {/*from   www .  j av  a 2  s. com*/
        // Search for the credential entry
        NamingEnumeration<SearchResult> searchResults = this.context.search(this.entrySearchBaseDn,
                "(&(objectClass=inetOrgPerson)(uid=" + userId + "))", null);
        if (!searchResults.hasMore()) {
            return null; // entry not found
        }
        SearchResult result = searchResults.next();

        // Obtain the attributes
        String entryDn = result.getNameInNamespace();

        // Create and return the credential entry
        return new JndiLdapCredentialEntry(entryDn);

    } catch (NamingException ex) {
        throw new IOException(ex);
    }
}

From source file:edu.vt.middleware.ldap.dsml.Dsmlv1.java

/**
 * This will take a DSML <code>Element</code> containing an entry of type
 * <dsml:entry name="name"/> and convert it to a LDAP search result.
 *
 * @param  entryElement  <code>Element</code> of DSML content
 *
 * @return  <code>SearchResult</code>
 *//*from   ww  w  . j  av a 2 s  . com*/
protected SearchResult createSearchResult(final Element entryElement) {
    String name = "";
    final Attributes entryAttributes = new BasicAttributes(true);
    SearchResult attrResults = null;

    if (entryElement != null) {

        name = entryElement.attributeValue("dn");
        if (name == null) {
            name = "";
        }

        if (entryElement.hasContent()) {

            final Iterator<?> ocIterator = entryElement.elementIterator("objectclass");
            while (ocIterator.hasNext()) {
                final Element ocElement = (Element) ocIterator.next();
                if (ocElement != null && ocElement.hasContent()) {
                    final String ocName = "objectClass";
                    final Attribute entryAttribute = new BasicAttribute(ocName);
                    final Iterator<?> valueIterator = ocElement.elementIterator("oc-value");
                    while (valueIterator.hasNext()) {
                        final Element valueElement = (Element) valueIterator.next();
                        if (valueElement != null) {
                            final String value = valueElement.getText();
                            if (value != null) {
                                entryAttribute.add(value);
                            }
                        }
                    }
                    entryAttributes.put(entryAttribute);
                }
            }

            attrResults = super.createSearchResult(entryElement);
        }
    }

    if (attrResults != null) {
        final Attributes attrs = attrResults.getAttributes();
        if (attrs != null) {
            final NamingEnumeration<? extends Attribute> ae = attrs.getAll();
            if (ae != null) {
                try {
                    while (ae.hasMore()) {
                        entryAttributes.put(ae.next());
                    }
                } catch (NamingException e) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Could not read attribute in SearchResult from parent");
                    }
                }
            }
        }
    }
    return new SearchResult(name, null, entryAttributes);
}