Example usage for java.io StreamTokenizer nextToken

List of usage examples for java.io StreamTokenizer nextToken

Introduction

In this page you can find the example usage for java.io StreamTokenizer nextToken.

Prototype

public int nextToken() throws IOException 

Source Link

Document

Parses the next token from the input stream of this tokenizer.

Usage

From source file:com.redskyit.scriptDriver.RunTests.java

private void runCommand(final StreamTokenizer tokenizer, File file, String source, ExecutionContext script)
        throws Exception {
    // Automatic log dumping
    if (autolog && null != driver) {
        dumpLog();//from  ww w .j av a  2 s . co m
    }

    String cmd = tokenizer.sval;
    System.out.printf((new Date()).getTime() + ": [%s,%d] ", source, tokenizer.lineno());
    System.out.print(tokenizer.sval);

    if (cmd.equals("version")) {
        // HELP: version
        System.out.println();
        System.out.println("ScriptDriver version " + version);
        return;
    }

    if (cmd.equals("browser")) {
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            System.out.print(' ');
            System.out.print(tokenizer.sval);

            if (tokenizer.sval.equals("prefs")) {
                // HELP: browser prefs ...
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                    System.out.print(' ');
                    System.out.print(tokenizer.sval);
                    String pref = tokenizer.sval;
                    tokenizer.nextToken();
                    System.out.print(' ');
                    if (_skip)
                        return;
                    if (null == options)
                        options = new ChromeOptions();
                    if (null == prefs)
                        prefs = new HashMap<String, Object>();
                    switch (tokenizer.ttype) {
                    case StreamTokenizer.TT_WORD:
                    case '"':
                        System.out.println(tokenizer.sval);
                        if (tokenizer.sval.equals("false")) {
                            prefs.put(pref, false);
                        } else if (tokenizer.sval.equals("true")) {
                            prefs.put(pref, true);
                        } else {
                            prefs.put(pref, tokenizer.sval);
                        }
                        return;
                    case StreamTokenizer.TT_NUMBER:
                        System.out.println(tokenizer.nval);
                        prefs.put(pref, tokenizer.nval);
                        return;
                    }
                }
                System.out.println();
                throw new Exception("browser option command argument missing");
            }

            if (tokenizer.sval.equals("option")) {
                // HELP: browser option ...
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') { // expect a quoted string
                    System.out.print(' ');
                    System.out.println(tokenizer.sval);
                    if (_skip)
                        return;
                    if (null == options)
                        options = new ChromeOptions();
                    options.addArguments(tokenizer.sval);
                    return;
                }
                System.out.println();
                throw new Exception("browser option command argument missing");
            }

            // HELP: browser wait <seconds>
            if (tokenizer.sval.equals("wait")) {
                tokenizer.nextToken();
                double nval = script.getExpandedNumber(tokenizer);
                System.out.print(' ');
                System.out.println(nval);
                if (_skip)
                    return;
                driver.manage().timeouts().implicitlyWait((long) (tokenizer.nval * 1000),
                        TimeUnit.MILLISECONDS);
                return;
            }

            if (tokenizer.sval.equals("start")) {
                // HELP: browser start
                System.out.println();
                if (null == driver) {
                    // https://sites.google.com/a/chromium.org/chromedriver/capabilities
                    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
                    LoggingPreferences logs = new LoggingPreferences();
                    logs.enable(LogType.BROWSER, Level.ALL);
                    capabilities.setCapability(CapabilityType.LOGGING_PREFS, logs);
                    if (null == options)
                        options = new ChromeOptions();
                    if (null == prefs)
                        prefs = new HashMap<String, Object>();
                    options.setExperimentalOption("prefs", prefs);
                    options.merge(capabilities);
                    driver = new ChromeDriver(options);
                    driver.setLogLevel(Level.ALL);
                    actions = new Actions(driver); // for advanced actions
                }
                return;
            }

            if (null == driver) {
                System.out.println();
                throw new Exception("browser start must be used before attempt to interract with the browser");
            }

            if (tokenizer.sval.equals("get")) {
                // HELP: browser get "url"
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') { // expect a quoted string
                    System.out.print(' ');
                    System.out.println(tokenizer.sval);
                    if (_skip)
                        return;
                    if (null == driver)
                        driver = new ChromeDriver(options);
                    driver.get(tokenizer.sval);
                    return;
                }
                System.out.println();
                throw new Exception("browser get command argument should be a quoted url");
            }

            if (tokenizer.sval.equals("refresh")) {
                // HELP: browser refresh
                System.out.println();
                driver.navigate().refresh();
                return;
            }

            if (tokenizer.sval.equals("back")) {
                // HELP: browser refresh
                System.out.println();
                driver.navigate().back();
                return;
            }

            if (tokenizer.sval.equals("forward")) {
                // HELP: browser refresh
                System.out.println();
                driver.navigate().forward();
                return;
            }

            if (tokenizer.sval.equals("close")) {
                // HELP: browser close
                System.out.println();
                if (!_skip) {
                    driver.close();
                    autolog = false;
                }
                return;
            }

            if (tokenizer.sval.equals("chrome")) {
                // HELP: browser chrome <width>,<height>
                int w = 0, h = 0;
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    w = (int) tokenizer.nval;
                    System.out.print(' ');
                    System.out.print(w);
                    tokenizer.nextToken();
                    if (tokenizer.ttype == ',') {
                        tokenizer.nextToken();
                        System.out.print(',');
                        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                            h = (int) tokenizer.nval;
                            System.out.print(h);
                            System.out.println();
                            if (!_skip) {
                                this.chrome = new Dimension(w, h);
                            }
                            return;
                        }
                    }
                }
                throw new Exception("browser chrome arguments error at line " + tokenizer.lineno());
            }

            if (tokenizer.sval.equals("size")) {
                // HELP: browser size <width>,<height>
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    final int w = (int) tokenizer.nval;
                    System.out.print(' ');
                    System.out.print(w);
                    tokenizer.nextToken();
                    if (tokenizer.ttype == ',') {
                        tokenizer.nextToken();
                        System.out.print(',');
                        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                            final int h = (int) tokenizer.nval;
                            System.out.print(h);
                            System.out.println();
                            if (!_skip) {
                                new WaitFor(cmd, tokenizer, false) {
                                    @Override
                                    protected void run() throws RetryException {
                                        Dimension size = new Dimension(chrome.width + w, chrome.height + h);
                                        System.out.println("// chrome " + chrome.toString());
                                        System.out.println("// size with chrome " + size.toString());
                                        try {
                                            driver.manage().window().setSize(size);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            throw new RetryException("Could not set browser size");
                                        }
                                    }
                                };
                            }
                            return;
                        }
                    }
                }
                throw new Exception("browser size arguments error at line " + tokenizer.lineno());
            }
            if (tokenizer.sval.equals("pos")) {
                // HELP: browser pos <x>,<y>
                int x = 0, y = 0;
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    x = (int) tokenizer.nval;
                    System.out.print(' ');
                    System.out.print(x);
                    tokenizer.nextToken();
                    if (tokenizer.ttype == ',') {
                        tokenizer.nextToken();
                        System.out.print(',');
                        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                            y = (int) tokenizer.nval;
                            System.out.print(y);
                            System.out.println();
                            if (!_skip)
                                driver.manage().window().setPosition(new Point(x, y));
                            return;
                        }
                    }
                }
                throw new Exception("browser size arguments error at line " + tokenizer.lineno());
            }
            throw new Exception("browser unknown command argument at line " + tokenizer.lineno());
        }
        throw new Exception("browser missing command argument at line " + tokenizer.lineno());
    }

    if (cmd.equals("alias") || cmd.equals("function")) {
        // HELP: alias <name> { body }
        // HELP: function <name> (param, ...) { body }
        String name = null, args = null;
        List<String> params = null;
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            System.out.print(' ');
            System.out.print(tokenizer.sval);
            name = tokenizer.sval;
            params = getParams(tokenizer);
            args = getBlock(script, tokenizer, ' ', false);
            System.out.println();
            if (_skip)
                return;
            addFunction(name, params, args); // add alias
            return;
        }
        System.out.println();
        throw new Exception("alias name expected");
    }

    if (cmd.equals("while")) {
        // HELP: while { block }
        String block = null;
        block = getBlock(script, tokenizer, ' ', false);
        if (_skip)
            return;
        boolean exitloop = false;
        while (!exitloop) {
            try {
                runString(block, file, "while");
            } catch (Exception e) {
                exitloop = true;
            }
        }
        return;
    }

    if (cmd.equals("include")) {
        // HELP: include <script>
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            if (_skip)
                return;
            System.out.print(' ');
            System.out.println(tokenizer.sval);
            File include = new File(tokenizer.sval.startsWith("/") ? tokenizer.sval
                    : file.getParentFile().getCanonicalPath() + "/" + tokenizer.sval);
            runScript(include.getCanonicalPath());
            return;
        }
        throw new Exception("include argument should be a quoted filename");
    }

    if (cmd.equals("exec")) {
        // HELP: exec <command> { args ... }
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String command = tokenizer.sval;
            System.out.print(' ');
            System.out.print(command);
            List<String> args = getArgs(tokenizer, script);
            File include = new File(command.startsWith("/") ? command
                    : file.getParentFile().getCanonicalPath() + "/" + command);
            command = include.getCanonicalPath();
            System.out.println(command);
            List<String> arguments = new ArrayList<String>();
            arguments.add(command);
            arguments.addAll(args);
            Process process = Runtime.getRuntime().exec(arguments.toArray(new String[arguments.size()]));
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int exitStatus = process.waitFor();
            if (exitStatus != 0) {
                throw new Exception("exec command returned failure status " + exitStatus);
            }
            return;
        }
        System.out.println();
        throw new Exception("exec argument should be string or a word");
    }

    if (cmd.equals("exec-include")) {
        // HELP: exec-include <command> { args ... }
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String command = tokenizer.sval;
            System.out.print(' ');
            System.out.print(command);
            List<String> args = getArgs(tokenizer, script);
            File include = new File(command.startsWith("/") ? command
                    : file.getParentFile().getCanonicalPath() + "/" + command);
            command = include.getCanonicalPath();
            System.out.println(command);
            List<String> arguments = new ArrayList<String>();
            arguments.add(command);
            arguments.addAll(args);
            Process process = Runtime.getRuntime().exec(arguments.toArray(new String[arguments.size()]));
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String s = "", line = "";
            while ((line = reader.readLine()) != null) {
                s += line + "\n";
            }
            int exitStatus = process.waitFor();
            if (exitStatus != 0) {
                throw new Exception("exec-include command returned failure status " + exitStatus);
            }
            if (s.length() > 0) {
                runString(s, file, tokenizer.sval);
            }
            return;
        }
        System.out.println();
        throw new Exception(cmd + " argument should be string or a word");
    }

    if (cmd.equals("log")) {
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            if (action.equals("dump")) {
                // HELP: log dump
                System.out.println("");
                if (driver != null)
                    dumpLog();
                return;
            }
            if (action.equals("auto")) {
                // HELP: log auto <on|off>
                // HELP: log auto <true|false>
                tokenizer.nextToken();
                String onoff = tokenizer.sval;
                System.out.print(' ');
                System.out.println(onoff);
                autolog = onoff.equals("on") || onoff.equals("true");
                return;
            }
            System.out.println();
            throw new Exception("invalid log action");
        }
        System.out.println();
        throw new Exception("log argument should be string or a word");
    }

    if (cmd.equals("default")) {
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            if (action.equals("wait")) {
                // HELP: default wait <seconds>
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                    System.out.print(' ');
                    System.out.println(tokenizer.nval);
                    _defaultWaitFor = (int) (tokenizer.nval * 1000.0);
                }
                return;
            }
            if (action.equals("screenshot")) {
                // HELP: default screenshot <path>
                tokenizer.nextToken();
                if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                    System.out.print(' ');
                    System.out.println(tokenizer.sval);
                    screenShotPath = tokenizer.sval;
                }
                return;
            }
            System.out.println();
            throw new Exception("invalid default property " + tokenizer.sval);
        }
        System.out.println();
        throw new Exception("default argument should be string or a word");
    }

    if (cmd.equals("push")) {
        // HELP: push wait
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            ArrayList<Object> stack = stacks.get(action);
            if (null == stack) {
                stack = new ArrayList<Object>();
                stacks.put(action, stack);
            }
            if (action.equals("wait")) {
                stack.add(new Long(_waitFor));
                System.out.println();
                return;
            }
        }
        System.out.println();
        throw new Error("Invalid push argument");
    }

    if (cmd.equals("pop")) {
        // HELP: pop wait
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String action = tokenizer.sval;
            System.out.print(' ');
            System.out.print(action);
            ArrayList<Object> stack = stacks.get(action);
            if (null == stack || stack.isEmpty()) {
                throw new Error("pop called without corresponding push");
            }
            if (action.equals("wait")) {
                int index = stack.size() - 1;
                _waitFor = (Long) stack.get(index);
                stack.remove(index);
                System.out.println();
                return;
            }
        }
        System.out.println();
        throw new Error("Invalid push argument");
    }

    if (cmd.equals("echo")) {
        // HELP: echo "string"
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String text = script.getExpandedString(tokenizer);
            System.out.print(' ');
            System.out.println(text);
            if (!_skip)
                System.out.println(text);
            return;
        }
        System.out.println();
        throw new Exception("echo argument should be string or a word");
    }

    if (cmd.equals("sleep")) {
        // HELP: sleep <seconds>
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
            System.out.print(' ');
            System.out.println(tokenizer.nval);
            this.sleep((long) (tokenizer.nval * 1000));
            return;
        }
        System.out.println();
        throw new Exception("sleep command argument should be a number");
    }

    if (cmd.equals("fail")) {
        // HELP: fail "<message>"
        tokenizer.nextToken();
        if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
            String text = tokenizer.sval;
            System.out.print(' ');
            System.out.println(text);
            if (!_skip) {
                System.out.println("TEST FAIL: " + text);
                throw new Exception(text);
            }
            return;
        }
        System.out.println();
        throw new Exception("echo argument should be string or a word");
    }

    if (cmd.equals("debugger")) {
        // HELP: debugger
        System.out.println();
        this.sleepSeconds(10);
        return;
    }

    if (cmd.equals("if")) {
        // HELP: if <commands> then <commands> [else <commands>] endif
        _if = true;
        System.out.println();
        return;
    }

    if (cmd.equals("then")) {
        _if = false;
        _skip = !_test;
        System.out.println();
        return;
    }

    if (cmd.equals("else")) {
        _if = false;
        _skip = _test;
        System.out.println();
        return;
    }

    if (cmd.equals("endif")) {
        _skip = false;
        System.out.println();
        return;
    }

    if (cmd.equals("not")) {
        // HELP: not <check-command>
        System.out.println();
        _not = true;
        return;
    }

    if (null != driver) {

        // all these command require the browser to have been started

        if (cmd.equals("field") || cmd.equals("id") || cmd.equals("test-id")) {
            // HELP: field "<test-id>"
            // HELP: id "<test-id>"
            // HELP: test-id "<test-id>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                this.setContextToField(script, tokenizer);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a form.field argument");
        }

        if (cmd.equals("select")) {
            // HELP: select "<query-selector>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                selectContext(tokenizer, script);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a css selector argument");
        }

        if (cmd.equals("xpath")) {
            // HELP: xpath "<xpath-expression>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                this.xpathContext(script, tokenizer);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a css selector argument");
        }

        if (cmd.equals("wait")) {
            // HELP: wait <seconds>
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                System.out.print(' ');
                System.out.println(tokenizer.nval);

                // we will repeat then next select type command until it succeeds or we timeout
                _waitFor = (long) ((new Date()).getTime() + (tokenizer.nval * 1000));
                return;
            }

            // HELP: wait <action>
            if (tokenizer.ttype == StreamTokenizer.TT_WORD) {
                String action = tokenizer.sval;
                System.out.println(' ');
                System.out.println(action);
                if (action.equals("clickable")) {
                    long sleep = (_waitFor - (new Date()).getTime()) / 1000;
                    if (sleep > 0) {
                        System.out.println("WebDriverWait for " + sleep + " seconds");
                        WebDriverWait wait = new WebDriverWait(driver, sleep);
                        WebElement element = wait.until(ExpectedConditions.elementToBeClickable(selection));
                        if (element != selection) {
                            throw new Exception("element is not clickable");
                        }
                    } else {
                        System.out.println("WebDriverWait for " + sleep + " seconds (skipped)");
                    }
                    return;
                }
            }
            throw new Exception(cmd + " command requires a seconds argument");
        }

        if (cmd.equals("set") || cmd.equals("send")) {
            // HELP: set "<value>"
            // HELP: send "<value>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                if (_skip)
                    return;
                System.out.print(' ');
                System.out.println(script.getExpandedString(tokenizer));
                this.setContextValue(cmd, script, tokenizer, cmd.equals("set"));
                return;
            }
            System.out.println();
            throw new Exception("set command requires a value argument");
        }

        if (cmd.equals("test") || cmd.equals("check")) {
            // HELP: test "<value>"
            // HELP: check "<value>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"'
                    || tokenizer.ttype == '\'') {
                if (_skip)
                    return;
                System.out.print(' ');
                System.out.println(script.getExpandedString(tokenizer));
                this.testContextValue(cmd, script, tokenizer, false);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a value argument");
        }

        if (cmd.equals("checksum")) {
            // HELP: checksum "<checksum>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"'
                    || tokenizer.ttype == '\'') {
                if (_skip)
                    return;
                System.out.print(' ');
                System.out.println(script.getExpandedString(tokenizer));
                this.testContextValue(cmd, script, tokenizer, true);
                return;
            }
            System.out.println();
            throw new Exception(cmd + " command requires a value argument");
        }

        if (cmd.equals("click") || cmd.equals("click-now")) {
            // HELP: click
            System.out.println();
            final boolean wait = !cmd.equals("click-now");
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (wait) {
                            long sleep = (_waitFor - (new Date()).getTime()) / 1000;
                            if (sleep > 0) {
                                System.out.println("WebDriverWait for " + sleep + " seconds");
                                WebDriverWait wait = new WebDriverWait(driver, sleep);
                                WebElement element = wait
                                        .until(ExpectedConditions.elementToBeClickable(selection));
                                if (element == selection) {
                                    selection.click();
                                    return;
                                } else {
                                    throw new RetryException("click failed");
                                }
                            }
                        }
                        // click-nowait, no or negative wait period, just click
                        selection.click();
                    }
                }
            };
            return;
        }

        if (cmd.equals("scroll-into-view")) {
            // HELP: scroll-into-view
            System.out.println();
            if (null == selection)
                throw new Exception(cmd + " command requires a field selection at line " + tokenizer.lineno());
            if (!_skip) {
                try {
                    scrollContextIntoView(selection);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    info(selection, selectionCommand, false);
                    throw e;
                }
            }
            return;
        }

        if (cmd.equals("clear")) {
            // HELP: clear
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() {
                    if (!_skip)
                        selection.clear();
                }
            };
            return;
        }

        if (cmd.equals("call")) {
            // HELP: call <function> { args ... }
            String function = null, args = null;
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') { // expect a quoted string
                function = script.getExpandedString(tokenizer);
                System.out.print(' ');
                System.out.print(function);
                args = getBlock(script, tokenizer, ',', true);
                System.out.println();
                if (_skip)
                    return;
                if (null == args)
                    args = "";
                String js = "var result = window.RegressionTest.test('" + function + "',[" + args + "]);"
                        + "arguments[arguments.length-1](result);";
                System.out.println("> " + js);
                Object result = driver.executeAsyncScript(js);
                if (null != result) {
                    if (result.getClass() == RemoteWebElement.class) {
                        selection = (RemoteWebElement) result;
                        stype = SelectionType.Script;
                        selector = js;
                        System.out.println("new selection " + selection);
                    }
                }
                return;
            }
            System.out.println();
            throw new Exception("missing arguments for call statement at line " + tokenizer.lineno());
        }

        if (cmd.equals("enabled")) {
            // HELP: enabled
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (selection.isEnabled() != _not) {
                            _not = false;
                            return;
                        }
                        throw new RetryException("enabled check failed");
                    }
                }
            };
            return;
        }

        if (cmd.equals("selected")) {
            // HELP: selected
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (selection.isSelected() != _not) {
                            _not = false;
                            return;
                        }
                        throw new RetryException("selected check failed");
                    }
                }
            };
            return;
        }

        if (cmd.equals("displayed")) {
            // HELP: displayed
            System.out.println();
            new WaitFor(cmd, tokenizer, true) {
                @Override
                protected void run() throws RetryException {
                    if (!_skip) {
                        if (selection.isDisplayed() != _not) {
                            _not = false;
                            return;
                        }
                        throw new RetryException("displayed check failed");
                    }
                }
            };
            return;
        }

        if (cmd.equals("at")) {
            // HELP: at <x|*>,<y>
            int x = 0, y = 0;
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_NUMBER || tokenizer.ttype == '*') {
                x = (int) tokenizer.nval;
                System.out.print(' ');
                if (tokenizer.ttype == '*') {
                    x = -1;
                    System.out.print('*');
                } else {
                    x = (int) tokenizer.nval;
                    System.out.print(x);
                }
                tokenizer.nextToken();
                if (tokenizer.ttype == ',') {
                    tokenizer.nextToken();
                    System.out.print(',');
                    if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                        y = (int) tokenizer.nval;
                        System.out.print(y);
                        System.out.println();
                        final int X = x;
                        final int Y = y;
                        new WaitFor(cmd, tokenizer, true) {
                            @Override
                            protected void run() throws RetryException {
                                if (!_skip) {
                                    Point loc = selection.getLocation();
                                    if (((loc.x == X || X == -1) && loc.y == Y) != _not) {
                                        _not = false;
                                        return;
                                    }
                                    throw new RetryException("location check failed");
                                }
                            }
                        };
                        return;
                    }
                }
            }
            System.out.println();
            throw new Exception("at missing co-ordiantes at line " + tokenizer.lineno());
        }

        if (cmd.equals("size")) {
            // HELP: size <w|*>,<h>
            int mw = 0, w = 0, h = 0;
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_NUMBER || tokenizer.ttype == '*') {
                System.out.print(' ');
                if (tokenizer.ttype == '*') {
                    mw = w = -1;
                    System.out.print('*');
                } else {
                    mw = w = (int) tokenizer.nval;
                    System.out.print(w);
                }
                tokenizer.nextToken();
                if (tokenizer.ttype == ':') {
                    tokenizer.nextToken();
                    w = (int) tokenizer.nval;
                    System.out.print(':');
                    System.out.print(w);
                    tokenizer.nextToken();
                }
                if (tokenizer.ttype == ',') {
                    tokenizer.nextToken();
                    System.out.print(',');
                    if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) {
                        h = (int) tokenizer.nval;
                        System.out.print(h);
                        System.out.println();
                        final int MW = mw;
                        final int W = w;
                        final int H = h;
                        new WaitFor(cmd, tokenizer, true) {
                            @Override
                            protected void run() throws RetryException {
                                if (!_skip) {
                                    Dimension size = selection.getSize();
                                    if (((MW == -1 || (size.width >= MW && size.width <= W))
                                            && size.height == H) != _not) {
                                        _not = false;
                                        return;
                                    }
                                    throw new RetryException("size check failed");
                                }
                            }
                        };
                        return;
                    }
                }
            }
            System.out.println();
            throw new Exception("size missing dimensions at line " + tokenizer.lineno());
        }

        if (cmd.equals("tag")) {
            // HELP: tag <tag-name>
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                System.out.print(' ');
                System.out.print(tokenizer.sval);
                System.out.println();
                new WaitFor(cmd, tokenizer, true) {
                    @Override
                    protected void run() throws RetryException {
                        if (!_skip) {
                            String tag = selection.getTagName();
                            if (tokenizer.sval.equals(tag) != _not) {
                                _not = false;
                                return;
                            }
                            throw new RetryException("tag \"" + tokenizer.sval + "\" check failed, tag is "
                                    + tag + " at line " + tokenizer.lineno());
                        }
                    }
                };
                return;
            }
            System.out.println();
            throw new Exception("tag command has missing tag name at line " + tokenizer.lineno());
        }

        if (cmd.equals("info")) {
            // HELP: info
            System.out.println();
            if (null == selection)
                throw new Exception("info command requires a selection at line " + tokenizer.lineno());
            info(selection, selectionCommand, true);
            return;
        }

        if (cmd.equals("alert")) {
            // HELP: alert accept
            System.out.println();
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                System.out.print(' ');
                System.out.print(tokenizer.sval);
                if (tokenizer.sval.equals("accept")) {
                    System.out.println();
                    if (!_skip)
                        driver.switchTo().alert().accept();
                    return;
                }
            }
            System.out.println();
            throw new Exception("alert syntax error at line " + tokenizer.lineno());
        }

        if (cmd.equals("dump")) {
            // HELP: dump
            System.out.println();
            if (!_skip)
                dump();
            return;
        }

        if (cmd.equals("mouse")) {
            // HELP: mouse { <center|0,0|origin|body|down|up|click|+/-x,+/-y> commands ... }
            parseBlock(script, tokenizer, new BlockHandler() {
                public void parseToken(StreamTokenizer tokenizer, String token) {
                    int l = token.length();
                    if (token.equals("center")) {
                        actions.moveToElement(selection);
                    } else if ((l > 1 && token.substring(1, l - 1).equals("0,0")) || token.equals("origin")) {
                        actions.moveToElement(selection, 0, 0);
                    } else if (token.equals("body")) {
                        actions.moveToElement(driver.findElement(By.tagName("body")), 0, 0);
                    } else if (token.equals("down")) {
                        actions.clickAndHold();
                    } else if (token.equals("up")) {
                        actions.release();
                    } else if (token.equals("click")) {
                        actions.click();
                    } else if (l > 1) {
                        String[] a = token.substring(1, l - 1).split(",");
                        actions.moveByOffset(Integer.valueOf(a[0]), Integer.valueOf(a[1]));
                    } else {
                        // no-op
                    }
                }
            });
            System.out.println();
            actions.release();
            actions.build().perform();
            return;
        }

        if (cmd.equals("screenshot")) {
            // HELP: screenshot "<path>"
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '"') {
                String path = tokenizer.sval;
                System.out.print(' ');
                System.out.println(path);
                if (!_skip) {
                    WebDriver augmentedDriver = new Augmenter().augment(driver);
                    File screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
                    String outputPath;
                    if (screenShotPath == null || path.startsWith("/") || path.substring(1, 1).equals(":")) {
                        outputPath = path;
                    } else {
                        outputPath = screenShotPath + (screenShotPath.endsWith("/") ? "" : "/") + path;
                    }
                    System.out.println(screenshot.getAbsolutePath() + " -> " + path);
                    FileUtils.moveFile(screenshot, new File(outputPath));
                }
                return;
            }
            System.out.println();
            throw new Exception("screenshot argument should be a path");
        }
    }

    if (functions.containsKey(cmd)) {
        executeFunction(cmd, file, tokenizer, script);
        return;
    }

    if (null == driver) {
        throw new Exception("browser start must be used before attempt to interract with the browser");
    }

    System.out.println();
    throw new Exception("unrecognised command, " + cmd);
}

