Example usage for java.util Stack empty

List of usage examples for java.util Stack empty

Introduction

In this page you can find the example usage for java.util Stack empty.

Prototype

public boolean empty() 

Source Link

Document

Tests if this stack is empty.

Usage

From source file:org.dhatim.json.JSONReader.java

public void parse(InputSource csvInputSource) throws IOException, SAXException {
    if (contentHandler == null) {
        throw new IllegalStateException("'contentHandler' not set.  Cannot parse JSON stream.");
    }//from  w  w  w .ja v  a 2  s.  c om
    if (executionContext == null) {
        throw new IllegalStateException(
                "Smooks container 'executionContext' not set.  Cannot parse JSON stream.");
    }

    try {
        // Get a reader for the JSON source...
        Reader jsonStreamReader = csvInputSource.getCharacterStream();
        if (jsonStreamReader == null) {
            jsonStreamReader = new InputStreamReader(csvInputSource.getByteStream(), encoding);
        }

        // Create the JSON parser...
        JsonParser jp = null;
        try {

            if (logger.isTraceEnabled()) {
                logger.trace("Creating JSON parser");
            }

            jp = jsonFactory.createJsonParser(jsonStreamReader);

            // Start the document and add the root "csv-set" element...
            contentHandler.startDocument();
            startElement(rootName, 0);

            if (logger.isTraceEnabled()) {
                logger.trace("Starting JSON parsing");
            }

            boolean first = true;
            Stack<String> elementStack = new Stack<String>();
            Stack<Type> typeStack = new Stack<Type>();
            JsonToken t;
            while ((t = jp.nextToken()) != null) {

                if (logger.isTraceEnabled()) {
                    logger.trace("Token: " + t.name());
                }

                switch (t) {

                case START_OBJECT:
                case START_ARRAY:
                    if (!first) {
                        if (!typeStack.empty() && typeStack.peek() == Type.ARRAY) {
                            startElement(arrayElementName, typeStack.size());
                        }
                    }
                    typeStack.push(t == JsonToken.START_ARRAY ? Type.ARRAY : Type.OBJECT);
                    break;

                case END_OBJECT:
                case END_ARRAY:

                    typeStack.pop();

                    boolean typeStackPeekIsArray = !typeStack.empty() && typeStack.peek() == Type.ARRAY;

                    if (!elementStack.empty() && !typeStackPeekIsArray) {
                        endElement(elementStack.pop(), typeStack.size());
                    }

                    if (typeStackPeekIsArray) {
                        endElement(arrayElementName, typeStack.size());
                    }
                    break;

                case FIELD_NAME:

                    String text = jp.getText();

                    if (logger.isTraceEnabled()) {
                        logger.trace("Field name: " + text);
                    }

                    String name = getElementName(text);

                    startElement(name, typeStack.size());
                    elementStack.add(name);

                    break;

                default:

                    String value;

                    if (t == JsonToken.VALUE_NULL) {
                        value = nullValueReplacement;
                    } else {
                        value = jp.getText();
                    }

                    if (typeStack.peek() == Type.ARRAY) {

                        startElement(arrayElementName, typeStack.size());
                    }

                    contentHandler.characters(value.toCharArray(), 0, value.length());

                    if (typeStack.peek() == Type.ARRAY) {

                        endElement(arrayElementName);

                    } else {

                        endElement(elementStack.pop());

                    }

                    break;

                }

                first = false;
            }
            endElement(rootName, 0);
            contentHandler.endDocument();
        } finally {

            try {
                jp.close();
            } catch (Exception e) {
            }

        }
    } finally {
        // These properties need to be reset for every execution (e.g. when reader is pooled).
        contentHandler = null;
        executionContext = null;
    }
}

From source file:com.handcraftedbits.bamboo.plugin.go.parser.GoTestParser.java

