Example usage for javax.naming.directory DirContext getAttributes

List of usage examples for javax.naming.directory DirContext getAttributes

Introduction

In this page you can find the example usage for javax.naming.directory DirContext getAttributes.

Prototype

public Attributes getAttributes(String name, String[] attrIds) throws NamingException;

Source Link

Document

Retrieves selected attributes associated with a named object.

Usage

From source file:org.apache.hadoop.net.DNS.java

/**
 * Returns the hostname associated with the specified IP address by the
 * provided nameserver.//from  w  w  w . ja v a  2  s .c o  m
 *
 * Loopback addresses 
 * @param hostIp The address to reverse lookup
 * @param ns The host name of a reachable DNS server
 * @return The host name associated with the provided IP
 * @throws NamingException If a NamingException is encountered
 */
public static String reverseDns(InetAddress hostIp, @Nullable String ns) throws NamingException {
    //
    // Builds the reverse IP lookup form
    // This is formed by reversing the IP numbers and appending in-addr.arpa
    //
    String[] parts = hostIp.getHostAddress().split("\\.");
    String reverseIP = parts[3] + "." + parts[2] + "." + parts[1] + "." + parts[0] + ".in-addr.arpa";

    DirContext ictx = new InitialDirContext();
    Attributes attribute;
    try {
        attribute = ictx.getAttributes("dns://" // Use "dns:///" if the default
                + ((ns == null) ? "" : ns) +
                // nameserver is to be used
                "/" + reverseIP, new String[] { "PTR" });
    } finally {
        ictx.close();
    }

    String hostname = attribute.get("PTR").get().toString();
    int hostnameLength = hostname.length();
    if (hostname.charAt(hostnameLength - 1) == '.') {
        hostname = hostname.substring(0, hostnameLength - 1);
    }
    return hostname;
}

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

public Set<Attribute> getAttributes(String uid, String attrName) {
    Set<Attribute> values = CollectUtils.newHashSet();
    DirContext ctx = getContext();
    if (ctx == null)
        return values;
    try {/*from  www.j  a  va  2s .c  o m*/
        String dn = getUserDN(uid);
        if (dn == null) {
            logger.debug("User {} not found", uid);
            return values;
        }
        javax.naming.Name userID = new CompositeName(dn);
        Attributes attrs = null;
        if (null != attrName) {
            attrs = ctx.getAttributes(userID, new String[] { attrName });
        } else {
            attrs = ctx.getAttributes(userID);
        }
        for (NamingEnumeration<? extends Attribute> ne = attrs.getAll(); ne.hasMoreElements();) {
            Attribute attr = ne.nextElement();
            values.add(attr);
        }
    } catch (NamingException e) {
        e.printStackTrace();
    }
    return values;
}

From source file:org.cloudfoundry.identity.uaa.ldap.extension.SpringSecurityLdapTemplate.java

/**
 * Composes an object from the attributes of the given DN.
 *
 * @param dn the directory entry which will be read
 * @param attributesToRetrieve the named attributes which will be retrieved from the directory entry.
 *
 * @return the object created by the mapper
 *//* w w  w. j  a v a  2s  .c o m*/
public DirContextOperations retrieveEntry(final String dn, final String[] attributesToRetrieve) {

    return (DirContextOperations) executeReadOnly(new ContextExecutor() {
        public Object executeWithContext(DirContext ctx) throws NamingException {
            Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve);

            // Object object = ctx.lookup(LdapUtils.getRelativeName(dn, ctx));

            return new DirContextAdapter(attrs, new DistinguishedName(dn),
                    new DistinguishedName(ctx.getNameInNamespace()));
        }
    });
}

From source file:org.fao.geonet.kernel.security.ldap.LdapUserDetailsManager.java