From source file:FourByFour.java

public void actionPerformed(ActionEvent event) {

    Object target = event.getSource();

    // Process the button events.
    if (target == skill_return_button) {
        skill_panel.setVisible(false);/*from  w w  w.jav  a  2  s . co m*/
        skill_return_button.setVisible(false);
        c_container.setVisible(true);
        b_container.setVisible(true);
        newGame();
    } else if (target == winner_return_button) {
        if (winner_flag) {
            String name = winner_name.getText();
            String tmp_name = new String("");
            int tmp_score = 0;
            boolean insert_flag = false;
            winner_flag = false;
            for (int i = 0; i < 20; i++) {
                if (insert_flag) {
                    name = names[i];
                    score = scores[i];
                    names[i] = tmp_name;
                    scores[i] = tmp_score;
                    tmp_name = name;
                    tmp_score = score;
                }
                if (!insert_flag && score > scores[i]) {
                    tmp_name = names[i];
                    tmp_score = scores[i];
                    scores[i] = score;
                    names[i] = name;
                    insert_flag = true;
                }
                high_names[i].setText(names[i]);
                high_scores[i].setText(Integer.toString(scores[i]));
            }
            scoresString = new String("");
            int place;
            for (int i = 0; i < 20; i++) {
                place = (int) places[i];
                scoresString += Integer.toString(place);
                scoresString += "\t";
                scoresString += names[i];
                scoresString += "   ";
                scoresString += Integer.toString(scores[i]);
                scoresString += "\n";
            }

            if (appletFlag) {
                // Use this section of code when writing the high
                // scores file back to a server. Requires the use
                // of a deamon on the server to receive the socket
                // connection.
                //
                // Create the output stream.
                // try {
                //    Socket socket = new Socket(host, port);
                //    outStream = new BufferedOutputStream
                //       (socket.getOutputStream(), 8192);
                // }
                // catch(IOException ioe) {
                //    System.out.println("Error: " + ioe.toString());
                // }
                // System.out.println("Output stream opened");
                //
                // Write the scores to the file back on the server.
                // outText = scoresString.getBytes();
                // try {
                //    outStream.write(outText);
                //    outStream.flush();
                //    outStream.close();
                //    outStream = null;
                // }
                // catch (IOException ioe) {
                //    System.out.println("Error: " + ioe.toString());
                // }
                // System.out.println("Output stream written");

                try {
                    OutputStreamWriter outFile = new OutputStreamWriter(new FileOutputStream("scores.txt"));
                    outFile.write(scoresString);
                    outFile.flush();
                    outFile.close();
                    outFile = null;
                } catch (IOException ioe) {
                    System.out.println("Error: " + ioe.toString());
                } catch (Exception e) {
                    System.out.println("Error: " + e.toString());
                }
            } else {

                try {
                    OutputStreamWriter outFile = new OutputStreamWriter(new FileOutputStream("scores.txt"));
                    outFile.write(scoresString);
                    outFile.flush();
                    outFile.close();
                    outFile = null;
                } catch (IOException ioe) {
                    System.out.println("Error: " + ioe.toString());
                }
            }
        }
        winner_panel.setVisible(false);
        winner_return_button.setVisible(false);
        winner_label.setVisible(false);
        winner_score_label.setVisible(false);
        winner_name_label.setVisible(false);
        winner_top_label.setVisible(false);
        winner_name.setVisible(false);
        c_container.setVisible(true);
        b_container.setVisible(true);
    } else if (target == high_return_button) {
        high_return_button.setVisible(false);
        high_panel.setVisible(false);
        c_container.setVisible(true);
        b_container.setVisible(true);
    } else if (target == instruct_return_button) {
        instruct_text.setVisible(false);
        instruct_return_button.setVisible(false);
        instruct_text.repaint();
        c_container.setVisible(true);
        b_container.setVisible(true);
    } else if (target == undo_button) {
        board.undo_move();
        canvas2D.repaint();
    } else if (target == instruct_button) {
        c_container.setVisible(false);
        b_container.setVisible(false);
        instruct_text.setVisible(true);
        instruct_return_button.setVisible(true);
    } else if (target == new_button) {
        newGame();
    } else if (target == skill_button) {
        c_container.setVisible(false);
        b_container.setVisible(false);
        skill_panel.setVisible(true);
        skill_return_button.setVisible(true);
    } else if (target == high_button) {
        // Read the high scores file.
        if (appletFlag) {
            try {
                inStream = new BufferedInputStream(new URL(getCodeBase(), "scores.txt").openStream(), 8192);
                Reader read = new BufferedReader(new InputStreamReader(inStream));
                StreamTokenizer st = new StreamTokenizer(read);
                st.whitespaceChars(32, 44);
                st.eolIsSignificant(false);

                int count = 0;
                int token = st.nextToken();
                boolean scoreFlag = true;
                String string;
                while (count < 20) {
                    places[count] = (int) st.nval;
                    string = new String("");
                    token = st.nextToken();
                    while (token == StreamTokenizer.TT_WORD) {
                        string += st.sval;
                        string += " ";
                        token = st.nextToken();
                    }
                    names[count] = string;
                    scores[count] = (int) st.nval;
                    token = st.nextToken();
                    count++;
                }
                inStream.close();
            } catch (Exception ioe) {
                System.out.println("Error: " + ioe.toString());
            }
        } else {
            try {
                inStream = new BufferedInputStream(new FileInputStream("scores.txt"));
                Reader read = new BufferedReader(new InputStreamReader(inStream));
                StreamTokenizer st = new StreamTokenizer(read);
                st.whitespaceChars(32, 44);
                st.eolIsSignificant(false);

                int count = 0;
                int token = st.nextToken();
                boolean scoreFlag = true;
                String string;
                while (count < 20) {
                    places[count] = (int) st.nval;
                    string = new String("");
                    token = st.nextToken();
                    while (token == StreamTokenizer.TT_WORD) {
                        string += st.sval;
                        string += " ";
                        token = st.nextToken();
                    }
                    names[count] = string;
                    scores[count] = (int) st.nval;
                    token = st.nextToken();
                    count++;
                }
                inStream.close();
            } catch (Exception ioe) {
                System.out.println("Error: " + ioe.toString());
            }
        }
        c_container.setVisible(false);
        b_container.setVisible(false);
        high_panel.setVisible(true);
        high_return_button.setVisible(true);
    }

    Checkbox box = group.getSelectedCheckbox();
    String label = box.getLabel();
    if (label.equals("Babe in the Woods        ")) {
        board.set_skill_level(0);
    } else if (label.equals("Walk and Chew Gum        ")) {
        board.set_skill_level(1);
    } else if (label.equals("Jeopardy Contestant      ")) {
        board.set_skill_level(2);
    } else if (label.equals("Rocket Scientist         ")) {
        board.set_skill_level(3);
    } else if (label.equals("Be afraid, be very afraid")) {
        board.set_skill_level(4);
    }
}