@SuppressWarnings("unchecked")
public static List<PackageTestResults> parseTests(final InputStream input) throws Exception {
    final List<String> lines = IOUtils.readLines(input, "UTF-8");
    final List<PackageTestResults> packageTestResults = new LinkedList<>();
    final Stack<SingleTestResult> testResults = new Stack<>();

    for (final String line : lines) {
        // A test has finished.  Parse it out and push it on the stack until we know which package it belongs to.

        if (line.startsWith("---")) {
            final Matcher matcher = GoTestParser.patternTestFinish.matcher(line);

            if (matcher.matches()) {
                TestStatus status = null;

                switch (matcher.group(1)) {
                case "FAIL": {
                    status = TestStatus.FAILED;

                    break;
                }/*from   w w w.  j  a v a2  s. c o  m*/

                case "PASS": {
                    status = TestStatus.PASSED;

                    break;
                }

                case "SKIP": {
                    status = TestStatus.SKIPPED;

                    break;
                }
                }

                if (status != null) {
                    testResults.push(new SingleTestResult(matcher.group(2), status,
                            Double.parseDouble(matcher.group(3))));
                }
            }
        }

        // This is either noise or a finished set of package tests.

        else {
            final Matcher matcher = GoTestParser.patternPackageFinish.matcher(line);

            // We have a finished set of package tests, so create the model for it and clear the stack of tests.

            if (matcher.matches()) {
                final PackageTestResults packageResults = new PackageTestResults(matcher.group(2));

                // In this case, either the go test run did not specify -v or there are no tests in the
                // package.  We'll create a single "AllTests" test and assign it the correct status.  In the
                // case of no tests existing for the package, the status will be "skipped".

                if (testResults.empty()) {
                    double duration = 0.0d;
                    final String durationStr = matcher.group(3);
                    TestStatus testStatus = TestStatus.SKIPPED;

                    switch (matcher.group(1)) {
                    case "FAIL": {
                        testStatus = TestStatus.FAILED;

                        break;
                    }

                    case "ok  ": {
                        testStatus = TestStatus.PASSED;

                        break;
                    }
                    }

                    // If there are tests in the package, we should be able to extract the duration.

                    if (durationStr.endsWith("s")) {
                        duration = Double.parseDouble(durationStr.substring(0, durationStr.length() - 1));
                    }

                    packageResults.addTestResult(new SingleTestResult("AllTests", testStatus, duration));
                }

                while (!testResults.empty()) {
                    packageResults.addTestResult(testResults.pop());
                }

                packageTestResults.add(packageResults);
            }
        }
    }

    IOUtils.closeQuietly(input);

    return packageTestResults;
}

From source file:NimbleTree.java

/**
 * A static constructor (is this the right term?) where a lisp-style s-expression
 * is passed in as a string. This can't be a true constructor because the result
 * is a tree over String, not a generic tree.
 *//*from w  w w. jav  a 2 s .  c o m*/
public static NimbleTree<String> makeTreeOverStringFromSExpression(String input) {
    NimbleTree<String> tree = new NimbleTree<String>();
    Stack<TreeNode<String>> previousParents = new Stack<TreeNode<String>>();

    // Make sure the string is tokenizable
    // FIXME allow [] and maybe other delimiters?
    input = input.replace("(", " ( ");
    input = input.replace(")", " ) ");

    StringTokenizer st = new StringTokenizer(input);

    boolean firstTimeThrough = true;
    while (st.hasMoreTokens()) {
        String currTok = st.nextToken().trim();

        if (currTok.equals("")) {
            // Tokenizer gave us an empty token, do nothing.

        } else if (currTok.equals("(")) {
            // Get the *next* token and make a new subtree on it.
            currTok = st.nextToken().trim();

            if (firstTimeThrough == true) {
                // The tree is of the form "(x)"
                // This is the root node: just set its data
                firstTimeThrough = false;
                tree.getRoot().setData(currTok);

            } else {
                // This is the root of a new subtree. Save parent,
                // then set this node to be the new parent.
                tree.addChild(currTok);
                tree.getCurrentNode().getEnd().setID(tree.getNodeCount());
                previousParents.push(tree.getCurrentNode());
                tree.setCurrentNode(tree.getCurrentNode().getEnd());
            }

        } else if (currTok.equals(")")) {
            // Finished adding children to current parent. Go back
            // to previous parent (if there was none, it's because
            // current parent is root, so we're finished anyway).
            if (!previousParents.empty()) {
                tree.setCurrentNode(previousParents.pop());
            }

        } else {
            if (firstTimeThrough == true) {
                // The tree is of the form "x".
                // This is to be the root node: just set its data. 
                firstTimeThrough = false;
                tree.getRoot().setData(currTok);
            } else {
                // Add a child node to current parent.
                tree.addChild(currTok);
                tree.getCurrentNode().getEnd().setID(tree.getNodeCount());
            }
        }
    }

    return tree;
}

