Example usage for java.util Scanner findWithinHorizon

List of usage examples for java.util Scanner findWithinHorizon

Introduction

In this page you can find the example usage for java.util Scanner findWithinHorizon.

Prototype

public String findWithinHorizon(Pattern pattern, int horizon) 

Source Link

Document

Attempts to find the next occurrence of the specified pattern.

Usage

From source file:org.perf4j.log4j.AppenderTest.java

public void testAppenders() throws Exception {
    DOMConfigurator.configure(getClass().getResource("log4j.xml"));

    AsyncCoalescingStatisticsAppender appender = (AsyncCoalescingStatisticsAppender) Logger
            .getLogger(StopWatch.DEFAULT_LOGGER_NAME).getAppender("coalescingStatistics");

    //log from a bunch of threads
    TestLoggingThread[] testThreads = new TestLoggingThread[10];
    for (int i = 0; i < testThreads.length; i++) {
        testThreads[i] = new TestLoggingThread();
        testThreads[i].start();/* ww  w . ja  v a 2  s .com*/
    }

    for (TestLoggingThread testThread : testThreads) {
        testThread.join();
    }

    //close the output appender, which prevents us from returning until this method completes.
    appender.close();

    //simple verification ensures that the total number of logged messages is correct.
    //tagName  avg           min     max     std dev       count, which is group 1
    String regex = "tag\\d\\s*\\d+\\.\\d\\s*\\d+\\s*\\d+\\s*\\d+\\.\\d\\s*(\\d+)";
    Pattern statLinePattern = Pattern.compile(regex);
    Scanner scanner = new Scanner(new File("target/statisticsLog.log"));

    int totalCount = 0;
    while (scanner.findWithinHorizon(statLinePattern, 0) != null) {
        totalCount += Integer.parseInt(scanner.match().group(1));
    }
    assertEquals(testThreads.length * TestLoggingThread.STOP_WATCH_COUNT, totalCount);
}

From source file:org.seedstack.seed.shell.internal.AbstractShell.java

protected List<Command> createCommandActions(String line) {
    if (Strings.isNullOrEmpty(line)) {
        return new ArrayList<Command>();
    }/*from  w  ww  . ja v  a 2 s .  c o  m*/

    List<Command> commands = new ArrayList<Command>();

    Scanner scanner = new Scanner(new StringReader(line));

    String qualifiedName = null;
    List<String> args = new ArrayList<String>();

    while (scanner.hasNext()) {
        if (qualifiedName == null) {
            if (scanner.hasNext(COMMAND_PATTERN)) {
                qualifiedName = scanner.next(COMMAND_PATTERN);
            } else {
                throw SeedException.createNew(ShellErrorCode.COMMAND_PARSING_ERROR);
            }
        } else {
            // Find next token respecting quoted strings
            String arg = scanner.findWithinHorizon("[^\"\\s]+|\"(\\\\.|[^\\\\\"])*\"", 0);
            if (arg != null) {
                if ("|".equals(arg)) {
                    // unquoted pipe, we execute the command and store the result for the next one
                    commands.add(createCommandAction(qualifiedName, args));

                    qualifiedName = null;
                    args = new ArrayList<String>();
                } else {
                    // if it's a quoted string, unquote it
                    if (arg.startsWith("\"")) {
                        arg = arg.substring(1);
                    }
                    if (arg.endsWith("\"")) {
                        arg = arg.substring(0, arg.length() - 1);
                    }

                    // replace any escaped quote by real quote
                    args.add(arg.replaceAll("\\\\\"", "\""));
                }
            } else {
                throw SeedException.createNew(ShellErrorCode.COMMAND_SYNTAX_ERROR).put("value", scanner.next());
            }
        }
    }

    commands.add(createCommandAction(qualifiedName, args));

    return commands;
}

From source file:org.seedstack.shell.internal.AbstractShell.java

