Example usage for javax.naming.directory Attribute get

List of usage examples for javax.naming.directory Attribute get

Introduction

In this page you can find the example usage for javax.naming.directory Attribute get.

Prototype

Object get(int ix) throws NamingException;

Source Link

Document

Retrieves the attribute value from the ordered list of attribute values.

Usage

From source file:org.webterm.core.plugin.authentication.LdapAuthentication.java

@Override
public boolean isValidUser(final String user, final String passwd) {
    boolean result = false; // NOPMD - init

    final Attribute pwd = fetch(user);
    if ((pwd != null) && (this.checkMethode != null)) {
        try {/*w  w  w.j  a  v a 2 s.  c o  m*/
            final byte[] pwdAttr = (byte[]) pwd.get(0);
            result = this.checkMethode.isValidPassword(passwd, pwdAttr);
        } catch (final Exception ex) {
            LOG.error(ex, ex);
        }
    }
    return result;
}

From source file:org.nuxeo.ecm.directory.ldap.dns.DNSServiceResolverImpl.java

/**
 * Returns the host name and port that a server providing the specified service can be reached at. A DNS lookup for
 * a SRV record in the form "_service.example.com" is attempted.
 * <p>//from ww  w .ja va  2s.com
 * As an example, a lookup for "example.com" for the service _gc._tcp may return "dc01.example.com:3268".
 *
 * @param service the service.
 * @param domain the domain.
 * @return a List of DNSServiceEntrys, which encompasses the hostname and port that the server can be reached at for
 *         the specified domain.
 * @throws NamingException if the DNS server is unreachable
 */
protected List<DNSServiceEntry> resolveDnsServiceRecord(final String service, final String domain)
        throws NamingException {
    List<DNSServiceEntry> addresses = new ArrayList<>();

    if (context == null) {
        return addresses;
    }

    final String key = service + "." + domain;
    /*
     * Return item from cache if it exists.
     */
    if (System.currentTimeMillis() - lastCacheUpdate > maxDelay) {
        cache.clear();
    }
    if (cache.containsKey(key)) {
        List<DNSServiceEntry> cachedAddresses = cache.get(key);
        if (cachedAddresses != null) {
            return cachedAddresses;
        }
    }

    Attributes dnsLookup = context.getAttributes(service + "." + domain, new String[] { SRV_RECORD });

    Attribute attribute = dnsLookup.get(SRV_RECORD);
    for (int i = 0; i < attribute.size(); i++) {
        /*
         * Get the current resource record
         */
        String entry = (String) attribute.get(i);

        String[] records = entry.split(" ");
        String host = records[records.length - 1];
        int port = Integer.parseInt(records[records.length - 2]);
        int weight = Integer.parseInt(records[records.length - 3]);
        int priority = Integer.parseInt(records[records.length - 4]);

        /*
         * possible to get TTL?
         */

        /*
         * Host entries in DNS should end with a "."
         */
        if (host.endsWith(".")) {
            host = host.substring(0, host.length() - 1);
        }

        addresses.add(new DNSServiceEntry(host, port, priority, weight));
    }

    /*
     * Sort the addresses by DNS priority and weight settings
     */
    Collections.sort(addresses);

    /*
     * Add item to cache.
     */
    if (cache.size() > 100) {
        cache.clear();
    }
    cache.put(key, addresses);
    lastCacheUpdate = System.currentTimeMillis();
    return addresses;
}

From source file:org.glite.slcs.pki.bouncycastle.X509PrincipalUtil.java

/**
 * Reads the given {@link Attribute} and recurses into RDN attributes, fills
 * the given vectors.//from  w  ww  . j av a  2s .com
 * 
 * @param attr
 *            The {@link Attribute} to read.
 * @param oids
 *            The vector of OID.
 * @param values
 *            The vector of value.
 * @param added
 *            The added status vector.
 * @throws NamingException
 *             if a naming error occurs.
 */
private void readAttr(Attribute attr, Vector<DERObjectIdentifier> oids, Vector<Object> values,
        Vector<Boolean> added) throws NamingException {
    // Recursively looking into each attribute
    LOG.debug("Attribute: " + attr);
    for (int i = 0; i < attr.size(); i++) {
        if (attr.get(i) instanceof Attribute) {
            Attribute rdnAttr = (Attribute) attr.get(i);
            LOG.debug("Attribute RDN: " + rdnAttr);
            readAttr(rdnAttr, oids, values, added);
        } else { // Get back the OID from name
            DERObjectIdentifier oid = (DERObjectIdentifier) X509Name.DefaultLookUp
                    .get(Strings.toLowerCase(attr.getID()));
            oids.add(oid);
            Object attrValue = attr.get(i);
            LOG.debug("Attribute value: " + attrValue);
            values.add(attrValue);
            added.add(start_);
            start_ = true;

        }
    }

}

From source file:nl.nn.adapterframework.webcontrol.LoginFilter.java

private boolean isMemberOf(DirContext ctx, String dnUser, String dnGroup) throws NamingException {
    DirContext lookedContext = (DirContext) (ctx.lookup(dnGroup));
    Attribute attrs = lookedContext.getAttributes("").get("member");
    for (int i = 0; i < attrs.size(); i++) {
        String foundMember = (String) attrs.get(i);
        if (foundMember.equalsIgnoreCase(dnUser)) {
            return true;
        }//from w w w.j  av a  2s.  c  om
    }
    return false;
}

From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java

