Example usage for javax.naming NamingEnumeration hasMoreElements

List of usage examples for javax.naming NamingEnumeration hasMoreElements

Introduction

In this page you can find the example usage for javax.naming NamingEnumeration hasMoreElements.

Prototype

boolean hasMoreElements();

Source Link

Document

Tests if this enumeration contains more elements.

Usage

From source file:org.apache.catalina.util.ExtensionValidator.java

/**
 * Runtime validation of a Web Applicaiton.
 *
 * This method uses JNDI to look up the resources located under a 
 * <code>DirContext</code>. It locates Web Application MANIFEST.MF 
 * file in the /META-INF/ directory of the application and all 
 * MANIFEST.MF files in each JAR file located in the WEB-INF/lib 
 * directory and creates an <code>ArrayList</code> of 
 * <code>ManifestResorce<code> objects. These objects are then passed 
 * to the validateManifestResources method for validation.
 *
 * @param dirContext The JNDI root of the Web Application
 * @param context The context from which the Logger and path to the
 *                application/*from   w w w.  j  a v  a 2 s .  c  om*/
 *
 * @return true if all required extensions satisfied
 */
public static synchronized boolean validateApplication(DirContext dirContext, StandardContext context)
        throws IOException {

    String appName = context.getPath();
    ArrayList appManifestResources = new ArrayList();
    ManifestResource appManifestResource = null;
    // If the application context is null it does not exist and 
    // therefore is not valid
    if (dirContext == null)
        return false;
    // Find the Manifest for the Web Applicaiton
    InputStream inputStream = null;
    try {
        NamingEnumeration wne = dirContext.listBindings("/META-INF/");
        Binding binding = (Binding) wne.nextElement();
        if (binding.getName().toUpperCase().equals("MANIFEST.MF")) {
            Resource resource = (Resource) dirContext.lookup("/META-INF/" + binding.getName());
            inputStream = resource.streamContent();
            Manifest manifest = new Manifest(inputStream);
            inputStream.close();
            inputStream = null;
            ManifestResource mre = new ManifestResource(
                    sm.getString("extensionValidator.web-application-manifest"), manifest,
                    ManifestResource.WAR);
            appManifestResources.add(mre);
        }
    } catch (NamingException nex) {
        // Application does not contain a MANIFEST.MF file
    } catch (NoSuchElementException nse) {
        // Application does not contain a MANIFEST.MF file
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Throwable t) {
                // Ignore
            }
        }
    }

    // Locate the Manifests for all bundled JARs
    NamingEnumeration ne = null;
    try {
        if (dirContext != null) {
            ne = dirContext.listBindings("WEB-INF/lib/");
        }
        while ((ne != null) && ne.hasMoreElements()) {
            Binding binding = (Binding) ne.nextElement();
            if (!binding.getName().toLowerCase().endsWith(".jar")) {
                continue;
            }
            Resource resource = (Resource) dirContext.lookup("/WEB-INF/lib/" + binding.getName());
            Manifest jmanifest = getManifest(resource.streamContent());
            if (jmanifest != null) {
                ManifestResource mre = new ManifestResource(binding.getName(), jmanifest,
                        ManifestResource.APPLICATION);
                appManifestResources.add(mre);
            }
        }
    } catch (NamingException nex) {
        // Jump out of the check for this application because it 
        // has no resources
    }

    return validateManifestResources(appName, appManifestResources);
}

From source file:org.apache.cloudstack.ldap.ADLdapUserManagerImpl.java

@Override
public List<LdapUser> getUsersInGroup(String groupName, LdapContext context) throws NamingException {
    if (StringUtils.isBlank(groupName)) {
        throw new IllegalArgumentException("ldap group name cannot be blank");
    }/*  www .j  a va2 s.c  om*/

    String basedn = _ldapConfiguration.getBaseDn();
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException("ldap basedn is not configured");
    }

    final SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    NamingEnumeration<SearchResult> results = context.search(basedn, generateADGroupSearchFilter(groupName),
            searchControls);
    final List<LdapUser> users = new ArrayList<LdapUser>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result));
    }
    return users;
}

