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:Methods.ManageKey.java

/**
 * Mtodo que procesa el fichero obtenido en el metodo Open
 * @param keyFile/*ww  w. j  a  v  a  2  s.c  o  m*/
 * @return 
 */
private String[] processFile(File keyFile) {
    String[] keys = new String[4];
    String line;
    // dentro de las primeras 20 lineas han de estar todos los componentes necesarios
    int numLines = 0;

    try {
        Scanner file = new Scanner(keyFile);

        while (file.hasNextLine() && numLines < 20) {

            line = file.nextLine();
            numLines++;

            if (StringUtils.contains(line, "P generado")) {
                line = file.nextLine();
                //para dejar solo los nmeros
                keys[0] = StringUtils.replaceAll(line, "[^0-9]", "");

                numLines++;
            }

            if (StringUtils.contains(line, "Q generado")) {
                line = file.nextLine();

                keys[1] = StringUtils.replaceAll(line, "[^0-9]", "");

                numLines++;
            }

            if (StringUtils.contains(line, "e generada")) {
                line = file.nextLine();

                keys[2] = StringUtils.replaceAll(line, "[^0-9]", "");

                numLines++;
            }

            if (StringUtils.contains(line, "Unidades:")) {

                if (StringUtils.contains(line, "Decimal")) {
                    keys[3] = "Decimal";
                } else {
                    keys[3] = "Hexadecimal";
                }

                numLines++;
            }
        }

    } catch (FileNotFoundException e) {
        this.errorDialog.readingFile();
        return null;
    }

    if (this.keysNotOk(keys)) {
        this.errorDialog.missingComponents();
        keys = null;
    }

    return keys;

}

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

/**
 * This is the helper function that initializes the schema and tables.
 * Initialization is as follows: // w w  w.j ava2s  .  c o  m
 *    (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:edu.utah.further.core.util.text.LineListFileScanner.java

/**
 * Template method that parses an entire input from a scanner.
 *
 * @param scanner//from   ww w  .  j  av  a2 s. c o  m
 *            provides input
 * @param lineScanner
 *            scans each line into an entity
 * @return list of entities, one per line
 */
@Override
protected List<T> parseInput(final Scanner scanner) {
    final List<T> entities = CollectionUtil.newList();
    int lineNumber = 0;
    String line = null;
    try {
        while (scanner.hasNextLine()) {
            lineNumber++;
            line = scanner.nextLine();
            if (isIgnoreBlankLines() && StringUtils.isBlank(line)) {
                if (log.isDebugEnabled()) {
                    log.debug("Ignoring blank line " + lineNumber);
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Parsing line " + lineNumber + ": " + quote(line));
                }
                final String filteredLine = filterLine(line);
                entities.add(getLineScanner().parse(filteredLine));
            }
        }
    } catch (final Exception e) {
        throw new ApplicationException("Failed to parse file at line " + lineNumber + ": " + quote(line), e);
    } finally {
        // Ensure the underlying stream is always closed
        scanner.close();
    }
    return entities;
}

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

/**
 * Creates a new instance of SimpleGraphView
 *//*from w w  w. jav a 2s  . co  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:de.vandermeer.skb.commons.utils.Json2Collections.java

/**
 * Reads JSON from the input scanner, transforms into an SKB map and logs errors.
 * /* w  w  w.  ja  v  a  2 s .  c  o m*/
 * This method parses the <code>input</code> and removes every line starting with either of the two possible single line comments: '//' and '#'.
 * It then calls s2o with the altered input.
 * @param input scanner wit JSON specification
 * @return a tree with information from the JSON file or null in case of errors
 */
public Object read(Scanner input) {
    Object ret = null;
    if (input != null) {
        String content = new String();
        try {
            while (input.hasNextLine()) {
                String line = input.nextLine();
                if (!StringUtils.startsWithAny(line.trim(), new String[] { "//", "#" }))
                    content += line.trim();
            }
        } catch (Exception ignore) {
        }
        ret = this.s2o(content);
    }
    return ret;
}

From source file:br.edu.ifes.bd2dao.cgt.Menu.java

private Disciplina buscarDisciplinaPorNomeEPeriodo() {
    Scanner scanId = new Scanner(System.in);
    System.out.println("Infome o nome desejado: ");
    String nome = scanId.nextLine();
    System.out.println("Infome o perodo desejado: ");
    String periodo = scanId.nextLine();
    return new Disciplina().selecionar(nome, periodo);
}

From source file:biblivre3.cataloging.CatalogingHandler.java