From source file:FourByFour.java

/**
 * Initialization//from w w  w .ja  va  2  s  .  co  m
 */
public void init() {

    // Set the port number.
    port = 4111;

    // Set the graphics window size.
    width = 350;
    height = 350;

    // Set the weighting factors used for scoring.
    level_weight = 1311;
    move_weight = 111;
    time_weight = 1000;

    // Create the "base" color for the AWT components.
    setBackground(new Color(200, 200, 200));

    // Read the instructions file.
    if (appletFlag) {

        // Get the host from which this applet came.
        host = getCodeBase().getHost();

        try {
            inStream = new BufferedInputStream(new URL(getCodeBase(), "instructions.txt").openStream(), 8192);
            text = new byte[5000];
            int character = inStream.read();
            int count = 0;
            while (character != -1) {
                text[count++] = (byte) character;
                character = inStream.read();
            }
            textString = new String(text);
            inStream.close();
        } catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }
    } else {

        try {
            inStream = new BufferedInputStream(new FileInputStream("instructions.txt"));
            text = new byte[5000];
            int character = inStream.read();
            int count = 0;
            while (character != -1) {
                text[count++] = (byte) character;
                character = inStream.read();
            }
            textString = new String(text);
            inStream.close();
        } catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }
    }

    // Read the high-scores file.
    places = new int[20];
    scores = new int[20];
    names = new String[20];
    if (appletFlag) {
        try {
            inStream = new BufferedInputStream(new URL(getCodeBase(), "scores.txt").openStream(), 8192);
            Reader read = new BufferedReader(new InputStreamReader(inStream));
            StreamTokenizer st = new StreamTokenizer(read);
            st.whitespaceChars(32, 44);
            st.eolIsSignificant(false);

            int count = 0;
            int token = st.nextToken();
            boolean scoreFlag = true;
            String string;
            while (count < 20) {
                places[count] = (int) st.nval;
                string = new String("");
                token = st.nextToken();
                while (token == StreamTokenizer.TT_WORD) {
                    string += st.sval;
                    string += " ";
                    token = st.nextToken();
                }
                names[count] = string;
                scores[count] = (int) st.nval;
                token = st.nextToken();
                count++;
            }
            inStream.close();
        } catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }
    } else {
        try {
            inStream = new BufferedInputStream(new FileInputStream("scores.txt"));
            Reader read = new BufferedReader(new InputStreamReader(inStream));
            StreamTokenizer st = new StreamTokenizer(read);
            st.whitespaceChars(32, 44);
            st.eolIsSignificant(false);

            int count = 0;
            int token = st.nextToken();
            boolean scoreFlag = true;
            String string;
            while (count < 20) {
                places[count] = (int) st.nval;
                string = new String("");
                token = st.nextToken();
                while (token == StreamTokenizer.TT_WORD) {
                    string += st.sval;
                    string += " ";
                    token = st.nextToken();
                }
                names[count] = string;
                scores[count] = (int) st.nval;
                token = st.nextToken();
                count++;
            }
            inStream.close();
        } catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }
    }

    // The positions object sets up the switch nodes which
    // control the rendering of the player's positions.
    positions = new Positions();

    // Create the game board object which is responsible
    // for keeping track of the moves on the game board
    // and determining what move the computer should make.
    board = new Board(this, positions, width, height);
    positions.setBoard(board);

    // Create a 2D graphics canvas.
    canvas2D = new Canvas2D(board);
    canvas2D.setSize(width, height);
    canvas2D.setLocation(width + 10, 5);
    canvas2D.addMouseListener(canvas2D);
    board.setCanvas(canvas2D);

    // Create the 2D backbuffer
    backbuffer2D = createImage(width, height);
    canvas2D.setBuffer(backbuffer2D);

    // Create a 3D graphics canvas.
    canvas3D = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
    canvas3D.setSize(width, height);
    canvas3D.setLocation(5, 5);

    // Create the scene branchgroup.
    BranchGroup scene3D = createScene3D();

    // Create a universe with the Java3D universe utility.
    universe = new SimpleUniverse(canvas3D);
    universe.addBranchGraph(scene3D);

    // Use parallel projection.
    View view = universe.getViewer().getView();
    view.setProjectionPolicy(View.PARALLEL_PROJECTION);

    // Set the universe Transform3D object.
    TransformGroup tg = universe.getViewingPlatform().getViewPlatformTransform();
    Transform3D transform = new Transform3D();
    transform.set(65.f, new Vector3f(0.0f, 0.0f, 400.0f));
    tg.setTransform(transform);

    // Create the canvas container.
    c_container = new Panel();
    c_container.setSize(720, 360);
    c_container.setLocation(0, 0);
    c_container.setVisible(true);
    c_container.setLayout(null);
    add(c_container);

    // Add the 2D and 3D canvases to the container.
    c_container.add(canvas2D);
    c_container.add(canvas3D);

    // Turn off the layout manager, widgets will be sized
    // and positioned explicitly.
    setLayout(null);

    // Create the button container.
    b_container = new Panel();
    b_container.setSize(720, 70);
    b_container.setLocation(0, 360);
    b_container.setVisible(true);
    b_container.setLayout(null);

    // Create the buttons.
    instruct_button = new Button("Instructions");
    instruct_button.setSize(135, 25);
    instruct_button.setLocation(10, 10);
    instruct_button.setVisible(true);
    instruct_button.addActionListener(this);

    new_button = new Button("New Game");
    new_button.setSize(135, 25);
    new_button.setLocation(150, 10);
    new_button.setVisible(true);
    new_button.addActionListener(this);

    undo_button = new Button("Undo Move");
    undo_button.setSize(135, 25);
    undo_button.setLocation(290, 10);
    undo_button.setVisible(true);
    undo_button.addActionListener(this);

    skill_button = new Button("Skill Level");
    skill_button.setSize(135, 25);
    skill_button.setLocation(430, 10);
    skill_button.setVisible(true);
    skill_button.addActionListener(this);

    high_button = new Button("High Scores");
    high_button.setSize(135, 25);
    high_button.setLocation(570, 10);
    high_button.setVisible(true);
    high_button.addActionListener(this);

    b_container.add(new_button);
    b_container.add(undo_button);
    b_container.add(skill_button);
    b_container.add(high_button);
    b_container.add(instruct_button);

    // Add the button container to the applet.
    add(b_container);

    // Create the "Skill Level" dialog box.
    skill_panel = new Panel();
    skill_panel.setSize(400, 300);
    skill_panel.setLocation(200, 20);
    skill_panel.setLayout(null);

    skill_label = new Label("Pick your skill level:");
    skill_label.setSize(200, 25);
    skill_label.setLocation(25, 20);
    skill_label.setVisible(true);
    skill_panel.add(skill_label);

    group = new CheckboxGroup();
    Checkbox skill_1 = new Checkbox("Babe in the Woods        ", group, false);
    Checkbox skill_2 = new Checkbox("Walk and Chew Gum        ", group, false);
    Checkbox skill_3 = new Checkbox("Jeopardy Contestant      ", group, false);
    Checkbox skill_4 = new Checkbox("Rocket Scientist         ", group, false);
    Checkbox skill_5 = new Checkbox("Be afraid, be very afraid", group, true);
    skill_1.setSize(170, 25);
    skill_1.setLocation(80, 60);
    skill_1.setVisible(true);
    skill_2.setSize(170, 25);
    skill_2.setLocation(80, 100);
    skill_2.setVisible(true);
    skill_3.setSize(170, 25);
    skill_3.setLocation(80, 140);
    skill_3.setVisible(true);
    skill_4.setSize(170, 25);
    skill_4.setLocation(80, 180);
    skill_4.setVisible(true);
    skill_5.setSize(170, 25);
    skill_5.setLocation(80, 220);
    skill_5.setVisible(true);
    skill_return_button = new Button("Return");
    skill_return_button.setSize(120, 25);
    skill_return_button.setLocation(300, 370);
    skill_return_button.setVisible(false);
    skill_return_button.addActionListener(this);
    skill_panel.add(skill_1);
    skill_panel.add(skill_2);
    skill_panel.add(skill_3);
    skill_panel.add(skill_4);
    skill_panel.add(skill_5);
    skill_panel.setVisible(false);
    add(skill_return_button);
    add(skill_panel);

    // Create the "Instructions" panel.
    instruct_return_button = new Button("Return");
    instruct_return_button.setLocation(300, 370);
    instruct_return_button.setSize(120, 25);
    instruct_return_button.setVisible(false);
    instruct_return_button.addActionListener(this);
    instruct_text = new TextArea(textString, 100, 200, TextArea.SCROLLBARS_VERTICAL_ONLY);
    instruct_text.setSize(715, 350);
    instruct_text.setLocation(0, 0);
    instruct_text.setVisible(false);
    add(instruct_text);

    add(instruct_return_button);

    high_panel = new Panel();
    high_panel.setSize(715, 350);
    high_panel.setLocation(0, 0);
    high_panel.setVisible(false);
    high_panel.setLayout(null);

    high_label = new Label("High Scores");
    high_label.setLocation(330, 5);
    high_label.setSize(200, 30);
    high_label.setVisible(true);
    high_panel.add(high_label);

    high_places = new Label[20];
    high_names = new Label[20];
    high_scores = new Label[20];
    for (int i = 0; i < 20; i++) {
        high_places[i] = new Label(Integer.toString(i + 1));
        high_places[i].setSize(20, 30);
        high_places[i].setVisible(true);
        high_names[i] = new Label(names[i]);
        high_names[i].setSize(150, 30);
        high_names[i].setVisible(true);
        high_scores[i] = new Label(Integer.toString(scores[i]));
        high_scores[i].setSize(150, 30);
        high_scores[i].setVisible(true);
        if (i < 10) {
            high_places[i].setLocation(70, i * 30 + 40);
            high_names[i].setLocation(100, i * 30 + 40);
            high_scores[i].setLocation(260, i * 30 + 40);
        } else {
            high_places[i].setLocation(425, (i - 10) * 30 + 40);
            high_names[i].setLocation(455, (i - 10) * 30 + 40);
            high_scores[i].setLocation(615, (i - 10) * 30 + 40);
        }
        high_panel.add(high_places[i]);
        high_panel.add(high_names[i]);
        high_panel.add(high_scores[i]);
    }
    high_return_button = new Button("Return");
    high_return_button.setSize(120, 25);
    high_return_button.setLocation(300, 370);
    high_return_button.setVisible(false);
    high_return_button.addActionListener(this);
    add(high_return_button);
    add(high_panel);

    // Create the "Winner" dialog box
    winner_panel = new Panel();
    winner_panel.setLayout(null);
    winner_panel.setSize(600, 500);
    winner_panel.setLocation(0, 0);
    winner_return_button = new Button("Return");
    winner_return_button.setSize(120, 25);
    winner_return_button.setLocation(300, 360);
    winner_return_button.addActionListener(this);
    winner_panel.add(winner_return_button);
    winner_label = new Label("");
    winner_label.setSize(200, 30);
    winner_label.setLocation(270, 110);
    winner_score_label = new Label("");
    winner_score_label.setSize(200, 30);
    winner_top_label = new Label("You have a score in the top 20.");
    winner_top_label.setSize(200, 25);
    winner_top_label.setLocation(260, 185);
    winner_top_label.setVisible(false);
    winner_name_label = new Label("Enter your name here:");
    winner_name_label.setSize(150, 25);
    winner_name_label.setLocation(260, 210);
    winner_name_label.setVisible(false);
    winner_name = new TextField("");
    winner_name.setSize(200, 30);
    winner_name.setLocation(260, 240);
    winner_name.setVisible(false);
    winner_panel.add(winner_label);
    winner_panel.add(winner_score_label);
    winner_panel.add(winner_top_label);
    winner_panel.add(winner_name_label);
    winner_panel.add(winner_name);
    winner_panel.setVisible(false);
    add(winner_panel);
}

