Example usage for java.util Collection iterator

List of usage examples for java.util Collection iterator

Introduction

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

Prototype

Iterator<E> iterator();

Source Link

Document

Returns an iterator over the elements in this collection.

Usage

From source file:Main.java

/**
 * <p>/*from w  ww .  ja  va2s . c  om*/
 * Joins the elements of the provided <code>Collection</code> into a single
 * String containing the provided elements.
 * </p>
 * <p>
 * No delimiter is added before or after the list. A <code>null</code>
 * separator is the same as an empty String ("").
 * </p>
 * <p>
 * See the examples here: {@link #join(Object[],String)}.
 * </p>
 * 
 * @param collection the <code>Collection</code> of values to join together,
 *            may be null
 * @param separator the separator character to use, null treated as ""
 * @return the joined String, <code>null</code> if null iterator input
 * @since 2.3
 */
public static String join(Collection<?> collection, String separator) {
    if (collection == null) {
        return null;
    }
    return join(collection.iterator(), separator);
}

From source file:Main.java

/**
 * // w  w  w.  java2 s  .  co  m
 * @param collection
 * @return String
 */
public static String toToolTip(final Collection<?> collection) {
    if (collection == null || collection.size() == 0) {
        return null;
    }

    final String START_SEPARATOR = "<p>"; //$NON-NLS-1$
    final String END_SEPARATOR = "</p>"; //$NON-NLS-1$
    final StringBuffer buffer = new StringBuffer("<html>"); //$NON-NLS-1$

    for (Iterator<?> iterator = collection.iterator(); iterator.hasNext();) {
        buffer.append(START_SEPARATOR);
        buffer.append(iterator.next());
        buffer.append(END_SEPARATOR);
    }

    buffer.append("</html>"); //$NON-NLS-1$

    return buffer.toString();
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.CreationAndUpdateTests.java

public static Collection<Object[]> getReferencedUrls(String base)
        throws IOException, XPathException, ParserConfigurationException, SAXException {
    Properties setupProps = SetupProperties.setup(null);
    String userId = setupProps.getProperty("userId");
    String pw = setupProps.getProperty("pw");

    HttpResponse resp = OSLCUtils.getResponseFromUrl(base, base, new UsernamePasswordCredentials(userId, pw),
            OSLCConstants.CT_DISC_CAT_XML + ", " + OSLCConstants.CT_DISC_DESC_XML);

    //If our 'base' is a ServiceDescription, find and add the factory service url
    if (resp.getEntity().getContentType().getValue().contains(OSLCConstants.CT_DISC_DESC_XML)) {
        Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity()));
        Node factoryUrl = (Node) OSLCUtils.getXPath().evaluate("//oslc_cm:factory/oslc_cm:url", baseDoc,
                XPathConstants.NODE);
        Collection<Object[]> data = new ArrayList<Object[]>();
        data.add(new Object[] { factoryUrl.getTextContent() });
        return data;
    }//from w ww .j a  v a2 s . co m

    Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity()));

    //ArrayList to contain the urls from all of the SPCs
    Collection<Object[]> data = new ArrayList<Object[]>();

    //Get all the ServiceDescriptionDocuments from this ServiceProviderCatalog
    NodeList sDescs = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_disc:services/@rdf:resource", baseDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < sDescs.getLength(); i++) {
        Collection<Object[]> subCollection = getReferencedUrls(sDescs.item(i).getNodeValue());
        Iterator<Object[]> iter = subCollection.iterator();
        while (iter.hasNext()) {
            data.add(iter.next());
        }
    }

    //Get all ServiceProviderCatalog urls from the base document in order to recursively add all the
    //simple query services from the eventual service description documents from them as well.
    NodeList spcs = (NodeList) OSLCUtils.getXPath().evaluate(
            "//oslc_disc:entry/oslc_disc:ServiceProviderCatalog/@rdf:about", baseDoc, XPathConstants.NODESET);
    for (int i = 0; i < spcs.getLength(); i++) {
        if (!spcs.item(i).getNodeValue().equals(base)) {
            Collection<Object[]> subCollection = getReferencedUrls(spcs.item(i).getNodeValue());
            Iterator<Object[]> iter = subCollection.iterator();
            while (iter.hasNext()) {
                data.add(iter.next());
            }
        }
    }
    return data;
}

From source file:Main.java

