Example usage for java.util Scanner hasNext

List of usage examples for java.util Scanner hasNext

Introduction

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

Prototype

public boolean hasNext() 

Source Link

Document

Returns true if this scanner has another token in its input.

Usage

From source file:edu.clemson.cs.nestbed.server.management.instrumentation.ProgramWeaverManagerImpl.java

public String findComponentFromMakefile(File makefile) throws RemoteException {
    String component = null;/*www  .  java 2  s.  c o m*/
    Scanner scanner = null;

    try {
        log.debug("Makefile:  " + makefile);
        scanner = new Scanner(makefile);

        while (scanner.hasNext() && component == null) {
            String line = scanner.nextLine();
            String regExp = "^COMPONENT=(\\S+)";
            Pattern pattern = Pattern.compile(regExp);
            Matcher matcher = pattern.matcher(line);

            if (matcher.find()) {
                component = matcher.group(1);
            }
        }
    } catch (FileNotFoundException fnfe) {
        throw new RemoteException("FileNotFoundException", fnfe);
    } finally {
        try {
            scanner.close();
        } catch (Exception ex) {
            /* empty */ }
    }

    if (component == null) {
        // FIXME:  Shouldn't be throwing generic Exceptions
        throw new RemoteException("No main component found in Makefile.");
    }

    return component;
}

From source file:csns.importer.parser.csula.RosterParserImpl.java

/**
 * This parser handles the format under Self Service -> Faculty Center -> My
 * Schedule on GET. A sample record is as follows:
 * "Doe,John M 302043188 3.00 Engr, Comp Sci, & Tech  CS MS". Again, not all
 * fields may be present./*  w w  w.j a  v a  2 s .co m*/
 */
private List<ImportedUser> parse2(String text) {
    List<ImportedUser> students = new ArrayList<ImportedUser>();
    Stack<String> stack = new Stack<String>();

    Scanner scanner = new Scanner(text);
    scanner.useDelimiter("\\s+|\\r\\n|\\r|\\n");
    while (scanner.hasNext()) {
        String name = "";
        do {
            String token = scanner.next();
            if (!isName(token))
                stack.push(token);
            else {
                name = token;
                while (!stack.isEmpty() && !isDegree(stack.peek()))
                    name = stack.pop() + " " + name;
                break;
            }
        } while (scanner.hasNext());

        String cin = "";
        boolean cinFound = false;
        while (scanner.hasNext()) {
            cin = scanner.next();
            if (isCin(cin)) {
                cinFound = true;
                break;
            } else
                name += " " + cin;
        }

        if (cinFound) {
            ImportedUser student = new ImportedUser();
            student.setCin(cin);
            student.setName(name);
            students.add(student);
        }
    }
    scanner.close();

    return students;
}

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 ww  w  . j  a 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:cpd3314.project.CPD3314ProjectTest.java

private void assertFilesEqual(File a, File b) throws IOException {
    Scanner aIn = new Scanner(a);
    Scanner bIn = new Scanner(b);
    while (aIn.hasNext() && bIn.hasNext()) {
        assertEquals(aIn.nextLine().trim(), bIn.nextLine().trim());
    }//from   w w  w .  j  av a  2 s .c  o m
    assertTrue("Files Not Equal Length", !aIn.hasNext() && !bIn.hasNext());
}

From source file:com.sonicle.webtop.core.versioning.SqlUpgradeScript.java

private void readFile(InputStreamReader readable, boolean flatNewLines) throws IOException {
    this.statements = new ArrayList<>();
    StringBuilder sb = null, sbsql = null;
    String lines[] = null;/*from   w  w  w  .  j ava  2  s  .co m*/

    Scanner s = new Scanner(readable);
    s.useDelimiter("(;( )?(\r)?\n)");
    //s.useDelimiter("(;( )?(\r)?\n)|(--\n)");
    while (s.hasNext()) {
        String block = s.next();
        block = StringUtils.replace(block, "\r", "");
        if (!StringUtils.isEmpty(block)) {
            // Remove remaining ; at the end of the block (only if this block is the last one)
            if (!s.hasNext() && StringUtils.endsWith(block, ";"))
                block = StringUtils.left(block, block.length() - 1);

            sb = new StringBuilder();
            sbsql = new StringBuilder();
            lines = StringUtils.split(block, "\n");
            for (String line : lines) {
                if (AnnotationLine.matches(line)) {
                    if (DataSourceAnnotationLine.matches(line)) {
                        statements.add(new DataSourceAnnotationLine(line));
                    } else if (IgnoreErrorsAnnotationLine.matches(line)) {
                        statements.add(new IgnoreErrorsAnnotationLine(line));
                    } else if (RequireAdminAnnotationLine.matches(line)) {
                        statements.add(new RequireAdminAnnotationLine(line));
                    } else {
                        throw new IOException("Bad line: " + line);
                    }
                } else if (CommentLine.matches(line)) {
                    sb.append(line);
                    sb.append("\n");
                } else {
                    sbsql.append(StringUtils.trim(line));
                    sbsql.append(" ");
                    if (!flatNewLines)
                        sbsql.append("\n");
                }
            }
            if (sb.length() > 0)
                statements.add(new CommentLine(StringUtils.removeEnd(sb.toString(), "\n")));
            if (sbsql.length() > 0)
                statements.add(new SqlLine(StringUtils.removeEnd(sbsql.toString(), "\n")));
        }
    }
}

