Example usage for com.google.common.collect Iterators forEnumeration

List of usage examples for com.google.common.collect Iterators forEnumeration

Introduction

In this page you can find the example usage for com.google.common.collect Iterators forEnumeration.

Prototype

public static <T> UnmodifiableIterator<T> forEnumeration(final Enumeration<T> enumeration) 

Source Link

Document

Adapts an Enumeration to the Iterator interface.

Usage

From source file:org.diqube.tool.transpose.TransposeImplementation.java

private LoaderColumnInfo loadColInfo(File colInfoFile) throws RuntimeException {
    Properties prop = new Properties();
    try (InputStream is = new FileInputStream(colInfoFile)) {
        prop.load(new InputStreamReader(is, Charset.forName("UTF-8")));

        logger.info("Loading column type info from '{}'", colInfoFile.getAbsolutePath());

        Map<String, ColumnType> colTypes = new HashMap<>();
        ColumnType defaultColType = ColumnType.LONG;

        Iterator<Object> it = Iterators.forEnumeration(prop.keys());
        while (it.hasNext()) {
            String colName = (String) it.next();
            if ("*".equals(colName))
                defaultColType = resolveColumnType(prop.getProperty(colName));
            else/*from  www .  ja  va  2 s  .co m*/
                colTypes.put(colName, resolveColumnType(prop.getProperty(colName)));
        }

        LoaderColumnInfo res = new LoaderColumnInfo(defaultColType);
        for (Entry<String, ColumnType> e : colTypes.entrySet())
            res.registerColumnType(e.getKey(), e.getValue());

        logger.info("Using column information with default column type '{}' and specific column types: {}",
                defaultColType, colTypes);

        return res;
    } catch (IOException e) {
        throw new RuntimeException("Could not read Column Info file", e);
    }
}

From source file:net.sourceforge.ganttproject.ResourceTreeTableModel.java

public ResourceNode getNodeForResource(final HumanResource hr) {
    try {/*from   w w  w  .ja v  a  2  s.  c  o  m*/
        return (ResourceNode) Iterators.find(Iterators.forEnumeration(root.children()),
                new Predicate<MutableTreeTableNode>() {
                    @Override
                    public boolean apply(MutableTreeTableNode input) {
                        return input.getUserObject().equals(hr);
                    }
                });
    } catch (NoSuchElementException e) {
        return null;
    }
}

From source file:com.b2international.snowowl.identity.ldap.LdapIdentityProvider.java

private String findUserDN(final DirContext context, final String username) {
    Preconditions.checkNotNull(context, "Directory context is null.");
    Preconditions.checkNotNull(username, "Username is null.");

    final String userFilterWithUsername = USER_FILTER.replaceAll(UID_PLACEHOLDER, conf.getUserIdProperty())
            .replaceAll(USER_NAME_PLACEHOLDER, username);

    NamingEnumeration<SearchResult> searchResultEnumeration = null;

    try {//from  ww  w.  j  a  va2s  . c o  m
        searchResultEnumeration = context.search(conf.getBaseDn(), userFilterWithUsername,
                createSearchControls(1));
        final List<SearchResult> searchResults = ImmutableList
                .copyOf(Iterators.forEnumeration(searchResultEnumeration));

        if (searchResults.size() != 1) {
            return null;
        }

        final SearchResult searchResult = Iterables.getOnlyElement(searchResults);
        return searchResult.getNameInNamespace();
    } catch (final NamingException e) {
        return null;
    } finally {
        closeNamingEnumeration(searchResultEnumeration);
    }
}

From source file:com.sector91.wit.server.watchers.AppFolderWatcher.java

