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:atfrogs.ox.api.OXWebDAVApi.java

/**
 * Returns a list of all OXResource objects of resources in resource group
 * with given gid.//from w  w  w .ja  va 2s  .  co m
 * You should not pass a pattern as gid. If done so you'll get the
 * list of OXResource objects of the resource group being the first search result.
 * 
 * @param gid the gid of resource group requested.
 * @return the list of OXUser objects.
 * @throws OXWebDAVApiException if an error occurs during operation.
 */
public List getResourcesOfResGroup(String gid) throws OXWebDAVApiException {
    List resourceIdList; // of String
    List resourceList; // of OXResource
    ListIterator iterator;

    if (gid == null)
        return null;

    try {
        resourceIdList = this.getResourceIdsOfResGroup(gid);
        if (resourceIdList == null)
            return null;

        resourceList = new Vector();

        iterator = resourceIdList.listIterator();

        while (iterator.hasNext()) {
            String uid;
            OXResource resource;

            uid = (String) iterator.next();
            resource = this.getOXResource(uid);
            resourceList.add(resource);
        }
    } catch (Exception exc) {
        exc.printStackTrace();
        throw new OXWebDAVApiException(exc.getMessage(), exc);
    }

    return resourceList; // note: may be empty
}

From source file:com.ibm.asset.trails.service.impl.ReconWorkspaceServiceImpl.java

@Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED)
public List<Long> findAffectedAlertUnlicensedSwList(Account pAccount, List<ReconWorkspace> plReconWorkspace,
        String psRunOn) {//  w ww  .  j  av  a2 s  . co  m
    ListIterator<ReconWorkspace> lliReconWorkspace = plReconWorkspace.listIterator();
    ReconWorkspace lrwTemp = null;
    List<Long> results;

    if (psRunOn.equalsIgnoreCase("SELECTED")) {
        List<Long> llAlertUnlicensedSwId = new ArrayList<Long>();

        while (lliReconWorkspace.hasNext()) {
            lrwTemp = lliReconWorkspace.next();
            llAlertUnlicensedSwId.add(lrwTemp.getAlertId());
        }
        results = alertDAO.findAffectedAlertList(llAlertUnlicensedSwId);
    } else {
        List<Long> llProductInfoId = new ArrayList<Long>();
        Map<Long, Long> lmProductInfoId = new HashMap<Long, Long>();

        while (lliReconWorkspace.hasNext()) {
            lrwTemp = lliReconWorkspace.next();

            if (!lmProductInfoId.containsKey(lrwTemp.getProductInfoId())) {
                llProductInfoId.add(lrwTemp.getProductInfoId());
            }
        }

        if (psRunOn.equalsIgnoreCase("ALL")) {
            results = alertDAO.findAffectedAlertList(pAccount, llProductInfoId);
        } else {
            results = alertDAO.findAffectedAlertList(pAccount, llProductInfoId, psRunOn);
        }
    }

    return results;
}

From source file:org.canova.image.recordreader.BaseImageRecordReader.java

