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:com.maxmind.geoip.LookupService.java

String getDnsAttributes(String ip) {
    try {/*from w  w  w .j ava 2  s.  c o  m*/
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        // TODO don't specify ws1, instead use ns servers for s.maxmind.com
        env.put("java.naming.provider.url", "dns://ws1.maxmind.com/");

        DirContext ictx = new InitialDirContext(env);
        Attributes attrs = ictx.getAttributes(licenseKey + "." + ip + ".s.maxmind.com", new String[] { "txt" });
        //System.out.println(attrs.get("txt").get());
        String str = attrs.get("txt").get().toString();
        return str;
    } catch (NamingException e) {
        // TODO fix this to handle exceptions
        System.out.println("DNS error");
        return null;
    }

}

From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java

/**
 * Performs recursive group membership lookup.
 *
 * This was how we did the lookup traditionally until we discovered 1.2.840.113556.1.4.1941.
 * But various people reported that it slows down the execution tremendously to the point that it is unusable,
 * while others seem to report that it runs faster than recursive search (http://social.technet.microsoft.com/Forums/fr-FR/f238d2b0-a1d7-48e8-8a60-542e7ccfa2e8/recursive-retrieval-of-all-ad-group-memberships-of-a-user?forum=ITCG)
 *
 * This implementation is kept for Windows 2003 that doesn't support 1.2.840.113556.1.4.1941, but it can be also
 * enabled for those who are seeing the performance problem.
 *
 * See JENKINS-22830/*from  w w w. jav  a  2 s.  com*/
 */
private void recursiveGroupLookup(DirContext context, Attributes id, Set<GrantedAuthority> groups)
        throws NamingException {
    Stack<Attributes> q = new Stack<Attributes>();
    q.push(id);
    while (!q.isEmpty()) {
        Attributes identity = q.pop();
        LOGGER.finer("Looking up group of " + identity);

        Attribute memberOf = identity.get("memberOf");
        if (memberOf == null)
            continue;

        for (int i = 0; i < memberOf.size(); i++) {
            try {
                LOGGER.log(Level.FINE, "Trying to get the CN of {0}", memberOf.get(i));
                Attributes group = context.getAttributes(new LdapName(memberOf.get(i).toString()),
                        new String[] { "CN", "memberOf" });
                Attribute cn = group.get("CN");
                if (cn == null) {
                    LOGGER.fine("Failed to obtain CN of " + memberOf.get(i));
                    continue;
                }
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine(cn.get() + " is a member of " + memberOf.get(i));

                if (groups.add(new GrantedAuthorityImpl(cn.get().toString()))) {
                    q.add(group); // recursively look for groups that this group is a member of.
                }
            } catch (NameNotFoundException e) {
                LOGGER.fine("Failed to obtain CN of " + memberOf.get(i));
            }
        }
    }
}

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

private String performOperationRead(String entryName, ParameterResolutionContext prc, Map paramValueMap)
        throws SenderException, ParameterException {
    DirContext dirContext = null;
    try {//  w  w w .ja  v  a  2 s . co m
        dirContext = getDirContext(paramValueMap);
        return attributesToXml(dirContext.getAttributes(entryName, getAttributesReturnedParameter())).toXML();
    } catch (NamingException e) {
        // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
        //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
        // Sun:
        //   [LDAP: error code 32 - No Such Object...
        if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
            if (log.isDebugEnabled())
                log.debug("Operation [" + getOperation() + "] found nothing - no such entryName: " + entryName);
            return DEFAULT_RESULT_READ;
        } else {
            storeLdapException(e, prc);
            throw new SenderException(
                    "Exception in operation [" + getOperation() + "] entryName=[" + entryName + "]", e);
        }
    } finally {
        closeDirContext(dirContext);
    }
}

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

private String performOperationChallenge(String principal, ParameterResolutionContext prc, Map paramValueMap)
        throws SenderException, ParameterException {
    DirContext dirContext = null;
    try {//from ww w  . j  av  a 2 s. c  o m
        // Use loopkupDirContext instead of getDirContext to prevent
        // NamingException (with error code 49) being converted to
        // SenderException.
        dirContext = loopkupDirContext(paramValueMap);
        attributesToXml(dirContext.getAttributes(principal, getAttributesReturnedParameter())).toXML();
        return DEFAULT_RESULT_CHALLENGE_OK;
    } catch (NamingException e) {
        // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
        //   49 LDAP_INVALID_CREDENTIALS Indicates that during a bind operation one of the following occurred: The client passed either an incorrect DN or password, or the password is incorrect because it has expired, intruder detection has locked the account, or another similar reason. This is equivalent to AD error code 52e.
        if (e.getMessage().startsWith("[LDAP: error code 49 - ")) {
            if (log.isDebugEnabled())
                log.debug("Operation [" + getOperation() + "] invalid credentials for: " + principal);
            return DEFAULT_RESULT_CHALLENGE_NOK;
        } else {
            storeLdapException(e, prc);
            throw new SenderException(
                    "Exception in operation [" + getOperation() + "] principal=[" + principal + "]", e);
        }
    } finally {
        closeDirContext(dirContext);
    }
}

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

