Example usage for java.util List iterator

List of usage examples for java.util List iterator

Introduction

In this page you can find the example usage for java.util List iterator.

Prototype

Iterator<E> iterator();

Source Link

Document

Returns an iterator over the elements in this list in proper sequence.

Usage

From source file:com.microsoft.tfs.core.httpclient.HttpState.java

/**
 * Returns a string representation of the cookies.
 *
 * @param cookies//from w ww . j  a  v a2s .co  m
 *        The cookies
 * @return The string representation.
 */
private static String getCookiesStringRepresentation(final List<Cookie> cookies) {
    final StringBuffer sbResult = new StringBuffer();
    final Iterator<Cookie> iter = cookies.iterator();
    while (iter.hasNext()) {
        final Cookie ck = iter.next();
        if (sbResult.length() > 0) {
            sbResult.append("#");
        }
        sbResult.append(ck.toExternalForm());
    }
    return sbResult.toString();
}

From source file:it.geosolutions.geoserver.jms.impl.handlers.catalog.CatalogUtils.java

public static <T extends PublishedInfo> List<LayerInfo> localizeLayers(final List<T> info,
        final Catalog catalog) throws IllegalAccessException, InvocationTargetException {
    if (info == null || catalog == null)
        throw new NullArgumentException("Arguments may never be null");
    final List<LayerInfo> localLayerList = new ArrayList<LayerInfo>(info.size());
    final Iterator<LayerInfo> it = localLayerList.iterator();
    while (it.hasNext()) {
        final LayerInfo layer = it.next();
        final LayerInfo localLayer = localizeLayer(layer, catalog);
        if (localLayer != null) {
            localLayerList.add(localLayer);
        } else {// ww  w.j av a 2 s.  com
            if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
                LOGGER.warning("No such layer called \'" + layer.getName() + "\' can be found: SKIPPING");
            }
        }
    }
    return localLayerList;
}

From source file:Main.java

public static Iterator getElementsByTagNames(Element element, String[] tags) {
    List<Element> children = new ArrayList<Element>();
    if (element != null && tags != null) {
        List tagList = Arrays.asList(tags);
        NodeList nodes = element.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node child = nodes.item(i);
            if (child.getNodeType() == Node.ELEMENT_NODE && tagList.contains(((Element) child).getTagName())) {
                children.add((Element) child);
            }/*from   w w w. ja  v  a 2 s.c  om*/
        }
    }
    return children.iterator();
}

From source file:de.tu_dortmund.ub.data.util.TPUUtil.java

public static String executeInit(final String initResourceFile, final String serviceName,
        final Integer engineThreads, final Properties config, final int cnt) throws Exception {

    // create job
    final Callable<String> initTask = new Init(initResourceFile, config, cnt);

    // work on jobs
    final ThreadPoolExecutor pool = new ThreadPoolExecutor(engineThreads, engineThreads, 0L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>());

    try {//  w w  w.  j  av a2 s.  com

        final List<Callable<String>> tasks = new LinkedList<>();
        tasks.add(initTask);

        final List<Future<String>> futureList = pool.invokeAll(tasks);
        final Iterator<Future<String>> iterator = futureList.iterator();

        if (iterator.hasNext()) {

            final Future<String> f = iterator.next();

            final String initResult = f.get();

            final String message1 = String.format("[%s][%d] initResult = '%s'", serviceName, cnt, initResult);

            LOG.info(message1);

            return initResult;
        }

    } catch (final Exception e) {

        LOG.error("[{]][{}] something went wrong at init part execution", serviceName, cnt, e);

        throw e;
    } finally {

        pool.shutdown();
    }

    return null;
}

From source file:com.alibaba.otter.node.etl.common.io.compress.impl.PackableObject.java

/**
 * Compares a file to a list of packables and identifies an object by
 * header. If no matching header is found, it identifies the file by file
 * extension. If identification was not successfull, null is returned
 * /*from www . j a  va 2s .co  m*/
 * @param file the file to identify
 * @param packables a list of packables
 * @return a matching packable object, or null
 * @throws IOException
 */
public static PackableObject identifyByHeader(File file, List packables) throws IOException {
    FileInputStream fis = null;
    try {
        /* Archive result */
        // PackableObject packable = null;
        // identify archive by header
        fis = new FileInputStream(file);
        byte[] headerBytes = new byte[20];
        fis.read(headerBytes, 0, 20);

        Iterator iter = packables.iterator();
        while (iter.hasNext()) {
            PackableObject p = (PackableObject) iter.next();
            byte[] fieldHeader = p.getHeader();

            if (fieldHeader != null) {
                if (compareByteArrays(headerBytes, fieldHeader)) {
                    return p;
                }
            }
        }

        // if we couldn't find an archiver by header bytes, we'll give it a
        // try
        // with the default name extension. This is useful, cause some
        // archives
        // like tar have no header.
        String name = file.getName();
        String extension = null;
        String[] s = name.split("\\.");

        if (s.length > 1) {
            extension = s[s.length - 1];
        }

        Iterator it = packables.iterator();

        while (it.hasNext()) {
            PackableObject p = (PackableObject) it.next();
            if (p.isPackableWith(extension, PackableObject.CHOOSE_EXTENSION)) {
                return p;
            }
        }
        // No implementation found
        return null;
    } finally {
        IOUtils.closeQuietly(fis);
    }
}