Iterable<WebApp> loadWebAppsFromJar(Path pathToJar, ClassLoader parentClassLoader) {
    try {//from   www . j a  v a2s.  c  om
        Log.info(TAG, "Loading WebApps from JAR file " + pathToJar);
        final URL jarUrl = pathToJar.toUri().toURL();
        final ClassLoader jarClassLoader = new URLClassLoader(new URL[] { jarUrl }, parentClassLoader);

        // FIXME: The classloader will also search its parent(s) when searching
        // for ServiceLoaders and app.* scripts. If any of these files exist in
        // library JARs, this may throw off the entire app-loading system. Some
        // method to check for this should be implemented.

        // Step 1: Look for WebApps exposed via the ServiceLoader API.
        Log.trace(TAG, "Checking for ServiceLoader configuration...");
        ServiceLoader<WebApp> loader = ServiceLoader.load(WebApp.class, jarClassLoader);
        try {
            final Iterator<WebApp> iterator = loader.iterator();
            if (iterator.hasNext()) {
                Log.debug(TAG, "Found ServiceLoader configuration!");
                final List<WebApp> list = new ArrayList<>();
                while (iterator.hasNext())
                    list.add(iterator.next());
                return list;
            }
        } catch (ServiceConfigurationError err) {
            Log.error(TAG, "Error in ServiceLoader configuration of JAR file " + pathToJar, err);
            return Collections.emptyList();
        }
        Log.debug(TAG, "No ServiceLoader configuration present.");

        // Step 2: Look for an app.* script that can be loaded via JSR-223.
        Log.trace(TAG, "Checking for app.* script...");
        for (Map.Entry<String, ScriptEngineFactory> entry : Scripting.scriptEngines(jarClassLoader)
                .entrySet()) {
            final String filename = "app." + entry.getKey();
            Log.trace(TAG, "Checking for " + filename + "...");
            final Enumeration<URL> resources = jarClassLoader.getResources(filename);
            if (resources.hasMoreElements()) {
                Log.debug(TAG, "Found app script file: " + filename);
                final URL scriptUrl = Iterators.getLast(Iterators.forEnumeration(resources));
                final ScriptEngine engine = entry.getValue().getScriptEngine();
                final Object result;
                try (final Reader reader = new InputStreamReader(scriptUrl.openStream())) {
                    result = engine.eval(reader);
                } catch (Exception ex) {
                    Log.error(TAG, "Could not load WebApp(s) from JAR file '" + pathToJar
                            + "'. Error occurred in script '" + filename + "'.", ex);
                    return Collections.emptyList();
                }
                if (result instanceof WebApp) {
                    return Collections.singletonList((WebApp) result);
                } else if (result instanceof Iterable) {
                    final List<WebApp> apps = new ArrayList<>();
                    for (Object obj : (Iterable<?>) result) {
                        if (obj instanceof WebApp) {
                            apps.add((WebApp) result);
                        } else {
                            Log.error(TAG,
                                    "Could not load WebApp(s) from JAR file '" + pathToJar + "'. Script '"
                                            + filename + "' returned an Iterable containing an object of"
                                            + " type " + obj.getClass() + " that does not implement WebApp.");
                            return Collections.emptyList();
                        }
                    }
                } else {
                    if (result == null)
                        Log.error(TAG, "Could not load WebApp(s) from JAR file '" + pathToJar + "'. Script '"
                                + filename + "' returned null.");
                    else
                        Log.error(TAG,
                                "Could not load WebApp(s) from JAR file '" + pathToJar + "'. Script '"
                                        + filename + "' returned an object of type " + result.getClass()
                                        + " that does not implement WebApp.");
                    return Collections.emptyList();
                }
            }
        }
        Log.debug(TAG, "No supported app.* script present.");

        // Step 3: All options have been exhausted. Give up and display an error.
        Log.error(TAG, "Could not load WebApp(s) from JAR file '" + pathToJar
                + "'. Did not file any ServiceLoader configuration or supported app.* scripts.");
        for (String ext : Scripting.HINT_EXTENSIONS) {
            if (jarClassLoader.getResources("app." + ext).hasMoreElements()) {
                Log.warn(TAG, "A file named 'app." + ext + "' exists, but could not be loaded. "
                        + Scripting.scriptHintMessage(ext, jarClassLoader));
                break;
            }
        }
        return Collections.emptyList();

    } catch (IOException | RuntimeException ex) {
        Log.error(TAG, "Failed to load JAR file " + pathToJar, ex);
        return Collections.emptyList();
    }
}

From source file:com.google.devtools.build.android.dexer.DexFileMerger.java

private static void processClassAndDexFiles(ZipFile zip, DexFileAggregator out, MergingDexer dexer,
        Predicate<ZipEntry> extraFilter) throws IOException {
    @SuppressWarnings("unchecked") // Predicates.and uses varargs parameter with generics
    ArrayList<? extends ZipEntry> filesToProcess = Lists
            .newArrayList(Iterators.filter(Iterators.forEnumeration(zip.entries()),
                    Predicates.and(Predicates.not(ZipEntryPredicates.isDirectory()),
                            ZipEntryPredicates.suffixes(".class", ".dex"), extraFilter)));
    Collections.sort(filesToProcess, ZipEntryComparator.LIKE_DX);
    for (ZipEntry entry : filesToProcess) {
        String filename = entry.getName();
        try (InputStream content = zip.getInputStream(entry)) {
            if (filename.endsWith(".dex")) {
                // We don't want to use the Dex(InputStream) constructor because it closes the stream,
                // which will break the for loop, and it has its own bespoke way of reading the file into
                // a byte buffer before effectively calling Dex(byte[]) anyway.
                out.add(new Dex(ByteStreams.toByteArray(content)));
            } else if (filename.endsWith(".class")) {
                dexer.add(Dexing.parseClassFile(ByteStreams.toByteArray(content), filename));
            } else {
                throw new IllegalStateException("Shouldn't get here: " + filename);
            }/* ww w  .  ja v a  2s . c  o m*/
        }
    }
}

From source file:com.github.mike10004.jenkinsbbhook.WebhookHandler.java

protected AppParams loadAppParams() {
    log.log(Level.FINER, "loading app params; defined: {0}",
            Iterators.toString(Iterators.forEnumeration(context.getInitParameterNames())));
    return new ContextAppParams(new ServletInitParamValueProvider(context));
}

From source file:com.b2international.snowowl.identity.ldap.LdapIdentityProvider.java