From source file:org.apache.openjpa.jdbc.kernel.SQLStoreQuery.java

/**
 * Utility method to substitute '?num' for parameters in the given SQL
 * statement, and fill-in the order of the parameter tokens
 *//*w w  w. ja  va2 s . co m*/
public static String substituteParams(String sql, List<Integer> paramOrder) throws IOException {
    // if there's no "?" parameter marker, then we don't need to
    // perform the parsing process
    if (sql.indexOf("?") == -1)
        return sql;

    paramOrder.clear();
    StreamTokenizer tok = new StreamTokenizer(new StringReader(sql));
    tok.resetSyntax();
    tok.quoteChar('\'');
    tok.wordChars('0', '9');
    tok.wordChars('?', '?');

    StringBuilder buf = new StringBuilder(sql.length());
    for (int ttype; (ttype = tok.nextToken()) != StreamTokenizer.TT_EOF;) {
        switch (ttype) {
        case StreamTokenizer.TT_WORD:
            // a token is a positional parameter if it starts with
            // a "?" and the rest of the token are all numbers
            if (tok.sval.startsWith("?")) {
                buf.append("?");
                String pIndex = tok.sval.substring(1);
                if (pIndex.length() > 0) {
                    paramOrder.add(Integer.valueOf(pIndex));
                } else { // or nothing
                    paramOrder.add(paramOrder.size() + 1);
                }
            } else
                buf.append(tok.sval);
            break;
        case '\'':
            buf.append('\'');
            if (tok.sval != null) {
                buf.append(tok.sval);
                buf.append('\'');
            }
            break;
        default:
            buf.append((char) ttype);
        }
    }
    return buf.toString();
}

