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:org.n52.ses.common.environment.SESMiniServlet.java

private String readFileContents(String string) {
    InputStream is = getClass().getResourceAsStream(string);

    if (is != null) {
        Scanner sc = new Scanner(is);
        StringBuilder sb = new StringBuilder();
        while (sc.hasNext()) {
            sb.append(sc.nextLine());//from w  w  w.  jav  a 2s. com
            sb.append(System.getProperty("line.separator"));
        }
        sb.deleteCharAt(sb.length() - 1);
        sc.close();
        return sb.toString();
    }
    return null;
}

From source file:org.wso2.extension.siddhi.execution.var.backtest.BacktestIncremental.java

public ArrayList<Event> readBacktestData(int id) throws FileNotFoundException {
    ClassLoader classLoader = getClass().getClassLoader();
    Scanner scan = new Scanner(new File(
            classLoader.getResource("without_duplicates/backtest-data-" + id + "" + ".csv").getFile()));
    ArrayList<Event> list = new ArrayList();
    Event event;//from   w  w  w.  j  a v  a  2 s. c om
    String[] split;
    while (scan.hasNext()) {
        event = new Event();
        split = scan.nextLine().split(",");
        event.setSymbol(split[2]);
        event.setPrice(Double.parseDouble(split[1]));
        list.add(event);
    }
    return list;
}

From source file:ru.histone.staticrender.StaticRender.java

public void renderSite(final Path srcDir, final Path dstDir) {
    log.info("Running StaticRender for srcDir={}, dstDir={}", srcDir.toString(), dstDir.toString());
    Path contentDir = srcDir.resolve("content/");
    final Path layoutDir = srcDir.resolve("layouts/");

    FileVisitor<Path> layoutVisitor = new SimpleFileVisitor<Path>() {
        @Override//from ww w. jav a2 s . c o m
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (file.toString().endsWith("." + TEMPLATE_FILE_EXTENSION)) {
                ArrayNode ast = null;
                try {
                    ast = histone.parseTemplateToAST(new FileReader(file.toFile()));
                } catch (HistoneException e) {
                    throw new RuntimeException("Error parsing histone template:" + e.getMessage(), e);
                }

                final String fileName = file.getFileName().toString();
                String layoutId = fileName.substring(0,
                        fileName.length() - TEMPLATE_FILE_EXTENSION.length() - 1);
                layouts.put(layoutId, ast);
                if (log.isDebugEnabled()) {
                    log.debug("Layout found id='{}', file={}", layoutId, file);
                } else {
                    log.info("Layout found id='{}'", layoutId);
                }
            } else {
                final Path relativeFileName = srcDir.resolve("layouts").relativize(Paths.get(file.toUri()));
                final Path resolvedFile = dstDir.resolve(relativeFileName);
                if (!resolvedFile.getParent().toFile().exists()) {
                    Files.createDirectories(resolvedFile.getParent());
                }
                Files.copy(Paths.get(file.toUri()), resolvedFile, StandardCopyOption.REPLACE_EXISTING,
                        LinkOption.NOFOLLOW_LINKS);
            }
            return FileVisitResult.CONTINUE;
        }
    };

    FileVisitor<Path> contentVisitor = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

            Scanner scanner = new Scanner(file, "UTF-8");
            scanner.useDelimiter("-----");

            String meta = null;
            StringBuilder content = new StringBuilder();

            if (!scanner.hasNext()) {
                throw new RuntimeException("Wrong format #1:" + file.toString());
            }

            if (scanner.hasNext()) {
                meta = scanner.next();
            }

            if (scanner.hasNext()) {
                content.append(scanner.next());
                scanner.useDelimiter("\n");
            }

            while (scanner.hasNext()) {
                final String next = scanner.next();
                content.append(next);

                if (scanner.hasNext()) {
                    content.append("\n");
                }
            }

            Map<String, String> metaYaml = (Map<String, String>) yaml.load(meta);

            String layoutId = metaYaml.get("layout");

            if (!layouts.containsKey(layoutId)) {
                throw new RuntimeException(MessageFormat.format("No layout with id='{0}' found", layoutId));
            }

            final Path relativeFileName = srcDir.resolve("content").relativize(Paths.get(file.toUri()));
            final Path resolvedFile = dstDir.resolve(relativeFileName);
            if (!resolvedFile.getParent().toFile().exists()) {
                Files.createDirectories(resolvedFile.getParent());
            }
            Writer output = new FileWriter(resolvedFile.toFile());
            ObjectNode context = jackson.createObjectNode();
            ObjectNode metaNode = jackson.createObjectNode();
            context.put("content", content.toString());
            context.put("meta", metaNode);
            for (String key : metaYaml.keySet()) {
                if (!key.equalsIgnoreCase("content")) {
                    metaNode.put(key, metaYaml.get(key));
                }
            }

            try {
                histone.evaluateAST(layoutDir.toUri().toString(), layouts.get(layoutId), context, output);
                output.flush();
            } catch (HistoneException e) {
                throw new RuntimeException("Error evaluating content: " + e.getMessage(), e);
            } finally {
                output.close();
            }

            return FileVisitResult.CONTINUE;
        }
    };

    try {
        Files.walkFileTree(layoutDir, layoutVisitor);
        Files.walkFileTree(contentDir, contentVisitor);
    } catch (Exception e) {
        throw new RuntimeException("Error during site render", e);
    }
}

