Example usage for java.util Scanner hasNextLine

List of usage examples for java.util Scanner hasNextLine

Introduction

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

Prototype

public boolean hasNextLine() 

Source Link

Document

Returns true if there is another line in the input of this scanner.

Usage

From source file:org.apache.hadoop.fs.tar.TarIndex.java

private boolean readIndexFile(FileSystem fs, Path indexPath) throws IOException {

    if (indexPath == null || !fs.exists(indexPath))
        return false;

    FSDataInputStream is = null;//ww w.  j  a  va2 s  .  c o m
    Scanner s = null;

    try {
        is = fs.open(indexPath);
        s = new Scanner(is);

        while (s.hasNextLine()) {
            String[] tokens = s.nextLine().split(" ");
            if (tokens.length != 3) {
                LOG.error("Invalid Index File: " + indexPath);
                return false;
            }

            IndexEntry ie = new IndexEntry(Long.parseLong(tokens[1]), Long.parseLong(tokens[2]));
            index.put(tokens[0], ie);
        }
        return true;
    } catch (AccessControlException e) {
        LOG.error("Can not open Index file for reading " + indexPath + " " + e.getMessage());
        return false;
    } finally {
        if (s != null)
            s.close();
        if (is != null)
            is.close();
    }
}

From source file:net.solarnetwork.node.control.ping.HttpRequesterJob.java

private void logInputStream(final InputStream src, final boolean errorStream) {
    new Thread(new Runnable() {

        @Override/*w w  w  .  j a  va  2  s  .  c  o  m*/
        public void run() {
            Scanner sc = new Scanner(src);
            while (sc.hasNextLine()) {
                if (errorStream) {
                    log.error(sc.nextLine());
                } else {
                    log.info(sc.nextLine());
                }
            }
        }
    }).start();
}

From source file:org.goko.core.rs274ngcv3.parser.GCodeLexer.java

public List<GCodeToken> createTokensFromInputStream(InputStream inStream) throws GkException {
    Scanner scanner = new Scanner(inStream);

    List<GCodeToken> lstFileTokens = new ArrayList<GCodeToken>();
    String line = null;/*w  w  w . j  ava  2s .  c o m*/
    GCodeToken newLineToken = new GCodeToken(GCodeTokenType.NEW_LINE, StringUtils.EMPTY);

    while (scanner.hasNextLine()) {
        line = scanner.nextLine();
        lstFileTokens.addAll(createTokens(line));
        lstFileTokens.add(newLineToken);//new GCodeToken(GCodeTokenType.NEW_LINE, StringUtils.EMPTY));
    }

    scanner.close();
    return lstFileTokens;
}

From source file:com.mgmtp.perfload.perfalyzer.binning.MeasuringResponseTimesBinningStrategy.java

@Override
public void binData(final Scanner scanner, final WritableByteChannel destChannel) throws IOException {
    while (scanner.hasNextLine()) {
        tokenizer.reset(scanner.nextLine());
        String[] tokens = tokenizer.getTokenArray();

        long timestampMillis = Long.parseLong(tokens[0]);
        Long responseTime = Long.valueOf(tokens[2]);
        String type = tokens[MEASURING_NORMALIZED_COL_REQUEST_TYPE];
        String uriAlias = tokens[MEASURING_NORMALIZED_COL_URI_ALIAS];
        String result = tokens[MEASURING_NORMALIZED_COL_RESULT];
        String executionId = tokens[MEASURING_NORMALIZED_COL_EXECUTION_ID];

        String key = type + "||" + uriAlias;
        UriMeasurings measurings = measuringsMap.get(key);
        if (measurings == null) {
            measurings = new UriMeasurings();
            measurings.type = type;/*from   www  .  ja v a 2s  .  c  o m*/
            measurings.uriAlias = uriAlias;
            measuringsMap.put(key, measurings);
        }

        if (responseTime > 0) {
            // response time distribution is calculated by grouping by response time
            // only positive values allowed on logarithmic axis
            // response time might by -1 in case of an error
            MutableInt mutableInt = measurings.responseDistributions.get(responseTime);
            if (mutableInt == null) {
                mutableInt = new MutableInt();
                measurings.responseDistributions.put(responseTime, mutableInt);
            }
            mutableInt.increment();
        }

        // collect all response times for a URI, so quantiles can be calculated later
        measurings.responseTimes.add(responseTime.doubleValue());

        if ("ERROR".equals(result)) {
            measurings.errorCount.increment();

            errorExecutions.add(executionId);
        }

        if (!isNullOrEmpty(executionId)) {
            ExecutionMeasurings execMeasurings = perExecutionResponseTimes.get(executionId);
            if (execMeasurings == null) {
                execMeasurings = new ExecutionMeasurings();
                execMeasurings.sumResponseTimes = new MutableLong(responseTime);
                perExecutionResponseTimes.put(executionId, execMeasurings);
            } else {
                perExecutionResponseTimes.get(executionId).sumResponseTimes.add(responseTime);
            }
            // always update timestamp so we eventually have the last timestamp of the execution
            execMeasurings.timestampMillis = timestampMillis;
        }
    }
}