@Override
public String processModule(HttpServletRequest request, HttpServletResponse response, String submitButton,
        HashMap<String, String> requestParametersHash) {

    if (submitButton.equals("EXPORT_RECORD")) {
        final String recordIds = request.getParameter("serial_list");
        final BiblioBO bo = new BiblioBO();
        final MemoryFileDTO export = bo.export(recordIds.split(","));
        if (export != null) {
            this.returnFile(export, response);
        }//from  w  w w  .ja v  a  2  s . c om
        return "x-download";
    } else if (submitButton.equals("UPLOAD_IMPORT")) {
        String records = "";

        int totalRecords = 0;
        int validRecords = 0;
        final HttpSession session = request.getSession();
        final UploadedFileBean file = (UploadedFileBean) session.getAttribute("UPLOADED_FILE");

        if (file != null) {
            final StringBuilder builder = new StringBuilder();
            final Scanner scanner = new Scanner(file.getInputStream(), "UTF-8");
            while (scanner.hasNextLine()) {
                String iso2709 = scanner.nextLine();
                if (StringUtils.isBlank(iso2709)) {
                    continue;
                }

                String lines[] = iso2709.replace("\u001E\u001D", "\u001E\u001D\r\n").split("\r\n");

                for (String line : lines) {
                    if (StringUtils.isNotBlank(line)) {
                        try {
                            String freemarc = MarcReader.iso2709ToMarc(line);
                            freemarc = TextUtils.combine(freemarc);
                            builder.append(freemarc);
                            builder.append(ApplicationConstants.FREEMARC_RECORD_SEPARATOR);
                            builder.append(ApplicationConstants.LINE_BREAK);
                            totalRecords++;
                            validRecords++;
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                }
            }
            records = builder.toString();
        }

        JSONObject json = new JSONObject();
        try {
            if (StringUtils.isBlank(records)) {
                json.put("success", false);
                json.put("message", I18nUtils.getText(session, "biblivre3", "ERROR_MARC_NOT_FILLED"));
            } else {
                json.put("success", true);
                json.put("marc", records);
                json.put("totalRecords", String.valueOf(totalRecords));
                json.put("validRecords", String.valueOf(validRecords));
            }
        } catch (JSONException je) {
        }
        this.returnJson(json, response);
        return "x-json";

    } else if (submitButton.equals("SAVE_IMPORT")) {
        final String freemarc = request.getParameter("marc");
        if (StringUtils.isBlank(freemarc)) {
            Dialog.showWarning(request, "ERROR_MARC_NOT_FILLED");
            return "/jsp/cataloging/import.jsp";
        }

        final String importType = request.getParameter("import_type");
        boolean success = false;

        //biblio_MAIN, biblio_WORK, authorities, vocabulary
        if (importType.startsWith("biblio")) {
            String[] ex_auto = null;

            if (request.getParameter("holding") != null) {
                ex_auto = new String[6];
                ex_auto[0] = request.getParameter("quant");
                ex_auto[1] = request.getParameter("nvol");
                ex_auto[2] = request.getParameter("nvol_obra");
                ex_auto[3] = request.getParameter("biblio_dep");
                ex_auto[4] = request.getParameter("aquis");
                ex_auto[5] = request.getParameter("dt_tomb");
            }

            String base = "WORK";
            if (importType.contains("MAIN")) {
                base = "MAIN";
            }

            FreeMarcBO fbo = new FreeMarcBO();
            success = fbo.importRecords(freemarc, Database.valueOf(base), null, ex_auto);

        } else {
            boolean authorities = importType.equals("authorities");

            MaterialType mt = authorities ? MaterialType.AUTHORITIES : MaterialType.VOCABULARY;

            AuthoritiesBO abo = new AuthoritiesBO();
            VocabularyBO vbo = new VocabularyBO();

            final String[] records = freemarc.split(ApplicationConstants.FREEMARC_RECORD_SEPARATOR);

            for (final String record : records) {
                if (StringUtils.isBlank(record)) {
                    continue;
                }

                Record recordObj = MarcReader.marcToRecord(record, mt, RecordStatus.NEW);
                success = authorities ? abo.insert(recordObj) : vbo.insert(recordObj);
            }
        }

        if (success) {
            Dialog.showNormal(request, "SUCCESS_IMPORT_RECORD");
            return "/jsp/cataloging/import.jsp";
        } else {
            Dialog.showError(request, "ERROR_IMPORT_RECORD");
            return "/jsp/cataloging/import.jsp";
        }
    }

    return "/jsp/cataloging/biblio.jsp";
}

From source file:analysePortalU.AnalysePortalUData.java

public void analyse()
        throws HttpException, IOException, ParserConfigurationException, SAXException, TransformerException {

    Map<String, Map<String, String>> resultMap = new HashMap<String, Map<String, String>>();

    Scanner in = new Scanner(getClass().getClassLoader().getResourceAsStream("keywords.txt"));
    while (in.hasNextLine()) {
        String keyword = URLEncoder.encode(in.nextLine().trim(), "UTF-8");

        int currentPage = 1;
        boolean moreResults = true;

        while (moreResults) {

            String url = "http://www.portalu.de/opensearch/query?q=" + keyword.replace(' ', '+')
                    + "+datatype:metadata+ranking:score&h=" + PAGE_SIZE + "&detail=1&ingrid=1&p=" + currentPage;

            HttpClientParams httpClientParams = new HttpClientParams();
            HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager();
            httpClientParams.setSoTimeout(60 * 1000);
            httpConnectionManager.getParams().setConnectionTimeout(60 * 1000);
            httpConnectionManager.getParams().setSoTimeout(60 * 1000);

            HttpClient client = new HttpClient(httpClientParams, httpConnectionManager);
            HttpMethod method = new GetMethod(url);

            // set a request header
            // this can change in the result of the response since it might
            // be
            // interpreted differently
            // method.addRequestHeader("Accept-Language", language);
            // //"de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4");

            System.out.println("Query: " + url);
            int status = client.executeMethod(method);
            if (status == 200) {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(method.getResponseBodyAsStream());
                XPathUtils xpath = new XPathUtils(new ConfigurableNamespaceContext());
                NodeList results = xpath.getNodeList(doc, "/rss/channel/item");
                int numberOfResults = results.getLength();

                for (int i = 0; i < results.getLength(); i++) {
                    Node node = results.item(i);
                    String fileIdentifier = xpath.getString(node, ".//*/fileIdentifier/CharacterString");
                    if (!resultMap.containsKey(fileIdentifier)) {
                        resultMap.put(fileIdentifier, new HashMap<String, String>());
                    }/*from  ww w  . j a  v  a 2 s  .  c om*/
                    Map<String, String> currentMap = resultMap.get(fileIdentifier);
                    currentMap.put("uuid", fileIdentifier);
                    currentMap.put("partner", xpath.getString(node, "partner"));
                    currentMap.put("provider", xpath.getString(node, "provider"));
                    currentMap.put("udk-class", xpath.getString(node, "udk-class"));
                    currentMap.put("source", xpath.getString(node, "source"));
                    currentMap.put("url", new URL(xpath.getString(node, "link")).toString());
                    currentMap.put("title", xpath.getString(node, ".//*/title/CharacterString"));
                    currentMap.put("description", xpath.getString(node, ".//*/abstract/CharacterString"));
                    Node addressNode = xpath.getNode(node, ".//*/contact/idfResponsibleParty");
                    String addressString = "";
                    String tmp = xpath.getString(addressNode, "indiviualName/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += tmp + "\n";

                    tmp = xpath.getString(addressNode, "organisationName/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += tmp + "\n";

                    tmp = xpath.getString(addressNode,
                            "contactInfo/CI_Contact/address/CI_Address/deliveryPoint/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += tmp + "\n";

                    tmp = xpath.getString(addressNode,
                            "contactInfo/CI_Contact/address/CI_Address/postalCode/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += tmp + " ";
                    tmp = xpath.getString(addressNode,
                            "ontactInfo/CI_Contact/address/CI_Address/city/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += tmp + "\n";

                    tmp = xpath.getString(addressNode,
                            "contactInfo/CI_Contact/address/CI_Address/country/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += tmp + "\n";

                    tmp = xpath.getString(addressNode,
                            "contactInfo/CI_Contact/address/CI_Address/electronicMailAddress/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += "Email: " + tmp + "\n";

                    tmp = xpath.getString(addressNode,
                            "contactInfo/CI_Contact/phone/CI_Telephone/voice/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += "Tel: " + tmp + "\n";

                    tmp = xpath.getString(addressNode,
                            "contactInfo/CI_Contact/phone/CI_Telephone/facsimile/CharacterString");
                    if (tmp != null && tmp.length() > 0)
                        addressString += "Fax: " + tmp + "\n";

                    currentMap.put("pointOfContact", addressString);
                }
                if (numberOfResults > 0 && numberOfResults >= PAGE_SIZE) {
                    currentPage++;
                } else {
                    moreResults = false;
                }
            } else {
                moreResults = false;
            }
        }

    }

    StringWriter sw = new StringWriter();
    ExcelCSVPrinter ecsvp = new ExcelCSVPrinter(sw);
    boolean fieldsWritten = false;
    for (String key : resultMap.keySet()) {
        Map<String, String> result = resultMap.get(key);
        if (!fieldsWritten) {
            for (String field : result.keySet()) {
                ecsvp.print(field);
            }
            ecsvp.println("");
            fieldsWritten = true;
        }
        for (String value : result.values()) {
            ecsvp.print(value);
        }
        ecsvp.println("");
    }

    PrintWriter out = new PrintWriter("result.csv");
    out.write(sw.toString());
    out.close();
    in.close();

    System.out.println("Done.");
}

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 www  . ja v  a 2 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.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  w w  w.  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;
        }
    }
}