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:gr.iit.demokritos.cru.cps.api.SubmitUserInformalEvaluationList.java

public JSONObject processRequest() throws IOException, Exception {

    String response_code = "e0";
    long user_id = 0;

    String[] users = users_list.split(";");
    ArrayList<Long> users_id = new ArrayList<Long>();

    for (int i = 0; i < users.length; i++) {
        users_id.add(Long.parseLong(users[i]));
    }//from w w  w.j  a v  a  2  s  .  c  o m

    String location = (String) properties.get("location");
    String database_name = (String) properties.get("database_name");
    String username = (String) properties.get("username");
    String password = (String) properties.get("password");

    MySQLConnector mysql = new MySQLConnector(location, database_name, username, password);

    try {
        user_id = Long.parseLong(evaluator_id);
        Connection connection = mysql.connectToCPSDatabase();
        Statement stmt = connection.createStatement();

        ResultSet rs = stmt.executeQuery("SELECT window FROM windows WHERE current_window=1");
        int window = -1;
        while (rs.next()) {
            window = rs.getInt(1);
        }
        rs.close();

        UserManager um = new UserManager(Long.parseLong(application_key), user_id, users_id);
        CreativityExhibitModelController cemc = new CreativityExhibitModelController(window,
                Long.parseLong(application_key), user_id, users_id);

        boolean isvalid = false;
        isvalid = um.validateClientApplication(mysql);
        if (isvalid == true) {
            isvalid = um.validateUser(mysql);
            if (isvalid == true) {
                Iterator it = users_id.iterator();
                while (it.hasNext()) {
                    um.setUser_id((Long) it.next());
                    isvalid = um.validateUser(mysql);
                    if (isvalid == false) {
                        break;
                    }
                }
            } else {
                response_code = "e102";
            }

            if (isvalid == true) {
                cemc.storeEvaluation(mysql);
                response_code = "OK";
            } else {
                response_code = "e102";
            }
        } else {
            response_code = "e101";
        }
    } catch (NumberFormatException ex) {
        response_code = "e101";
        Logger.getLogger(CreateUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(CreateUser.class.getName()).log(Level.SEVERE, null, ex);
    }

    JSONArray list = new JSONArray();

    for (Long temp_user : users_id) {
        list.add(Long.toString(temp_user));
    }

    JSONObject obj = new JSONObject();

    obj.put("application_key", application_key);
    obj.put("user_id", Long.toString(user_id));
    obj.put("users_id", list);
    obj.put("response_code", response_code);

    return obj;
}

From source file:hotbeans.support.FileSystemHotBeanModuleRepository.java

/**
 * Checks for module updates./*w w  w .  j a  v  a 2 s  . co  m*/
 */
protected void checkForModuleUpdates() {
    Log logger = this.getLog();
    if (logger.isDebugEnabled())
        logger.debug("Checking for updated modules in path '" + this.moduleRepositoryDirectory + "'.");

    synchronized (super.getLock()) {
        RepositoryFileLock fileLock = null;
        try {
            fileLock = this.obtainRepositoryFileLockNoRetries(true); // Obtain lock without retries since this method
                                                                     // will be executed again in the
                                                                     // near future...

            File[] moduleDirectories = this.moduleRepositoryDirectory.listFiles();
            ArrayList activeModuleNames = new ArrayList(Arrays.asList(super.getHotBeanModuleNames()));

            if (moduleDirectories != null) {
                String moduleName;

                for (int i = 0; i < moduleDirectories.length; i++) {
                    if (moduleDirectories[i].isDirectory()) {
                        moduleName = moduleDirectories[i].getName();

                        if (moduleName != null) {
                            activeModuleNames.remove(moduleName);
                            this.checkModuleDirectory(moduleName, moduleDirectories[i]);
                        }
                    }
                }
            }

            // Check for deleted modules...
            Iterator deletedModulesIterator = activeModuleNames.iterator();
            // HotBeanModule module;
            HotBeanModuleType moduleType;

            while (deletedModulesIterator.hasNext()) {
                moduleType = super.getHotBeanModuleType((String) deletedModulesIterator.next());
                if (moduleType != null)
                    moduleType.setRemoveType(true); // Set remove flag of type
            }
        } catch (Exception e) {
            logger.error("Error checking for updated modules - " + e + "!", e);
            // TODO: Handle/log exception
        } finally {
            this.releaseRepositoryFileLock(fileLock);
            fileLock = null;
        }
    }
}

From source file:fr.inria.oak.paxquery.pact.operations.xml.navigation.SingleDocumentExtractor.java

/**
 * This method attempts to locate children of em in the stack s, either
 * directly from em's children, or by transitivity from em's own children
 * (matches in the same stack, corresponding to ancestors of em). The method
 * returns em's resulting (potentially enhanced) children in the stack s.
 * /*from   www .j  a  v a2  s  . c  o  m*/
 * @param em
 *            The match.
 * @param s
 *            The stack for which we attempt to find children.
 * @return the set of the match's children in the stack, if any were found.
 */
private final ArrayList<ExtractorMatch> findChildInStack(ExtractorMatch em, ExtractorMatchStack s,
        boolean isParent) {

    if (em.childrenByStack == null) {
        return null;
    }
    ArrayList<ExtractorMatch> v = em.childrenByStack.get(s);

    if (em.ownChildren != null) {
        Iterator<ExtractorMatch> it = em.ownChildren.iterator();
        while (it.hasNext()) {
            ExtractorMatch emChild = it.next();
            // cannot be null
            ArrayList<ExtractorMatch> vAux = findChildInStack(emChild, s, isParent);
            if (vAux != null) {
                Iterator<ExtractorMatch> iAux = vAux.iterator();
                if (v == null) {
                    v = new ArrayList<ExtractorMatch>();
                    em.childrenByStack.put(s, v);
                }
                while (iAux.hasNext()) {
                    ExtractorMatch o = iAux.next();
                    if (v.indexOf(o) == -1) {
                        ExtractorMatch emo = o;
                        if ((!isParent) || (em.depth + 1 == emo.depth)) {
                            v.add(o);
                        }
                    }
                }
            }
        }
    }
    return v;
}

From source file:de.codesourcery.eve.skills.ui.components.impl.MarketPriceEditorComponent.java

protected void updateMultiplePrices(Map<Long, PriceInfoUpdateRequest> requests, PriceInfo.Type type,
        UpdateMode mode) throws PriceInfoUnavailableException {

    if (log.isDebugEnabled()) {
        log.debug("updateMultiplePrices(): " + requests.size() + " items , query type: " + type + " mode = "
                + mode);//from   w  ww.  j a v  a 2 s.c  o  m
    }

    final Map<Type, Set<InventoryType>> pricesByQueryType = new HashMap<Type, Set<InventoryType>>();

    for (PriceInfoUpdateRequest request : requests.values()) {

        Set<InventoryType> existing = pricesByQueryType.get(request.item);

        if (existing == null) {
            existing = new HashSet<InventoryType>();
            pricesByQueryType.put(type, existing);
        }
        existing.add(request.item);
    }

    if (log.isDebugEnabled()) {
        for (Map.Entry<Type, Set<InventoryType>> entry : pricesByQueryType.entrySet()) {
            log.debug("updateMultiplePrices(): query type " + entry.getKey() + " : " + entry.getValue().size()
                    + " items.");
        }
    }

    final ArrayList<InventoryType> queryBoth = new ArrayList<InventoryType>();
    final ArrayList<InventoryType> queryBuy = new ArrayList<InventoryType>();
    final ArrayList<InventoryType> querySell = new ArrayList<InventoryType>();

    nullSafeAdd(queryBoth, pricesByQueryType.get(PriceInfo.Type.ANY));
    nullSafeAdd(queryBuy, pricesByQueryType.get(PriceInfo.Type.BUY));
    nullSafeAdd(querySell, pricesByQueryType.get(PriceInfo.Type.SELL));

    for (Iterator<InventoryType> it = queryBuy.iterator(); it.hasNext();) {
        final InventoryType item = it.next();

        if (querySell.contains(item)) {
            it.remove();
            querySell.remove(item);
            queryBoth.add(item);
        }
    }

    for (Iterator<InventoryType> it = querySell.iterator(); it.hasNext();) {
        final InventoryType item = it.next();

        if (queryBuy.contains(item)) {
            it.remove();
            queryBuy.remove(item);
            queryBoth.add(item);
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("updateMultiplePrices(): [ after merge ] Type.ALL  = " + queryBoth.size());
        log.debug("updateMultiplePrices(): [ after merge ] Type.BUY  = " + queryBuy.size());
        log.debug("updateMultiplePrices(): [ after merge ] Type.SELL = " + querySell.size());
    }

    final IPriceQueryCallback callback = IPriceQueryCallback.NOP_INSTANCE;

    if (!queryBoth.isEmpty()) {

        MarketFilter filter = new MarketFilterBuilder(PriceInfo.Type.ANY, getDefaultRegion()).updateMode(mode)
                .end();

        final IUpdateStrategy updateStrategy = marketDataProvider.createUpdateStrategy(mode,
                PriceInfo.Type.ANY);

        if (log.isDebugEnabled()) {
            log.debug("updateMultiplePrices(): Updating Type.ALL item prices.");
        }
        marketDataProvider.updatePriceInfo(filter, queryBoth, callback, updateStrategy);
    }

    if (!querySell.isEmpty()) {

        final MarketFilter filter = new MarketFilterBuilder(PriceInfo.Type.SELL, getDefaultRegion())
                .updateMode(mode).end();

        if (log.isDebugEnabled()) {
            log.debug("updateMultiplePrices(): Updating Type.SELL item prices.");
        }

        final IUpdateStrategy updateStrategy = marketDataProvider.createUpdateStrategy(mode,
                PriceInfo.Type.SELL);

        marketDataProvider.updatePriceInfo(filter, querySell, callback, updateStrategy);
    }

    if (!queryBuy.isEmpty()) {

        final MarketFilter filter = new MarketFilterBuilder(PriceInfo.Type.BUY, getDefaultRegion())
                .updateMode(mode).end();

        if (log.isDebugEnabled()) {
            log.debug("updateMultiplePrices(): Updating Type.BUY item prices.");
        }

        final IUpdateStrategy updateStrategy = marketDataProvider.createUpdateStrategy(mode,
                PriceInfo.Type.BUY);

        marketDataProvider.updatePriceInfo(filter, queryBuy, callback, updateStrategy);
    }

}

From source file:it.cnr.icar.eric.client.ui.swing.graph.JBGraph.java

/**
 * Given a graph, a hub vertex in a graph and a list of spoke
 * vertices in teh graph this will modify the location of the
 * spokes so that they are laid out in a circle around the hub
 * started with first spoke at an angle of 135 degrees (left of
 * V).//from  ww w  . j  av  a  2 s .c om
 *
 * @param graph DOCUMENT ME!
 * @param hubCell DOCUMENT ME!
 * @param spokeCells DOCUMENT ME!
 */
@SuppressWarnings("unused")
public static void circleLayout(JGraph graph, GraphCell hubCell, ArrayList<Object> spokeCells) {
    if (spokeCells.size() == 0) {
        return;
    }

    GraphView graphView = graph.getView();
    CellView hubCellView = graphView.getMapping(hubCell, true);

    // Maximum width or height
    int max = 0;
    Rectangle bounds = hubCellView.getBounds();

    // Update Maximum
    if (bounds != null) {
        max = Math.max(Math.max(bounds.width, bounds.height), max);
    }

    //Now get the spokeCellViews
    ArrayList<Object> spokeCellViews = new ArrayList<Object>();

    Iterator<Object> iter = spokeCells.iterator();

    while (iter.hasNext()) {
        GraphCell spokeCell = (GraphCell) iter.next();
        CellView spokeCellView = graphView.getMapping(spokeCell, true);

        if (spokeCellView != null) {
            spokeCellViews.add(spokeCellView);
        } else {
            System.err.println("Null spokeCellView for spokeCell: " + spokeCell);
        }

        // Fetch Bounds
        //bounds = spokeCellView.getBounds();
        // Update Maximum
        //if (bounds != null)
        //   max = Math.max(Math.max(bounds.width, bounds.height), max);
    }

    Rectangle hubBounds = hubCellView.getBounds();

    // Compute Radius
    int r = (int) Math.max(((spokeCellViews.size()) * max) / Math.PI, 100);

    //System.err.println("Origin=" + hubBounds.getLocation() + " radius = " + r);
    //Set max radius to 250 pixels.
    if (r > 250) {
        r = 250;
    }

    // Compute step angle in radians
    double stepAngle = Math.toRadians(360.0 / ((double) (spokeCellViews.size())));

    //System.err.println("cellCount=" + spokeCellViews.size() + " stepAngle= " + stepAngle);
    //angle from hub to a spoke.
    double theta = Math.toRadians(90.0);

    if ((spokeCells.size() % 2) == 0) {
        theta = Math.toRadians(135.0);
    }

    // Arrange spokes in a circle around hub.
    iter = spokeCellViews.iterator();

    while (iter.hasNext()) {
        VertexView spokeCellView = (VertexView) iter.next();
        DefaultGraphCell spokeCell = (DefaultGraphCell) spokeCellView.getCell();
        Rectangle spokeBounds = spokeCellView.getBounds();

        //System.err.println("Cell=" + spokeCell.getUserObject() + " theta= " + theta);
        // Update Location
        if (spokeBounds != null) {
            int x = (hubBounds.x + (int) (r * Math.cos(theta))) - (int) ((spokeBounds.width) / 2.0);
            int y = hubBounds.y - (int) (r * Math.sin(theta)) - (int) ((spokeBounds.height) / 2.0);

            translate(spokeCellView, x - spokeBounds.x, y - spokeBounds.y);

            //spokeBounds.setLocation(x, y);
            //System.err.println("X=" + x + " Y=" + y);
        }

        theta -= stepAngle;
    }
}

From source file:com.skilrock.lms.web.scratchService.inventoryMgmt.common.SalesReturnAction.java

public String salesReturnAjax() {
    PrintWriter out;//  w w w .  ja  va  2 s  . co m
    SalesReturnHelper helper = new SalesReturnHelper();
    try {
        String html = "";
        out = getResponse().getWriter();

        String orgName = getType();
        logger.info("" + orgName);
        ArrayList gameList = null;
        if (orgId > 0) {
            gameList = helper.getGameList(orgId);
        } else {
            html = "<select class=\"option\" name=\"gameName\" id=\"gameName\"  onchange=\"saleReturnAjax('im_common_saleReturn_fetchPacknBookList.action?gameName='+(this.value).split(\'-\')[1]+'&agentOrgName=')\"><option class=\"option\" value=\"-1\">--Please Select--</option>";
            html += "</select>";
            response.setContentType("text/html");
            out.print(html);
            return null;
        }

        // session.setAttribute("GAME_LIST",characters);
        // And yes, I know creating HTML in an Action is generally very bad
        // form,
        // but I wanted to keep this exampel simple.

        html = "<select class=\"option\" name=\"gameName\" id=\"gameName\"  onchange=\"saleReturnAjax('im_common_saleReturn_fetchPacknBookList.action?gameName='+(this.value).split(\'-\')[1]+'&agentOrgName=')\"><option class=\"option\" value=\"-1\">--Please Select--</option>";

        GameBean bean = null;
        for (Iterator it = gameList.iterator(); it.hasNext();) {
            bean = (GameBean) it.next();
            html += "<option class=\"option\" value=\"" + (Integer) bean.getGameNbr() + "-" + bean.getGameName()
                    + "\">" + (Integer) bean.getGameNbr() + "-" + bean.getGameName() + "</option>";
        }
        html += "</select>";
        response.setContentType("text/html");
        out.print(html);
        return null;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:metdemo.Finance.SHNetworks.java

/**
 * This method does..// w ww.  ja  v a2s.  c o m
 *
 */
protected void moveVertices() {

    // first, organize the vertices by SocialScore Level (5 different
    // stages)
    HashMap<Integer, ArrayList<VIPVertex>> levels = stepDivide(SHNetworks.STRAIGHT_SCALE);

    // next, place the vertices according to their echelon
    Iterator levelIter = levels.keySet().iterator();
    while (levelIter.hasNext()) {
        // first, get critical objects/information for the current level
        Integer level = (Integer) levelIter.next();
        ArrayList<VIPVertex> verts = levels.get(level);
        int numVerts = verts.size();

        // next, get the dimension attributes of the current window
        Dimension winSize = m_layout.getCurrentSize();
        double winHeight = winSize.getHeight();
        double winWidth = winSize.getWidth();

        // then, place each of the vertices according window/level size
        double curY = (winHeight / 6) * level + 20;
        double xInc = winWidth / (numVerts + 1);
        double curX = xInc;
        Iterator vertIter = verts.iterator();
        while (vertIter.hasNext()) {
            VIPVertex vert = (VIPVertex) vertIter.next();
            m_layout.forceMove(vert, curX, curY);
            curX += xInc;
        }
    }
}

From source file:com.skilrock.lms.web.scratchService.inventoryMgmt.common.SalesReturnAgentAction.java

public String salesReturnAjax() {
    PrintWriter out;/*from   w  w  w.j a va2s . c  o  m*/
    SalesReturnHelper helper = new SalesReturnHelper();
    try {
        out = getResponse().getWriter();

        String orgName = getType();
        logger.info("" + orgName);
        ArrayList gameList = null;
        String html = "";
        if (orgId > 0) {

            gameList = helper.getGameList(orgId);
        } else {
            html = "<select class=\"option\" name=\"gameName\" id=\"gameName\"  onchange=\"_saleRetAgt('im_common_saleReturn_fetchPacknBookList.action?gameName='+(this.value).split(\'-\')[1]+'&agentOrgName=')\"><option class=\"option\" value=\"-1\">--Please Select--</option>";
            html += "</select>";
            response.setContentType("text/html");
            out.print(html);
            return null;
        }

        // session.setAttribute("GAME_LIST",characters);
        // And yes, I know creating HTML in an Action is generally very bad
        // form,
        // but I wanted to keep this exampel simple.

        html = "<select class=\"option\" name=\"gameName\" id=\"gameName\"  onchange=\"_saleRetAgt('im_common_saleReturn_fetchPacknBookList.action?gameName='+(this.value).split(\'-\')[1]+'&agentOrgName=')\"><option class=\"option\" value=\"-1\">--Please Select--</option>";

        GameBean bean = null;
        for (Iterator it = gameList.iterator(); it.hasNext();) {
            bean = (GameBean) it.next();
            html += "<option class=\"option\" value=\"" + (Integer) bean.getGameNbr() + "-" + bean.getGameName()
                    + "\">" + (Integer) bean.getGameNbr() + "-" + bean.getGameName() + "</option>";
        }
        html += "</select>";
        response.setContentType("text/html");
        out.print(html);
        return null;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:ec.coevolve.MultiPopCoevolutionaryEvaluatorExtra.java

protected Individual[] behaviourElite(EvolutionState state, int subpop) {
    // Generate the dataset
    ArrayList<IndividualClusterable> points = new ArrayList<IndividualClusterable>();
    if (novelChampionsOrigin == NovelChampionsOrigin.halloffame) {
        for (int i = 0; i < hallOfFame[subpop].size(); i++) {
            points.add(new IndividualClusterable(hallOfFame[subpop].get(i), i));
        }//from  w  w  w.  j  a va 2s .  c o m
    } else if (novelChampionsOrigin == NovelChampionsOrigin.archive) {
        for (ArchiveEntry ae : archives[subpop]) {
            points.add(new IndividualClusterable(ae.getIndividual(), ae.getGeneration()));
        }
    }

    // Cap -- only use the individuals with the highest fitness scores
    if (novelChampionsCap > 0) {
        // calculate the percentile
        DescriptiveStatistics ds = new DescriptiveStatistics();
        for (IndividualClusterable ic : points) {
            ds.addValue(ic.getFitness());
        }
        double percentile = ds.getPercentile(novelChampionsCap);

        // remove those below the percentile
        Iterator<IndividualClusterable> iter = points.iterator();
        while (iter.hasNext()) {
            IndividualClusterable next = iter.next();
            if (next.getFitness() < percentile) {
                iter.remove();
            }
        }
    }

    // Check if there are enough points for clustering
    if (points.size() <= novelChampions) {
        Individual[] elite = new Individual[points.size()];
        for (int i = 0; i < elite.length; i++) {
            elite[i] = points.get(i).getIndividual();
        }
        return elite;
    }

    // Do the k-means clustering
    KMeansPlusPlusClusterer<IndividualClusterable> clusterer = new KMeansPlusPlusClusterer<IndividualClusterable>(
            novelChampions, 100);
    List<CentroidCluster<IndividualClusterable>> clusters = clusterer.cluster(points);

    // Return one from each cluster
    Individual[] elite = new Individual[novelChampions];
    for (int i = 0; i < clusters.size(); i++) {
        CentroidCluster<IndividualClusterable> cluster = clusters.get(i);
        List<IndividualClusterable> clusterPoints = cluster.getPoints();
        if (novelChampionsMode == NovelChampionsMode.random) {
            int randIndex = state.random[0].nextInt(clusterPoints.size());
            elite[i] = clusterPoints.get(randIndex).getIndividual();
        } else if (novelChampionsMode == NovelChampionsMode.last) {
            IndividualClusterable oldest = null;
            for (IndividualClusterable ic : clusterPoints) {
                if (oldest == null || ic.age > oldest.age) {
                    oldest = ic;
                }
            }
            elite[i] = oldest.getIndividual();
        } else if (novelChampionsMode == NovelChampionsMode.centroid) {
            DistanceMeasure dm = clusterer.getDistanceMeasure();
            double[] centroid = cluster.getCenter().getPoint();
            IndividualClusterable closest = null;
            double closestDist = Double.MAX_VALUE;
            for (IndividualClusterable ic : clusterPoints) {
                double dist = dm.compute(centroid, ic.getPoint());
                if (dist < closestDist) {
                    closestDist = dist;
                    closest = ic;
                }
            }
            elite[i] = closest.getIndividual();
        } else if (novelChampionsMode == NovelChampionsMode.best) {
            IndividualClusterable best = null;
            float highestFit = Float.NEGATIVE_INFINITY;
            for (IndividualClusterable ic : clusterPoints) {
                if (ic.getFitness() > highestFit) {
                    best = ic;
                    highestFit = ic.getFitness();
                }
            }
            elite[i] = best.getIndividual();
        }
    }
    return elite;
}

From source file:br.gov.lexml.oaicat.LexMLOAICatalog.java

private Map internalListIdentifiers(final List<RegistroItem> ri_list, final InternalResumptionToken irt)
        throws CannotDisseminateFormatException, NoItemsMatchException {
    purge(); // clean out old resumptionTokens

    Map listIdentifiersMap = new HashMap();
    ArrayList headers = new ArrayList();
    ArrayList identifiers = new ArrayList();

    int numRows = ri_list.size();
    Iterator<RegistroItem> ri_iter = ri_list.iterator();

    if (numRows == 0) {
        throw new NoItemsMatchException();
    }/*from  ww  w.j  a  va 2 s.  co  m*/

    while (ri_iter.hasNext()) {
        String[] header = getRecordFactory().createHeader(getNativeHeader(ri_iter.next()));
        headers.add(header[0]);
        identifiers.add(header[1]);
    }

    // Verifica se temos que informar um ResumptionToken
    if (numRows >= maxListSize) {
        String resumptionId = LexMLOAICatalog.getRSName();
        String lastId = getLastId(ri_list);
        InternalResumptionToken novoIRT = new InternalResumptionToken(irt, lastId, numRows);
        resumptionTokens.put(resumptionId, novoIRT);
        listIdentifiersMap.put("resumptionMap", getResumptionMap(resumptionId, irt.total, irt.offset));
    }

    listIdentifiersMap.put("headers", headers.iterator());
    listIdentifiersMap.put("identifiers", identifiers.iterator());

    return listIdentifiersMap;

}