private static SSLContext sslContextForTrustedCertificates(InputStream in) {
    try {/*from   ww w . jav a2s  .c o  m*/
        CertificateFactory e = CertificateFactory.getInstance("X.509");
        Collection certificates = e.generateCertificates(in);
        if (certificates.isEmpty()) {
            throw new IllegalArgumentException("expected non-empty set of trusted certificates");
        } else {
            char[] password = "password".toCharArray();
            KeyStore keyStore = newEmptyKeyStore(password);
            int index = 0;
            Iterator keyManagerFactory = certificates.iterator();
            while (keyManagerFactory.hasNext()) {
                Certificate trustManagerFactory = (Certificate) keyManagerFactory.next();
                String sslContext = Integer.toString(index++);
                keyStore.setCertificateEntry(sslContext, trustManagerFactory);
            }

            KeyManagerFactory var10 = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            var10.init(keyStore, password);
            TrustManagerFactory var11 = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            var11.init(keyStore);
            SSLContext var12 = SSLContext.getInstance("TLS");
            var12.init(var10.getKeyManagers(), var11.getTrustManagers(), new SecureRandom());
            return var12;
        }
    } catch (Exception var9) {
        var9.printStackTrace();
    }
    return null;
}

From source file:io.github.bonigarcia.wdm.Downloader.java

public static final File extractMsi(File msi) throws IOException {
    File tmpMsi = new File(Files.createTempDir().getAbsoluteFile() + File.separator + msi.getName());
    Files.move(msi, tmpMsi);/*from w  w  w .  jav  a 2  s. c  o  m*/
    log.trace("Temporal msi file: {}", tmpMsi);

    Process process = Runtime.getRuntime()
            .exec(new String[] { "msiexec", "/a", tmpMsi.toString(), "/qb", "TARGETDIR=" + msi.getParent() });
    try {
        process.waitFor();
    } catch (InterruptedException e) {
        log.error("Exception waiting to msiexec to be finished", e);
    } finally {
        process.destroy();
    }

    tmpMsi.delete();

    Collection<File> listFiles = FileUtils.listFiles(new File(msi.getParent()), new String[] { "exe" }, true);
    return listFiles.iterator().next();
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.ServiceProviderCatalogTests.java

public static Collection<Object[]> getReferencedCatalogUrls(String base)
        throws IOException, ParserConfigurationException, SAXException, XPathException {
    Properties setupProps = SetupProperties.setup(null);
    String userId = setupProps.getProperty("userId");
    String pw = setupProps.getProperty("pw");

    HttpResponse resp = OSLCUtils.getResponseFromUrl(base, base, new UsernamePasswordCredentials(userId, pw),
            OSLCConstants.CT_DISC_CAT_XML);
    //If we're not looking at a catalog, return empty list.
    if (!resp.getEntity().getContentType().getValue().contains(OSLCConstants.CT_DISC_CAT_XML)) {
        System.out.println("The url: " + base + " does not refer to a ServiceProviderCatalog.");
        System.out.println(// w  w  w. j a va  2s  .c  o m
                "The content-type of a ServiceProviderCatalog should be " + OSLCConstants.CT_DISC_CAT_XML);
        System.out.println("The content-type returned was " + resp.getEntity().getContentType());
        EntityUtils.consume(resp.getEntity());
        return new ArrayList<Object[]>();
    }
    Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity()));

    //ArrayList to contain the urls from all SPCs
    Collection<Object[]> data = new ArrayList<Object[]>();
    data.add(new Object[] { base });

    //Get all ServiceProviderCatalog urls from the base document in order to test them as well,
    //recursively checking them for other ServiceProviderCatalogs further down.
    NodeList spcs = (NodeList) OSLCUtils.getXPath().evaluate(
            "//oslc_disc:entry/oslc_disc:ServiceProviderCatalog/@rdf:about", baseDoc, XPathConstants.NODESET);
    for (int i = 0; i < spcs.getLength(); i++) {
        String uri = spcs.item(i).getNodeValue();
        uri = OSLCUtils.absoluteUrlFromRelative(base, uri);
        if (!uri.equals(base)) {
            Collection<Object[]> subCollection = getReferencedCatalogUrls(uri);
            Iterator<Object[]> iter = subCollection.iterator();
            while (iter.hasNext()) {
                data.add(iter.next());
            }
        }
    }
    return data;
}

From source file:com.stratio.deep.commons.utils.CellsUtils.java

/**
 * converts from cell class to JSONObject
 *
 * @param cells the cells/* w w  w . j a v  a  2  s.c om*/
 * @return json from cell
 * @throws IllegalAccessException the illegal access exception
 * @throws IllegalAccessException the instantiation exception
 * @throws IllegalAccessException the invocation target exception
 */