From source file:it.isti.cnr.hpc.europeana.hackthon.domain.GoogleQuery2Entity.java

/**
 * @param string/*w w w. j av a  2s  . com*/
 * @return
 */
private List<Result> parseResults(String string) {
    Scanner scanner = new Scanner(string).useDelimiter("<h3");
    List<Result> results = new ArrayList<Result>(10);
    while (scanner.hasNext()) {
        Result r = getResult(scanner.next());
        if (r != null)
            results.add(r);
    }
    return results;
}

From source file:com.inaetics.demonstrator.MainActivity.java

/**
 * Method called when QR-code scanner has been triggered and finished.
 * If a qr-code is scanned it will process the content.
 *///from  w w w.  jav a2 s. c o m
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if (result != null) {
        if (result.getContents() == null) {
            Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
        } else {
            String content = result.getContents();
            try {
                new URL(content);
                // Is a url!
                download(content);
            } catch (MalformedURLException e) {
                //Not an url
                Scanner sc = new Scanner(content);
                boolean autostart = false;
                while (sc.hasNextLine()) {
                    String[] keyValue = sc.nextLine().split("=");
                    switch (keyValue[0]) {
                    case "cosgi.auto.start.1":
                        autostart = true;
                        String startBundles = "";
                        Scanner bscan = new Scanner(keyValue[1]);
                        while (bscan.hasNext()) {
                            startBundles += model.getBundleLocation() + "/" + bscan.next() + " ";
                        }
                        bscan.close();
                        config.putProperty(keyValue[0], startBundles);
                        break;
                    case "deployment_admin_identification":
                        config.putProperty(keyValue[0], keyValue[1] + "_" + model.getCpu_abi());
                        break;
                    default:
                        try {
                            config.putProperty(keyValue[0], keyValue[1]);
                        } catch (ArrayIndexOutOfBoundsException ex) {
                            //Ignore property there is no key/value combination
                            Log.e("Scanner", "couldn't scan: " + Arrays.toString(keyValue));
                        }
                    }
                }
                sc.close();
                if (autostart && !Celix.getInstance().isCelixRunning()) {
                    Celix.getInstance().startFramework(config.getConfigPath());
                }
                Toast.makeText(this, "Scanned QR", Toast.LENGTH_SHORT).show();
            }

        }
    }
}

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  av a  2  s  .c  o m
    assertTrue("Files Not Equal Length", !aIn.hasNext() && !bIn.hasNext());
    assertXMLEqual(aXML.toString(), bXML.toString());
}

From source file:com.mendhak.gpslogger.common.OpenGTSClient.java