From source file:org.apache.wiki.plugin.DefaultPluginManager.java

/**
 *  Parses plugin arguments.  Handles quotes and all other kewl stuff.
 *
 *  <h3>Special parameters</h3>
 *  The plugin body is put into a special parameter defined by {@link #PARAM_BODY};
 *  the plugin's command line into a parameter defined by {@link #PARAM_CMDLINE};
 *  and the bounds of the plugin within the wiki page text by a parameter defined
 *  by {@link #PARAM_BOUNDS}, whose value is stored as a two-element int[] array,
 *  i.e., <tt>[start,end]</tt>.
 *
 * @param argstring The argument string to the plugin.  This is
 *  typically a list of key-value pairs, using "'" to escape
 *  spaces in strings, followed by an empty line and then the
 *  plugin body.  In case the parameter is null, will return an
 *  empty parameter list.// w  w w. java 2 s .c om
 *
 * @return A parsed list of parameters.
 *
 * @throws IOException If the parsing fails.
 */
public Map<String, String> parseArgs(String argstring) throws IOException {
    Map<String, String> arglist = new HashMap<String, String>();

    //
    //  Protection against funny users.
    //
    if (argstring == null)
        return arglist;

    arglist.put(PARAM_CMDLINE, argstring);

    StringReader in = new StringReader(argstring);
    StreamTokenizer tok = new StreamTokenizer(in);
    int type;

    String param = null;
    String value = null;

    tok.eolIsSignificant(true);

    boolean potentialEmptyLine = false;
    boolean quit = false;

    while (!quit) {
        String s;

        type = tok.nextToken();

        switch (type) {
        case StreamTokenizer.TT_EOF:
            quit = true;
            s = null;
            break;

        case StreamTokenizer.TT_WORD:
            s = tok.sval;
            potentialEmptyLine = false;
            break;

        case StreamTokenizer.TT_EOL:
            quit = potentialEmptyLine;
            potentialEmptyLine = true;
            s = null;
            break;

        case StreamTokenizer.TT_NUMBER:
            s = Integer.toString((int) tok.nval);
            potentialEmptyLine = false;
            break;

        case '\'':
            s = tok.sval;
            break;

        default:
            s = null;
        }

        //
        //  Assume that alternate words on the line are
        //  parameter and value, respectively.
        //
        if (s != null) {
            if (param == null) {
                param = s;
            } else {
                value = s;

                arglist.put(param, value);

                // log.debug("ARG: "+param+"="+value);
                param = null;
            }
        }
    }

    //
    //  Now, we'll check the body.
    //

    if (potentialEmptyLine) {
        StringWriter out = new StringWriter();
        FileUtil.copyContents(in, out);

        String bodyContent = out.toString();

        if (bodyContent != null) {
            arglist.put(PARAM_BODY, bodyContent);
        }
    }

    return arglist;
}

