Example usage for java.util ArrayList iterator

List of usage examples for java.util ArrayList iterator

Introduction

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

Prototype

public Iterator<E> iterator() 

Source Link

Document

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

Usage

From source file:com.tremolosecurity.proxy.filter.PostProcess.java

protected void setHeadersCookies(HttpFilterRequest req, UrlHolder holder, HttpRequestBase method,
        String finalURL) throws Exception {
    Iterator<String> names;
    names = req.getHeaderNames();/*  ww w.  j ava2  s . com*/
    String cookieName = null;
    URL url = new URL(finalURL);

    while (names.hasNext()) {
        String name = names.next();
        if (name.equalsIgnoreCase("Cookie")) {
            cookieName = name;
            continue;
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Header : " + name);
        }

        Attribute attrib = req.getHeader(name);
        Iterator<String> attrVals = attrib.getValues().iterator();
        while (attrVals.hasNext()) {
            String val = attrVals.next();

            if (name.equalsIgnoreCase("Content-Type")) {
                continue;
            } else if (name.equalsIgnoreCase("If-Range")) {
                continue;
            } else if (name.equalsIgnoreCase("Range")) {
                continue;
            } else if (name.equalsIgnoreCase("If-None-Match")) {
                continue;
            }

            if (name.equalsIgnoreCase("HOST")) {

                if (holder.isOverrideHost()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Final URL : '" + finalURL + "'");
                    }

                    val = url.getHost();
                    if (url.getPort() != -1) {
                        StringBuffer b = new StringBuffer();
                        b.append(val).append(":").append(url.getPort());
                        val = b.toString();
                    }
                }
            } else if (name.equalsIgnoreCase("Referer")) {

                if (holder.isOverrideReferer()) {
                    URL origRef = new URL(val);
                    StringBuffer newRef = new StringBuffer();

                    newRef.append(url.getProtocol()).append("://").append(url.getHost());

                    if (url.getPort() != -1) {
                        newRef.append(':').append(url.getPort());
                    }

                    newRef.append(origRef.getPath());

                    if (origRef.getQuery() != null) {
                        newRef.append('?').append(origRef.getQuery());
                    }

                    if (logger.isDebugEnabled()) {
                        logger.debug("Final Ref : '" + newRef.toString() + "'");
                    }

                    val = newRef.toString();

                }

            }

            if (this.addHeader(name)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Header Added - '" + name + "'='" + val + "'");
                }
                method.addHeader(new BasicHeader(attrib.getName(), val));
            }
        }
    }

    HashMap<String, Attribute> fromResults = (HashMap<String, Attribute>) req
            .getAttribute(AzSys.AUTO_IDM_HTTP_HEADERS);
    if (fromResults != null) {
        names = fromResults.keySet().iterator();

        while (names.hasNext()) {
            String name = names.next();
            method.removeHeaders(name);

            Attribute attrib = fromResults.get(name);
            Iterator<String> attrVals = attrib.getValues().iterator();
            while (attrVals.hasNext()) {
                String val = attrVals.next();
                if (logger.isDebugEnabled()) {
                    logger.debug("Header Added - '" + name + "'='" + val + "'");
                }
                method.addHeader(new BasicHeader(name, val));
            }
        }
    }

    String sessionCookieName = "";

    if (holder.getApp().getCookieConfig() != null) {
        sessionCookieName = holder.getApp().getCookieConfig().getSessionCookieName();
    }

    HashSet<String> toRemove = new HashSet<String>();
    toRemove.add(sessionCookieName);
    toRemove.add("autoIdmSessionCookieName");
    toRemove.add("autoIdmAppName");
    toRemove.add("JSESSIONID");

    names = req.getCookieNames().iterator();
    StringBuffer cookieHeader = new StringBuffer();
    boolean isFirst = true;

    while (names.hasNext()) {
        String name = names.next();

        if (toRemove.contains(name)) {
            continue;
        }

        ArrayList<Cookie> cookies = req.getCookies(name);

        Iterator<Cookie> itc = cookies.iterator();
        while (itc.hasNext()) {
            Cookie cookie = itc.next();
            String cookieFinalName;
            if (cookie.getName().startsWith("JSESSIONID")) {
                String host = cookie.getName().substring(cookie.getName().indexOf('-') + 1);
                host = host.replaceAll("[|]", " ");
                if (!holder.getApp().getName().equalsIgnoreCase(host)) {
                    continue;
                }

                cookieFinalName = "JSESSIONID";
            } else {
                cookieFinalName = cookie.getName();
            }

            String val = cookie.getValue();
            if (logger.isDebugEnabled()) {
                logger.debug("Cookie Added - '" + name + "'='" + val + "'");
            }

            cookieHeader.append(cookieFinalName).append('=').append(val).append("; ");
        }
    }

    if (cookieHeader.length() > 0) {
        if (cookieName == null) {
            cookieName = "Cookie";
        }

        method.addHeader(new BasicHeader(cookieName, cookieHeader.toString()));
    }
}