From source file:org.apache.cloudstack.ldap.LdapUserManager.java

public List<LdapUser> getUsersInGroup(String groupName, LdapContext context) throws NamingException {
    String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute();
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(_ldapConfiguration.getScope());
    controls.setReturningAttributes(new String[] { attributeName });

    NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(),
            generateGroupSearchFilter(groupName), controls);

    final List<LdapUser> users = new ArrayList<LdapUser>();
    //Expecting only one result which has all the users
    if (result.hasMoreElements()) {
        Attribute attribute = result.nextElement().getAttributes().get(attributeName);
        NamingEnumeration<?> values = attribute.getAll();

        while (values.hasMoreElements()) {
            String userdn = String.valueOf(values.nextElement());
            try {
                users.add(getUserForDn(userdn, context));
            } catch (NamingException e) {
                s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage());
            }/*w w  w  .jav a  2  s  .  c  om*/
        }
    }

    Collections.sort(users);

    return users;
}

From source file:org.apache.cloudstack.ldap.LdapUserManager.java

private LdapUser getUserForDn(String userdn, LdapContext context) throws NamingException {
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(_ldapConfiguration.getScope());
    controls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    NamingEnumeration<SearchResult> result = context.search(userdn,
            "(objectClass=" + _ldapConfiguration.getUserObject() + ")", controls);
    if (result.hasMoreElements()) {
        return createUser(result.nextElement());
    } else {//ww  w.j  ava  2  s  .co m
        throw new NamingException("No user found for dn " + userdn);
    }
}

From source file:org.apache.cloudstack.ldap.LdapUserManager.java

public List<LdapUser> searchUsers(final String username, final LdapContext context)
        throws NamingException, IOException {

    final SearchControls searchControls = new SearchControls();

    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    String basedn = _ldapConfiguration.getBaseDn();
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException("ldap basedn is not configured");
    }/*w w w .  j  a v a  2 s  .c o  m*/
    byte[] cookie = null;
    int pageSize = _ldapConfiguration.getLdapPageSize();
    context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
    final List<LdapUser> users = new ArrayList<LdapUser>();
    NamingEnumeration<SearchResult> results;
    do {
        results = context.search(basedn, generateSearchFilter(username), searchControls);
        while (results.hasMoreElements()) {
            final SearchResult result = results.nextElement();
            users.add(createUser(result));
        }
        Control[] contextControls = context.getResponseControls();
        if (contextControls != null) {
            for (Control control : contextControls) {
                if (control instanceof PagedResultsResponseControl) {
                    PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                    cookie = prrc.getCookie();
                }
            }
        } else {
            s_logger.info("No controls were sent from the ldap server");
        }
        context.setRequestControls(
                new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
    } while (cookie != null);

    return users;
}

From source file:org.apache.cloudstack.ldap.OpenLdapUserManagerImpl.java

@Override
public List<LdapUser> getUsersInGroup(String groupName, LdapContext context) throws NamingException {
    String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute();
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(_ldapConfiguration.getScope());
    controls.setReturningAttributes(new String[] { attributeName });

    NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(),
            generateGroupSearchFilter(groupName), controls);

    final List<LdapUser> users = new ArrayList<LdapUser>();
    //Expecting only one result which has all the users
    if (result.hasMoreElements()) {
        Attribute attribute = result.nextElement().getAttributes().get(attributeName);
        NamingEnumeration<?> values = attribute.getAll();

        while (values.hasMoreElements()) {
            String userdn = String.valueOf(values.nextElement());
            try {
                users.add(getUserForDn(userdn, context));
            } catch (NamingException e) {
                s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage());
            }/*from   w  w  w  .j  av a2 s . co m*/
        }
    }

    Collections.sort(users);

    return users;
}

