Example usage for java.util Scanner nextLine

List of usage examples for java.util Scanner nextLine

Introduction

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

Prototype

public String nextLine() 

Source Link

Document

Advances this scanner past the current line and returns the input that was skipped.

Usage

From source file:org.apache.asterix.experiment.builder.AbstractLSMBaseExperimentBuilder.java

protected Map<String, List<String>> readDatagenPairs(Path p) throws IOException {
    Map<String, List<String>> dgenPairs = new HashMap<>();
    Scanner s = new Scanner(p, StandardCharsets.UTF_8.name());
    try {//www.j  a v a2s.  c  o  m
        while (s.hasNextLine()) {
            String line = s.nextLine();
            String[] pair = line.split("\\s+");
            List<String> vals = dgenPairs.get(pair[0]);
            if (vals == null) {
                vals = new ArrayList<>();
                dgenPairs.put(pair[0], vals);
            }
            vals.add(pair[1]);
        }
    } finally {
        s.close();
    }
    return dgenPairs;
}

From source file:org.apache.activemq.transport.discovery.http.HTTPDiscoveryAgent.java

synchronized private Set<String> doLookup(long freshness) {
    String url = registryURL + "?freshness=" + freshness;
    try {/*  w w  w  . java 2  s  .c om*/
        HttpGet method = new HttpGet(url);
        ResponseHandler<String> handler = new BasicResponseHandler();
        String response = httpClient.execute(method, handler);
        LOG.debug("GET to " + url + " got a " + response);
        Set<String> rc = new HashSet<String>();
        Scanner scanner = new Scanner(response);
        while (scanner.hasNextLine()) {
            String service = scanner.nextLine();
            if (service.trim().length() != 0) {
                rc.add(service);
            }
        }
        scanner.close();
        return rc;
    } catch (Exception e) {
        LOG.debug("GET to " + url + " failed with: " + e);
        return null;
    }
}

From source file:dbcount.DBCountPageView.java

public void run(String[] args) throws Exception {
    DBCountJobConf jobConf = new DBCountJobConf();
    processArgs(args, jobConf);//from  w w w  .  j a v a2 s. c  o m

    GridClient grid = new GridClient();
    long totalPageview = initialize(grid, jobConf);
    LOG.info("Initialized... totalPageview: " + totalPageview);

    Scanner kbd = new Scanner(System.in);
    String answer;
    do {
        System.out.println("Are you ready to run a Job? Type 'yes' to proceed.");
        answer = kbd.nextLine();
    } while (!"yes".equalsIgnoreCase(answer));

    LOG.info("Ready to run a MapReduce job! Go..");
    StopWatch sw = new StopWatch();
    runJob(grid, jobConf);
    sw.stop();

    boolean correct = verify(jobConf, totalPageview);
    if (correct) {
        LOG.info("Finished successfully in " + sw.toString() + "  :-)");
    } else {
        LOG.info("Finished abnormally in " + sw.toString() + "  ;-(");
        throw new RuntimeException("Evaluation was not correct!");
    }

}

From source file:com.gitblit.auth.HtpasswdAuthProvider.java

/**
 * Reads the realm file and rebuilds the in-memory lookup tables.
 *//* ww w .  j a v a  2s  .c om*/
protected synchronized void read() {
    boolean forceReload = false;
    File file = getFileOrFolder(KEY_HTPASSWD_FILE, DEFAULT_HTPASSWD_FILE);
    if (!file.equals(htpasswdFile)) {
        this.htpasswdFile = file;
        this.htUsers.clear();
        forceReload = true;
    }

    if (htpasswdFile.exists() && (forceReload || (htpasswdFile.lastModified() != lastModified))) {
        lastModified = htpasswdFile.lastModified();
        htUsers.clear();

        Pattern entry = Pattern.compile("^([^:]+):(.+)");

        Scanner scanner = null;
        try {
            scanner = new Scanner(new FileInputStream(htpasswdFile));
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine().trim();
                if (!line.isEmpty() && !line.startsWith("#")) {
                    Matcher m = entry.matcher(line);
                    if (m.matches()) {
                        htUsers.put(m.group(1), m.group(2));
                    }
                }
            }
        } catch (Exception e) {
            logger.error(MessageFormat.format("Failed to read {0}", htpasswdFile), e);
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
    }
}

