Example usage for java.util ListIterator next

List of usage examples for java.util ListIterator next

Introduction

In this page you can find the example usage for java.util ListIterator next.

Prototype

E next();

Source Link

Document

Returns the next element in the list and advances the cursor position.

Usage

From source file:com.projity.algorithm.buffer.GroupedCalculatedValues.java

public static GroupedCalculatedValues union(GroupedCalculatedValues values1, GroupedCalculatedValues values2) {
    GroupedCalculatedValues c1, c2;//from  w w w  .  j  av  a2s. c  om
    if (values1.size() >= values2.size()) {
        c1 = values1;
        c2 = values2;
    } else {
        c1 = values2;
        c2 = values1;
    }
    GroupedCalculatedValues c = new GroupedCalculatedValues();
    ListIterator i1 = c1.values.listIterator();
    ListIterator i2 = c2.values.listIterator();
    Point p1, p2 = null;
    while (i1.hasNext()) {
        p1 = (Point) i1.next();
        while (i2.hasNext()) {
            p2 = (Point) i2.next();
            if (p2.date < p1.date) {
                c.values.add(p2);
            } else if (p2.date > p1.date) {
                i2.previous();
                break;
            } else
                break;
        }
        if (p2 != null && p1.date == p2.date)
            c.values.add(new Point(p1.date, p1.value + p2.value));
        else
            c.values.add(p1);
    }
    while (i2.hasNext()) {
        c.values.add((Point) i2.next());
    }
    return c;
}

From source file:exm.stc.ic.ICUtil.java

public static void removeDuplicates(List<Var> varList) {
    ListIterator<Var> it = varList.listIterator();
    HashSet<Var> alreadySeen = new HashSet<Var>();
    while (it.hasNext()) {
        Var v = it.next();
        if (alreadySeen.contains(v)) {
            it.remove();//from w  w w .  j  a v  a 2  s  .c  om
        } else {
            alreadySeen.add(v);
        }
    }
}

From source file:com.cinchapi.concourse.lang.Parser.java

/**
 * Go through a list of symbols and group the expressions together in a
 * {@link Expression} object.//w  w  w  .jav  a 2s. co m
 * 
 * @param symbols
 * @return the expression
 */
protected static List<Symbol> groupExpressions(List<Symbol> symbols) { // visible
                                                                       // for
                                                                       // testing
    try {
        List<Symbol> grouped = Lists.newArrayList();
        ListIterator<Symbol> it = symbols.listIterator();
        while (it.hasNext()) {
            Symbol symbol = it.next();
            if (symbol instanceof KeySymbol) {
                // NOTE: We are assuming that the list of symbols is well
                // formed, and, as such, the next elements will be an
                // operator and one or more symbols. If this is not the
                // case, this method will throw a ClassCastException
                OperatorSymbol operator = (OperatorSymbol) it.next();
                ValueSymbol value = (ValueSymbol) it.next();
                Expression expression;
                if (operator.getOperator() == Operator.BETWEEN) {
                    ValueSymbol value2 = (ValueSymbol) it.next();
                    expression = Expression.create((KeySymbol) symbol, operator, value, value2);
                } else {
                    expression = Expression.create((KeySymbol) symbol, operator, value);
                }
                grouped.add(expression);
            } else if (symbol instanceof TimestampSymbol) { // Add the
                                                            // timestamp to the
                                                            // previously
                                                            // generated
                                                            // Expression
                ((Expression) Iterables.getLast(grouped)).setTimestamp((TimestampSymbol) symbol);
            } else {
                grouped.add(symbol);
            }
        }
        return grouped;
    } catch (ClassCastException e) {
        throw new SyntaxException(e.getMessage());
    }
}

From source file:Alias2.java

public static void verify(List output, List expected) {
    verifyLength(output.size(), expected.size(), Test.EXACT);
    if (!expected.equals(output)) {
        //find the line of mismatch
        ListIterator it1 = expected.listIterator();
        ListIterator it2 = output.listIterator();
        while (it1.hasNext() && it2.hasNext() && it1.next().equals(it2.next()))
            ;//from w ww. j  a v a 2s  . c  om
        throw new LineMismatchException(it1.nextIndex(), it1.previous().toString(), it2.previous().toString());
    }
}

From source file:com.worldline.easycukes.commons.helpers.JSONHelper.java

/**
 * Returns <b>true</b> if JSON array a1 is equals to JSON array a2.
 *
 * @param a1 a {@link JSONArray} containing some JSON data
 * @param a2 another {@link JSONArray} containing some JSON data
 * @return true if the json arrays are equals
 *///w  ww .java  2 s. c  o  m