From source file:gov.nih.nci.caintegrator.application.download.caarray.CaArrayFileDownloadManager.java

@SuppressWarnings("unchecked")
public static Collection<DownloadTask> getAllSessionDownloads(BusinessTierCache _businessCacheManager,
        String _sessionId) {//from www .j  a  va  2s  .c o m
    Collection<DownloadTask> beans = new ArrayList<DownloadTask>();
    if (_businessCacheManager != null && _sessionId != null
            && _businessCacheManager.getSessionCache(_sessionId) != null) {
        Cache sessionCache = _businessCacheManager.getSessionCache(_sessionId);
        try {
            List keys = sessionCache.getKeys();
            for (Iterator i = keys.iterator(); i.hasNext();) {
                Element element = sessionCache.get((String) i.next());
                Object object = element.getValue();
                if (object instanceof DownloadTask) {
                    beans.add((DownloadTask) object);
                }
            }
        } catch (CacheException ce) {
            logger.error(ce);
        }
    }
    return beans;
}

From source file:com.astamuse.asta4d.util.annotation.AnnotatedPropertyUtil.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static AnnotatedPropertyInfoMap retrievePropertiesMap(Class cls) {
    String cacheKey = cls.getName();
    AnnotatedPropertyInfoMap map = propertiesMapCache.get(cacheKey);
    if (map == null) {
        List<AnnotatedPropertyInfo> infoList = new LinkedList<>();
        Set<String> beanPropertyNameSet = new HashSet<>();

        Method[] mtds = cls.getMethods();
        for (Method method : mtds) {
            List<Annotation> annoList = ConvertableAnnotationRetriever
                    .retrieveAnnotationHierarchyList(AnnotatedProperty.class, method.getAnnotations());

            if (CollectionUtils.isEmpty(annoList)) {
                continue;
            }//from   w w w  .ja v  a  2  s  .  com

            AnnotatedPropertyInfo info = new AnnotatedPropertyInfo();
            info.setAnnotations(annoList);

            boolean isGet = false;
            boolean isSet = false;
            String propertySuffixe = method.getName();
            if (propertySuffixe.startsWith("set")) {
                propertySuffixe = propertySuffixe.substring(3);
                isSet = true;
            } else if (propertySuffixe.startsWith("get")) {
                propertySuffixe = propertySuffixe.substring(3);
                isGet = true;
            } else if (propertySuffixe.startsWith("is")) {
                propertySuffixe = propertySuffixe.substring(2);
                isSet = true;
            } else {
                String msg = String.format("Method [%s]:[%s] can not be treated as a getter or setter method.",
                        cls.getName(), method.toGenericString());
                throw new RuntimeException(msg);
            }

            char[] cs = propertySuffixe.toCharArray();
            cs[0] = Character.toLowerCase(cs[0]);
            info.setBeanPropertyName(new String(cs));

            AnnotatedProperty ap = (AnnotatedProperty) annoList.get(0);// must by
            String name = ap.name();
            if (StringUtils.isEmpty(name)) {
                name = info.getBeanPropertyName();
            }

            info.setName(name);

            if (isGet) {
                info.setGetter(method);
                info.setType(method.getReturnType());
                String setterName = "set" + propertySuffixe;
                Method setter = null;
                try {
                    setter = cls.getMethod(setterName, method.getReturnType());
                } catch (NoSuchMethodException | SecurityException e) {
                    String msg = "Could not find setter method:[{}({})] in class[{}] for annotated getter:[{}]";
                    logger.warn(msg, new Object[] { setterName, method.getReturnType().getName(), cls.getName(),
                            method.getName() });
                }
                info.setSetter(setter);
            }

            if (isSet) {
                info.setSetter(method);
                info.setType(method.getParameterTypes()[0]);
                String getterName = "get" + propertySuffixe;
                Method getter = null;
                try {
                    getter = cls.getMethod(getterName);
                } catch (NoSuchMethodException | SecurityException e) {
                    String msg = "Could not find getter method:[{}:{}] in class[{}] for annotated setter:[{}]";
                    logger.warn(msg, new Object[] { getterName, method.getReturnType().getName(), cls.getName(),
                            method.getName() });
                }
                info.setGetter(getter);
            }

            infoList.add(info);
            beanPropertyNameSet.add(info.getBeanPropertyName());
        }

        List<Field> list = new ArrayList<>(ClassUtil.retrieveAllFieldsIncludeAllSuperClasses(cls));
        Iterator<Field> it = list.iterator();

        while (it.hasNext()) {
            Field f = it.next();
            List<Annotation> annoList = ConvertableAnnotationRetriever
                    .retrieveAnnotationHierarchyList(AnnotatedProperty.class, f.getAnnotations());
            if (CollectionUtils.isNotEmpty(annoList)) {
                AnnotatedProperty ap = (AnnotatedProperty) annoList.get(0);// must by

                String beanPropertyName = f.getName();
                if (beanPropertyNameSet.contains(beanPropertyName)) {
                    continue;
                }

                String name = ap.name();
                if (StringUtils.isEmpty(name)) {
                    name = f.getName();
                }

                AnnotatedPropertyInfo info = new AnnotatedPropertyInfo();
                info.setAnnotations(annoList);
                info.setBeanPropertyName(beanPropertyName);
                info.setName(name);
                info.setField(f);
                info.setGetter(null);
                info.setSetter(null);
                info.setType(f.getType());
                infoList.add(info);
            }
        }

        map = new AnnotatedPropertyInfoMap(infoList);
        if (Configuration.getConfiguration().isCacheEnable()) {
            propertiesMapCache.put(cacheKey, map);
        }
    }
    return map;
}

