Example usage for java.util List listIterator

List of usage examples for java.util List listIterator

Introduction

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

Prototype

ListIterator<E> listIterator();

Source Link

Document

Returns a list iterator over the elements in this list (in proper sequence).

Usage

From source file:com.danielme.muspyforandroid.services.MusicBrainzClient.java

/**
 *  Label, country, format and mbid of the concrete release
 * @since 1.2//from  w w  w  . ja v  a  2s.  c o m
 */
public void loadReleaseConcrete(Release release) {
    if (releases.get(release.getMbid()) != null) {
        Release temp = releases.get(release.getMbid());
        release.setCountry(temp.getCountry());
        release.setFormat(temp.getFormat());
        release.setLabel(temp.getLabel());
        release.setTrackCount(temp.getTrackCount());
        release.setMbidConcreteRelease(temp.getMbidConcreteRelease());
    } else {
        String url = String.format(Constants.MBRAINZ.URL_RELEASES, URLEncoder.encode(release.getMbid()));

        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader(Constants.CONTENT_TYPE, Constants.TYPE_JSON);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            //sometimes we receive HTTP 504
            if (statusLine != null && statusLine.getStatusCode() == MBGatewayTimeOutException.STATUS_CODE) {
                throw new MBGatewayTimeOutException();
            }
            String responseString = EntityUtils.toString(response.getEntity());
            JSONObject responseJSON = new JSONObject(responseString);
            JSONArray jsonArray = responseJSON.getJSONArray(Constants.MBRAINZ.RELEASES);
            String date = getReleaseDate(release);
            List<JSONObject> candidates = new LinkedList<JSONObject>();
            for (int i = 0; i < jsonArray.length(); i++) {
                if (jsonArray.getJSONObject(i).getString("date").equals(date)) {
                    candidates.add(jsonArray.getJSONObject(i));
                }

            }

            ListIterator<JSONObject> listIterator = candidates.listIterator();
            boolean found = false;
            JSONObject releaseJson = null;
            String country = null;

            //USA
            while (listIterator.hasNext() && !found) {
                releaseJson = listIterator.next();
                country = releaseJson.getString("country");
                if (country.equals("US")) {
                    found = true;
                    loadDetails(releaseJson, release);
                }
            }
            //UK
            if (!found) {
                listIterator = candidates.listIterator();
                while (listIterator.hasNext() && !found) {
                    releaseJson = listIterator.next();
                    country = releaseJson.getString("country");
                    if (country.equals("GB")) {
                        found = true;
                        loadDetails(releaseJson, release);
                    }
                }
            }

            //the first release
            if (!found && !candidates.isEmpty()) {
                loadDetails(jsonArray.getJSONObject(0), release);
            }

        } catch (Exception ex) {
            //this feature is not critical
            Log.w(this.getClass().toString(), ex.getMessage());
        }
        releases.put(release.getMbid(), release);
    }
}

From source file:org.jfree.data.statistics.DefaultMultiValueCategoryDataset.java

/**
 * Adds a list of values to the dataset (<code>null</code> and Double.NaN
 * items are automatically removed) and sends a {@link DatasetChangeEvent}
 * to all registered listeners./*from ww  w.  jav  a  2 s  . c o m*/
 *
 * @param values  a list of values (<code>null</code> not permitted).
 * @param rowKey  the row key (<code>null</code> not permitted).
 * @param columnKey  the column key (<code>null</code> not permitted).
 */