From source file:com.joliciel.jochre.lexicon.TextFileLexicon.java

public TextFileLexicon(File textFile, String charset) {
    Scanner scanner;
    try {//from  w  w w  .  java  2s.  com
        scanner = new Scanner(
                new BufferedReader(new InputStreamReader(new FileInputStream(textFile), charset)));

        try {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                if (!line.startsWith("#")) {
                    String[] parts = line.split("\t");

                    if (parts.length > 0) {
                        String word = parts[0];
                        int frequency = 1;
                        if (parts.length > 1)
                            frequency = Integer.parseInt(parts[1]);
                        entries.put(word, frequency);
                    }

                }

            }
        } finally {
            scanner.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.mythesis.userbehaviouranalysis.Utils.java

/**
 * a method that reads a txt file with the necessary parameters
 * @param input the file that includes the necessary parameters
 *//* ww w . jav  a2  s  . c  o m*/
public void readInput(File input) {
    FileInputStream inputStream = null;
    Scanner sc = null;
    wordvectors = new HashMap<>();
    crawlerOutputPaths = new HashMap<>();

    HashMap<String, String> wordvectorsPaths = new HashMap<>();
    try {
        inputStream = new FileInputStream(input);
        sc = new Scanner(inputStream);

        if (sc.hasNextLine()) {
            int numProfiles = Integer.parseInt(sc.nextLine().split(";")[1].trim().toLowerCase());

            int j = 0;
            while (j < numProfiles) {
                String profile = "";
                if (sc.hasNextLine()) {
                    profile = sc.nextLine().split(";")[1].trim();
                }
                if (sc.hasNextLine()) {
                    String path = sc.nextLine().split(";")[1].trim();
                    crawlerOutputPaths.put(profile, path);
                }
                if (sc.hasNextLine()) {
                    String path = sc.nextLine().split(";")[1].trim();
                    wordvectorsPaths.put(profile, path);
                }
                j++;
            }
        }

        for (String profile : wordvectorsPaths.keySet()) {
            File file = new File(wordvectorsPaths.get(profile));
            try {
                List<String> wordvector = FileUtils.readLines(file);
                wordvectors.put(profile, (ArrayList<String>) wordvector);
            } catch (IOException ex) {
                Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (sc != null) {
            sc.close();
        }
    }

}

From source file:org.openinfinity.sso.common.ss.sp.SpringAuthenticationMessageConverter.java

@Override
protected Authentication readInternal(Class<? extends Authentication> clazz, HttpInputMessage inputMessage)
        throws IOException, HttpMessageNotReadableException {
    String resultString = stringHttpMessageConverter.read(String.class, inputMessage);
    Scanner resultScanner = new Scanner(resultString);
    Map<String, String> properties = new HashMap<String, String>();
    Collection<GrantedAuthorityImpl> authorities = new HashSet<GrantedAuthorityImpl>();
    String name = null, attributeName = null;
    boolean collectingAttributeValues = false;
    while (resultScanner.hasNextLine()) {
        String resultLine = resultScanner.nextLine();
        if (collectingAttributeValues && !resultLine.startsWith("userdetails.attribute.value")) {
            collectingAttributeValues = false;
        }//from   w  ww .ja v  a2  s  . c  om
        if (resultLine.startsWith("userdetails.token.id")) {
            properties.put(SSO_TOKEN_ID_KEY, valueFrom(resultLine));
        } else if (resultLine.startsWith("userdetails.attribute.name")) {
            attributeName = valueFrom(resultLine);
            collectingAttributeValues = true;
        } else if (collectingAttributeValues && resultLine.startsWith("userdetails.attribute.value")) {
            String value = valueFrom(resultLine);
            if (attributeName.equals("memberof")) {
                authorities.add(new GrantedAuthorityImpl(value));
            } else {
                if (attributeName.equals("screenname")) {
                    name = value;
                }
                properties.put(attributeName, value);
            }
        }
    }

    return new PreAuthenticatedAuthenticationToken(new User(name, properties), properties.get(SSO_TOKEN_ID_KEY),
            authorities);
}

From source file:com.networknt.light.rule.LoadRuleMojo.java

public void parseRuleFile(final String filePath) {
    System.out.println("Process file = " + filePath);
    String packageName = null;/*from   ww  w.  j a va 2  s.  c  o  m*/
    StringBuilder sourceCode = new StringBuilder();
    boolean validRule = false;
    try {
        File file = new File(filePath);
        String className = getClassName(file);
        if (".java".equals(getExtension(file))) {
            final Scanner scan = new Scanner(file, encoding);
            String line = scan.nextLine();
            while (scan.hasNext()) {
                if (!line.trim().isEmpty()) {
                    if (line.startsWith("package")) {
                        packageName = line.substring(8, line.length() - 1);
                    }
                    if (!validRule && line.indexOf("implements") != -1 && line.indexOf("Rule") != -1) {
                        validRule = true;
                    }
                }
                sourceCode.append(line);
                sourceCode.append("\n");
                line = scan.nextLine();
            }
            sourceCode.append(line);
            sourceCode.append("\n");
        }
        if (validRule) {
            // connect to example:8080 to upload rule here.
            String ruleClass = packageName + "." + className;

            // only import the rule if source has been changed after comparing with server
            if (!sourceCode.toString().equals(ruleMap.get(ruleClass))) {
                impRule(ruleClass, sourceCode.toString());
                // generate SQL insert statements

                String sql = "INSERT INTO RULE(class_name, source_code) VALUES ('" + ruleClass + "', '"
                        + sourceCode.toString().replaceAll("'", "''") + "');\n";
                sqlString += sql;
            }
        }
    } catch (final IOException e) {
        getLog().error(e.getMessage());
    }

}

From source file:cpd3314.project.CPD3314ProjectTest.java

private void assertXMLFilesEqual(File a, File b) throws IOException, SAXException {
    Scanner aIn = new Scanner(a);
    Scanner bIn = new Scanner(b);
    StringBuilder aXML = new StringBuilder();
    StringBuilder bXML = new StringBuilder();
    while (aIn.hasNext() && bIn.hasNext()) {
        aXML.append(aIn.nextLine().trim());
        bXML.append(bIn.nextLine().trim());
    }//w w  w.  j  a  v a 2 s.  c om
    assertTrue("Files Not Equal Length", !aIn.hasNext() && !bIn.hasNext());
    assertXMLEqual(aXML.toString(), bXML.toString());
}

From source file:cpd3314.project.CPD3314ProjectTest.java

private void assertJSONFilesEqual(File a, File b) throws IOException {
    Scanner aIn = new Scanner(a);
    Scanner bIn = new Scanner(b);
    StringBuilder aJSON = new StringBuilder();
    StringBuilder bJSON = new StringBuilder();
    while (aIn.hasNext() && bIn.hasNext()) {
        aJSON.append(aIn.nextLine().trim());
        bJSON.append(bIn.nextLine().trim());
    }//from  ww w. j a  va 2s  .  c om
    assertTrue("Files Not Equal Length", !aIn.hasNext() && !bIn.hasNext());
    JSONObject aJ = (JSONObject) JSONValue.parse(aJSON.toString());
    JSONObject bJ = (JSONObject) JSONValue.parse(bJSON.toString());
    assertEquals(aJ.toJSONString(), bJ.toJSONString());
}