private User processEntry(SearchResult entry) throws NamingException {
    User user = new User();
    Attributes attrs = entry.getAttributes();
    Attribute attrBits = attrs.get(LDAPAttributeNames.BITS.getLdapKey());
    if (attrBits != null) {
        long lng = Long.parseLong(attrBits.get(0).toString());
        long secondBit = lng & 2; // get bit 2
        if (secondBit != 0) {
            // User not enabled
            return null;
        }/*w w  w .j  av  a 2 s  .c o m*/
    }
    user.setUserId(StringUtils.lowerCase(getStringValue(attrs, LDAPAttributeNames.USERID)));
    user.setFirstname(getStringValue(attrs, LDAPAttributeNames.FIRSTNAME));
    user.setLastname(getStringValue(attrs, LDAPAttributeNames.LASTNAME));
    user.setEmail(getStringValue(attrs, LDAPAttributeNames.EMAIL));
    user.setTelephone(getStringValue(attrs, LDAPAttributeNames.TELEPHONE));
    user.setMobile(getStringValue(attrs, LDAPAttributeNames.MOBILE));
    user.setRoom(getStringValue(attrs, LDAPAttributeNames.ROOM));
    user.setLocation(getStringValue(attrs, LDAPAttributeNames.LOCATION));
    user.setDepartment(getStringValue(attrs, LDAPAttributeNames.DEPARTMENT));
    user.setCompany(getStringValue(attrs, LDAPAttributeNames.COMPANY));
    user.setSip(getStringValue(attrs, LDAPAttributeNames.SIP));
    return user;
}

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

private boolean findMember(String host, int port, String dnSearchIn, boolean useSsl, String dnFind,
        boolean recursiveSearch) throws NamingException {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    String provUrl = retrieveUrl(host, port, dnSearchIn, useSsl);
    env.put(Context.PROVIDER_URL, provUrl);
    if (StringUtils.isNotEmpty(cf.getUsername())) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, cf.getUsername());
        env.put(Context.SECURITY_CREDENTIALS, cf.getPassword());
    } else {/*from   w ww  . j  a  v a2 s  .  c  o  m*/
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx = null;
    try {
        try {
            ctx = new InitialDirContext(env);
        } catch (CommunicationException e) {
            log.info("Cannot create constructor for DirContext (" + e.getMessage()
                    + "], will try again with dummy SocketFactory");
            env.put("java.naming.ldap.factory.socket", DummySSLSocketFactory.class.getName());
            ctx = new InitialLdapContext(env, null);
        }
        Attribute attrs = ctx.getAttributes("").get("member");
        if (attrs != null) {
            boolean found = false;
            for (int i = 0; i < attrs.size() && !found; i++) {
                String dnFound = (String) attrs.get(i);
                if (dnFound.equalsIgnoreCase(dnFind)) {
                    found = true;
                } else {
                    if (recursiveSearch) {
                        found = findMember(host, port, dnFound, useSsl, dnFind, recursiveSearch);
                    }
                }
            }
            return found;
        }
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.warn("Exception closing DirContext", e);
            }
        }
    }
    return false;
}

From source file:org.cloudfoundry.identity.uaa.ldap.PasswordComparisonAuthenticator.java

public DirContextOperations localCompareAuthenticate(DirContextOperations user, String password) {
    boolean match = false;
    try {/*from  www  .  ja v  a2 s  . c o  m*/
        Attributes attributes = user.getAttributes();
        Attribute attr = attributes.get(getPasswordAttributeName());
        if (attr.size() == 0) {
            throw new AuthenticationCredentialsNotFoundException(
                    "Missing " + getPasswordAttributeName() + " attribute.");
        }
        for (int i = 0; (attr != null) && (!match) && (i < attr.size()); i++) {
            Object valObject = attr.get(i);
            if (valObject != null && valObject instanceof byte[]) {
                if (passwordEncoder instanceof DynamicPasswordComparator) {
                    byte[] received = password.getBytes();
                    byte[] stored = (byte[]) valObject;
                    match = ((DynamicPasswordComparator) passwordEncoder).comparePasswords(received, stored);
                } else {
                    String encodedPassword = passwordEncoder.encodePassword(password, null);
                    byte[] passwordBytes = Utf8.encode(encodedPassword);
                    match = Arrays.equals(passwordBytes, (byte[]) valObject);
                }
            }
        }
    } catch (NamingException e) {
        throw new BadCredentialsException("Bad credentials", e);
    }
    if (!match)
        throw new BadCredentialsException("Bad credentials");
    return user;
}

From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java

private String getStringValue(Attributes attributes, LDAPAttributeNames attributeName) throws NamingException {
    String ret = null;//from w  w w .j a v a  2s  .  c o  m
    Attribute attribute = attributes.get(attributeName.getLdapKey());
    if (attribute != null) {
        for (int i = 0; i < attribute.size(); i++) {
            ret = (String) attribute.get(i);
        }
    }
    return ret;
}

From source file:ca.tnt.ldaputils.impl.LdapEntry.java

public String getStringValue(final String attribute) {
    final Attribute ldapAttribute;
    try {//from w  ww .  j av  a2s.  c o  m
        ldapAttribute = attributes.get(attribute);
        if (ldapAttribute != null && ldapAttribute.size() != 0)
            return (String) ldapAttribute.get(0);
        else {
            return null;
        }
    } catch (NamingException e) {
        throw new LdapNamingException(e);
    }

}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * Get next free uidNumber.//from w  w w.j a  v  a 2  s. co m
 *
 * @return next free uidNumber
 */
private String getNextUidNumber() {
    Hashtable<String, String> env = getLdapConnectionSettings();
    env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
    env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));
    DirContext ctx;
    String rueckgabe = "";
    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(ConfigCore.getParameter("ldap_nextFreeUnixId"));
        Attribute la = attrs.get("uidNumber");
        rueckgabe = (String) la.get(0);
        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
        Helper.setFehlerMeldung(e.getMessage());
    }
    return rueckgabe;
}