From source file:org.eclipse.mylyn.internal.phabricator.core.client.TracWebClient.java

/**
 * Parses the JavaScript code from the query page to extract repository configuration.
 *///  w  ww  .j a v a2  s .  c  om
private void parseAttributesTokenizer(String text) throws IOException {
    StreamTokenizer t = new StreamTokenizer(new StringReader(text));
    t.quoteChar('"');

    TracConfiguration configuration = new TracConfiguration(data);
    AttributeFactory attributeFactory = null;
    String attributeType = null;

    AttributeState state = AttributeState.INIT;
    int tokenType;
    while ((tokenType = t.nextToken()) != StreamTokenizer.TT_EOF) {
        switch (tokenType) {
        case StreamTokenizer.TT_WORD:
        case '"':
            if (state == AttributeState.IN_LIST) {
                attributeFactory = configuration.getFactoryByField(t.sval);
                if (attributeFactory != null) {
                    attributeFactory.initialize();
                }
            } else if (state == AttributeState.IN_ATTRIBUTE_KEY) {
                attributeType = t.sval;
            } else if (state == AttributeState.IN_ATTRIBUTE_VALUE_LIST && "options".equals(attributeType)) { //$NON-NLS-1$
                if (attributeFactory != null) {
                    attributeFactory.addAttribute(t.sval);
                }
            }
            break;
        case ':':
            if (state == AttributeState.IN_ATTRIBUTE_KEY) {
                state = AttributeState.IN_ATTRIBUTE_VALUE;
            }
            break;
        case ',':
            if (state == AttributeState.IN_ATTRIBUTE_VALUE) {
                state = AttributeState.IN_ATTRIBUTE_KEY;
            }
            break;
        case '[':
            if (state == AttributeState.IN_ATTRIBUTE_VALUE) {
                state = AttributeState.IN_ATTRIBUTE_VALUE_LIST;
            }
            break;
        case ']':
            if (state == AttributeState.IN_ATTRIBUTE_VALUE_LIST) {
                state = AttributeState.IN_ATTRIBUTE_VALUE;
            }
            break;
        case '{':
            if (state == AttributeState.INIT) {
                state = AttributeState.IN_LIST;
            } else if (state == AttributeState.IN_LIST) {
                state = AttributeState.IN_ATTRIBUTE_KEY;
            } else {
                throw new IOException("Error parsing attributes: unexpected token '{'"); //$NON-NLS-1$
            }
            break;
        case '}':
            if (state == AttributeState.IN_ATTRIBUTE_KEY || state == AttributeState.IN_ATTRIBUTE_VALUE) {
                state = AttributeState.IN_LIST;
            } else if (state == AttributeState.IN_LIST) {
                state = AttributeState.INIT;
            } else {
                throw new IOException("Error parsing attributes: unexpected token '}'"); //$NON-NLS-1$
            }
            break;
        }
    }
}