From source file:org.apache.fop.fo.FONode.java

/**
 * Conditionally add a new delimited text range to RANGES, where new range is
 * associated with current FONode. A new text range is added unless all of the following are
 * true:/*  w w  w. j  a va  2  s.  c om*/
 * <ul>
 * <li>there exists a current range RCUR in RANGES</li>
 * <li>RCUR is empty</li>
 * <li>the node of the RCUR is the same node as FN or a descendent node of FN</li>
 * </ul>
 * @param ranges stack of delimited text ranges
 * @return new range (if constructed and pushed onto stack) or current range (if any) or null
 */
private DelimitedTextRange maybeNewRange(Stack ranges) {
    DelimitedTextRange rCur = null; // current range (top of range stack)
    DelimitedTextRange rNew = null; // new range to be pushed onto range stack
    if (ranges.empty()) {
        if (isBidiRangeBlockItem()) {
            rNew = new DelimitedTextRange(this);
        }
    } else {
        rCur = (DelimitedTextRange) ranges.peek();
        if (rCur != null) {
            if (!rCur.isEmpty() || !isSelfOrDescendent(rCur.getNode(), this)) {
                rNew = new DelimitedTextRange(this);
            }
        }
    }
    if (rNew != null) {
        ranges.push(rNew);
    } else {
        rNew = rCur;
    }
    return rNew;
}

From source file:alluxio.job.persist.PersistDefinition.java

@Override
public SerializableVoid runTask(PersistConfig config, SerializableVoid args, JobWorkerContext context)
        throws Exception {
    AlluxioURI uri = new AlluxioURI(config.getFilePath());
    String ufsPath = config.getUfsPath();

    // check if the file is persisted in UFS and delete it, if we are overwriting it
    UfsManager.UfsClient ufsClient = context.getUfsManager().get(config.getMountId());
    try (CloseableResource<UnderFileSystem> ufsResource = ufsClient.acquireUfsResource()) {
        UnderFileSystem ufs = ufsResource.get();
        if (ufs == null) {
            throw new IOException("Failed to create UFS instance for " + ufsPath);
        }//from   ww w . j  a  va  2 s. c  om
        if (ufs.exists(ufsPath)) {
            if (config.isOverwrite()) {
                LOG.info("File {} is already persisted in UFS. Removing it.", config.getFilePath());
                ufs.deleteFile(ufsPath);
            } else {
                throw new IOException("File " + config.getFilePath()
                        + " is already persisted in UFS, to overwrite the file, please set the overwrite flag"
                        + " in the config.");
            }
        }

        FileSystem fs = FileSystem.Factory.get();
        long bytesWritten;
        try (Closer closer = Closer.create()) {
            OpenFileOptions options = OpenFileOptions.defaults().setReadType(ReadType.NO_CACHE);
            FileInStream in = closer.register(fs.openFile(uri, options));
            AlluxioURI dstPath = new AlluxioURI(ufsPath);
            // Create ancestor directories from top to the bottom. We cannot use recursive create
            // parents here because the permission for the ancestors can be different.
            Stack<Pair<String, MkdirsOptions>> ufsDirsToMakeWithOptions = new Stack<>();
            AlluxioURI curAlluxioPath = uri.getParent();
            AlluxioURI curUfsPath = dstPath.getParent();
            // Stop at the Alluxio root because the mapped directory of Alluxio root in UFS may not
            // exist.
            while (!ufs.isDirectory(curUfsPath.toString()) && curAlluxioPath != null) {
                URIStatus curDirStatus = fs.getStatus(curAlluxioPath);
                ufsDirsToMakeWithOptions.push(new Pair<>(curUfsPath.toString(),
                        MkdirsOptions.defaults().setCreateParent(false).setOwner(curDirStatus.getOwner())
                                .setGroup(curDirStatus.getGroup())
                                .setMode(new Mode((short) curDirStatus.getMode()))));
                curAlluxioPath = curAlluxioPath.getParent();
                curUfsPath = curUfsPath.getParent();
            }
            while (!ufsDirsToMakeWithOptions.empty()) {
                Pair<String, MkdirsOptions> ufsDirAndPerm = ufsDirsToMakeWithOptions.pop();
                // UFS mkdirs might fail if the directory is already created. If so, skip the mkdirs
                // and assume the directory is already prepared, regardless of permission matching.
                if (!ufs.mkdirs(ufsDirAndPerm.getFirst(), ufsDirAndPerm.getSecond())
                        && !ufs.isDirectory(ufsDirAndPerm.getFirst())) {
                    throw new IOException("Failed to create " + ufsDirAndPerm.getFirst() + " with permission "
                            + ufsDirAndPerm.getSecond().toString());
                }
            }
            URIStatus uriStatus = fs.getStatus(uri);
            OutputStream out = closer.register(
                    ufs.create(dstPath.toString(), CreateOptions.defaults().setOwner(uriStatus.getOwner())
                            .setGroup(uriStatus.getGroup()).setMode(new Mode((short) uriStatus.getMode()))));
            bytesWritten = IOUtils.copyLarge(in, out);
            incrementPersistedMetric(ufsClient.getUfsMountPointUri(), bytesWritten);
        }
        LOG.info("Persisted file {} with size {}", ufsPath, bytesWritten);
    }
    return null;
}

