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:csns.importer.parser.csula.RosterParserImpl.java

/**
 * This parser handles the format under CSULA Baseline -> CSULA Student
 * Records -> Class Roster on GET. A sample record is as follows:
 * "1 123456789 Doe,John M 3.00 ETG CS MS G1". Note that some fields like
 * middle name and units may not be present, and some people's last name has
 * space in it.//  ww w  .  j  a v  a 2s  .  co  m
 */
private List<ImportedUser> parse1(String text) {
    List<ImportedUser> students = new ArrayList<ImportedUser>();

    Scanner scanner = new Scanner(text);
    scanner.useDelimiter("\\s+|\\r\\n|\\r|\\n");
    while (scanner.hasNext()) {
        String cin = scanner.next();
        if (!isCin(cin))
            continue;

        String name = "";
        boolean nameFound = false;
        while (scanner.hasNext()) {
            String token = scanner.next();
            name += token + " ";
            if (token.matches(".+,.*")) {
                if (token.endsWith(",") && scanner.hasNext())
                    name += scanner.next();
                nameFound = true;
                break;
            }
        }

        String grade = null;
        boolean gradeFound = false;
        boolean unitsFound = false;
        while (nameFound && scanner.hasNext()) {
            String token = scanner.next();
            if (isUnits(token)) {
                unitsFound = true;
                continue;
            }
            if (isGrade(token)) {
                if (unitsFound) // this must be a grade
                {
                    grade = token;
                    gradeFound = true;
                    break;
                } else
                // this could be a grade or a middle name
                {
                    grade = token;
                    continue;
                }
            }
            if (isProgram(token)) {
                if (grade != null)
                    gradeFound = true;
                break;
            }

            name += token + " ";
        }

        if (nameFound) {
            ImportedUser student = new ImportedUser();
            student.setCin(cin);
            student.setName(name);
            if (gradeFound)
                student.setGrade(grade);
            students.add(student);
        }
    }
    scanner.close();

    return students;
}

From source file:org.opentides.persistence.hibernate.MultiTenantSchemaUpdate.java

/**
 * This is the helper function that initializes the schema and tables.
 * Initialization is as follows: /*from w w  w .  j av  a 2 s. com*/
 *    (1) Get the latest initialization sql script. Execute the sql script.
 *    (2) If there is no initialization script, use the hibernate SchemaExport.
 *    
 * @param tenantId
 */