@Override
public void initialize(InputSplit split) throws IOException {
    inputSplit = split;//from  w  ww . ja v a 2  s  .  com
    if (split instanceof FileSplit) {
        URI[] locations = split.locations();
        if (locations != null && locations.length >= 1) {
            if (locations.length > 1) {
                List<File> allFiles = new ArrayList<>();
                for (URI location : locations) {
                    File imgFile = new File(location);
                    if (!imgFile.isDirectory() && containsFormat(imgFile.getAbsolutePath()))
                        allFiles.add(imgFile);
                    if (appendLabel) {
                        File parentDir = imgFile.getParentFile();
                        String name = parentDir.getName();
                        if (!labels.contains(name))
                            labels.add(name);
                        if (pattern != null) {
                            String label = name.split(pattern)[patternPosition];
                            fileNameMap.put(imgFile.toString(), label);
                        }
                    }
                }
                iter = allFiles.listIterator();
            } else {
                File curr = new File(locations[0]);
                if (!curr.exists())
                    throw new IllegalArgumentException("Path " + curr.getAbsolutePath() + " does not exist!");
                if (curr.isDirectory())
                    iter = FileUtils.iterateFiles(curr, null, true);
                else
                    iter = Collections.singletonList(curr).listIterator();

            }
        }
        //remove the root directory
        FileSplit split1 = (FileSplit) split;
        labels.remove(split1.getRootDir());
    }

    else if (split instanceof InputStreamInputSplit) {
        InputStreamInputSplit split2 = (InputStreamInputSplit) split;
        InputStream is = split2.getIs();
        URI[] locations = split2.locations();
        INDArray load = imageLoader.asRowVector(is);
        record = RecordConverter.toRecord(load);
        for (int i = 0; i < load.length(); i++) {
            if (appendLabel) {
                Path path = Paths.get(locations[0]);
                String parent = path.getParent().toString();
                //could have been a uri
                if (parent.contains("/")) {
                    parent = parent.substring(parent.lastIndexOf('/') + 1);
                }
                int label = labels.indexOf(parent);
                if (label >= 0)
                    record.add(new DoubleWritable(labels.indexOf(parent)));
                else
                    throw new IllegalStateException("Illegal label " + parent);
            }
        }
        is.close();
    }
}

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

@Override
protected Object executeInternal() throws MojoExecutionException, MojoFailureException {
    // TODO: Deal with withVersionLabels
    DescribeApplicationVersionsRequest describeApplicationVersionsRequest = new DescribeApplicationVersionsRequest()
            .withApplicationName(applicationName);

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

    DescribeEnvironmentsRequest describeEnvironmentsRequest = new DescribeEnvironmentsRequest()
            .withApplicationName(applicationName).withEnvironmentIds(curEnv.getEnvironmentId())
            .withEnvironmentNames(curEnv.getEnvironmentName()).withIncludeDeleted(false);

    DescribeEnvironmentsResult environments = getService().describeEnvironments(describeEnvironmentsRequest);

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

    List<EnvironmentDescription> environmentList = environments.getEnvironments();

    if (environmentList.isEmpty()) {
        throw new MojoFailureException("No environments were found");
    }/*from w  ww.ja v a 2  s .  c o m*/

    EnvironmentDescription d = environmentList.get(0);

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

    Collections.reverse(appVersionList);

    if (latestVersionInstead) {
        ApplicationVersionDescription latestVersionDescription = appVersionList.get(0);

        return changeToVersion(d, latestVersionDescription);
    }

    ListIterator<ApplicationVersionDescription> versionIterator = appVersionList.listIterator();

    String curVersionLabel = d.getVersionLabel();

    while (versionIterator.hasNext()) {
        ApplicationVersionDescription versionDescription = versionIterator.next();

        String versionLabel = versionDescription.getVersionLabel();

        if (curVersionLabel.equals(versionLabel) && versionIterator.hasNext()) {
            return changeToVersion(d, versionIterator.next());
        }
    }

    throw new MojoFailureException("No previous version was found (current version: " + curVersionLabel);
}

From source file:org.apache.openjpa.kernel.exps.InMemoryExpressionFactory.java

/**
 * Filter the given list of matches, removing duplicate entries.
 *///from   w  w  w.  ja  v a2  s.c  o m
public List distinct(QueryExpressions exps, boolean fromExtent, List matches) {
    if (matches == null || matches.isEmpty())
        return matches;

    // no need to do distinct if not instructed to, or if these are
    // candidate objects from an extent
    int len = exps.projections.length;
    if ((exps.distinct & exps.DISTINCT_TRUE) == 0 || (fromExtent && len == 0))
        return matches;

    Set seen = new HashSet(matches.size());
    List distinct = null;
    Object cur;
    Object key;
    for (ListIterator li = matches.listIterator(); li.hasNext();) {
        cur = li.next();
        key = (len > 0 && cur != null) ? new ArrayKey((Object[]) cur) : cur;

        if (seen.add(key)) {
            // key hasn't been seen before; if we've created a distinct
            // list, keep adding to it
            if (distinct != null)
                distinct.add(cur);
        } else if (distinct == null) {
            // we need to copy the matches list because the distinct list
            // will be different (we've come across a non-unique key); add
            // all the elements we've skipped over so far
            distinct = new ArrayList(matches.size());
            distinct.addAll(matches.subList(0, li.previousIndex()));
        }
    }
    return (distinct == null) ? matches : distinct;
}