From source file:org.jdesigner.platform.web.converter.AbstractArrayConverter.java

/**
 * <p>/*from w w w . j ava 2s.  co  m*/
 * Parse an incoming String of the form similar to an array initializer in
 * the Java language into a <code>List</code> individual Strings for each
 * element, according to the following rules.
 * </p>
 * <ul>
 * <li>The string is expected to be a comma-separated list of values.</li>
 * <li>The string may optionally have matching '{' and '}' delimiters around
 * the list.</li>
 * <li>Whitespace before and after each element is stripped.</li>
 * <li>Elements in the list may be delimited by single or double quotes.
 * Within a quoted elements, the normal Java escape sequences are valid.</li>
 * </ul>
 * 
 * @param svalue
 *            String value to be parsed
 * @return The parsed list of String values
 * 
 * @exception ConversionException
 *                if the syntax of <code>svalue</code> is not syntactically
 *                valid
 * @exception NullPointerException
 *                if <code>svalue</code> is <code>null</code>
 */
protected List parseElements(String svalue) {

    // Validate the passed argument
    if (svalue == null) {
        throw new NullPointerException();
    }

    // Trim any matching '{' and '}' delimiters
    svalue = svalue.trim();
    if (svalue.startsWith("{") && svalue.endsWith("}")) {
        svalue = svalue.substring(1, svalue.length() - 1);
    }

    try {

        // Set up a StreamTokenizer on the characters in this String
        StreamTokenizer st = new StreamTokenizer(new StringReader(svalue));
        st.whitespaceChars(',', ','); // Commas are delimiters
        st.ordinaryChars('0', '9'); // Needed to turn off numeric flag
        st.ordinaryChars('.', '.');
        st.ordinaryChars('-', '-');
        st.wordChars('0', '9'); // Needed to make part of tokens
        st.wordChars('.', '.');
        st.wordChars('-', '-');

        // Split comma-delimited tokens into a List
        ArrayList list = new ArrayList();
        while (true) {
            int ttype = st.nextToken();
            if ((ttype == StreamTokenizer.TT_WORD) || (ttype > 0)) {
                list.add(st.sval);
            } else if (ttype == StreamTokenizer.TT_EOF) {
                break;
            } else {
                throw new ConversionException("Encountered token of type " + ttype);
            }
        }

        // Return the completed list
        return (list);

    } catch (IOException e) {

        throw new ConversionException(e);

    }

}