public void add(List values, Comparable rowKey, Comparable columnKey) {

    ParamChecks.nullNotPermitted(values, "values");
    ParamChecks.nullNotPermitted(rowKey, "rowKey");
    ParamChecks.nullNotPermitted(columnKey, "columnKey");
    List vlist = new ArrayList(values.size());
    Iterator iterator = values.listIterator();
    while (iterator.hasNext()) {
        Object obj = iterator.next();
        if (obj instanceof Number) {
            Number n = (Number) obj;
            double v = n.doubleValue();
            if (!Double.isNaN(v)) {
                vlist.add(n);
            }
        }
    }
    Collections.sort(vlist);
    this.data.addObject(vlist, rowKey, columnKey);

    if (vlist.size() > 0) {
        double maxval = Double.NEGATIVE_INFINITY;
        double minval = Double.POSITIVE_INFINITY;
        for (int i = 0; i < vlist.size(); i++) {
            Number n = (Number) vlist.get(i);
            double v = n.doubleValue();
            minval = Math.min(minval, v);
            maxval = Math.max(maxval, v);
        }

        // update the cached range values...
        if (this.maximumRangeValue == null) {
            this.maximumRangeValue = new Double(maxval);
        } else if (maxval > this.maximumRangeValue.doubleValue()) {
            this.maximumRangeValue = new Double(maxval);
        }

        if (this.minimumRangeValue == null) {
            this.minimumRangeValue = new Double(minval);
        } else if (minval < this.minimumRangeValue.doubleValue()) {
            this.minimumRangeValue = new Double(minval);
        }
        this.rangeBounds = new Range(this.minimumRangeValue.doubleValue(),
                this.maximumRangeValue.doubleValue());
    }

    fireDatasetChanged();
}

From source file:hudson.util.spring.BeanBuilder.java

/**
 * Checks whether there are any runtime refs inside the list and
 * converts it to a ManagedList if necessary
 *
 * @param value The object that represents the list
 * @return Either a new list or a managed one
 *//*w w  w .  j a va  2  s  .  co  m*/