From source file:org.apache.tez.dag.api.DAG.java

private Deque<String> detectCycles(Map<Vertex, List<Edge>> edgeMap, Map<String, AnnotatedVertex> vertexMap)
        throws IllegalStateException {
    Deque<String> topologicalVertexStack = new LinkedList<String>();
    Integer nextIndex = 0; // boxed integer so it is passed by reference.
    Stack<AnnotatedVertex> stack = new Stack<DAG.AnnotatedVertex>();
    for (AnnotatedVertex av : vertexMap.values()) {
        if (av.index == -1) {
            assert stack.empty();
            strongConnect(av, vertexMap, edgeMap, stack, nextIndex, topologicalVertexStack);
        }/*from   w ww  .  j  a v a  2  s  .  c om*/
    }
    return topologicalVertexStack;
}

From source file:org.xlrnet.tibaija.processor.FullTIBasicVisitor.java

@Override
public Object visitCommandList(@NotNull TIBasicParser.CommandListContext ctx) {
    final List<TIBasicParser.CommandContext> commandList = ctx.command();
    final int commandListSize = commandList.size();

    Stack<ControlFlowElement> flowElementStack = new Stack<>();
    Stack<ControlFlowElement.ControlFlowToken> skipCommandsStack = new Stack<>();

    try {//from w  w  w. ja va2  s .c om
        for (int commandCounter = 0; commandCounter < commandListSize; commandCounter++) {
            final TIBasicParser.CommandContext nextCommand = commandList.get(commandCounter);

            // Skipping logic
            if (!skipCommandsStack.empty()) {
                if (nextCommand.isControlFlowStatement) {
                    commandCounter = internalHandleSkipFlowLogic(commandCounter, commandList, skipCommandsStack,
                            nextCommand);
                } else {
                    LOGGER.debug("Skipping command {}", commandCounter);
                }
            } else if (nextCommand.isControlFlowStatement) {
                commandCounter = internalHandleControlFlowLogic(commandCounter, commandList, flowElementStack,
                        skipCommandsStack, nextCommand);
            } else {
                nextCommand.accept(this);
            }
        }
    } catch (TIStopException stop) {
        LOGGER.debug("Forced program stop in line {} at char {}", stop.getLinenumber(), stop.getCharInLine());
    }
    return null;
}

From source file:hugonicolau.openbrailleinput.wordcorrection.mafsa.MAFSA.java