public static JSONObject getJsonFromCell(Cells cells)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {

    JSONObject json = new JSONObject();
    for (Cell cell : cells) {
        if (cell.getCellValue() != null) {
            if (Collection.class.isAssignableFrom(cell.getCellValue().getClass())) {
                Collection c = (Collection) cell.getCellValue();
                Iterator iterator = c.iterator();
                List innerJsonList = new ArrayList<>();

                while (iterator.hasNext()) {
                    Object innerObject = iterator.next();
                    if (innerObject instanceof Cells) {
                        innerJsonList.add(getJsonFromCell((Cells) innerObject));
                    } else {
                        innerJsonList.add(innerObject);
                    }

                }
                json.put(cell.getCellName(), innerJsonList);
            } else if (Cells.class.isAssignableFrom(cell.getCellValue().getClass())) {
                json.put(cell.getCellName(), getJsonFromCell((Cells) cell.getCellValue()));
            } else {
                json.put(cell.getCellName(), cell.getCellValue());
            }

        }
    }

    return json;
}

From source file:Main.java

public static <T> List<T>[] split(Collection<T> set, int n) {
    if (set.size() >= n) {
        @SuppressWarnings("unchecked")
        List<T>[] arrays = new List[n];
        int minSegmentSize = (int) Math.floor(set.size() / (double) n);

        int start = 0;
        int stop = minSegmentSize;

        Iterator<T> it = set.iterator();

        for (int i = 0; i < n - 1; i++) {
            int segmentSize = stop - start;
            List<T> segment = new ArrayList<>(segmentSize);
            for (int k = 0; k < segmentSize; k++) {
                segment.add(it.next());//w  w  w  . jav  a 2 s.c om
            }
            arrays[i] = segment;
            start = stop;
            stop += segmentSize;
        }

        int segmentSize = set.size() - start;
        List<T> segment = new ArrayList<>(segmentSize);
        for (int k = 0; k < segmentSize; k++) {
            segment.add(it.next());
        }
        arrays[n - 1] = segment;

        return arrays;
    } else {
        throw new IllegalArgumentException("n must not be smaller set size!");
    }
}

From source file:org.zkoss.spring.security.SecurityUtil.java

private static Set authoritiesToRoles(Collection c) {
    final Set target = new HashSet();
    for (Iterator iterator = c.iterator(); iterator.hasNext();) {
        GrantedAuthority authority = (GrantedAuthority) iterator.next();

        if (null == authority.getAuthority()) {
            throw new IllegalArgumentException(
                    "Cannot process GrantedAuthority objects which return null from getAuthority() - attempting to process "
                            + authority.toString());
        }/*from w  ww  . j av a  2  s.  c  o m*/

        target.add(authority.getAuthority());
    }

    return target;
}

From source file:net.sourceforge.stripes.integration.spring.SpringHelper.java

/**
 * Fetches the methods on a class that are annotated with SpringBean. The first time it
 * is called for a particular class it will introspect the class and cache the results.
 * All non-overridden methods are examined, including protected and private methods.
 * If a method is not public an attempt it made to make it accessible - if it fails
 * it is removed from the collection and an error is logged.
 *
 * @param clazz the class on which to look for SpringBean annotated methods
 * @return the collection of methods with the annotation
 *///from   ww  w.  j  a  v  a 2  s  .  c o m
protected static Collection<Method> getMethods(Class<?> clazz) {
    Collection<Method> methods = methodMap.get(clazz);
    if (methods == null) {
        methods = ReflectUtil.getMethods(clazz);
        Iterator<Method> iterator = methods.iterator();

        while (iterator.hasNext()) {
            Method method = iterator.next();
            if (!method.isAnnotationPresent(SpringBean.class)) {
                iterator.remove();
            } else {
                // If the method isn't public, try to make it accessible
                if (!method.isAccessible()) {
                    try {
                        method.setAccessible(true);
                    } catch (SecurityException se) {
                        throw new StripesRuntimeException("Method " + clazz.getName() + "." + method.getName()
                                + "is marked " + "with @SpringBean and is not public. An attempt to call "
                                + "setAccessible(true) resulted in a SecurityException. Please "
                                + "either make the method public or modify your JVM security "
                                + "policy to allow Stripes to setAccessible(true).", se);
                    }
                }

                // Ensure the method has only the one parameter
                if (method.getParameterTypes().length != 1) {
                    throw new StripesRuntimeException(
                            "A method marked with @SpringBean must have exactly one parameter: "
                                    + "the bean to be injected. Method [" + method.toGenericString() + "] has "
                                    + method.getParameterTypes().length + " parameters.");
                }
            }
        }

        methodMap.put(clazz, methods);
    }

    return methods;
}