Example usage for javax.naming.directory Attributes getAll

List of usage examples for javax.naming.directory Attributes getAll

Introduction

In this page you can find the example usage for javax.naming.directory Attributes getAll.

Prototype

NamingEnumeration<? extends Attribute> getAll();

Source Link

Document

Retrieves an enumeration of the attributes in the attribute set.

Usage

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

protected XmlBuilder attributesToXml(Attributes atts) throws NamingException {
    XmlBuilder attributesElem = new XmlBuilder("attributes");

    NamingEnumeration all = atts.getAll();
    while (all.hasMore()) {
        Attribute attribute = (Attribute) all.next();
        XmlBuilder attributeElem = new XmlBuilder("attribute");
        attributeElem.addAttribute("name", attribute.getID());
        if (attribute.size() == 1 && attribute.get() != null) {
            attributeElem.addAttribute("value", attribute.get().toString());
        } else {/*from ww  w  . j av  a2s  . c  o m*/
            NamingEnumeration values = attribute.getAll();
            while (values.hasMore()) {
                Object value = values.next();
                XmlBuilder itemElem = new XmlBuilder("item");
                itemElem.addAttribute("value", value.toString());
                attributeElem.addSubElement(itemElem);
            }
        }
        attributesElem.addSubElement(attributeElem);
    }
    return attributesElem;
}

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 a  2 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.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java

private void execute() throws Exception {
    // Connecting to server and retreiving entries
    NamingEnumeration entries = connectToServerAndGetEntries();

    // Creating destination file
    File destionationFile = new File(ldifFileName);

    // Deleting the destination file if it already exists
    if (destionationFile.exists()) {
        destionationFile.delete();/*from w  ww  . j a va  2 s .co  m*/
    }

    // Creating the writer to generate the LDIF file
    FileWriter fw = new FileWriter(ldifFileName, true);

    BufferedWriter writer = new BufferedWriter(fw);
    OtcLdifComposerImpl composer = new OtcLdifComposerImpl();
    MultiValueMap map = new MultiValueMap();
    //      MultiMap map = new MultiMap() {
    //         // FIXME Stop forking commons-collections.
    //         private final MultiValueMap map = new MultiValueMap();
    //
    //         public Object remove(Object arg0, Object arg1) {
    //            return map.remove(arg0, arg1);
    //         }
    //
    //         public int size() {
    //            return map.size();
    //         }
    //
    //         public Object get(Object arg0) {
    //            return map.get(arg0);
    //         }
    //
    //         public boolean containsValue(Object arg0) {
    //            return map.containsValue(arg0);
    //         }
    //
    //         public Object put(Object arg0, Object arg1) {
    //            return map.put(arg0, arg1);
    //         }
    //
    //         public Object remove(Object arg0) {
    //            return map.remove(arg0);
    //         }
    //
    //         public Collection values() {
    //            return map.values();
    //         }
    //
    //         public boolean isEmpty() {
    //            return map.isEmpty();
    //         }
    //
    //         public boolean containsKey(Object key) {
    //            return map.containsKey(key);
    //         }
    //
    //         public void putAll(Map arg0) {
    //            map.putAll(arg0);
    //         }
    //
    //         public void clear() {
    //            map.clear();
    //         }
    //
    //         public Set keySet() {
    //            return map.keySet();
    //         }
    //
    //         public Set entrySet() {
    //            return map.entrySet();
    //         }
    //      };

    int entriesCounter = 1;
    long t0 = System.currentTimeMillis();

    while (entries.hasMoreElements()) {
        SearchResult sr = (SearchResult) entries.nextElement();
        Attributes attributes = sr.getAttributes();
        NamingEnumeration attributesEnumeration = attributes.getAll();

        map.clear();

        while (attributesEnumeration.hasMoreElements()) {
            Attribute attr = (Attribute) attributesEnumeration.nextElement();
            NamingEnumeration e2 = null;

            e2 = attr.getAll();

            while (e2.hasMoreElements()) {
                Object value = e2.nextElement();
                map.put(attr.getID(), value);
            }
        }

        // Writing entry in the file
        writer.write("dn: " + sr.getNameInNamespace() + "\n");
        writer.write(composer.compose(map) + "\n");

        notifyEntryWrittenListener(sr.getNameInNamespace());
        entriesCounter++;

        if (entriesCounter % 10 == 0) {
            notifyOutputListener(new Character('.'));
        }

        if (entriesCounter % 500 == 0) {
            notifyOutputListener("" + entriesCounter);
        }
    }

    writer.flush();
    writer.close();
    fw.close();

    long t1 = System.currentTimeMillis();

    notifyOutputListener("Done!");
    notifyOutputListener(entriesCounter + " entries exported in " + ((t1 - t0) / 1000) + " seconds");
}