public Set<SuggestionResult> searchMSD(String transWord, int maxCost, float insertionCost,
        float substitutionCost, float omissionCost, Distance distance) {
    // build first row
    List<Float> row = range(transWord.length() + 1);

    // results//  w ww .  j  a v a2  s  .com
    Set<SuggestionResult> results = new HashSet<SuggestionResult>();

    // iteratively (to prevent stack overflow) search each branch of the graph
    // a stack of paths to traverse. This prevents the StackOverflowException.
    Stack<StackLevenshteinEntry> stack = new Stack<StackLevenshteinEntry>();
    for (Iterator<Long> iter = childIterator(nodes[0]); iter.hasNext();) {
        long child = iter.next();
        char c = getChar(child);

        StackLevenshteinEntry entry = new StackLevenshteinEntry(child, transWord.toUpperCase().toCharArray(),
                String.valueOf(c), row);
        stack.push(entry);
    }

    // thread to control time to search for suggestions
    mAreTimeAvailable = true;
    mTimerTask = new TimerTask() {

        @Override
        public void run() {
            //Log.v(BrailleSpellCheckerService.TAG, "Search Interrupted!");
            mAreTimeAvailable = false;
        }
    };
    mTimer = new Timer();
    mTimer.schedule(mTimerTask, 500); //500 ms to find all suggestions

    while (!stack.empty() && mAreTimeAvailable) {
        StackLevenshteinEntry entry = stack.pop();
        List<Float> previousRow = entry.previousRow;

        int columns = entry.chars.length + 1;
        List<Float> currentRow = new LinkedList<Float>();
        currentRow.add(previousRow.get(0) + omissionCost);

        // build one row for the letter, with a column for each letter in the target word, 
        // plus one for the empty string at column 0
        for (int column = 1; column < columns; column++) {
            // cost * braille_distance
            float insertCost = currentRow.get(column - 1) + insertionCost;// * 
            //getInsertionDistance(entry.chars, column-1, getChar(entry.node));
            float omitCost = previousRow.get(column) + omissionCost;
            float substituteCost = previousRow.get(column - 1);

            if (entry.chars[column - 1] != getChar(entry.node))
                substituteCost += substitutionCost
                        * distance.getDistance(entry.chars[column - 1], getChar(entry.node));

            currentRow.add(Math.min(insertCost, Math.min(omitCost, substituteCost)));
        }

        // if last entry in the row indicates the optimal cost is less than the maximum cost,
        // and there is a word in this node, then add it.
        int last = currentRow.size() - 1;
        if (currentRow.get(last) <= maxCost && canTerminate(entry.node)) {
            results.add(new SuggestionResult(entry.subword, currentRow.get(last)));
        }

        // if any entries in the row are less than the maximum cost, then iteratively search each branch
        if (min(currentRow) <= maxCost) {
            for (Iterator<Long> iter = childIterator(entry.node); iter.hasNext();) {
                // get child
                long child = iter.next();

                // build subword
                StackLevenshteinEntry nextEntry = new StackLevenshteinEntry(child, entry.chars,
                        entry.subword + getChar(child), currentRow);

                // search that branch
                stack.push(nextEntry);
            }
        }
    }

    mTimer.cancel();

    // return list of results
    return results;
}

From source file:org.xlrnet.tibaija.processor.FullTIBasicVisitor.java