/**
 * Send locations sing HTTP GET request to the server
 * <p/>// w ww . j a  v a  2  s . c o m
 * See <a href="http://opengts.sourceforge.net/OpenGTS_Config.pdf">OpenGTS_Config.pdf</a>
 * section 9.1.2 Default "gprmc" Configuration
 *
 * @param id        id of the device
 * @param locations locations
 */

public void sendHTTP(String id, String accountName, SerializableLocation[] locations) throws Exception {

    for (SerializableLocation loc : locations) {

        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("id", id));
        qparams.add(new BasicNameValuePair("dev", id));
        if (!Utilities.IsNullOrEmpty(accountName)) {
            qparams.add(new BasicNameValuePair("acct", accountName));
        } else {
            qparams.add(new BasicNameValuePair("acct", id));
        }

        //OpenGTS 2.5.5 requires batt param or it throws exception...
        qparams.add(new BasicNameValuePair("batt", "0"));
        qparams.add(new BasicNameValuePair("code", "0xF020"));
        qparams.add(new BasicNameValuePair("alt", String.valueOf(loc.getAltitude())));
        qparams.add(new BasicNameValuePair("gprmc", OpenGTSClient.GPRMCEncode(loc)));

        URI uri = URIUtils.createURI("http", server, port, path, getQuery(qparams), null);
        HttpGet httpget = new HttpGet(uri);
        URL url = httpget.getURI().toURL();

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        Scanner s;
        if (conn.getResponseCode() != 200) {
            s = new Scanner(conn.getErrorStream());
            tracer.error("Status code: " + String.valueOf(conn.getResponseCode()));
            if (s.hasNext()) {
                tracer.error(s.useDelimiter("\\A").next());
            }
        } else {
            tracer.debug("Status code: " + String.valueOf(conn.getResponseCode()));
        }

    }

}

From source file:org.bibsonomy.webapp.controller.MySearchController.java

/**
 * extract the last names of the authors
 * //from   w  w w  .  j a v  a2 s . c o m
 * @param authors
 * @return string list of the last names of the authors
 */
private List<String> extractAuthorsLastNames(String authors) {
    List<String> authorsList = new LinkedList<String>();
    List<String> names = new LinkedList<String>();
    Pattern pattern = Pattern.compile("[0-9]+"); // only numbers

    Scanner s = new Scanner(authors);
    s.useDelimiter(" and ");
    while (s.hasNext())
        names.add(s.next());

    for (String person : names) {
        /*
         * extract all parts of a name
         */
        List<String> nameList = new LinkedList<String>();
        StringTokenizer token = new StringTokenizer(person);
        while (token.hasMoreTokens()) {
            /*
             * ignore numbers (from DBLP author names)
             */
            final String part = token.nextToken();
            if (!pattern.matcher(part).matches()) {
                nameList.add(part);
            }
        }

        /*
         * detect lastname
         */
        int i = 0;
        while (i < nameList.size() - 1) { // iterate up to the last but one
            // part
            final String part = nameList.get(i++);
            /*
             * stop, if this is the last abbreviated forename
             */
            if (part.contains(".") && !nameList.get(i).contains(".")) {
                break;
            }
        }

        StringBuilder lastName = new StringBuilder();
        while (i < nameList.size()) {
            lastName.append(nameList.get(i++) + " ");
        }

        // add name to list
        authorsList.add(lastName.toString().trim());
    }
    return authorsList;
}

From source file:org.pepstock.jem.ant.tasks.utilities.sort.DefaultComparator.java

/**
 * Reads a input stream putting all in a string buffer for further parsing.
 * Removes <code>/n</code> chars. 
 * //from  w w w .  j  av  a  2 s . co m
 * @param is
 *            input stream with all commands
 * @return string buffer with all commands
 * @throws IOException
 *             if IO error occurs
 */
private StringBuilder read(InputStream is) throws IOException {
    StringBuilder sb = new StringBuilder();
    Scanner sc = new Scanner(is, CharSet.DEFAULT_CHARSET_NAME);
    sc.useDelimiter("\n");
    while (sc.hasNext()) {
        String record = sc.next().toString();
        sb.append(record.trim()).append(' ');
    }
    sc.close();
    return sb;
}

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 w  w  w.  ja  v a2 s  . 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());
}