List<Command> createCommandActions(String line) {
    if (Strings.isNullOrEmpty(line)) {
        return new ArrayList<>();
    }/*from   w w  w  .j  av a  2 s  . c  o  m*/

    List<Command> commands = new ArrayList<>();

    Scanner scanner = new Scanner(new StringReader(line));

    String qualifiedName = null;
    List<String> args = new ArrayList<>();

    while (scanner.hasNext()) {
        if (qualifiedName == null) {
            if (scanner.hasNext(COMMAND_PATTERN)) {
                qualifiedName = scanner.next(COMMAND_PATTERN);
            } else {
                throw SeedException.createNew(ShellErrorCode.COMMAND_PARSING_ERROR);
            }
        } else {
            // Find next token respecting quoted strings
            String arg = scanner.findWithinHorizon("[^\"\\s]+|\"(\\\\.|[^\\\\\"])*\"", 0);
            if (arg != null) {
                if ("|".equals(arg)) {
                    // unquoted pipe, we execute the command and store the result for the next one
                    commands.add(createCommandAction(qualifiedName, args));

                    qualifiedName = null;
                    args = new ArrayList<>();
                } else {
                    // if it's a quoted string, unquote it
                    if (arg.startsWith("\"")) {
                        arg = arg.substring(1);
                    }
                    if (arg.endsWith("\"")) {
                        arg = arg.substring(0, arg.length() - 1);
                    }

                    // replace any escaped quote by real quote
                    args.add(arg.replaceAll("\\\\\"", "\""));
                }
            } else {
                throw SeedException.createNew(ShellErrorCode.COMMAND_SYNTAX_ERROR).put("value", scanner.next());
            }
        }
    }

    commands.add(createCommandAction(qualifiedName, args));

    return commands;
}

From source file:plptool.gui.ProjectDriver.java

/**
 * Open plp file specified by path.//  ww w . j a v a  2 s.  c  o m
 *
 * @param path Path to project file to load.
 * @param assemble Attempt to assemble after opening (if dirty is not set)
 * @return PLP_OK on successful operation, error code otherwise
 */