From source file:org.apache.fop.layoutmgr.SpaceResolver.java

/**
 * Main constructor.//from  www .j a  v  a2s  . c om
 * @param first Element list before a break (optional)
 * @param breakPoss Break possibility (optional)
 * @param second Element list after a break (or if no break possibility in vicinity)
 * @param isFirst Resolution at the beginning of a (full) element list
 * @param isLast Resolution at the end of a (full) element list
 */
private SpaceResolver(List first, BreakElement breakPoss, List second, boolean isFirst, boolean isLast) {
    this.isFirst = isFirst;
    this.isLast = isLast;
    //Create combined no-break list
    int c = 0;
    if (first != null) {
        c += first.size();
    }
    if (second != null) {
        c += second.size();
    }
    noBreak = new UnresolvedListElementWithLength[c];
    noBreakLengths = new MinOptMax[c];
    int i = 0;
    ListIterator iter;
    if (first != null) {
        iter = first.listIterator();
        while (iter.hasNext()) {
            noBreak[i] = (UnresolvedListElementWithLength) iter.next();
            noBreakLengths[i] = noBreak[i].getLength();
            i++;
        }
    }
    if (second != null) {
        iter = second.listIterator();
        while (iter.hasNext()) {
            noBreak[i] = (UnresolvedListElementWithLength) iter.next();
            noBreakLengths[i] = noBreak[i].getLength();
            i++;
        }
    }

    //Add pending elements from higher level FOs
    if (breakPoss != null) {
        if (breakPoss.getPendingAfterMarks() != null) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("    adding pending before break: " + breakPoss.getPendingAfterMarks());
            }
            first.addAll(0, breakPoss.getPendingAfterMarks());
        }
        if (breakPoss.getPendingBeforeMarks() != null) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("    adding pending after break: " + breakPoss.getPendingBeforeMarks());
            }
            second.addAll(0, breakPoss.getPendingBeforeMarks());
        }
    }
    if (LOG.isTraceEnabled()) {
        LOG.trace("before: " + first);
        LOG.trace("  break: " + breakPoss);
        LOG.trace("after: " + second);
        LOG.trace("NO-BREAK: " + toString(noBreak, noBreakLengths));
    }

    if (first != null) {
        firstPart = new UnresolvedListElementWithLength[first.size()];
        firstPartLengths = new MinOptMax[firstPart.length];
        first.toArray(firstPart);
        for (i = 0; i < firstPart.length; i++) {
            firstPartLengths[i] = firstPart[i].getLength();
        }
    }
    this.breakPoss = breakPoss;
    if (second != null) {
        secondPart = new UnresolvedListElementWithLength[second.size()];
        secondPartLengths = new MinOptMax[secondPart.length];
        second.toArray(secondPart);
        for (i = 0; i < secondPart.length; i++) {
            secondPartLengths[i] = secondPart[i].getLength();
        }
    }
    resolve();
}

From source file:com.aliyun.odps.conf.Configuration.java

@SuppressWarnings("rawtypes")
private void toString(List resources, StringBuffer sb) {
    ListIterator i = resources.listIterator();
    while (i.hasNext()) {
        if (i.nextIndex() != 0) {
            sb.append(", ");
        }/*from  w w w. jav  a2s.c o m*/
        sb.append(i.next());
    }
}

From source file:edu.iu.daal_linreg.LinRegDaalCollectiveMapper.java