From source file:com.google.gdt.eclipse.designer.Activator.java

/**
 * @return array of entry sub-paths in given path.
 *///from www .  j a v a  2 s  .c om
@SuppressWarnings("unchecked")
public static String[] getEntriesPaths(String path) {
    List<String> entryPaths;
    {
        entryPaths = Lists.newArrayList();
        Enumeration<String> entryPathsEnumeration = getBundleStatic().getEntryPaths(path);
        CollectionUtils.addAll(entryPaths, entryPathsEnumeration);
    }
    // remove ".svn" files (for case when we use runtime workbench)
    for (Iterator<String> I = entryPaths.iterator(); I.hasNext();) {
        String entryPath = I.next();
        if (entryPath.indexOf(".svn") != -1) {
            I.remove();
        }
    }
    // convert to array
    return entryPaths.toArray(new String[entryPaths.size()]);
}

From source file:com.qualogy.qafe.business.integration.adapter.MappingAdapter.java

/**
 * method knows toBeMapped is not an instance of any type of Collection or is an array!
 * @param toBeMapped//w w w .ja  v  a2s.  com
 * @param mapping
 * @param result
 * @return
 */
protected static Object adaptFromService(Object toBeMapped, AdapterMapping mapping) {
    Object result = null;
    //TODO: check 3 nested parents...since object is null every time
    //its cheaper to convert all than doing a nested get on each and every attribute of the mapping
    toBeMapped = ObjectMapConverter.convert(toBeMapped);

    if (mapping.hasParent()) {
        result = adaptFromService(toBeMapped, mapping.getParent());
    }

    List<AdapterAttribute> attributes = mapping.getAdapterAttributes();
    if (attributes != null) {
        if (result == null) {
            //            result = new CaseInsensitiveMap();
            result = new DataMap();
        }

        for (Iterator<AdapterAttribute> iter = attributes.iterator(); iter.hasNext();) {
            AdapterAttribute attribute = (AdapterAttribute) iter.next();
            Object value = null;
            if (attribute instanceof AttributeMapping) {//simple attribute or complex attribute with adapter
                AttributeMapping attrmapping = (AttributeMapping) attribute;
                if (attrmapping.getAdapter() != null) {//attribute has an adapter
                    value = adaptFromService(((Map) toBeMapped).remove(attrmapping.getName()),
                            attrmapping.getAdapter());
                } else {//simple attribute
                    value = ((Map) toBeMapped).remove(attrmapping.getName());//TODO:simple conversion
                }
            } else if (attribute instanceof AdapterMapping) {//internal adapter
                AdapterMapping adaptermapping = (AdapterMapping) attribute;
                value = adaptFromService(toBeMapped, adaptermapping);
            }
            ((Map) result).put(attribute.getName(), value);
        }
    }
    if (mapping.adaptAll() && ((result == null && toBeMapped != null && !((Map) toBeMapped).isEmpty())
            || result instanceof Map)) { //adaptall left (removed adapted ones)
        if (result == null) {
            //            result = new CaseInsensitiveMap();
            result = new DataMap();
        }
        ((Map) result).putAll((Map) toBeMapped);
    }

    return result;
}

From source file:Main.java

/**
 * Concatenates multiple iterables into a single iterable. The iterator exposed by the returned
 * iterable does not support {@link Iterator#remove()} even if the input iterables do.
 *
 * @throws NullPointerException if {@code iterables} or any of its elements are {@code null}
 *//*from   w  ww.  j  av a 2  s. co m*/
public static <T> Iterable<T> concat(List<Iterable<T>> iterables) {
    for (Iterable<T> iterable : iterables) {
        Objects.requireNonNull(iterable);
    }
    return new Iterable<T>() {
        @Override
        public Iterator<T> iterator() {
            if (iterables.size() == 0) {
                return Collections.emptyIterator();
            }
            return new Iterator<T>() {
                Iterator<Iterable<T>> cursor = iterables.iterator();
                Iterator<T> currentIterator = cursor.next().iterator();

                private void advance() {
                    while (!currentIterator.hasNext() && cursor.hasNext()) {
                        currentIterator = cursor.next().iterator();
                    }
                }

                @Override
                public boolean hasNext() {
                    advance();
                    return currentIterator.hasNext();
                }

                @Override
                public T next() {
                    advance();
                    return currentIterator.next();
                }
            };
        }

    };
}