public static boolean equals(@NonNull JSONArray a1, @NonNull JSONArray a2) {
    if (a1 == a2)
        return true;
    if (a1.size() != a2.size())
        return false;

    final ListIterator i1 = a1.listIterator();
    ListIterator i2;
    boolean found = false;
    while (i1.hasNext()) {
        final Object o1 = i1.next();
        found = false;
        i2 = a2.listIterator();
        if (o1 instanceof JSONObject)
            while (i2.hasNext()) {
                final Object o2 = i2.next();
                if (!(o2 instanceof JSONObject))
                    return false;
                if (equals((JSONObject) o1, (JSONObject) o2))
                    found = true;
            }
        else if (o1 instanceof JSONArray)
            while (i2.hasNext()) {
                final Object o2 = i2.next();
                if (!(o2 instanceof JSONArray))
                    return false;
                if (equals((JSONArray) o1, (JSONArray) o2))
                    found = true;
            }
        else
            while (i2.hasNext()) {
                final Object o2 = i2.next();
                if (o1.equals(o2))
                    found = true;
            }
        if (!found)
            return false;
    }
    return true;
}

From source file:com.cloud.utils.UriUtils.java

public static String getUpdateUri(String url, boolean encrypt) {
    String updatedPath = null;/*from   w  w w. j a  v a2 s .c o m*/
    try {
        String query = URIUtil.getQuery(url);
        URIBuilder builder = new URIBuilder(url);
        builder.removeQuery();

        StringBuilder updatedQuery = new StringBuilder();
        List<NameValuePair> queryParams = getUserDetails(query);
        ListIterator<NameValuePair> iterator = queryParams.listIterator();
        while (iterator.hasNext()) {
            NameValuePair param = iterator.next();
            String value = null;
            if ("password".equalsIgnoreCase(param.getName()) && param.getValue() != null) {
                value = encrypt ? DBEncryptionUtil.encrypt(param.getValue())
                        : DBEncryptionUtil.decrypt(param.getValue());
            } else {
                value = param.getValue();
            }

            if (updatedQuery.length() == 0) {
                updatedQuery.append(param.getName()).append('=').append(value);
            } else {
                updatedQuery.append('&').append(param.getName()).append('=').append(value);
            }
        }

        String schemeAndHost = "";
        URI newUri = builder.build();
        if (newUri.getScheme() != null) {
            schemeAndHost = newUri.getScheme() + "://" + newUri.getHost();
        }

        updatedPath = schemeAndHost + newUri.getPath() + "?" + updatedQuery;
    } catch (URISyntaxException e) {
        throw new CloudRuntimeException("Couldn't generate an updated uri. " + e.getMessage());
    }

    return updatedPath;
}

From source file:com.offbynull.coroutines.instrumenter.asm.SearchUtils.java

/**
 * Find trycatch blocks within a method that an instruction is apart of. Only includes the try portion, not the catch (handler) portion.
 * @param insnList instruction list for method
 * @param tryCatchBlockNodes trycatch blocks in method
 * @param insnNode instruction within method being searched against
 * @throws NullPointerException if any argument is {@code null} or contains {@code null}
 * @throws IllegalArgumentException if arguments aren't all from the same method
 * @return items from {@code tryCatchBlockNodes} that {@code insnNode} is a part of
 *//*www  .j a  va 2  s .c om*/
public static List<TryCatchBlockNode> findTryCatchBlockNodesEncompassingInstruction(InsnList insnList,
        List<TryCatchBlockNode> tryCatchBlockNodes, AbstractInsnNode insnNode) {
    Validate.notNull(insnList);
    Validate.notNull(tryCatchBlockNodes);
    Validate.notNull(insnNode);
    Validate.noNullElements(tryCatchBlockNodes);

    Map<LabelNode, Integer> labelPositions = new HashMap<>();
    int insnNodeIdx = -1;

    // Get index of labels and insnNode within method
    ListIterator<AbstractInsnNode> insnIt = insnList.iterator();
    int insnCounter = 0;
    while (insnIt.hasNext()) {
        AbstractInsnNode node = insnIt.next();

        // If our instruction, save index
        if (node == insnNode) {
            if (insnNodeIdx == -1) {
                insnNodeIdx = insnCounter;
            } else {
                throw new IllegalArgumentException(); // insnNode encountered multiple times in methodNode. Should not happen.
            }
        }

        // If label node, save position
        if (node instanceof LabelNode) {
            labelPositions.put((LabelNode) node, insnCounter);
        }

        // Increment counter
        insnCounter++;
    }

    Validate.isTrue(insnNodeIdx != -1); //throw exception if node not in method list

    // Find out which trycatch blocks insnNode is within
    List<TryCatchBlockNode> ret = new ArrayList<>();
    for (TryCatchBlockNode tryCatchBlockNode : tryCatchBlockNodes) {
        Integer startIdx = labelPositions.get(tryCatchBlockNode.start);
        Integer endIdx = labelPositions.get(tryCatchBlockNode.end);

        Validate.isTrue(startIdx != null);
        Validate.isTrue(endIdx != null);

        if (insnNodeIdx >= startIdx && insnNodeIdx < endIdx) {
            ret.add(tryCatchBlockNode);
        }
    }

    return ret;
}