From source file:org.apache.directory.studio.connection.core.io.jndi.LdifSearchLogger.java

/**
 * {@inheritDoc}/*from w  w  w. j  a v a2  s.  co  m*/
 */
public void logSearchResultEntry(Connection connection, StudioSearchResult studioSearchResult, long requestNum,
        NamingException ex) {
    if (!isSearchResultEntryLogEnabled()) {
        return;
    }

    try {
        String formattedString;
        if (studioSearchResult != null) {
            String dn = studioSearchResult.getNameInNamespace();
            Attributes attributes = studioSearchResult.getAttributes();

            LdifContentRecord record = new LdifContentRecord(LdifDnLine.create(dn));
            NamingEnumeration<? extends Attribute> attributeEnumeration = attributes.getAll();
            while (attributeEnumeration.hasMore()) {
                Attribute attribute = attributeEnumeration.next();
                String attributeName = attribute.getID();
                NamingEnumeration<?> valueEnumeration = attribute.getAll();
                while (valueEnumeration.hasMore()) {
                    Object o = valueEnumeration.next();
                    if (o instanceof String) {
                        record.addAttrVal(LdifAttrValLine.create(attributeName, (String) o));
                    }
                    if (o instanceof byte[]) {
                        record.addAttrVal(LdifAttrValLine.create(attributeName, (byte[]) o));
                    }
                }
            }
            record.finish(LdifSepLine.create());
            formattedString = record.toFormattedString(LdifFormatParameters.DEFAULT);
        } else {
            formattedString = LdifFormatParameters.DEFAULT.getLineSeparator();
        }

        log(formattedString, "SEARCH RESULT ENTRY (" + requestNum + ")", ex, connection); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (NamingException e) {
    }
}

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  .  jav  a  2s. c  om*/
 * @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.hadoop.hdfsproxy.LdapIpDirFilter.java

/**
 * check if client's ip is listed in the Ldap Roles if yes, return true and
 * update ldapent. if not, return false/*from  w w  w . j a  v a  2s . co m*/
 * */
@SuppressWarnings("unchecked")
private boolean getLdapRoleEntryFromUserIp(String userIp, LdapRoleEntry ldapent) throws NamingException {
    String ipMember = hdfsIpSchemaStrPrefix + userIp;
    Attributes matchAttrs = new BasicAttributes(true);
    matchAttrs.put(new BasicAttribute(hdfsIpSchemaStr, ipMember));
    matchAttrs.put(new BasicAttribute(hdfsUidSchemaStr));
    matchAttrs.put(new BasicAttribute(hdfsPathSchemaStr));

    String[] attrIDs = { hdfsUidSchemaStr, hdfsPathSchemaStr };

    NamingEnumeration<SearchResult> results = lctx.search(baseName, matchAttrs, attrIDs);
    if (results.hasMore()) {
        String userId = null;
        ArrayList<Path> paths = new ArrayList<Path>();
        SearchResult sr = results.next();
        Attributes attrs = sr.getAttributes();
        for (NamingEnumeration ne = attrs.getAll(); ne.hasMore();) {
            Attribute attr = (Attribute) ne.next();
            if (hdfsUidSchemaStr.equalsIgnoreCase(attr.getID())) {
                userId = (String) attr.get();
            } else if (hdfsPathSchemaStr.equalsIgnoreCase(attr.getID())) {
                for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
                    String pathStr = (String) e.next();
                    paths.add(new Path(pathStr));
                }
            }
        }
        ldapent.init(userId, paths);
        if (LOG.isDebugEnabled())
            LOG.debug(ldapent);
        return true;
    }
    LOG.info("Ip address " + userIp + " is not authorized to access the proxy server");
    return false;
}

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