private Object manageListIfNecessary(Object value) {
    List list = (List) value;
    boolean containsRuntimeRefs = false;
    for (ListIterator i = list.listIterator(); i.hasNext();) {
        Object e = i.next();
        if (e instanceof RuntimeBeanReference) {
            containsRuntimeRefs = true;
        }
        if (e instanceof BeanConfiguration) {
            BeanConfiguration c = (BeanConfiguration) e;
            i.set(c.getBeanDefinition());
            containsRuntimeRefs = true;
        }
    }
    if (containsRuntimeRefs) {
        List tmp = new ManagedList();
        tmp.addAll((List) value);
        value = tmp;
    }
    return value;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.json.GetEntitiesByVClassContinuation.java

@Override
protected JSONArray process() throws ServletException {
    log.debug("in getEntitiesByVClassContinuation()");
    String resKey = vreq.getParameter("resultKey");
    if (resKey == null)
        throw new ServletException("Could not get resultKey");
    HttpSession session = vreq.getSession();
    if (session == null)
        throw new ServletException("there is no session to get the pervious results from");
    @SuppressWarnings("unchecked")
    List<Individual> entsInVClass = (List<Individual>) session.getAttribute(resKey);
    if (entsInVClass == null)
        throw new ServletException("Could not find List<Individual> for resultKey " + resKey);

    List<Individual> entsToReturn = new ArrayList<Individual>(REPLY_SIZE);
    boolean more = false;
    int count = 0;
    /* we have a large number of items to send back so we need to stash the list in the session scope */
    if (entsInVClass.size() > REPLY_SIZE) {
        more = true;/* w ww.j a  v a 2 s. com*/
        ListIterator<Individual> entsFromVclass = entsInVClass.listIterator();
        while (entsFromVclass.hasNext() && count <= REPLY_SIZE) {
            entsToReturn.add(entsFromVclass.next());
            entsFromVclass.remove();
            count++;
        }
        if (log.isDebugEnabled())
            log.debug("getEntitiesByVClassContinuation(): Creating reply with continue token,"
                    + " sending in this reply: " + count + ", remaing to send: " + entsInVClass.size());
    } else {
        //send out reply with no continuation
        entsToReturn = entsInVClass;
        count = entsToReturn.size();
        session.removeAttribute(resKey);
        if (log.isDebugEnabled())
            log.debug("getEntitiesByVClassContinuation(): sending " + count + " Ind without continue token");
    }

    //put all the entities on the JSON array
    JSONArray ja = individualsToJson(entsToReturn);

    //put the responseGroup number on the end of the JSON array
    if (more) {
        try {
            JSONObject obj = new JSONObject();
            obj.put("resultGroup", "true");
            obj.put("size", count);

            StringBuffer nextUrlStr = vreq.getRequestURL();
            nextUrlStr.append("?").append("getEntitiesByVClass").append("=1&").append("resultKey=")
                    .append(resKey);
            obj.put("nextUrl", nextUrlStr.toString());

            ja.put(obj);
        } catch (JSONException je) {
            throw new ServletException(je.getMessage());
        }
    }
    log.debug("done with getEntitiesByVClassContinuation()");
    return ja;
}

From source file:com.oneops.daq.dao.LogDao.java

/**
 * Gets the available log types./*  w  w w .  j a  v  a2 s  .  c om*/
 *
 * @param ciList the ci list
 * @return the available log types
 */
public String getAvailableLogTypes(String[] ciList) {

    StringBuilder jsonOut = new StringBuilder("");
    try {
        long startTime = System.currentTimeMillis();

        MultigetSliceQuery<byte[], String, String> multigetSliceQuery = HFactory
                .createMultigetSliceQuery(keyspace, bytesSerializer, stringSerializer, stringSerializer);
        multigetSliceQuery.setColumnFamily(CI_LOG_TYPE_CF);
        List<byte[]> keys = new ArrayList<byte[]>();
        for (int i = 0; i < ciList.length; i++) {
            String ciId = ciList[i];
            keys.add(ciId.getBytes());

        }
        multigetSliceQuery.setKeys(keys);
        multigetSliceQuery.setRange("", "", false, 100000);

        long cassStart = System.currentTimeMillis();

        QueryResult<Rows<byte[], String, String>> result = multigetSliceQuery.execute();
        Rows<byte[], String, String> rows = result.get();

        long cassEnd = System.currentTimeMillis();
        long cassDuration = cassEnd - cassStart;

        // put the by-metric results into 1 csv-like table (time,metric1,metric2,etc) 
        // ... should find faster way to do this, but still 10x faster than gwt DataTable serialization
        int rowCount = 0;
        for (Row<byte[], String, String> row : rows) {

            if (rowCount > 0) {
                jsonOut.append(",");
            }
            jsonOut.append("{\"ci_id\":" + new String(row.getKey()) + ", \"metrics\":[");
            List<HColumn<String, String>> cols = row.getColumnSlice().getColumns();
            Iterator<HColumn<String, String>> listIter = cols.listIterator();
            int colCount = 0;
            while (listIter.hasNext()) {
                HColumn<String, String> c = (HColumn<String, String>) listIter.next();
                if (colCount > 0) {
                    jsonOut.append(",");
                }
                String dsAttributes = c.getValue();
                String[] dsAtrributeParts = dsAttributes.split(":");
                String unit = dsAtrributeParts[0];
                String min = dsAtrributeParts[1];
                String max = dsAtrributeParts[2];
                // nan is not json compliant so using 'null'
                if (min.length() == 0) {
                    min = "null";
                }
                if (max.length() == 0) {
                    max = "null";
                }
                // make json compliant null
                if (unit.equalsIgnoreCase("")) {
                    unit = "null";
                } else {
                    unit = "\"" + unit + "\"";
                }
                jsonOut.append("{\"metricDs\":\"" + c.getName() + "\",\"unit\":" + unit + "\",\"min\":" + min
                        + ",\"max\":" + max + "}");
                colCount++;
            }
            jsonOut.append("]}\n");
            rowCount++;
        }

        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        logger.debug("getAvailableMetrics took: " + duration + " ms (cass query:" + cassDuration
                + " ms) returning: " + rowCount + " rows of ci metric lists");

    } catch (HectorException he) {
        he.printStackTrace();
    }

    return jsonOut.toString();
}

From source file:br.com.ingenieux.mojo.beanstalk.version.CleanPreviousVersionsMojo.java

@Override
protected Object executeInternal() throws MojoExecutionException, MojoFailureException {
    boolean bVersionsToKeepDefined = (null != versionsToKeep);
    boolean bDaysToKeepDefined = (null != daysToKeep);

    if (!(bVersionsToKeepDefined ^ bDaysToKeepDefined)) {
        throw new MojoFailureException("Declare either versionsToKeep or daysToKeep, but not both nor none!");
    }/*from w w w .  java 2 s . c o m*/

    DescribeApplicationVersionsRequest describeApplicationVersionsRequest = new DescribeApplicationVersionsRequest()
            .withApplicationName(applicationName);

    DescribeApplicationVersionsResult appVersions = getService()
            .describeApplicationVersions(describeApplicationVersionsRequest);

    DescribeEnvironmentsResult environments = getService().describeEnvironments();

    List<ApplicationVersionDescription> appVersionList = new ArrayList<ApplicationVersionDescription>(
            appVersions.getApplicationVersions());

    deletedVersionsCount = 0;

    for (EnvironmentDescription d : environments.getEnvironments()) {
        boolean bActiveEnvironment = (d.getStatus().equals("Running") || d.getStatus().equals("Launching")
                || d.getStatus().equals("Ready"));

        for (ListIterator<ApplicationVersionDescription> appVersionIterator = appVersionList
                .listIterator(); appVersionIterator.hasNext();) {
            ApplicationVersionDescription appVersion = appVersionIterator.next();

            boolean bMatchesVersion = appVersion.getVersionLabel().equals(d.getVersionLabel());

            if (bActiveEnvironment && bMatchesVersion) {
                getLog().info("VersionLabel " + appVersion.getVersionLabel() + " is bound to environment "
                        + d.getEnvironmentName() + " - Skipping it");

                appVersionIterator.remove();
            }
        }
    }

    filterAppVersionListByVersionLabelPattern(appVersionList, cleanFilter);

    Collections.sort(appVersionList, new Comparator<ApplicationVersionDescription>() {
        @Override
        public int compare(ApplicationVersionDescription o1, ApplicationVersionDescription o2) {
            return new CompareToBuilder().append(o1.getDateUpdated(), o2.getDateUpdated()).toComparison();
        }
    });

    if (bDaysToKeepDefined) {
        Date now = new Date();

        for (ApplicationVersionDescription d : appVersionList) {
            long delta = now.getTime() - d.getDateUpdated().getTime();

            delta /= 1000;
            delta /= 86400;

            boolean shouldDeleteP = (delta > daysToKeep);

            if (getLog().isDebugEnabled()) {
                getLog().debug("Version " + d.getVersionLabel() + " was from " + delta
                        + " days ago. Should we delete? " + shouldDeleteP);
            }

            if (shouldDeleteP) {
                deleteVersion(d);
            }
        }
    } else {
        while (appVersionList.size() > versionsToKeep) {
            deleteVersion(appVersionList.remove(0));
        }
    }

    getLog().info("Deleted " + deletedVersionsCount + " versions.");

    return null;
}

From source file:com.oneops.daq.dao.LogDao.java

/**
 * Gets the log data by action or workorder.
 *
 * @param req the req// w  ww.  ja v a2  s.c o m
 * @return the log data by action or workorder
 */
public GetLogDataByIdResponse getLogDataByActionOrWorkorder(GetLogDataByIdRequest req) {
    GetLogDataByIdResponse resp = new GetLogDataByIdResponse(req);

    int maxColumns = 10000;

    List<LogData> logData = new ArrayList<LogData>();
    try {
        long startTime = System.currentTimeMillis();

        MultigetSliceQuery<byte[], com.eaio.uuid.UUID, String> multigetSliceQuery = HFactory
                .createMultigetSliceQuery(keyspace, bytesSerializer, timeuuidSerializer, stringSerializer);
        multigetSliceQuery.setColumnFamily(LOG_ACTION_WORKORDER_MAP_CF);
        List<byte[]> keys = new ArrayList<byte[]>();

        //          keys.add(new Long(req.getId()).toString().getBytes());
        keys.add(Long.valueOf(req.getId()).toString().getBytes());

        multigetSliceQuery.setKeys(keys);
        UUID startUuid = new UUID(0, UUIDGen.getClockSeqAndNode());
        UUID endUuid = new UUID(99992313900691274L, UUIDGen.getClockSeqAndNode());
        multigetSliceQuery.setRange(startUuid, endUuid, false, maxColumns);

        QueryResult<Rows<byte[], UUID, String>> result = multigetSliceQuery.execute();
        Rows<byte[], UUID, String> rows = result.get();

        long endTime = System.currentTimeMillis();
        long cassDuration = endTime - startTime;

        List<UUID> columnList = new ArrayList<UUID>();
        String dataRowKey = null;
        for (Row<byte[], UUID, String> row : rows) {
            List<HColumn<UUID, String>> cols = row.getColumnSlice().getColumns();
            Iterator<HColumn<UUID, String>> listIter = cols.listIterator();
            while (listIter.hasNext()) {
                HColumn<UUID, String> c = (HColumn<UUID, String>) listIter.next();
                columnList.add(c.getName());
                if (dataRowKey == null) {
                    dataRowKey = c.getValue();
                }
            }
        }

        if (dataRowKey == null) {
            logger.debug("no results for id:" + req.getId());
            return resp;
        }

        SliceQuery<byte[], com.eaio.uuid.UUID, String> sliceQuery = HFactory.createSliceQuery(keyspace,
                bytesSerializer, timeuuidSerializer, stringSerializer);
        sliceQuery.setColumnFamily(LOG_DATA_CF).setKey(dataRowKey.getBytes());

        // setColumnNames needs UUID[]
        UUID[] columns = new UUID[columnList.size()];
        int i = 0;
        for (UUID col : columnList) {
            columns[i] = col;
            i++;
        }
        sliceQuery.setColumnNames(columns);

        QueryResult<ColumnSlice<UUID, String>> res = sliceQuery.execute();
        ColumnSlice<UUID, String> columnSlice = res.get();

        String[] keyParts = dataRowKey.split(":");
        String logClass = keyParts[1];
        String level = keyParts[2];

        int colCount = 0;
        List<HColumn<UUID, String>> cols = columnSlice.getColumns();
        Iterator<HColumn<UUID, String>> listIter = cols.listIterator();
        while (listIter.hasNext()) {
            HColumn<UUID, String> c = (HColumn<UUID, String>) listIter.next();
            LogData logEntry = new LogData();
            UUID uuid = c.getName();
            logEntry.setTimestamp(uuid.getTime());
            logEntry.setMessage(c.getValue());
            logEntry.setLevel(level);
            logEntry.setLogClass(logClass);
            logData.add(logEntry);
            colCount++;
        }
        resp.setLogData(logData);

        endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        logger.debug("getLogData took: " + duration + " ms (cass query:" + cassDuration + " ms) returning:"
                + colCount + " rows");

    } catch (HectorException he) {
        he.printStackTrace();
    }

    return resp;
}

From source file:com.projity.pm.graphic.model.cache.ViewNodeModelCache.java

private List convertToBase(List gnodes) {
    if (gnodes == null)
        return null;
    for (ListIterator i = gnodes.listIterator(); i.hasNext();)
        i.set(((GraphicNode) i.next()).getNode());
    return gnodes;
}

From source file:amp.lib.io.db.Database.java

private void validataMetadata(List<MetaObject> metadata) {
    for (ListIterator<MetaObject> i = metadata.listIterator(); i.hasNext();) {
        MetaObject mo = i.next();//w w  w  . j  av a2s .c  o  m
        boolean valid = true;
        if (mo instanceof MetaTable) {
            valid = validateTable((MetaTable) mo);
        } else if (mo instanceof MetaView) {
            valid = validateView((MetaView) mo);
        }
        mo.setValid(valid);
    }

}

From source file:com.hortonworks.atlas.cli.AtlasCLI.java

/**
 * This method lists all types in the Atlas
 *//* w  w  w . ja v a2s. c  o  m*/
public void listTypes() {

    List<String> lt;
    try {
        lt = aClient.listTypes();

        ListIterator<String> lstItr = lt.listIterator();

        System.out.println("Listing all Types in atlas: ");

        while (lstItr.hasNext()) {

            System.out.println(lstItr.next());

        }
    } catch (AtlasServiceException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}