private DirContextAdapter loadUserAsContext(final DistinguishedName dn, final String username) {
    return (DirContextAdapter) template.executeReadOnly(new ContextExecutor() {
        public Object executeWithContext(DirContext ctx) throws NamingException {
            try {
                Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve);
                return new DirContextAdapter(attrs, LdapUtils.getFullDn(dn, ctx));
            } catch (NameNotFoundException notFound) {
                throw new UsernameNotFoundException("User " + username + " not found", notFound);
            }/*from  w w  w .  j  a v  a  2  s .  co m*/
        }
    });
}

From source file:org.javlo.external.agitos.dkim.DKIMUtil.java

public boolean checkDNSForPublickey(String signingDomain, String selector) throws DKIMSignerException {

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    String recordname = selector + "._domainkey." + signingDomain;
    String value = null;/*from   w  ww.  j  a v  a 2  s .  com*/

    try {
        DirContext dnsContext = new InitialDirContext(env);

        javax.naming.directory.Attributes attribs = dnsContext.getAttributes(recordname,
                new String[] { "TXT" });
        javax.naming.directory.Attribute txtrecord = attribs.get("txt");

        if (txtrecord == null) {
            throw new DKIMSignerException("There is no TXT record available for " + recordname);
        }

        // "v=DKIM1; g=*; k=rsa; p=MIGfMA0G ..."
        value = (String) txtrecord.get();

    } catch (NamingException ne) {
        throw new DKIMSignerException("Selector lookup failed", ne);
    }

    if (value == null) {
        throw new DKIMSignerException("Value of RR " + recordname + " couldn't be retrieved");
    }

    // try to read public key from RR
    String[] tags = value.split(";");
    for (String tag : tags) {
        tag = tag.trim();
        if (tag.startsWith("p=")) {

            try {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");

                // decode public key, FSTODO: convert to DER format
                PKCS8EncodedKeySpec pubSpec = new PKCS8EncodedKeySpec(tag.substring(2).getBytes());
                RSAPrivateKey pubKey = (RSAPrivateKey) keyFactory.generatePublic(pubSpec);
            } catch (NoSuchAlgorithmException nsae) {
                throw new DKIMSignerException("RSA algorithm not found by JVM");
            } catch (InvalidKeySpecException ikse) {
                throw new DKIMSignerException(
                        "The public key " + tag + " in RR " + recordname + " couldn't be decoded.");
            }

            // FSTODO: create test signature with privKey and test validation with pubKey to check on a valid key pair

            return true;
        }
    }

    throw new DKIMSignerException("No public key available in " + recordname);
}

From source file:org.lsc.jndi.JndiServices.java

private static String lookupLdapSrvThroughDNS(String hostname) {
    Properties env = new Properties();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    env.put("java.naming.provider.url", "dns:");
    DirContext ctx;
    try {//from  ww w.j av a2 s.com
        ctx = new InitialDirContext(env);
        if (ctx != null) {
            Attributes attrs = ctx.getAttributes(hostname, new String[] { "SRV" });
            String[] attributes = ((String) attrs.getAll().next().get()).split(" ");
            return attributes[3] + ":" + attributes[2];
        }
    } catch (NamingException e) {
    }
    return hostname + ":389";
}

From source file:org.lsc.jndi.JndiServices.java

/**
 * Return the LDAP schema.// www  .  jav  a  2  s .  com
 *
 * @param attrsToReturn
 *                list of attribute names to return (or null for all
 *                'standard' attributes)
 * @return the map of name => attribute
 * @throws NamingException
 *                 thrown if something goes wrong (bad
 */