private int internalHandleControlFlowLogic(int commandIndex, List<TIBasicParser.CommandContext> commandList,
        Stack<ControlFlowElement> flowElementStack,
        Stack<ControlFlowElement.ControlFlowToken> skipCommandsStack,
        TIBasicParser.CommandContext nextCommand) {
    int commandListSize = commandList.size();
    ControlFlowElement currentFlowElement = (ControlFlowElement) nextCommand.accept(this);
    ControlFlowElement topFlowElement;//from   w ww .j  av a2  s.  c o m
    if (!flowElementStack.empty()) {
        topFlowElement = flowElementStack.peek();
    } else {
        topFlowElement = null;
    }

    // Check if current token depends on a certain pre-token
    final int line = currentFlowElement.getLine();
    final int charIndex = currentFlowElement.getCharIndex();
    switch (currentFlowElement.getToken()) {
    case INCREMENT_SKIP_GREATER:
    case DECREMENT_SKIP_LESS:
        if (commandIndex + 1 >= commandList.size()) {
            throw new IllegalControlFlowException(line, charIndex, "Missing next command");
        }
        if (!currentFlowElement.getLastEvaluation()) {
            LOGGER.debug("Skipping next command...");
            commandIndex++;
        }
        break;
    case GOTO:
        JumpingControlFlowElement jumpElement = (JumpingControlFlowElement) currentFlowElement;
        String targetLabel = jumpElement.getTargetLabel();
        commandIndex = environment.getProgramStack().peek().getLabelJumpTarget(jumpElement.getTargetLabel());
        LOGGER.debug("Jumping to label {} at command {}", targetLabel, commandIndex);
        break;
    case LABEL:
        break; // Do nothing when encountering Label
    case FOR:
        boolean isFirstIteration = false;
        if ((topFlowElement == null || topFlowElement.getCommandIndex() != commandIndex)) {
            // Set start value (should be executed ALWAYS when this block is executed the *first* time from top-down
            TIBasicParser.ForStatementContext forStatementContext = commandList.get(commandIndex)
                    .controlFlowStatement().forStatement();
            String variableName = forStatementContext.numericalVariable().getText();
            Value value = (Value) forStatementContext.expression(0).accept(this);
            Variables.NumberVariable targetVariable = Variables.resolveNumberVariable(variableName);
            environment.getWritableMemory().setNumberVariableValue(targetVariable, value);
            isFirstIteration = true;
        }
        if (currentFlowElement.isRepeatable() && (currentFlowElement.getLastEvaluation() || isFirstIteration)) {
            if (isFirstIteration) {
                currentFlowElement.setLastEvaluation(true); // Hack for making sure, that the first increment is ALWAYS done at the end
                LOGGER.debug("Entering FOR loop at command {}", commandIndex);
            } else {
                LOGGER.debug("Continuing FOR loop at command {}", commandIndex);
                flowElementStack.pop();
            }
            currentFlowElement.setCommandIndex(commandIndex);
            flowElementStack.push(currentFlowElement);
        } else {
            if (topFlowElement != null && topFlowElement.getCommandIndex() == commandIndex) {
                flowElementStack.pop();
            }
            LOGGER.debug("Skipping commands until next END from FOR command {}", commandIndex);
            skipCommandsStack.push(ControlFlowElement.ControlFlowToken.FOR);
        }
        break;
    case REPEAT:
        currentFlowElement.setCommandIndex(commandIndex);
        LOGGER.debug("Entering repeat loop at command {}", commandIndex);
        flowElementStack.push(currentFlowElement);
        break;
    case WHILE:
        if (!currentFlowElement.getLastEvaluation()) {
            LOGGER.debug("Skipping commands until next END from WHILE command {}", commandIndex);
            skipCommandsStack.push(ControlFlowElement.ControlFlowToken.WHILE);
        } else {
            currentFlowElement.setCommandIndex(commandIndex);
            flowElementStack.push(currentFlowElement);
        }
        break;
    case THEN:
        if (topFlowElement == null) {
            throw new IllegalControlFlowException(line, charIndex, "Illegal 'Then' Statement");
        }
        if (topFlowElement.getToken() != ControlFlowElement.ControlFlowToken.IF) {
            throw new IllegalControlFlowException(line, charIndex,
                    "Illegal 'Then' Statement without preceding 'If'");
        }
        if (topFlowElement.getLastEvaluation()) {
            currentFlowElement.setLastEvaluation(true);
        } else {
            currentFlowElement.setLastEvaluation(false);
            skipCommandsStack.push(ControlFlowElement.ControlFlowToken.ELSE);
            LOGGER.debug("Skipping commands until next ELSE from THEN command {}", commandIndex);
        }
        flowElementStack.push(currentFlowElement);
        break;
    case ELSE:
        if (topFlowElement == null) {
            throw new IllegalControlFlowException(line, charIndex, "Illegal 'Else' Statement");
        }
        if (topFlowElement.getToken() != ControlFlowElement.ControlFlowToken.THEN) {
            throw new IllegalControlFlowException(line, charIndex,
                    "Illegal 'Else' Statement without preceding 'Then'");
        }
        if (topFlowElement.getLastEvaluation()) { // Skip until next "END" if previous if was true
            skipCommandsStack.push(ControlFlowElement.ControlFlowToken.END);
            LOGGER.debug("Skipping commands until next END from ELSE command {}", commandIndex);
        }
        break;
    case END:
        if (topFlowElement == null) {
            throw new IllegalControlFlowException(line, charIndex,
                    "Illegal 'End' Statement without preceding endable element");
        }
        if (topFlowElement.getToken() == ControlFlowElement.ControlFlowToken.REPEAT) {
            // Repeat will only be check at the END command!
            final TIBasicParser.CommandContext commandContext = commandList
                    .get(topFlowElement.getCommandIndex());
            Value v = (Value) commandContext.controlFlowStatement().repeatStatement().expression().accept(this);
            if (v.bool()) {
                topFlowElement.setRepeatable(false);
            } else {
                topFlowElement.setRepeatable(true);
            }
        } else if (topFlowElement.getToken() == ControlFlowElement.ControlFlowToken.FOR) {
            if (topFlowElement.getLastEvaluation()) {
                topFlowElement.setRepeatable(true);
                TIBasicParser.ForStatementContext forStatementContext = commandList
                        .get(topFlowElement.getCommandIndex()).controlFlowStatement().forStatement();
                String variableName = forStatementContext.numericalVariable().getText();
                Value increment;
                if (forStatementContext.expression().size() == 3)
                    increment = (Value) forStatementContext.expression(2).accept(this);
                else
                    increment = Value.of(1);
                Variables.NumberVariable targetVariable = Variables.resolveNumberVariable(variableName);
                Value value = environment
                        .runRegisteredExpressionFunction("+",
                                environment.getMemory().getNumberVariableValue(targetVariable), increment)
                        .get();
                environment.getWritableMemory().setNumberVariableValue(targetVariable, value);
                flowElementStack.push(topFlowElement); // Push the flow element again -> workaround
            } else {
                topFlowElement.setRepeatable(false);
            }
        }
        if (topFlowElement.isRepeatable()) {
            commandIndex = topFlowElement.getCommandIndex() - 1; // Move counter backwards
            LOGGER.debug("Moving command counter to index {}", commandIndex);
        }
        flowElementStack.pop();
        break;
    case IF:
        // Look ahead if the next command might be a "Then" i.e. if it is a controlflow statement
        if (commandListSize <= commandIndex + 1) {
            throw new IllegalControlFlowException(line, charIndex, "Illegal 'If' at the end of the program");
        } else if (commandList.get(commandIndex + 1).isControlFlowStatement) {
            flowElementStack.push(currentFlowElement);
            LOGGER.debug("Predicted multiline IF at command {}", commandIndex);
        } else if (!currentFlowElement.getLastEvaluation()) {
            // If the next command is not a flow statement and the If evaluated to false, skip the next command (i.e. no else allowed!)
            commandIndex++;
            LOGGER.debug("Skipped IF statement without ELSE clause at command {}", commandIndex);
        }
        break;
    default:
        throw new NotImplementedException("Flow not implemented");
    }
    return commandIndex;
}