From source file:com.robonobo.eon.ConnectionHolder.java

void closeAllConns(int waitTimeMs) {
    log.debug("Closing all EON connections");
    Date startWaitingTime = new Date();
    Date endWaitingTime = new Date(startWaitingTime.getTime() + waitTimeMs);
    List<EONConnection> connsToClose = new ArrayList<EONConnection>();
    connsToWaitFor = new ArrayList<EONConnection>();
    // Come out of this sync block before closing anything, else EONConnection.close() may cause a race condition
    synchronized (this) {
        ArrayList<EONConnection> allConns = new ArrayList<EONConnection>(defaultConns.values());
        Iterator<Map<EonSocketAddress, EONConnection>> spIter = specificConns.values().iterator();
        while (spIter.hasNext()) {
            Map<EonSocketAddress, EONConnection> thisMap = spIter.next();
            allConns.addAll(thisMap.values());
        }//www  . j a v a  2 s  . co m
        Iterator<EONConnection> allIter = allConns.iterator();
        while (allIter.hasNext()) {
            EONConnection conn = allIter.next();
            if (conn instanceof SEONConnection)
                connsToWaitFor.add(conn);
            connsToClose.add(conn);
        }
    }
    Iterator<EONConnection> i = connsToClose.iterator();
    while (i.hasNext()) {
        EONConnection conn = i.next();
        conn.close();
    }
    synchronized (this) {
        while (connsToWaitFor.size() > 0) {
            SEONConnection thisConn = (SEONConnection) connsToWaitFor.get(0);
            if (!thisConn.isOpen())
                connsToWaitFor.remove(0);
            else {
                try {
                    Date nowTime = new Date();
                    long msToWait = endWaitingTime.getTime() - nowTime.getTime();
                    if (msToWait <= 0) {
                        log.debug("EON finished waiting for connections");
                        break;
                    } else {
                        log.debug("EON waiting for " + connsToWaitFor + " conns, " + msToWait + "ms");
                        wait(msToWait);
                    }
                } catch (InterruptedException e) {
                    log.debug("EON caught InterruptedException while closing down", e);
                }
            }
        }
    }
    for (EONConnection eonConn : connsToWaitFor) {
        SEONConnection seonConn = (SEONConnection) eonConn;
        seonConn.cancelTimeouts();
    }
    connsToWaitFor.clear();
    log.debug("All EON conns closed");
}

From source file:com.spoiledmilk.cykelsuperstier.break_rote.BreakRouteActivity.java

private OverlayData getNearestDestinationStation(OverlayData od, ArrayList<OverlayData> stations) {
    OverlayData ret = null;//from  w w  w  .  ja  va2  s  .c  o m
    od.BStations = new ArrayList<OverlayData>();
    double distance = Double.MAX_VALUE;
    Iterator<OverlayData> it = stations.iterator();
    while (it.hasNext()) {
        OverlayData curr = it.next();
        if (curr == od)
            continue;
        String[] sourceLines = od.line.split(",");
        for (int i = 0; i < sourceLines.length; i++) {
            if (curr.line.contains(sourceLines[i].trim()) || sourceLines[i].contains(curr.line)
                    || curr.line.contains(sourceLines[i])) {
                if ((ret == null && curr != od) || (curr.loc.distanceTo(endLoc) < distance && curr != od)) {
                    distance = curr.loc.distanceTo(endLoc);
                    ret = curr;
                }
                OverlayData temp = curr.clone();
                temp.bikeDistance = curr.loc.distanceTo(endLoc);
                if (temp.bikeDistance <= distance)
                    od.BStations.add(temp);
                break;
            }
        }
    }
    Collections.sort(od.BStations);
    return ret;
}

From source file:org.archive.modules.fetcher.BdbCookieStoreTest.java

protected void assertCookieListsEquivalent(Collection<Cookie> list1, Collection<Cookie> list2) {
    Comparator<Cookie> comparator = new Comparator<Cookie>() {
        @Override// w  w w .java2 s.c  o  m
        public int compare(Cookie o1, Cookie o2) {
            return o1.toString().compareTo(o2.toString());
        }
    };

    ArrayList<Cookie> sorted1 = new ArrayList<Cookie>(list1);
    Collections.sort(sorted1, comparator);
    ArrayList<Cookie> sorted2 = new ArrayList<Cookie>(list2);
    Collections.sort(sorted2, comparator);

    assertEquals(list1.size(), list2.size());
    assertEquals(sorted1.size(), sorted2.size());

    Iterator<Cookie> iter1 = sorted1.iterator();
    Iterator<Cookie> iter2 = sorted2.iterator();
    for (int i = 0; i < list1.size(); i++) {
        Cookie c1 = iter1.next();
        Cookie c2 = iter2.next();
        assertCookiesIdentical(c1, c2);
    }
}