From source file:com.ettrema.zsync.UploadMakerEx.java

/**
 * Returns a Range representing a sequence of contiguous server blocks, beginning at blockIndex, that 
 * are to be relocated as a single chunk.
 * /*from w ww  .  ja  va2  s.  c  o  m*/
 * @param iter An iterator positioned immediately after the first match of the sequence
 * @param localOffset The local byte offset of the first matching block of the sequence
 * @param blockIndex The server block index of the first matching block of the sequence
 * @param blockSize The number of bytes in a block
 * @return A Range of contiguous blocks that are to be relocated to localOffset
 */
private static Range consecMatchesEx(ListIterator<OffsetPair> iter, long localOffset, long blockIndex,
        int blockSize) {

    long currBlock = blockIndex;
    long currByte = localOffset;

    while (iter.hasNext()) {

        OffsetPair pair = iter.next();

        currByte += blockSize;
        currBlock++;

        if (pair.localOffset != currByte || pair.remoteBlock != currBlock) {

            iter.previous();
            return new Range(blockIndex, currBlock);

        }

    }
    return new Range(blockIndex, currBlock + 1);
}

From source file:Main.java

/**
 * Returns a list iterator that swaps all previous/next calls.
 * <p><b>Important:</b> The returned iterator violates the {@link ListIterator#nextIndex()} and {@link ListIterator#previousIndex()} specifications.
 *///from w  w  w .  java 2  s.c  o m
public static <E> ListIterator<E> reverse(ListIterator<E> iterator) {
    return new ListIterator<E>() {
        @Override
        public boolean hasNext() {
            return iterator.hasPrevious();
        }

        @Override
        public E next() {
            return iterator.previous();
        }

        @Override
        public boolean hasPrevious() {
            return iterator.hasNext();
        }

        @Override
        public E previous() {
            return iterator.next();
        }

        @Override
        public int nextIndex() {
            return iterator.previousIndex();
        }

        @Override
        public int previousIndex() {
            return iterator.nextIndex();
        }

        @Override
        public void remove() {
            iterator.remove();
        }

        @Override
        public void set(E e) {
            iterator.set(e);
        }

        @Override
        public void add(E e) {
            iterator.add(e);
        }
    };
}

From source file:com.ibm.soatf.config.DirectoryStructureManager.java