From source file:org.apache.accumulo.core.util.shell.commands.CreateTableCommand.java

@Override
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState)
        throws AccumuloException, AccumuloSecurityException, TableExistsException, TableNotFoundException,
        IOException, ClassNotFoundException {

    final String testTableName = cl.getArgs()[0];

    if (!testTableName.matches(Tables.VALID_NAME_REGEX)) {
        shellState.getReader()/*from  w  w  w.j  a  v  a2 s  . c om*/
                .println("Only letters, numbers and underscores are allowed for use in table names.");
        throw new IllegalArgumentException();
    }

    final String tableName = cl.getArgs()[0];
    if (shellState.getConnector().tableOperations().exists(tableName)) {
        throw new TableExistsException(null, tableName, null);
    }
    final SortedSet<Text> partitions = new TreeSet<Text>();
    final boolean decode = cl.hasOption(base64Opt.getOpt());

    if (cl.hasOption(createTableOptSplit.getOpt())) {
        final String f = cl.getOptionValue(createTableOptSplit.getOpt());

        String line;
        Scanner file = new Scanner(new File(f), Constants.UTF8.name());
        try {
            while (file.hasNextLine()) {
                line = file.nextLine();
                if (!line.isEmpty())
                    partitions.add(decode ? new Text(Base64.decodeBase64(line.getBytes(Constants.UTF8)))
                            : new Text(line));
            }
        } finally {
            file.close();
        }
    } else if (cl.hasOption(createTableOptCopySplits.getOpt())) {
        final String oldTable = cl.getOptionValue(createTableOptCopySplits.getOpt());
        if (!shellState.getConnector().tableOperations().exists(oldTable)) {
            throw new TableNotFoundException(null, oldTable, null);
        }
        partitions.addAll(shellState.getConnector().tableOperations().listSplits(oldTable));
    }

    if (cl.hasOption(createTableOptCopyConfig.getOpt())) {
        final String oldTable = cl.getOptionValue(createTableOptCopyConfig.getOpt());
        if (!shellState.getConnector().tableOperations().exists(oldTable)) {
            throw new TableNotFoundException(null, oldTable, null);
        }
    }

    TimeType timeType = TimeType.MILLIS;
    if (cl.hasOption(createTableOptTimeLogical.getOpt())) {
        timeType = TimeType.LOGICAL;
    }

    // create table
    shellState.getConnector().tableOperations().create(tableName, true, timeType);
    if (partitions.size() > 0) {
        shellState.getConnector().tableOperations().addSplits(tableName, partitions);
    }

    shellState.setTableName(tableName); // switch shell to new table context

    if (cl.hasOption(createTableNoDefaultIters.getOpt())) {
        for (String key : IteratorUtil.generateInitialTableProperties(true).keySet()) {
            shellState.getConnector().tableOperations().removeProperty(tableName, key);
        }
    }

    // Copy options if flag was set
    if (cl.hasOption(createTableOptCopyConfig.getOpt())) {
        if (shellState.getConnector().tableOperations().exists(tableName)) {
            final Iterable<Entry<String, String>> configuration = shellState.getConnector().tableOperations()
                    .getProperties(cl.getOptionValue(createTableOptCopyConfig.getOpt()));
            for (Entry<String, String> entry : configuration) {
                if (Property.isValidTablePropertyKey(entry.getKey())) {
                    shellState.getConnector().tableOperations().setProperty(tableName, entry.getKey(),
                            entry.getValue());
                }
            }
        }
    }

    if (cl.hasOption(createTableOptEVC.getOpt())) {
        try {
            shellState.getConnector().tableOperations().addConstraint(tableName,
                    VisibilityConstraint.class.getName());
        } catch (AccumuloException e) {
            Shell.log.warn(e.getMessage() + " while setting visibility constraint, but table was created");
        }
    }

    // Load custom formatter if set
    if (cl.hasOption(createTableOptFormatter.getOpt())) {
        final String formatterClass = cl.getOptionValue(createTableOptFormatter.getOpt());

        shellState.getConnector().tableOperations().setProperty(tableName,
                Property.TABLE_FORMATTER_CLASS.toString(), formatterClass);
    }

    return 0;
}

From source file:com.valygard.aohruthless.Joystick.java

/**
 * Reads config file using a Scanner to search for tabs. In yaml files, the
 * presences of tabs instead of whitespace will cause the file to reset due
 * to snakeyaml errors. As a preventative measure, the scanner will read the
 * file for any tabs and an IllegalArgumentException will be thrown,
 * effectively forcing the file to remain in its current state until the
 * user fixes the file.//from  w w  w . j a  va2  s.  c  o  m
 * 
 * @throws IllegalArgumentException
 *             if a tab is found.
 */