From source file:com.apkcategorychecker.writer.WriterCSV.java

@Override
public void Write(AnalyzerResult result, String _csvPath, int _counter) {

    try {/*  w w  w .  j a v  a  2  s  . c o m*/

        ArrayList<AnalyzerResult> resultList = new ArrayList<AnalyzerResult>();
        resultList.add(result);

        /*--Create the CSVFormat object--*/

        CSVFormat format = CSVFormat.DEFAULT.withHeader();

        /*--Writing in a CSV file--*/

        FileWriter _out = new FileWriter(_csvPath, true);
        CSVPrinter printer;
        printer = new CSVPrinter(_out, format.withDelimiter('#'));

        /*--Retrieve APKResult and Write in file--*/

        Iterator<AnalyzerResult> it = resultList.iterator();
        while (it.hasNext()) {
            AnalyzerResult _resultElement = it.next();
            List<String> resultData = new ArrayList<>();
            resultData.add(String.valueOf(_counter));
            resultData.add(_resultElement.get_APKName());
            resultData.add(_resultElement.get_APKPath());
            resultData.add(_resultElement.get_Package());
            resultData.add(_resultElement.get_APKMainFramework());
            resultData.add(_resultElement.get_APKBaseFramework());
            resultData.add(String.valueOf(_resultElement.get_html()));
            resultData.add(String.valueOf(_resultElement.get_js()));
            resultData.add(String.valueOf(_resultElement.get_css()));
            resultData.add(_resultElement.get_debuggable());
            resultData.add(_resultElement.get_permissions());
            resultData.add(_resultElement.get_minSdkVersion());
            resultData.add(_resultElement.get_maxSdkVersion());
            resultData.add(_resultElement.get_targetSdkVersion());
            resultData.add(_resultElement.get_fileSize());
            resultData.add(String.valueOf(_resultElement.get_startAnalysis()));
            resultData.add(String.valueOf(_resultElement.get_durationAnalysis()));
            resultData.add(String.valueOf(_resultElement.get_decodeSuccess()));
            printer.printRecord(resultData);
        }

        /*--Close the printer--*/
        printer.close();
        System.out.println("Record added to CSV file");
        this.removeBlankLines(_csvPath);

    } catch (IOException ex) {
        Logger.getLogger(WriterCSV.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.collabnet.ccf.core.eis.connection.ConnectionPool.java

public void tearDown() {
    Set<Map.Entry<String, ArrayList<ConnectionInfo>>> entries = connectionPool.entrySet();
    Iterator<Map.Entry<String, ArrayList<ConnectionInfo>>> it = entries.iterator();
    while (it.hasNext()) {
        Map.Entry<String, ArrayList<ConnectionInfo>> entry = it.next();
        String key = entry.getKey();
        ArrayList<ConnectionInfo> connectionInfos = connectionPool.get(key);
        synchronized (connectionInfos) {
            Iterator<ConnectionInfo> itCI = connectionInfos.iterator();
            while (itCI.hasNext()) {
                ConnectionInfo info = itCI.next();
                itCI.remove();/*from w w  w  .j a v  a2  s  . co m*/
                reversePoolMap.remove(info.getConnection());
                try {
                    factory.closeConnection(info.getConnection());
                } catch (ConnectionException e) {
                    log.warn("Could not close one of the pooled connections for " + key, e);
                }
            }
        }
    }
}

From source file:net.geant.edugain.filter.EduGAINFilter.java

private HashMap<String, String> parseAttrs(AuthenticationResponse response) {
    HashMap<String, String> attrs = new HashMap<String, String>();

    ArrayList<AttributeValues> values = response.getAttributeValueList();
    Iterator it = values.iterator();
    while (it.hasNext()) {
        AttributeValues att = (AttributeValues) it.next();
        String clave = att.getAttributeName();
        String namespace = att.getAttributeNameSpace();
        String value = "";
        ArrayList<String> valor = att.getAttributeValue();
        Iterator valIt = valor.iterator();
        while (valIt.hasNext()) {
            String item = (String) valIt.next();
            String val = item.replace(";", "-");
            val = val.replace(":", "_");
            value = value + val + "-";
        }//from  ww w  .j  a  v  a  2 s  . co m

        value = value.substring(0, value.length() - 1);
        attrs.put(clave, value);
        //this.session.setAttribute(clave,value);

    }

    return attrs;
}

From source file:com.cyberway.issue.crawler.util.FPUriUniqFilterTest.java

/**
 * Test inserting and removing./*  ww w.j a v  a  2 s . c o m*/
 * @throws IOException
 * @throws FileNotFoundException
 */
public void testWriting() throws FileNotFoundException, IOException {
    long start = System.currentTimeMillis();
    ArrayList<UURI> list = new ArrayList<UURI>(1000);
    int count = 0;
    final int MAX_COUNT = 1000;
    for (; count < MAX_COUNT; count++) {
        UURI u = UURIFactory.getInstance("http://www" + count + ".archive.org/" + count + "/index.html");
        this.filter.add(u.toString(), new CandidateURI(u));
        if (count > 0 && ((count % 100) == 0)) {
            list.add(u);
        }
    }
    this.logger.info("Added " + count + " in " + (System.currentTimeMillis() - start));

    start = System.currentTimeMillis();
    for (Iterator i = list.iterator(); i.hasNext();) {
        UURI uuri = (UURI) i.next();
        this.filter.add(uuri.toString(), new CandidateURI(uuri));
    }
    this.logger.info("Added random " + list.size() + " in " + (System.currentTimeMillis() - start));

    start = System.currentTimeMillis();
    for (Iterator i = list.iterator(); i.hasNext();) {
        UURI uuri = (UURI) i.next();
        this.filter.add(uuri.toString(), new CandidateURI(uuri));
    }
    this.logger.info("Deleted random " + list.size() + " in " + (System.currentTimeMillis() - start));
    // Looks like delete doesn't work.
    assertTrue("Count is off: " + this.filter.count(), this.filter.count() == MAX_COUNT);
}

From source file:com.xpn.xwiki.XWikiTest.java

public void testLanguageSelection() {
    getContext().setRequest(new XWikiServletRequest(null) {
        @SuppressWarnings("unchecked")
        @Override/*from  w  ww.j a va  2s  .c  o  m*/
        public Enumeration getLocales() {
            ArrayList<Locale> locales = new ArrayList<Locale>();
            locales.add(new Locale("*"));
            locales.add(new Locale("en_US"));
            locales.add(new Locale("fr"));
            locales.add(new Locale("de"));
            return IteratorUtils.asEnumeration(locales.iterator());
        }

        @Override
        public String getHeader(String s) {
            if ("language".equals(s)) {
                return null;
            }
            return "en";
        }

        @Override
        public Cookie getCookie(String cookieName) {
            return null;
        }
    });
    assertEquals("fr", this.xwiki.getLanguagePreference(getContext()));
}

From source file:com.wegas.core.rest.ComboController.java

/**
 * Retrieve// w  ww  . j  av  a 2  s.  c o m
 *
 * @param req
 * @return HTTP 200 with requested data or HTTP forbidden response
 * @throws IOException
 */
@GET
@Produces({ MediaTypeJs, MediaTypeCss })
@CacheMaxAge(time = 3, unit = TimeUnit.HOURS)
public Response index(@Context Request req) throws IOException {
    try {
        Ehcache cache = cacheManagerHolder.getInstance().getEhcache(CACHE_NAME);

        final int hash = this.uriInfo.getRequestUri().getQuery().hashCode();

        final Element combo = cache.get(hash);
        CacheObject comboCache;

        if (combo != null) { // Get from cache
            comboCache = (CacheObject) combo.getObjectValue();
        } else { // build Cache.
            //final Set<String> files = this.uriInfo.getQueryParameters().keySet(); // Old version, removed cause query parameters where in the wrong order
            ArrayList<String> files = new ArrayList<>(); // New version, with parameters in the right order
            for (String parameter : this.uriInfo.getRequestUri().getQuery().split("&")) {
                String split = parameter.split("=")[0];
                if (split != null) {
                    files.add(split);
                }
            }
            files.remove("v");
            files.remove("version");
            final String mediaType = (files.iterator().next().endsWith("css")) ? MediaTypeCss : MediaTypeJs; // Select the content-type based on the first file extension
            comboCache = new CacheObject(this.getCombinedFile(files, mediaType), mediaType);
            cache.put(new Element(hash, comboCache));

        }
        ResponseBuilder rb = req.evaluatePreconditions(new EntityTag(comboCache.getETag()));
        if (rb != null) {
            return rb.tag(comboCache.getETag()).build();
        }
        // MediaType types[] = {"application/json", "application/xml"};
        // List<Variant> vars = Variant.mediaTypes(types).add().build();
        // Variant var = req.selectVariant(vars);
        //EntityTag etag = new EntityTag();
        //Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(updateTimestamp, etag);
        return Response.ok(comboCache.getFiles()).type(comboCache.getMediaType())
                //    .expires(new Date(System.currentTimeMillis() + (1000 * 60 * 60 * 24 * 3)))
                .tag(new EntityTag(comboCache.getETag())).build();

    } catch (WegasForbiddenException ex) {
        return Response.status(Response.Status.FORBIDDEN).entity(ex.getMessage()).build();
    }
}