From source file:org.apache.cloudstack.ldap.OpenLdapUserManagerImpl.java

public LdapUser searchUser(final String basedn, final String searchString, final LdapContext context)
        throws NamingException, IOException {
    final SearchControls searchControls = new SearchControls();

    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    NamingEnumeration<SearchResult> results = context.search(basedn, searchString, searchControls);
    final List<LdapUser> users = new ArrayList<LdapUser>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result));//from ww w.j ava  2s  . c  om
    }

    if (users.size() == 1) {
        return users.get(0);
    } else {
        throw new NamingException("No user found for basedn " + basedn + " and searchString " + searchString);
    }
}

From source file:org.apache.cloudstack.ldap.OpenLdapUserManagerImpl.java

@Override
public List<LdapUser> searchUsers(final String username, final LdapContext context)
        throws NamingException, IOException {

    final SearchControls searchControls = new SearchControls();

    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    String basedn = _ldapConfiguration.getBaseDn();
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException("ldap basedn is not configured");
    }//from www  .  j  ava  2 s . c om
    byte[] cookie = null;
    int pageSize = _ldapConfiguration.getLdapPageSize();
    context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
    final List<LdapUser> users = new ArrayList<LdapUser>();
    NamingEnumeration<SearchResult> results;
    do {
        results = context.search(basedn, generateSearchFilter(username), searchControls);
        while (results.hasMoreElements()) {
            final SearchResult result = results.nextElement();
            if (!isUserDisabled(result)) {
                users.add(createUser(result));
            }
        }
        Control[] contextControls = context.getResponseControls();
        if (contextControls != null) {
            for (Control control : contextControls) {
                if (control instanceof PagedResultsResponseControl) {
                    PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                    cookie = prrc.getCookie();
                }
            }
        } else {
            s_logger.info("No controls were sent from the ldap server");
        }
        context.setRequestControls(
                new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
    } while (cookie != null);

    return users;
}

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 w  w.  j  a v  a  2s .  c om
    }

    // 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.hadoop.security.LdapGroupsMapping.java

List<String> doGetGroups(String user) throws NamingException {
    List<String> groups = new ArrayList<String>();

    DirContext ctx = getDirContext();

    // Search for the user. We'll only ever need to look at the first result
    NamingEnumeration<SearchResult> results = ctx.search(baseDN, userSearchFilter, new Object[] { user },
            SEARCH_CONTROLS);/* w  ww . j  a va  2s .  co m*/
    if (results.hasMoreElements()) {
        SearchResult result = results.nextElement();
        String userDn = result.getNameInNamespace();

        NamingEnumeration<SearchResult> groupResults = null;

        if (isPosix) {
            String gidNumber = null;
            String uidNumber = null;
            Attribute gidAttribute = result.getAttributes().get(posixGidAttr);
            Attribute uidAttribute = result.getAttributes().get(posixUidAttr);
            if (gidAttribute != null) {
                gidNumber = gidAttribute.get().toString();
            }
            if (uidAttribute != null) {
                uidNumber = uidAttribute.get().toString();
            }
            if (uidNumber != null && gidNumber != null) {
                groupResults = ctx.search(
                        baseDN, "(&" + groupSearchFilter + "(|(" + posixGidAttr + "={0})" + "("
                                + groupMemberAttr + "={1})))",
                        new Object[] { gidNumber, uidNumber }, SEARCH_CONTROLS);
            }
        } else {
            groupResults = ctx.search(baseDN, "(&" + groupSearchFilter + "(" + groupMemberAttr + "={0}))",
                    new Object[] { userDn }, SEARCH_CONTROLS);
        }
        if (groupResults != null) {
            while (groupResults.hasMoreElements()) {
                SearchResult groupResult = groupResults.nextElement();
                Attribute groupName = groupResult.getAttributes().get(groupNameAttr);
                groups.add(groupName.get().toString());
            }
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("doGetGroups(" + user + ") return " + groups);
    }
    return groups;
}