From source file:org.colombbus.tangara.core.Version.java

private void doExtractFieldsFromText(String textVersion) throws Exception {
    Scanner scanner = new Scanner(textVersion);
    scanner.useDelimiter("\\."); //$NON-NLS-1$
    major = scanner.nextInt();//from   w w w .j  av  a  2  s.c o  m
    if (scanner.hasNext())
        minor = scanner.nextInt();
    if (scanner.hasNext())
        fix = scanner.nextInt();
    if (scanner.hasNext())
        qualifier = scanner.next();
    if (scanner.hasNext()) {
        throw new Exception("Too many fields"); //$NON-NLS-1$
    }
    scanner.close();
}

From source file:eu.project.ttc.resources.FixedExpressionResource.java

public void load(DataResource data) throws ResourceInitializationException {
    InputStream inputStream = null;
    try {/*  ww w  .  j a v a  2  s  .c om*/
        inputStream = data.getInputStream();
        Scanner scanner = null;
        try {
            String fixedExpression, line;
            String[] str;
            scanner = new Scanner(inputStream, "UTF-8");
            scanner.useDelimiter(TermSuiteConstants.LINE_BREAK);
            while (scanner.hasNext()) {
                line = scanner.next().split(TermSuiteConstants.DIESE)[0].trim();
                str = line.split(TermSuiteConstants.TAB);
                fixedExpression = str[0];

                fixedExpressionLemmas.add(fixedExpression);
            }
        } catch (Exception e) {
            throw new ResourceInitializationException(e);
        } finally {
            IOUtils.closeQuietly(scanner);
        }
    } catch (IOException e) {
        LOGGER.error("Could not load file {}", data.getUrl());
        throw new ResourceInitializationException(e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:MediaLibrary.java

public MediaLibrary(String jsonFilename) {
    this.mediaFiles = new HashMap<String, MediaDescription>();
    count = 0;// w  w  w.j av  a  2  s  . c  om

    Scanner ifstr = null;

    try {
        ifstr = new Scanner(new FileInputStream(jsonFilename));

        StringBuilder sb = new StringBuilder();

        while (ifstr.hasNext()) {
            sb.append(ifstr.next());
        }

        JSONObject obj = new JSONObject(sb.toString());

        for (String title : JSONObject.getNames(obj)) {
            JSONObject tobj = new JSONObject(obj.get(title).toString());

            MediaDescription md = new MediaDescription(tobj);

            mediaFiles.put(md.getTitle(), md);
        }

    } catch (FileNotFoundException fnfe) {
        System.out.println("File not found");
        fnfe.printStackTrace();
    } finally {
        ifstr.close();
    }

}

From source file:com.github.matthesrieke.realty.CrawlerServlet.java

private void readCrawlingLinks() {
    InputStream is = getClass().getResourceAsStream("/links.txt");
    if (is != null) {
        Scanner sc = new Scanner(is);
        String l;//from  w w  w.  j a v  a 2s  .  co m
        while (sc.hasNext()) {
            l = sc.nextLine().trim();
            if (!l.startsWith("#")) {
                this.crawlLinks.add(l);
            }
        }
        sc.close();
    }
}

From source file:org.galicaster.dashboard.snapshot.GstreamerSnapshotTaker.java

@Override
public File call() {

    // Marks the file to be deleted on exist, if an error occurred
    boolean deleteOnExit = true;

    ProcessBuilder pb = new ProcessBuilder(splitCommandArguments(String.format(pipeStr, EXEC_NAME,
            agent.getUrl(), password, rfbVersion, destFile.getAbsolutePath())));

    Scanner s = null;
    try {// w  w w .  ja  v  a2  s. c om
        p = pb.start();

        if (p.waitFor() != 0) {
            s = new Scanner(p.getErrorStream()).useDelimiter("\\A");
            String error = s.hasNext() ? s.next() : "";

            error = String.format("The subprocess returned error code %s: %s", p.exitValue(), error);
            logger.error(error);
            throw new RuntimeException(error);
        }

        if (!destFile.isFile())
            throw new RuntimeException("The subprocess did not create a file");

        deleteOnExit = false;

        return destFile;

    } catch (IOException e) {
        logger.error("Error when initiating the helper subprocess: {}", e.getMessage());
        throw new RuntimeException("Error when initiating the helper subprocess.", e);
    } catch (InterruptedException e) {
        logger.error("The subprocess was unexpectedly interrupted: {}", e.getMessage());
        throw new RuntimeException("The subprocess was unexpectedly interrupted.", e);
    } finally {
        if (s != null)
            s.close();
        if (deleteOnExit)
            FileUtils.deleteQuietly(destFile);
    }

}