From source file:org.jdesigner.platform.web.converter.ArrayConverter.java

/**
 * <p>/*from w w w . j  av  a2s  . c om*/
 * Parse an incoming String of the form similar to an array initializer in
 * the Java language into a <code>List</code> individual Strings for each
 * element, according to the following rules.
 * </p>
 * <ul>
 * <li>The string is expected to be a comma-separated list of values.</li>
 * <li>The string may optionally have matching '{' and '}' delimiters around
 * the list.</li>
 * <li>Whitespace before and after each element is stripped.</li>
 * <li>Elements in the list may be delimited by single or double quotes.
 * Within a quoted elements, the normal Java escape sequences are valid.</li>
 * </ul>
 * 
 * @param type
 *            The type to convert the value to
 * @param value
 *            String value to be parsed
 * @return List of parsed elements.
 * 
 * @throws ConversionException
 *             if the syntax of <code>svalue</code> is not syntactically
 *             valid
 * @throws NullPointerException
 *             if <code>svalue</code> is <code>null</code>
 */
private List parseElements(Class type, String value) {

    if (log().isDebugEnabled()) {
        log().debug("Parsing elements, delimiter=[" + delimiter + "], value=[" + value + "]");
    }

    // Trim any matching '{' and '}' delimiters
    value = value.trim();
    if (value.startsWith("{") && value.endsWith("}")) {
        value = value.substring(1, value.length() - 1);
    }

    try {

        // Set up a StreamTokenizer on the characters in this String
        StreamTokenizer st = new StreamTokenizer(new StringReader(value));
        st.whitespaceChars(delimiter, delimiter); // Set the delimiters
        st.ordinaryChars('0', '9'); // Needed to turn off numeric flag
        st.wordChars('0', '9'); // Needed to make part of tokens
        for (int i = 0; i < allowedChars.length; i++) {
            st.ordinaryChars(allowedChars[i], allowedChars[i]);
            st.wordChars(allowedChars[i], allowedChars[i]);
        }

        // Split comma-delimited tokens into a List
        List list = null;
        while (true) {
            int ttype = st.nextToken();
            if ((ttype == StreamTokenizer.TT_WORD) || (ttype > 0)) {
                if (st.sval != null) {
                    if (list == null) {
                        list = new ArrayList();
                    }
                    list.add(st.sval);
                }
            } else if (ttype == StreamTokenizer.TT_EOF) {
                break;
            } else {
                throw new ConversionException(
                        "Encountered token of type " + ttype + " parsing elements to '" + toString(type) + ".");
            }
        }

        if (list == null) {
            list = Collections.EMPTY_LIST;
        }
        if (log().isDebugEnabled()) {
            log().debug(list.size() + " elements parsed");
        }

        // Return the completed list
        return (list);

    } catch (IOException e) {

        throw new ConversionException(
                "Error converting from String to '" + toString(type) + "': " + e.getMessage(), e);

    }

}

From source file:org.opencms.main.CmsShell.java

/**
 * Executes all commands read from the given input stream.<p>
 * //from   w  w w. j  a v  a  2s.  c o  m
 * @param fileInputStream a file input stream from which the commands are read
 */
private void executeCommands(FileInputStream fileInputStream) {

    try {
        LineNumberReader lnr = new LineNumberReader(new InputStreamReader(fileInputStream));
        while (!m_exitCalled) {
            printPrompt();
            String line = lnr.readLine();
            if (line == null) {
                // if null the file has been read to the end
                try {
                    Thread.sleep(500);
                } catch (Throwable t) {
                    // noop
                }
                break;
            }
            if (line.trim().startsWith("#")) {
                System.out.println(line);
                continue;
            }
            StringReader reader = new StringReader(line);
            StreamTokenizer st = new StreamTokenizer(reader);
            st.eolIsSignificant(true);

            // put all tokens into a List
            List<String> parameters = new ArrayList<String>();
            while (st.nextToken() != StreamTokenizer.TT_EOF) {
                if (st.ttype == StreamTokenizer.TT_NUMBER) {
                    parameters.add(Integer.toString(new Double(st.nval).intValue()));
                } else {
                    parameters.add(st.sval);
                }
            }
            reader.close();

            // extract command and arguments
            if (parameters.size() == 0) {
                if (m_echo) {
                    System.out.println();
                }
                continue;
            }
            String command = parameters.get(0);
            parameters = parameters.subList(1, parameters.size());

            // execute the command
            executeCommand(command, parameters);
        }
    } catch (Throwable t) {
        t.printStackTrace(System.err);
    }
}

From source file:org.openhab.io.caldav.internal.util.ExecuteCommandJob.java

/**
 * Parses a <code>command</code>. Utilizes the {@link StreamTokenizer} which
 * takes care of quoted Strings as well.
 * /*ww  w.  j a  v  a 2 s  . c  om*/
 * @param command the command to parse 
 * @return the tokenized command which can be processed by the 
 * <code>ConsoleInterpreter</code>
 * 
 * @see org.openhab.io.console.ConsoleInterpreter
 */
protected String[] parseCommand(String command) {
    logger.trace("going to parse command '{}'", command);

    // if the command starts with '>' it contains a script which needs no
    // further handling here ...
    if (command.startsWith(">")) {
        return new String[] { ">", command.substring(1).trim() };
    }

    StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(command));
    tokenizer.wordChars('_', '_');
    tokenizer.wordChars('-', '-');
    tokenizer.wordChars('.', '.');

    List<String> tokens = new ArrayList<String>();
    try {
        int tokenType = 0;
        while (tokenType != StreamTokenizer.TT_EOF && tokenType != StreamTokenizer.TT_EOL) {
            tokenType = tokenizer.nextToken();
            String token = "";
            switch (tokenType) {
            case StreamTokenizer.TT_WORD:
            case 34 /* quoted String */:
                token = tokenizer.sval;
                break;
            case StreamTokenizer.TT_NUMBER:
                token = String.valueOf(tokenizer.nval);
                break;
            }
            tokens.add(token);
            logger.trace("read value {} from the given command", token);
        }
    } catch (IOException ioe) {
    }

    return tokens.toArray(new String[0]);
}