private void initializeSchema(Configuration cfg, Connection connection, String schema) {
    // check if there SQL file under the sslScript folder
    boolean initialized = false;

    if (ddlScript != null && ddlScript.exists()) {
        _log.info("Initializing schema [" + schema + "] using DDL script [" + ddlScript.getFilename() + "].");
        InputStream inputStream = null;
        try {
            inputStream = ddlScript.getInputStream();
            Scanner f = new Scanner(inputStream);
            StringBuilder stmt = new StringBuilder();
            while (f.hasNext()) {
                String line = f.nextLine();
                // ignore comment
                if (line.startsWith("--"))
                    continue;
                stmt.append(" ").append(line);
                if (line.endsWith(";")) {
                    // end of statement, execute then clear
                    connection.createStatement().execute(stmt.toString());
                    System.out.println(stmt.toString());
                    stmt.setLength(0);
                }
            }
            f.close();
            initialized = true;
        } catch (SQLException e) {
            _log.error("Failed to execute sql script for initialization", e);
        } catch (IOException e) {
            _log.error("Failed to read sql script for initialization", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
        }
    }

    if (!initialized) {
        _log.info("Initializing schema [" + schema + "] using SchemaExport. ");
        SchemaExport export = new SchemaExport(cfg, connection);
        if (this.logDdl) {
            String dir = ddlLogs + "/" + DateUtil.convertShortDate(new Date());
            _log.info("DDL logs can be found in " + dir + "/schema-" + schema + ".sql");
            FileUtil.createDirectory(dir);
            export.setOutputFile(dir + "/schema-" + schema + ".sql");
            export.setDelimiter(";");
        }
        export.execute(this.logDdl, true, false, true);
    }

}

From source file:com.hubrick.raml.codegen.springweb.RestControllerClassGenerator.java

private void annotateActionMethod(JMethod actionMethod, ActionMetaInfo actionMetaInfo) {
    final JAnnotationUse requestMapping = actionMethod
            .annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping"));
    requestMapping.param("method", codeModel.ref("org.springframework.web.bind.annotation.RequestMethod")
            .staticRef(actionMetaInfo.getAction().getType().name()));

    final List<String> stringBuffer = new LinkedList<>();

    final Map<String, UriParameterDefinition> uriParameterIndex = actionMetaInfo.getUriParameterDefinitions()
            .stream().collect(toMap(p -> p.getName(), p -> p));

    JExpression uriExpression = null;/* w w w  . ja v  a  2  s .c om*/
    final String uri = actionMetaInfo.getAction().getResource().getUri();
    final Scanner scanner = new Scanner(uri).useDelimiter("/");
    while (scanner.hasNext()) {
        final String token = scanner.next();
        final Matcher m = URI_PARAMETER_PATTERN.matcher(token);
        if (m.find()) {
            final String param = m.group("param");

            final UriParameterDefinition p = uriParameterIndex.get(param);

            checkState(p != null, "Parameter [%s] definition not found", param);

            final PatternDefinition patternDefinition = p.getPattern();
            if (patternDefinition instanceof InlinePatternDefinition) {
                stringBuffer.add(
                        "/{" + param + ":" + ((InlinePatternDefinition) patternDefinition).getPattern() + "}");
            } else if (patternDefinition instanceof ReferencedPatternDefinition) {
                final String reference = ((ReferencedPatternDefinition) patternDefinition).getReference();
                stringBuffer.add("/{" + p.getName() + ":");

                final String[] components = reference.split("\\.(?=[^\\.]+$)");
                uriExpression = concat(uriExpression, concat(flushBuffer(stringBuffer),
                        codeModel.ref(components[0]).staticRef(components[1])));
                stringBuffer.add("}");
            } else if (patternDefinition == null) {
                stringBuffer.add("/{" + param + "}");
            } else {
                throw new IllegalStateException(
                        "Unknown pattern definition type: " + patternDefinition.getClass().getName());
            }

        } else {
            stringBuffer.add("/" + token);
        }
    }

    uriExpression = concat(uriExpression, flushBuffer(stringBuffer));

    requestMapping.param("value", uriExpression);
}

From source file:com.frankdye.marvelgraphws2.MarvelGraphView.java

/**
 * Creates a new instance of SimpleGraphView
 *///from   w ww.ja v  a  2 s  .c o  m
public MarvelGraphView() {
    try {
        Path fFilePath;

        /**
         * Assumes UTF-8 encoding. JDK 7+.
         */
        String aFileName = "C:\\Users\\Frank Dye\\Desktop\\Programming Projects\\MarvelGraph\\data\\marvel_labeled_edges.tsv";
        fFilePath = Paths.get(aFileName);

        // New code
        // Read words from file and put into a simulated multimap
        Map<String, List<String>> map1 = new HashMap<String, List<String>>();
        Set<String> set1 = new HashSet<String>();

        Scanner scan1 = null;
        try {
            scan1 = new Scanner(fFilePath, ENCODING.name());
            while (scan1.hasNext()) {
                processLine(scan1.nextLine(), map1, set1);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Creating an URL object.
        JSONObject newObj = new JSONObject();

        newObj.put("Heroes", set1);

        //Write out our set to a file
        PrintWriter fileWriter = null;
        try {
            fileWriter = new PrintWriter("heroes-json.txt", "UTF-8");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        fileWriter.println(newObj);
        fileWriter.close();

        System.out.println(newObj);

        // Close our scanner
        scan1.close();

        log("Done.");

        // Graph<V, E> where V is the type of the vertices
        // and E is the type of the edges
        g = new SparseMultigraph<String, String>();
        // Add some vertices. From above we defined these to be type Integer.

        for (String s : set1) {
            g.addVertex(s);
        }

        for (Entry<String, List<String>> entry : map1.entrySet()) {
            String issue = entry.getKey();
            ListIterator<String> heroes = entry.getValue().listIterator();
            String firstHero = heroes.next();
            while (heroes.hasNext()) {
                String secondHero = heroes.next();

                if (!g.containsEdge(issue)) {
                    g.addEdge(issue, firstHero, secondHero);
                }
            }
        }

        // Let's see what we have. Note the nice output from the
        // SparseMultigraph<V,E> toString() method
        // System.out.println("The graph g = " + g.toString());
        // Note that we can use the same nodes and edges in two different
        // graphs.
        DijkstraShortestPath alg = new DijkstraShortestPath(g, true);
        Map<String, Number> distMap = new HashMap<String, Number>();
        String n1 = "VOLSTAGG";
        String n4 = "ROM, SPACEKNIGHT";

        List<String> l = alg.getPath(n1, n4);
        distMap = alg.getDistanceMap(n1);
        System.out.println("The shortest unweighted path from " + n1 + " to " + n4 + " is:");
        System.out.println(l.toString());

        System.out.println("\nDistance Map: " + distMap.get(n4));
    } catch (JSONException ex) {
        Logger.getLogger(MarvelGraphView.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.unitedinternet.cosmo.db.DbInitializer.java

private List<String> readStatements(String resource) {
    List<String> statements = new ArrayList<>();
    Scanner scanner = null;
    try {//from w w w .j  av  a  2  s.  co  m
        scanner = new Scanner(this.getClass().getResourceAsStream(resource), StandardCharsets.UTF_8.name());
        scanner.useDelimiter(";");
        while (scanner.hasNext()) {
            String statement = scanner.next().replace("\n", " ").trim();
            if (!statement.isEmpty()) {
                statements.add(statement);
            }
        }
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
    return statements;
}

From source file:org.couch4j.http.DatabaseChangeNotificationService.java

private void receiveChangeNotifications() {
    if (receivingChangeNotifications) {
        return;/*from  ww  w .j a v a  2s. com*/
    }
    logger.info("[" + Thread.currentThread().getName() + "] Start receiveChangeNotifications()...");

    receivingChangeNotifications = true;
    executor = Executors.newSingleThreadExecutor();
    Runnable r = new Runnable() {
        private void streamChanges(int updateSeq) {
            if (!receivingChangeNotifications) {
                return;
            }
            // Do we need the "heartbeat" param?
            HttpGet method = new HttpGet(urlResolver.urlForPath("_changes", map("feed", "continuous", "style",
                    "all_docs", "since", String.valueOf(updateSeq), "heartbeat", "5000")));

            HttpResponse response = null;
            HttpEntity entity = null;
            try {
                // int statusCode = client.executeMethod(method);
                response = client.execute(method);
                entity = response.getEntity();
                // Read the response body.
                Reader in = new InputStreamReader(entity.getContent(), EntityUtils.getContentCharSet(entity));

                Scanner s = new Scanner(in).useDelimiter("\n");
                String line;
                while (s.hasNext() && null != (line = s.next())) {
                    // dispatch change event
                    if (line.length() > 1 && JSONUtils.mayBeJSON(line)) {
                        JSONObject json = JSONObject.fromObject(line);
                        if (json.has("seq")) {
                            if (logger.isLoggable(Level.FINE)) {
                                logger.fine("Dispatch new change event: " + line);
                            }
                            dispatchEvent(new DatabaseChangeEvent(json));
                        } else if (json.has("last_seq")) {
                            if (logger.isLoggable(Level.FINE)) {
                                logger.fine("CouchDB server closed _changes connection. Reconnecting...");
                            }
                            streamChanges(json.getInt("last_seq"));
                        }
                    }
                }
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine("[" + Thread.currentThread().getName() + "] Stop receiving changes...");
                }
            } catch (IOException e) {
                throw new Couch4JException(e);
            } finally {
                if (null != entity) {
                    try {
                        entity.consumeContent();
                    } catch (IOException e) {
                        // swallow
                    }
                }
            }
        }

        public void run() {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("[" + Thread.currentThread().getName() + "] Start receiving changes... ");
            }
            // Start with current udpate seq
            int updateSeq = database.getDatabaseInfo().getUpdateSeq();
            streamChanges(updateSeq);
        }
    };
    executor.submit(r);
}

From source file:org.chromium.ChromeI18n.java

private JSONObject getAssetContents(String assetName) throws IOException, JSONException {
    Context context = this.cordova.getActivity();
    InputStream is = context.getAssets().open(assetName);
    //Small trick to get the scanner to pull the entire input stream in one go
    Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    String contents = s.hasNext() ? s.next() : "";
    return new JSONObject(contents);
}

From source file:org.grouter.core.readers.FtpReaderJob.java

/**
 * Parses comma separated string of paths.
 *
 * @param pathIncludingFiles a list with comma separated strings, e.g /tmp/kalle.xml,nisse.xml
 * @return paths//from   w ww .  j  ava  2s  . co m
 */
private List<String> getPathIncludingFile(String pathIncludingFiles) {
    List<String> paths = new ArrayList<String>();
    Scanner scanner = new Scanner(pathIncludingFiles);
    try {
        scanner.useDelimiter(",");
        while (scanner.hasNext()) {
            String pathInclFile = scanner.next();
            logger.debug(pathInclFile);
            paths.add(pathInclFile);
        }
    } catch (Exception e) {
        logger.warn(e, e);
    } finally {
        scanner.close();
    }
    return paths;
}

From source file:org.scigap.iucig.controller.ScienceDisciplineController.java

private String convertStreamToString(InputStream is) {
    Scanner s = new Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

From source file:com.bt.heliniumstudentapp.UpdateClass.java

@Override
protected String doInBackground(Void... Void) {
    try {/*from w ww .  j av a2s .  c  o  m*/
        URLConnection connection = new URL(HeliniumStudentApp.URL_UPDATE_CHANGELOG).openConnection();

        connection.setConnectTimeout(HeliniumStudentApp.TIMEOUT_CONNECT);
        connection.setReadTimeout(HeliniumStudentApp.TIMEOUT_READ);

        connection.setRequestProperty("Accept-Charset", HeliniumStudentApp.CHARSET);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=" + HeliniumStudentApp.CHARSET);

        connection.connect();

        final Scanner line = new Scanner(connection.getInputStream()).useDelimiter("\\A");
        final String html = line.hasNext() ? line.next() : "";

        ((HttpURLConnection) connection).disconnect();

        if (((HttpURLConnection) connection).getResponseCode() == 200)
            return html;
        else
            return null;
    } catch (IOException e) {
        return null;
    }
}