private void writeSearchResult(final SearchResult sr, final XMLBuffer xmlb) throws NamingException {
    final Attributes attrs = sr.getAttributes();
    final int size = attrs.size();
    final ArrayList<Attribute> sortedAttrs = new ArrayList<>(size);

    xmlb.openTag("searchresult"); // $NON-NLS-1$
    xmlb.tag("dn", sr.getName()); // $NON-NLS-1$
    xmlb.tag("returnedattr", Integer.toString(size)); // $NON-NLS-1$
    xmlb.openTag("attributes"); // $NON-NLS-1$

    try {//from w w  w.j  av  a2  s. c o  m
        for (NamingEnumeration<? extends Attribute> en = attrs.getAll(); en.hasMore();) {
            final Attribute attr = en.next();
            sortedAttrs.add(attr);
        }
        sortAttributes(sortedAttrs);
        for (final Attribute attr : sortedAttrs) {
            StringBuilder sb = new StringBuilder();
            if (attr.size() == 1) {
                sb.append(getWriteValue(attr.get()));
            } else {
                final ArrayList<String> sortedVals = new ArrayList<>(attr.size());
                boolean first = true;

                for (NamingEnumeration<?> ven = attr.getAll(); ven.hasMore();) {
                    final Object value = getWriteValue(ven.next());
                    sortedVals.add(value.toString());
                }

                Collections.sort(sortedVals);

                for (final String value : sortedVals) {
                    if (first) {
                        first = false;
                    } else {
                        sb.append(", "); // $NON-NLS-1$
                    }
                    sb.append(value);
                }
            }
            xmlb.tag(attr.getID(), sb);
        }
    } finally {
        xmlb.closeTag("attributes"); // $NON-NLS-1$
        xmlb.closeTag("searchresult"); // $NON-NLS-1$
    }
}

From source file:org.apache.zeppelin.realm.ActiveDirectoryGroupRealm.java

public List<String> searchForUserName(String containString, LdapContext ldapContext) throws NamingException {
    List<String> userNameList = new ArrayList<>();

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

    String searchFilter = "(&(objectClass=*)(userPrincipalName=*" + containString + "*))";
    Object[] searchArguments = new Object[] { containString };

    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);

    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        if (log.isDebugEnabled()) {
            log.debug("Retrieving userprincipalname names for user [" + sr.getName() + "]");
        }//from  w  ww  .  j a  v  a2  s .  c o  m

        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            NamingEnumeration ae = attrs.getAll();
            while (ae.hasMore()) {
                Attribute attr = (Attribute) ae.next();
                if (attr.getID().toLowerCase().equals("cn")) {
                    userNameList.addAll(LdapUtils.getAllAttributeValues(attr));
                }
            }
        }
    }
    return userNameList;
}

From source file:org.apache.zeppelin.realm.ActiveDirectoryGroupRealm.java

private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
    Set<String> roleNames = new LinkedHashSet<>();

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String userPrincipalName = username;
    if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) {
        userPrincipalName += principalSuffix;
    }/*from  w w  w . ja va  2s  . co m*/

    String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";
    Object[] searchArguments = new Object[] { userPrincipalName };

    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);

    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        if (log.isDebugEnabled()) {
            log.debug("Retrieving group names for user [" + sr.getName() + "]");
        }

        Attributes attrs = sr.getAttributes();

        if (attrs != null) {
            NamingEnumeration ae = attrs.getAll();
            while (ae.hasMore()) {
                Attribute attr = (Attribute) ae.next();

                if (attr.getID().equals("memberOf")) {

                    Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);

                    if (log.isDebugEnabled()) {
                        log.debug("Groups found for user [" + username + "]: " + groupNames);
                    }

                    Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
                    roleNames.addAll(rolesForGroups);
                }
            }
        }
    }
    return roleNames;
}

From source file:org.apache.zeppelin.server.ActiveDirectoryGroupRealm.java

private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
    Set<String> roleNames = new LinkedHashSet<>();

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String userPrincipalName = username;
    if (principalSuffix != null) {
        userPrincipalName += principalSuffix;
    }//  www.  j a  v a  2 s .  c  o  m

    String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";
    Object[] searchArguments = new Object[] { userPrincipalName };

    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);

    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        if (log.isDebugEnabled()) {
            log.debug("Retrieving group names for user [" + sr.getName() + "]");
        }

        Attributes attrs = sr.getAttributes();

        if (attrs != null) {
            NamingEnumeration ae = attrs.getAll();
            while (ae.hasMore()) {
                Attribute attr = (Attribute) ae.next();

                if (attr.getID().equals("memberOf")) {

                    Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);

                    if (log.isDebugEnabled()) {
                        log.debug("Groups found for user [" + username + "]: " + groupNames);
                    }

                    Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
                    roleNames.addAll(rolesForGroups);
                }
            }
        }
    }
    return roleNames;
}