public int open(String path, boolean assemble) {
    File plpFile = new File(path);
    CallbackRegistry.callback(CallbackRegistry.PROJECT_OPEN, plpFile);

    if (!plpFile.exists())
        return Msg.E("open(" + path + "): File not found.", Constants.PLP_BACKEND_PLP_OPEN_ERROR, null);

    boolean metafileFound = false;
    dirty = true;

    Msg.I("Opening " + path, null);

    if (arch != null) {
        arch.cleanup();
        arch = null;
    }
    asm = null;
    asms = new ArrayList<PLPAsmSource>();
    smods = null;
    watcher = null;
    pAttrSet = new HashMap<String, Object>();
    HashMap<String, Integer> asmFileOrder = new HashMap<String, Integer>();

    try {

        TarArchiveInputStream tIn = new TarArchiveInputStream(new FileInputStream(plpFile));
        TarArchiveEntry entry;
        byte[] image;
        String metaStr;

        // Find meta file first
        while ((entry = tIn.getNextTarEntry()) != null) {
            if (entry.getName().equals("plp.metafile")) {
                image = new byte[(int) entry.getSize()];
                tIn.read(image, 0, (int) entry.getSize());
                metaStr = new String(image);

                metafileFound = true;
                meta = metaStr;
                Scanner metaScanner;

                String lines[] = meta.split("\\r?\\n");
                if (lines[0].equals(Text.projectFileVersionString)) {

                } else {
                    Msg.W("This is not a " + Text.projectFileVersionString + " project file. Opening anyways.",
                            this);
                }

                metaScanner = new Scanner(meta);
                metaScanner.findWithinHorizon("DIRTY=", 0);
                if (metaScanner.nextInt() == 0)
                    dirty = false;
                if (metaScanner.findWithinHorizon("ARCH=", 0) != null) {
                    String temp = metaScanner.nextLine();
                    if (Config.cfgOverrideISA >= 0) { // ISA ID override, ignore the metafile
                        arch = ArchRegistry.getArchitecture(this, Config.cfgOverrideISA);
                        arch.init();
                    } else if (temp.equals("plpmips")) {
                        Msg.W("This project file was created by PLPTool version 3 or earlier. "
                                + "Meta data for this project will be updated "
                                + "with the default ISA (plpmips) when the project " + "file is saved.", this);
                        arch = ArchRegistry.getArchitecture(this, ArchRegistry.ISA_PLPMIPS);
                        arch.init();
                    } else {
                        arch = ArchRegistry.getArchitecture(this, Integer.parseInt(temp));
                        if (arch == null) {
                            Msg.W("Invalid ISA ID is specified in the project file: '" + temp
                                    + "'. Assuming PLPCPU.", this);
                            arch = ArchRegistry.getArchitecture(this, ArchRegistry.ISA_PLPMIPS);
                        }
                        arch.init();
                    }
                    arch.hook(this);
                }

                // get asm files order
                int asmOrder = 0;
                while (metaScanner.hasNext()) {
                    String asmName = metaScanner.nextLine();
                    if (asmName.endsWith(".asm")) {
                        asmFileOrder.put(asmName, new Integer(asmOrder));
                        asmOrder++;
                        asms.add(null);
                    }
                }
            }
        }

        if (!metafileFound)
            return Msg.E("No PLP metadata found.", Constants.PLP_BACKEND_INVALID_PLP_FILE, this);

        // reset the tar input stream
        tIn = new TarArchiveInputStream(new FileInputStream(plpFile));

        while ((entry = tIn.getNextTarEntry()) != null) {
            boolean handled = false;
            image = new byte[(int) entry.getSize()];
            tIn.read(image, 0, (int) entry.getSize());
            metaStr = new String(image);

            // Hook for project open for each entry
            Object[] eParams = { entry.getName(), image, plpFile };
            handled = CallbackRegistry.callback(CallbackRegistry.PROJECT_OPEN_ENTRY, eParams) || handled;

            if (entry.getName().endsWith("asm") && !entry.getName().startsWith("plp.")) {
                Integer order = (Integer) asmFileOrder.get(entry.getName());
                if (order == null)
                    Msg.W("The file '" + entry.getName() + "' is not listed in "
                            + "the meta file. This file will be removed when the project " + "is saved.", this);
                else {
                    asms.set(order, new PLPAsmSource(metaStr, entry.getName(), order));
                }

            } else if (entry.getName().equals("plp.metafile")) {
                // we've done reading the metafile

            } else if (entry.getName().equals("plp.image")) {
                binimage = new byte[(int) entry.getSize()];
                binimage = image;

            } else if (entry.getName().equals("plp.hex")) {
                hexstring = new String(image);

                // Restore bus modules states
            } else if (entry.getName().equals("plp.simconfig")) {
                Msg.D("simconfig:\n" + metaStr + "\n", 4, this);
                String lines[] = metaStr.split("\\r?\\n");
                int i;

                for (i = 0; i < lines.length; i++) {
                    String tokens[] = lines[i].split("::");

                    if (lines[i].startsWith("simRunnerDelay")) {
                        Config.simRunnerDelay = Integer.parseInt(tokens[1]);
                    }

                    if (lines[i].equals("MODS")) {
                        i++;
                        this.smods = new Preset();

                        while (i < lines.length && !lines[i].equals("END")) {
                            tokens = lines[i].split("::");
                            if (tokens.length > 4 && tokens[4].equals("noframe"))
                                smods.addModuleDefinition(Integer.parseInt(tokens[0]),
                                        Long.parseLong(tokens[2]), Long.parseLong(tokens[3]), false, false);
                            else if (tokens.length > 4)
                                smods.addModuleDefinition(Integer.parseInt(tokens[0]),
                                        Long.parseLong(tokens[2]), Long.parseLong(tokens[3]), true,
                                        Boolean.parseBoolean(tokens[5]));

                            i++;
                        }
                    }

                    if (lines[i].equals("WATCHER")) {
                        i++;
                        this.watcher = Watcher.getTableInitialModel();

                        while (i < lines.length && !lines[i].equals("END")) {
                            tokens = lines[i].split("::");
                            Object row[] = { tokens[0], tokens[1], null, null };
                            watcher.addRow(row);
                            i++;
                        }
                    }

                    if (lines[i].equals("ISASPECIFIC")) {
                        i++;

                        while (i < lines.length && !lines[i].equals("END")) {
                            tokens = lines[i].split("::");
                            arch.restoreArchSpecificSimStates(tokens);
                            i++;
                        }
                    }
                }
            } else if (handled) {

            } else {
                Msg.W("open(" + path + "): unable to process entry: " + entry.getName()
                        + ". This file will be removed when" + " you save the project.", this);
            }
        }

        tIn.close();

        if (asmFileOrder.isEmpty()) {
            return Msg.E("open(" + path + "): no .asm files found.", Constants.PLP_BACKEND_INVALID_PLP_FILE,
                    null);
        }

    } catch (Exception e) {
        Msg.trace(e);
        return Msg.E("open(" + path + "): Invalid PLP archive.", Constants.PLP_BACKEND_INVALID_PLP_FILE, null);
    }

    if (arch == null) {
        Msg.W("No ISA information specified in the archive, assuming plpmips", this);
        arch = ArchRegistry.getArchitecture(this, ArchRegistry.ISA_PLPMIPS);
        arch.init();
    }

    plpfile = new File(path);
    modified = false;
    open_asm = 0;

    for (int i = 0; i < asms.size(); i++)
        Msg.I(i + ": " + asms.get(i).getAsmFilePath(), null);

    if (g)
        refreshProjectView(false);
    if (!dirty && assemble) {
        assemble();
        asm_req = false;
    } else
        asm_req = true;

    if (g) {
        g_opts.restoreSavedOpts();
        desimulate();

        if (asm != null && asm.isAssembled())
            g_dev.enableSimControls();
        else
            g_dev.disableSimControls();

        this.setUnModified();
        updateWindowTitle();
        g_dev.updateDevelopRecentProjectList(plpFile.getAbsolutePath());
        if (g_asmview != null)
            g_asmview.dispose();
    }

    CallbackRegistry.callback(CallbackRegistry.PROJECT_OPEN_SUCCESSFUL, plpFile);
    return Constants.PLP_OK;
}