private void scanConfig() {
    // declare our scanner variable
    Scanner scan = null;
    try {
        scan = new Scanner(file);

        int row = 0;
        String line = "";

        while (scan.hasNextLine()) {
            line = scan.nextLine();
            row++;

            if (line.indexOf("\t") != -1) {
                // Tell the user where the tab is!
                String error = ("Tab found in config-file on line # " + row + "!");
                throw new IllegalArgumentException(error);
            }
        }
        /*
         * load the file, if tabs were found then this will never execute
         * because of IllegalArgumentException
         */
        config.load(file);
    } catch (IOException | InvalidConfigurationException e) {
        e.printStackTrace();
    } finally {
        if (scan != null) {
            scan.close();
        }
    }
}

From source file:com.joliciel.csvLearner.EventCombinationGenerator.java

void scanResultsFile() {
    Scanner resultScanner;
    try {// ww  w  .j  a  v  a 2  s .co  m
        resultScanner = new Scanner(new FileInputStream(resultFilePath), "UTF-8");

        try {
            boolean firstLine = true;
            while (resultScanner.hasNextLine()) {
                String line = resultScanner.nextLine();
                if (!firstLine) {
                    List<String> cells = CSVFormatter.getCSVCells(line);
                    String ref = cells.get(0);
                    String outcome = cells.get(1);
                    List<String> eventsForThisOutcome = this.eventsPerOutcome.get(outcome);
                    if (eventsForThisOutcome == null) {
                        eventsForThisOutcome = new ArrayList<String>();
                        this.eventsPerOutcome.put(outcome, eventsForThisOutcome);
                    }
                    eventsForThisOutcome.add(ref);
                }
                firstLine = false;

            }
        } finally {
            resultScanner.close();
        }
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:com.logisima.selenium.server.action.StaticAction.java

@Override
public void execute() {
    this.setContentType();
    try {//from  w  w w  . j  a v  a  2 s.co  m
        if (request.getUri().endsWith(".png") | request.getUri().endsWith(".gif")) {
            File image = new File(documentRoot.getAbsolutePath() + request.getUri());
            this.content = ChannelBuffers.copiedBuffer(FileUtils.readFileToByteArray(image));
        } else {
            // Process the request
            StringBuilder buf = new StringBuilder();
            buf.setLength(0);
            Scanner scanner = null;
            String fileName = documentRoot.getAbsolutePath() + request.getUri().split("[?]")[0];
            String NL = System.getProperty("line.separator");
            scanner = new Scanner(new FileInputStream(fileName), "utf-8");
            while (scanner.hasNextLine()) {
                buf.append(scanner.nextLine() + NL);
            }
            this.content = ChannelBuffers.copiedBuffer(buf.toString(), CharsetUtil.UTF_8);
        }
    } catch (FileNotFoundException e) {
        this.status = HttpResponseStatus.NOT_FOUND;
        this.content = ChannelBuffers.copiedBuffer(e.toString(), CharsetUtil.UTF_8);
    } catch (IOException e) {
        this.status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        this.content = ChannelBuffers.copiedBuffer(e.toString(), CharsetUtil.UTF_8);
    }
}

From source file:de.betterform.agent.web.resources.ResourceServlet.java

private long getLastModifiedValue() {
    if (this.lastModified == 0) {
        long bfTimestamp;
        try {//from   w w  w  . ja  v a 2s  . com
            String path = WebFactory.getRealPath("/WEB-INF/betterform-version.info", this.getServletContext());
            StringBuilder versionInfo = new StringBuilder();
            String NL = System.getProperty("line.separator");
            Scanner scanner = new Scanner(new FileInputStream(path), "UTF-8");
            try {
                while (scanner.hasNextLine()) {
                    versionInfo.append(scanner.nextLine() + NL);
                }
            } finally {
                scanner.close();
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("VersionInfo: " + versionInfo);
            }
            // String APP_NAME = APP_INFO.substring(0, APP_INFO.indexOf(" "));
            // String APP_VERSION = APP_INFO.substring(APP_INFO.indexOf(" ") + 1, APP_INFO.indexOf("-") - 1);
            String timestamp = versionInfo.substring(versionInfo.indexOf("Timestamp:") + 10,
                    versionInfo.length());
            String df = "yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat sdf = new SimpleDateFormat(df);
            Date date = sdf.parse(timestamp);
            bfTimestamp = date.getTime();
        } catch (Exception e) {
            LOG.error("Error setting HTTP Header 'Last Modified', could not parse the given date.");
            bfTimestamp = 0;
        }
        this.lastModified = bfTimestamp;
    }
    return lastModified;
}

From source file:org.caldfir.rawxml.tools.Relationship.java

public boolean lookup(String parent, String child) {
    r.lock();// www  .  j a va 2  s.c om
    if (map.getCollection(parent) == null) {
        try {
            r.unlock();
            w.lock();
            FileReader f = new FileReader("Paramaters/" + redirect.get(parent) + ".txt");
            Scanner scn = new Scanner(f);
            while (scn.hasNextLine()) {
                map.put(parent, scn.nextLine());
            }
        } catch (FileNotFoundException e) {
            map.put(parent, "");
        } finally {
            w.unlock();
            r.lock();
        }
    }
    boolean contains = map.containsValue(parent, child);
    r.unlock();
    return contains;
}