From source file:net.firejack.platform.core.utils.Factory.java

public Class getGenericParameterClass(Class actualClass, Class genericClass, int parameterIndex) {
    if (!genericClass.isAssignableFrom(actualClass) || genericClass.equals(actualClass)) {
        throw new IllegalArgumentException(
                "Class " + genericClass.getName() + " is not a superclass of " + actualClass.getName() + ".");
    }//from  w w w  .j  a va2s . c  o m

    Stack<ParameterizedType> types = new Stack<ParameterizedType>();

    Class clazz = actualClass;

    while (true) {
        Type currentType = genericClass.isInterface() ? getGenericInterface(clazz, genericClass)
                : clazz.getGenericSuperclass();

        Type rawType;
        if (currentType instanceof ParameterizedType) {
            ParameterizedType type = (ParameterizedType) currentType;
            types.push(type);
            rawType = type.getRawType();
        } else {
            types.clear();
            rawType = currentType;
        }

        if (!rawType.equals(genericClass)) {
            clazz = (Class) rawType;
        } else {
            break;
        }
    }

    if (types.isEmpty()) {
        return (Class) genericClass.getTypeParameters()[parameterIndex].getGenericDeclaration();
    }

    Type result = types.pop().getActualTypeArguments()[parameterIndex];

    while (result instanceof TypeVariable && !types.empty()) {
        int actualArgumentIndex = getParameterTypeDeclarationIndex((TypeVariable) result);
        ParameterizedType type = types.pop();
        result = type.getActualTypeArguments()[actualArgumentIndex];
    }

    if (result instanceof TypeVariable) {
        throw new IllegalStateException("Unable to resolve type variable " + result + "."
                + " Try to replace instances of parametrized class with its non-parameterized subtype.");
    }

    if (result instanceof ParameterizedType) {
        result = ((ParameterizedType) result).getRawType();
    }

    if (result == null) {
        throw new IllegalStateException(
                "Unable to determine actual parameter type for " + actualClass.getName() + ".");
    }

    if (!(result instanceof Class)) {
        throw new IllegalStateException(
                "Actual parameter type for " + actualClass.getName() + " is not a Class.");
    }

    return (Class) result;
}