private NumericTable getNumericTableHDFS(DaalContext daal_Context, Configuration conf, String inputFiles,
        int vectorSize, int numRows) throws IOException {
    Path inputFilePaths = new Path(inputFiles);
    List<String> inputFileList = new LinkedList<>();

    try {/*w  ww  . j a  v a 2  s  . co  m*/
        FileSystem fs = inputFilePaths.getFileSystem(conf);
        RemoteIterator<LocatedFileStatus> iterator = fs.listFiles(inputFilePaths, true);

        while (iterator.hasNext()) {
            String name = iterator.next().getPath().toUri().toString();
            inputFileList.add(name);
        }

    } catch (IOException e) {
        LOG.error("Fail to get test files", e);
    }
    int dataSize = vectorSize * numRows;
    // float[] data = new float[dataSize];
    double[] data = new double[dataSize];
    long[] dims = { numRows, vectorSize };
    int index = 0;

    FSDataInputStream in = null;

    //loop over all the files in the list
    ListIterator<String> file_itr = inputFileList.listIterator();
    while (file_itr.hasNext()) {
        String file_name = file_itr.next();
        LOG.info("read in file name: " + file_name);

        Path file_path = new Path(file_name);
        try {

            FileSystem fs = file_path.getFileSystem(conf);
            in = fs.open(file_path);

        } catch (Exception e) {
            LOG.error("Fail to open file " + e.toString());
            return null;
        }

        //read file content
        while (true) {
            String line = in.readLine();
            if (line == null)
                break;

            String[] lineData = line.split(",");

            for (int t = 0; t < vectorSize; t++) {
                if (index < dataSize) {
                    // data[index] = Float.parseFloat(lineData[t]);
                    data[index] = Double.parseDouble(lineData[t]);
                    index++;
                } else {
                    LOG.error("Incorrect size of file: dataSize: " + dataSize + "; index val: " + index);
                    return null;
                }

            }
        }

        in.close();

    }

    if (index != dataSize) {
        LOG.error("Incorrect total size of file: dataSize: " + dataSize + "; index val: " + index);
        return null;
    }
    //debug check the vals of data
    // for(int p=0;p<60;p++)
    //     LOG.info("data at: " + p + " is: " + data[p]);

    NumericTable predictionData = new HomogenNumericTable(daal_Context, data, vectorSize, numRows);
    return predictionData;

}

From source file:org.canova.api.records.reader.impl.FileRecordReader.java

protected void doInitialize(InputSplit split) {
    URI[] locations = split.locations();

    if (locations != null && locations.length >= 1) {
        if (locations.length > 1) {
            List<File> allFiles = new ArrayList<>();
            for (URI location : locations) {
                File iter = new File(location);
                if (labels == null && appendLabel) {
                    //root dir relative to example where the label is the parent directory and the root directory is
                    //recursively the parent of that
                    File parent = iter.getParentFile().getParentFile();
                    //calculate the labels relative to the parent file
                    labels = new ArrayList<>();

                    for (File labelDir : parent.listFiles())
                        labels.add(labelDir.getName());
                }/*from  w  w w  .  java2  s  . c  o m*/

                if (iter.isDirectory()) {
                    Iterator<File> allFiles2 = FileUtils.iterateFiles(iter, null, true);
                    while (allFiles2.hasNext())
                        allFiles.add(allFiles2.next());
                }

                else
                    allFiles.add(iter);
            }

            iter = allFiles.listIterator();
        } else {
            File curr = new File(locations[0]);
            if (curr.isDirectory())
                iter = FileUtils.iterateFiles(curr, null, true);
            else
                iter = Collections.singletonList(curr).iterator();
        }
    }

}

From source file:org.apache.fop.layoutmgr.BlockStackingLayoutManager.java