From source file:plptool.gui.ProjectDriver.java

/**
 * GUI: update the develop window to reflect the current state of the
 * project driver (open file, etc.)//from ww w.  ja va 2  s.  c  om
 *
 * @param commitCurrentAsm Whether to commit currently open asm file
 * in the editor before refreshing.
 * @return PLP_OK
 */
public int refreshProjectView(boolean commitCurrentAsm) {
    Msg.D("Project view refresh...", 3, this);

    if (plpfile == null) {
        g_dev.disableBuildControls();
        g_dev.catchyPLP();

        g_dev.getProjectTree()
                .setModel(new DefaultTreeModel(new DefaultMutableTreeNode("No project file open.")));

        return Constants.PLP_OK;
    }

    if (commitCurrentAsm)
        updateAsm(open_asm, g_dev.getEditorText());

    updateWindowTitle();

    DefaultMutableTreeNode root = new DefaultMutableTreeNode(plpfile.getName());
    DefaultMutableTreeNode srcRoot = new DefaultMutableTreeNode("Source Files");
    DefaultMutableTreeNode metaRoot = new DefaultMutableTreeNode("Meta Information");
    root.add(srcRoot);
    root.add(metaRoot);
    for (int i = 0; i < asms.size(); i++)
        srcRoot.add(new DefaultMutableTreeNode(i + ": " + asms.get(i).getAsmFilePath()));

    Scanner metaScanner = new Scanner(meta);
    metaScanner.findWithinHorizon("DIRTY=", 0);
    int meta_dirty = metaScanner.nextInt();
    metaRoot.add(new DefaultMutableTreeNode("meta.DIRTY=" + meta_dirty));
    metaRoot.add(new DefaultMutableTreeNode("ISA=" + ArchRegistry.getStringID(arch.getID())));

    g_dev.getProjectTree().setModel(new DefaultTreeModel(root));
    for (int i = 0; i < g_dev.getProjectTree().getRowCount(); i++)
        g_dev.getProjectTree().expandRow(i);

    if (!asms.get(open_asm).getAsmString().equals(g_dev.getEditorText()))
        g_dev.setEditorText(asms.get(open_asm).getAsmString());

    g_dev.getEditor().setEnabled(true);
    g_dev.getEditor().setVisible(true);
    g_dev.getEditor().setCaretPosition(0);
    g_dev.enableBuildControls();

    String header = asms.get(open_asm).getAsmFilePath();

    if (open_asm == 0)
        header += " <main program>";

    g_dev.setCurFile(header);

    CallbackRegistry.callback(CallbackRegistry.GUI_VIEW_REFRESH, commitCurrentAsm);
    Msg.D("Done.", 3, this);
    return Constants.PLP_OK;
}

From source file:ui.UI.java

private void jButtonConvertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConvertActionPerformed

    if (toddler.getOutputFile().exists()) {
        toddler.getOutputFile().delete();
    }//from   w  ww . j  a  v  a 2  s .  c  o m

    BufferedReader reader = new BufferedReader(new InputStreamReader(toddler.getProcessOutputStream()));

    toddler.execute();

    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {

            Scanner outputScanner = new Scanner(toddler.getProcessOutputStream());
            Pattern durPattern = Pattern.compile("(?<=Duration: )[^,]*");
            Pattern timePattern = Pattern.compile("(?<=time=)[\\d:.]*");

            String[] durationHMS = outputScanner.findWithinHorizon(durPattern, 0).split(":");
            double totalSecs = Integer.parseInt(durationHMS[0]) * 3600 + Integer.parseInt(durationHMS[1]) * 60
                    + Double.parseDouble(durationHMS[2]);

            String match;
            String[] matchSplit;
            while (null != (match = outputScanner.findWithinHorizon(timePattern, 0))) {
                matchSplit = match.split(":");
                double progress = (Integer.parseInt(matchSplit[0]) * 3600 + Integer.parseInt(matchSplit[1]) * 60
                        + Double.parseDouble(matchSplit[2])) / totalSecs * 100;
                position((int) progress);
                System.out.printf("Progress: %.2f%%%n", progress);

            }
            CompletionPopup popup = new CompletionPopup();
            popup.setVisible(true);
            popup.setUIInstance(UI.this);

        }
    });
    thread.start();

}