private static void validateIfaceStructure(Interface iface) throws FrameworkConfigurationException {
    try {//from   www.  j a v a  2 s.  c  o m
        final MasterFrameworkConfig FCFG = ConfigurationManager.getInstance().getFrameworkConfig();
        final MasterConfiguration MCFG = ConfigurationManager.getInstance().getMasterConfig();
        File soaTestHome = FCFG.getSoaTestHome();
        final File interfaceFolder = new File(soaTestHome,
                iface.getName() + "_" + FCFG.getValidFileSystemObjectName(iface.getDescription()));
        logger.trace("Working directory after format: " + interfaceFolder);
        try {
            createFolder(interfaceFolder);
        } catch (FrameworkExecutionException ex) {
            logger.error("Could not create folder " + interfaceFolder.getAbsolutePath());
        }

        /*
        * Create interface dummy projects folders. There will be nothing saved under those folders.
        * Main purpose is just to have the user view on all projects under the interface, because there doesn't exist
        * one general naming interace convention, which is wrong!!!
        */
        if (iface.getProjects() != null) {
            final ListIterator<Project> projectIt = iface.getProjects().getProject().listIterator();
            while (projectIt.hasNext()) {
                File projectFolder = new File(interfaceFolder,
                        OSB_REFERENCE_PROJECT_DIR_NAME_PREFIX + projectIt.next().getName());
                try {
                    createFolder(projectFolder);
                } catch (FrameworkExecutionException ex) {
                    logger.error("Could not create project folder " + projectFolder.getAbsolutePath());
                }
            }
            final File interfaceConfigFile = new File(interfaceFolder, IFACE_CONFIG_FILENAME);
            if (!interfaceConfigFile.exists()) {
                logger.warn("Interface configuration file is missing for interface " + iface.getName() + " "
                        + iface.getDescription());
                return;
            }
            //masterConfig.getIfaceConfigFile(iface.getName());
            if (interfaceConfigFile.exists()) {
                try {
                    InterfaceConfiguration ICFG = MCFG.getInterfaceConfig(iface);
                    final ListIterator<IfaceFlowPattern> ifaceFlowPatternIterator = ICFG.getIfaceFlowPatterns()
                            .listIterator();
                    IfaceFlowPattern ifaceFlowPattern;
                    logger.debug("Processing " + interfaceConfigFile.getAbsolutePath());
                    while (ifaceFlowPatternIterator.hasNext()) {
                        ifaceFlowPattern = ifaceFlowPatternIterator.next();

                        final File patternDirectory = new File(interfaceFolder, FLOW_PATTERN_DIR_NAME_PREFIX
                                + FCFG.getValidFileSystemObjectName(ifaceFlowPattern.getRefId()));
                        createFolder(patternDirectory);

                        final String testName = ifaceFlowPattern.getInstanceMetadata().getTestName();
                        if (testName.isEmpty()) {
                            throw new FrameworkConfigurationException(
                                    "There is missing test name in config.xml instance metadata element in file "
                                            + interfaceConfigFile.getAbsolutePath() + ".");
                        }
                        final File testScenarioNameDirectory = new File(patternDirectory,
                                FCFG.getValidFileSystemObjectName(testName));
                        createFolder(testScenarioNameDirectory);

                        /*final ListIterator<FileSystemProjectStructure.FlowPatternInstanceRoot.Directory> patternFoldersIterator = masterConfig.getXmlConfig().getFileSystemStructure().getFlowPatternInstanceRoot().getDirectory().listIterator();
                        while (patternFoldersIterator.hasNext()) {
                        final String fldName = frameworkConfig.getValidFileSystemObjectName(patternFoldersIterator.next().getName());
                        final File dir = new File(testScenarioNameDirectory, fldName);
                        createFolder(dir);
                        // This is to check the pattern source folder and don't let it clean up
                        cleanFolder(dir);
                        }*/

                        final File reportDir = new File(testScenarioNameDirectory, MCFG.getReportDirName());
                        createFolder(reportDir);
                        cleanFolder(reportDir);

                        final File archiveDir = new File(testScenarioNameDirectory, MCFG.getArchiveDirName());
                        createFolder(archiveDir);

                        final ListIterator<IfaceTestScenario> ifaceTCIterator = ifaceFlowPattern
                                .getIfaceTestScenario().listIterator();
                        IfaceTestScenario ifaceTestScenario;
                        while (ifaceTCIterator.hasNext()) {
                            ifaceTestScenario = ifaceTCIterator.next();
                            final File testScenario = new File(testScenarioNameDirectory,
                                    FCFG.getValidFileSystemObjectName(ifaceTestScenario.getRefId()));
                            createFolder(testScenario);
                            final ListIterator<FileSystemProjectStructure.TestRoot.Directory> foldersIterator = MCFG
                                    .getXmlConfig().getFileSystemStructure().getTestRoot().getDirectory()
                                    .listIterator();
                            while (foldersIterator.hasNext()) {
                                final String fldName = FCFG
                                        .getValidFileSystemObjectName(foldersIterator.next().getName());
                                final File dir = new File(testScenario, fldName);
                                createFolder(dir);
                                // This is to check the pattern source folder and don't let it clean up
                                cleanFolder(dir);
                            }
                        }
                    }
                } catch (FrameworkConfigurationException fce) {
                    logger.error("Configuration for interface " + iface.getName() + " is invalid", fce);
                } catch (FrameworkExecutionException fee) {
                    logger.error("Could not create folder.", fee);
                }
            } else {
                generateSampleIfaceConfigFile(interfaceConfigFile);
            }
        } else {
            logger.warn("Interface " + iface.getName() + "_" + iface.getDescription()
                    + " has no projects defined.");
        }
    } catch (FrameworkConfigurationException ex) {
        final String msg = "TODO";
        throw new FrameworkConfigurationException(msg, ex);
    }
}