/** {@inheritDoc} */
@Override// w  w  w .  j a  v  a  2  s .co  m
public List getChangedKnuthElements(List oldList, int alignment) {
    ListIterator<KnuthElement> oldListIterator = oldList.listIterator();
    KnuthElement currElement = null;
    KnuthElement prevElement = null;
    List<KnuthElement> returnedList = new LinkedList<KnuthElement>();
    List<KnuthElement> returnList = new LinkedList<KnuthElement>();
    int fromIndex = 0;

    // "unwrap" the Positions stored in the elements
    KnuthElement oldElement;
    while (oldListIterator.hasNext()) {
        oldElement = oldListIterator.next();
        assert oldElement.getPosition() != null;
        Position innerPosition = oldElement.getPosition().getPosition();
        if (innerPosition != null) {
            // oldElement was created by a descendant
            oldElement.setPosition(innerPosition);
        } else {
            // oldElement was created by this LM:
            // modify its position in order to recognize it was not created
            // by a child
            oldElement.setPosition(new Position(this));
        }
    }

    // create the iterator
    ListIterator<KnuthElement> workListIterator = oldList.listIterator();
    while (workListIterator.hasNext()) {
        currElement = workListIterator.next();
        if (prevElement != null && prevElement.getLayoutManager() != currElement.getLayoutManager()) {
            // prevElement is the last element generated by the same LM
            BlockLevelLayoutManager prevLM = (BlockLevelLayoutManager) prevElement.getLayoutManager();
            BlockLevelLayoutManager currLM = (BlockLevelLayoutManager) currElement.getLayoutManager();
            boolean somethingAdded = false;
            if (prevLM != this) {
                returnedList.addAll(prevLM.getChangedKnuthElements(
                        oldList.subList(fromIndex, workListIterator.previousIndex()), alignment));
                somethingAdded = true;
            } else {
                // do nothing
            }
            fromIndex = workListIterator.previousIndex();

            /*
             * TODO: why are KnuthPenalties added here,
             *       while in getNextKE they were changed to BreakElements?
             */
            // there is another block after this one
            if (somethingAdded && (this.mustKeepTogether() || prevLM.mustKeepWithNext()
                    || currLM.mustKeepWithPrevious())) {
                // add an infinite penalty to forbid a break between blocks
                returnedList.add(makeZeroWidthPenalty(KnuthPenalty.INFINITE));
            } else if (somethingAdded && !ListUtil.getLast(returnedList).isGlue()) {
                // add a null penalty to allow a break between blocks
                returnedList.add(makeZeroWidthPenalty(KnuthPenalty.INFINITE));
            }
        }
        prevElement = currElement;
    }
    if (currElement != null) {
        LayoutManager currLM = currElement.getLayoutManager();
        if (currLM != this) {
            returnedList.addAll(
                    currLM.getChangedKnuthElements(oldList.subList(fromIndex, oldList.size()), alignment));
        } else {
            // there are no more elements to add
            // remove the last penalty added to returnedList
            if (!returnedList.isEmpty()) {
                ListUtil.removeLast(returnedList);
            }
        }
    }

    // append elements representing space-before
    boolean spaceBeforeIsConditional = true;
    if (fobj instanceof org.apache.fop.fo.flow.Block) {
        spaceBeforeIsConditional = getSpaceBeforeProperty().isDiscard();
    }
    if (adjustedSpaceBefore != 0) {
        if (!spaceBeforeIsConditional) {
            // add elements to prevent the glue to be discarded
            returnList.add(makeZeroWidthBox());
            returnList.add(makeZeroWidthPenalty(KnuthPenalty.INFINITE));
        }

        returnList.add(makeSpaceAdjustmentGlue(adjustedSpaceBefore, Adjustment.SPACE_BEFORE_ADJUSTMENT, false));
    }

    // "wrap" the Position stored in each element of returnedList
    // and add elements to returnList
    for (KnuthElement el : returnedList) {
        el.setPosition(new NonLeafPosition(this, el.getPosition()));
        returnList.add(el);
    }

    // append elements representing space-after
    boolean spaceAfterIsConditional = true;
    if (fobj instanceof org.apache.fop.fo.flow.Block) {
        spaceAfterIsConditional = getSpaceAfterProperty().isDiscard();
    }
    if (adjustedSpaceAfter != 0) {
        if (!spaceAfterIsConditional) {
            returnList.add(makeZeroWidthPenalty(KnuthPenalty.INFINITE));
        }

        returnList.add(makeSpaceAdjustmentGlue(adjustedSpaceAfter, Adjustment.SPACE_AFTER_ADJUSTMENT,
                spaceAfterIsConditional));

        if (!spaceAfterIsConditional) {
            returnList.add(makeZeroWidthBox());
        }
    }

    return returnList;
}