@SuppressWarnings("unchecked")
public Map<String, List<String>> getSchema(final String[] attrsToReturn) throws NamingException {
    Map<String, List<String>> attrsResult = new HashMap<String, List<String>>();

    // connect to directory
    Hashtable<String, String> props = (Hashtable<String, String>) ctx.getEnvironment();
    String baseUrl = (String) props.get(Context.PROVIDER_URL);
    baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf('/'));
    props.put(Context.PROVIDER_URL, baseUrl);
    DirContext schemaCtx = new InitialLdapContext(props, null);

    // find schema entry
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.OBJECT_SCOPE);
    sc.setReturningAttributes(new String[] { "subschemaSubentry" });

    NamingEnumeration<SearchResult> schemaDnSR = schemaCtx.search("", "(objectclass=*)", sc);

    SearchResult sr = null;
    Attribute subschemaSubentry = null;
    String subschemaSubentryDN = null;

    if (schemaDnSR.hasMore()) {
        sr = schemaDnSR.next();
    }
    if (sr != null) {
        subschemaSubentry = sr.getAttributes().get("subschemaSubentry");
    }
    if (subschemaSubentry != null && subschemaSubentry.size() > 0) {
        subschemaSubentryDN = (String) subschemaSubentry.get();
    }

    if (subschemaSubentryDN != null) {
        // get schema attributes from subschemaSubentryDN
        Attributes schemaAttrs = schemaCtx.getAttributes(subschemaSubentryDN,
                attrsToReturn != null ? attrsToReturn : new String[] { "*", "+" });

        if (schemaAttrs != null) {
            for (String attr : attrsToReturn) {
                Attribute schemaAttr = schemaAttrs.get(attr);
                if (schemaAttr != null) {
                    attrsResult.put(schemaAttr.getID(), (List<String>) Collections.list(schemaAttr.getAll()));
                }
            }
        }
    }

    return attrsResult;
}

From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * Uses the context provided to refresh the user information from the directory.
 * //from ww w.j  a va 2 s  . c om
 * @param userInfo  the user information to be refreshed
 * @param context  the directory context to use for the refresh
 */
private void refreshUserInfo(UserInfo userInfo, DirContext context) throws NamingException {
    String userId = (userInfo == null) ? null : userInfo.getUserId();
    String userDn;

    if (userId != null) {
        System.out.println("REFRESHING USER: " + userId);
        if (mode == AuthenticationMode.USER_LOOKUP) {
            userDn = userPattern.format(new String[] { userId });

        } else {
            userDn = findUserDn(userId, context);
        }

        if (userDn == null) {
            throw new NamingException("User account does not exist in the directory: " + userId);

        } else { // Make sure the account profile fields are populated from the directory
            String contextDnSuffix = "," + context.getNameInNamespace();
            if (userDn.endsWith(contextDnSuffix)) {
                userDn = userDn.replaceAll(contextDnSuffix, "");
            }

            Attributes userAttrs = context.getAttributes(userDn,
                    new String[] { userLastNameAttribute, userFirstNameAttribute, userEmailAttribute });

            userInfo.setLastName(getAttributeValue(userAttrs, userLastNameAttribute));
            userInfo.setFirstName(getAttributeValue(userAttrs, userFirstNameAttribute));
            userInfo.setEmailAddress(getAttributeValue(userAttrs, userEmailAttribute));
        }
    }
}

From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * Performs a lookup of the user's password in the remote directory.
 * //  w  w w . j a  v  a  2 s  . c  o m
 * @param userId
 *            the ID of the user whose password is to be retrieved
 * @param context
 *            the directory context from which to retrieve the user's password
 * @return String
 * @throws NamingException
 */
protected String lookupUserPassword(String userId, DirContext context) throws NamingException {
    String userPassword = null;
    try {
        String userDn = userPattern.format(new String[] { userId });
        Attributes userAttributes = context.getAttributes(userDn, new String[] { userPasswordAttribute });

        userPassword = getAttributeValue(userAttributes, userPasswordAttribute);

    } catch (NameNotFoundException e) {
        // Ignore and return null
    }
    return userPassword;
}

From source file:org.pentaho.di.trans.steps.mailvalidator.MailValidation.java

/**
 * verify if there is a mail server registered to the domain name. and return the email servers count
 *//* w  w  w  .j a v a 2s  .c om*/
public static int mailServersCount(String hostName) throws NamingException {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    DirContext ictx = new InitialDirContext(env);
    Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
    Attribute attr = attrs.get("MX");
    if (attr == null) {
        return (0);
    }
    return (attr.size());
}