@Override
public Promise<Users> searchUsers(Collection<String> usernames, int limit) {
    final ImmutableList.Builder<User> resultBuilder = ImmutableList.builder();

    final String baseDn = conf.getBaseDn();
    final String uidProp = conf.getUserIdProperty();

    InitialLdapContext context = null;
    NamingEnumeration<SearchResult> searchResultEnumeration = null;

    try {//w w  w  . j  av a  2s. c o  m
        context = createLdapContext();
        Collection<LdapRole> ldapRoles = getAllLdapRoles(context, baseDn);

        searchResultEnumeration = context.search(baseDn, ALL_USER_QUERY,
                createSearchControls(ATTRIBUTE_DN, uidProp));
        for (final SearchResult searchResult : ImmutableList
                .copyOf(Iterators.forEnumeration(searchResultEnumeration))) {
            final Attributes attributes = searchResult.getAttributes();

            if (hasAttribute(attributes, uidProp)) {
                final String userName = (String) attributes.get(uidProp).get();
                final List<Role> userRoles = ldapRoles.stream()
                        .filter(role -> role.getUniqueMembers().contains(searchResult.getNameInNamespace()))
                        .map(role -> new Role(role.getName(), role.getPermissions()))
                        .collect(Collectors.toList());

                resultBuilder.add(new User(userName, userRoles));
            }
        }

        final List<User> users = resultBuilder.build().stream()
                .sorted((u1, u2) -> u1.getUsername().compareTo(u2.getUsername()))
                .filter(user -> usernames.isEmpty() || usernames.contains(user.getUsername())).limit(limit)
                .collect(Collectors.toList());
        return Promise.immediate(new Users(users, limit, users.size()));

    } catch (final NamingException e) {
        throw new SnowowlRuntimeException(e);
    } finally {
        closeNamingEnumeration(searchResultEnumeration);
        closeLdapContext(context);
    }
}

From source file:org.killbill.billing.util.security.shiro.realm.KillBillJndiLdapRealm.java

private String extractGroupNameFromSearchResult(final SearchResult searchResult) {
    // Get all attributes for that group
    final Iterator<? extends Attribute> attributesIterator = Iterators
            .forEnumeration(searchResult.getAttributes().getAll());

    // Find the attribute representing the group name
    final Iterator<? extends Attribute> groupNameAttributesIterator = Iterators.filter(attributesIterator,
            new Predicate<Attribute>() {
                @Override/*  w ww .  j ava 2s .com*/
                public boolean apply(final Attribute attribute) {
                    return groupNameId.equalsIgnoreCase(attribute.getID());
                }
            });

    // Extract the group name from the attribute
    // Note: at this point, groupNameAttributesIterator should really contain a single element
    final Iterator<String> groupNamesIterator = Iterators.transform(groupNameAttributesIterator,
            new Function<Attribute, String>() {
                @Override
                public String apply(final Attribute groupNameAttribute) {
                    try {
                        final NamingEnumeration<?> enumeration = groupNameAttribute.getAll();
                        if (enumeration.hasMore()) {
                            return enumeration.next().toString();
                        } else {
                            return null;
                        }
                    } catch (NamingException namingException) {
                        log.warn("Unable to read group name", namingException);
                        return null;
                    }
                }
            });
    final Iterator<String> finalGroupNamesIterator = Iterators.<String>filter(groupNamesIterator,
            Predicates.notNull());

    if (finalGroupNamesIterator.hasNext()) {
        return finalGroupNamesIterator.next();
    } else {
        log.warn("Unable to find an attribute matching {}", groupNameId);
        return null;
    }
}

From source file:com.google.reducisaurus.servlets.BaseServlet.java

private Collection<String> getSortedParameterNames(HttpServletRequest req) {
    // We want a deterministic order so that dependencies can span input files.
    // We don't trust the servlet container to return query parameters in any
    // order, so we impose our own ordering. In this case, we use natural String
    // ordering./*from w  w  w .  ja v  a2s. c o m*/
    List<String> list = Lists
            .newArrayList(Iterators.forEnumeration((Enumeration<String>) req.getParameterNames()));
    // Some parameter names should be ignored.
    Iterable<String> filtered = Collections2.filter(list, new Predicate<String>() {
        @Override
        public boolean apply(@Nullable String s) {
            return !(s.contains("_") || s.contains("-"));
        }
    });
    return Ordering.natural().sortedCopy(filtered);
}

From source file:com.rainycape.reducer.servlets.BaseServlet.java

private Collection<String> getSortedParameterNames(HttpServletRequest req) {
    // We want a deterministic order so that dependencies can span input files.
    // We don't trust the servlet container to return query parameters in any
    // order, so we impose our own ordering. In this case, we use natural String
    // ordering.//  w  ww  .  j a  va  2s.  c  o  m
    @SuppressWarnings("unchecked")
    List<String> list = Lists
            .newArrayList(Iterators.forEnumeration((Enumeration<String>) req.getParameterNames()));
    // Some parameter names should be ignored.
    Iterable<String> filtered = Collections2.filter(list, new Predicate<String>() {
        @Override
        public boolean apply(@Nullable String s) {
            return !(s.contains("_") || s.contains("-"));
        }
    });
    return Ordering.natural().sortedCopy(filtered);
}