/** 
 * Return xml element containing all of the subcontexts of the parent context with their attributes. 
 * @return tree xml./*from   w ww.  java2 s .  c om*/
 */
private XmlBuilder getTree(DirContext parentContext, String context, ParameterResolutionContext prc,
        Map paramValueMap) {
    XmlBuilder contextElem = new XmlBuilder("context");
    contextElem.addAttribute("name", context);

    String[] subCtxList = getSubContextList(parentContext, context, prc);
    try {
        if (subCtxList.length == 0) {
            XmlBuilder attrs = attributesToXml(
                    parentContext.getAttributes(context, getAttributesReturnedParameter()));
            contextElem.addSubElement(attrs);
        } else {
            for (int i = 0; i < subCtxList.length; i++) {
                contextElem.addSubElement(
                        getTree((DirContext) parentContext.lookup(context), subCtxList[i], prc, paramValueMap));
            }
            contextElem.addSubElement(
                    attributesToXml(parentContext.getAttributes(context, getAttributesReturnedParameter())));
        }

    } catch (NamingException e) {
        storeLdapException(e, prc);
        log.error("Exception in operation [" + getOperation() + "]: ", e);
    }

    return contextElem;
}

From source file:org.apache.directory.server.jndi.ServerContextFactory.java

private Attributes getLdifFileEntry(DirContext root, File ldif) {
    try {//from  w  ww  .j av  a  2  s  . c o  m
        return root.getAttributes(buildProtectedFileEntry(ldif), new String[] { "createTimestamp" });
    } catch (NamingException e) {
        return null;
    }
}

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

/**
 * Tests to make sure the server properly returns the supportedSASLMechanisms.
 *//*ww w .j av  a2  s  .co m*/
@Test
public void testSupportedSASLMechanisms() throws Exception {
    // We have to tell the server that it should accept anonymous
    // auth, because we are reading the rootDSE
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Point on rootDSE
    DirContext context = new InitialDirContext();

    Attributes attrs = context.getAttributes(Network.ldapLoopbackUrl(getLdapServer().getPort()),
            new String[] { "supportedSASLMechanisms" });

    //             Thread.sleep( 10 * 60 * 1000 );
    NamingEnumeration<? extends Attribute> answer = attrs.getAll();
    Attribute result = answer.next();
    assertEquals(6, result.size());
    assertTrue(result.contains(SupportedSaslMechanisms.GSSAPI));
    assertTrue(result.contains(SupportedSaslMechanisms.DIGEST_MD5));
    assertTrue(result.contains(SupportedSaslMechanisms.CRAM_MD5));
    assertTrue(result.contains(SupportedSaslMechanisms.NTLM));
    assertTrue(result.contains(SupportedSaslMechanisms.PLAIN));
    assertTrue(result.contains(SupportedSaslMechanisms.GSS_SPNEGO));
}

From source file:org.apache.geode.internal.net.SocketCreator.java

/**
 * This method uses JNDI to look up an address in DNS and return its name
 * /*  w  ww .  j  a va2  s . co m*/
 * @param addr
 *
 * @return the host name associated with the address or null if lookup isn't possible or there is
 *         no host name for this address
 */
public static String reverseDNS(InetAddress addr) {
    byte[] addrBytes = addr.getAddress();
    // reverse the address suitable for reverse lookup
    String lookup = "";
    for (int index = addrBytes.length - 1; index >= 0; index--) {
        lookup = lookup + (addrBytes[index] & 0xff) + '.';
    }
    lookup += "in-addr.arpa";
    // System.out.println("Looking up: " + lookup);

    try {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        DirContext ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(lookup, new String[] { "PTR" });
        for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements();) {
            Attribute attr = (Attribute) ae.next();
            for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) {
                Object elem = vals.nextElement();
                if ("PTR".equals(attr.getID()) && elem != null) {
                    return elem.toString();
                }
            }
        }
        ctx.close();
    } catch (Exception e) {
        // ignored
    }
    return null;
}

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

protected void bindUser(DirContext context, String dn) throws NamingException, FailedLoginException {

    context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
    try {/*  ww w.  j a va 2 s.c o m*/
        context.getAttributes("", null);
    } catch (AuthenticationException e) {
        log.debug("Authentication failed for dn=" + dn);
        throw new FailedLoginException();
    } finally {

        if (connectionUsername != null) {
            context.addToEnvironment(Context.SECURITY_PRINCIPAL, connectionUsername);
        } else {
            context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
        }

        if (connectionPassword != null) {
            context.addToEnvironment(Context.SECURITY_CREDENTIALS, connectionPassword);
        } else {
            context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
        }
    }
}