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:edu.lafayette.metadb.web.controlledvocab.UpdateVocab.java

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*//*from   w  w  w.  ja  va2 s .c  om*/
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    String vocabName = null;
    String name = "nothing";
    String status = "Upload failed ";

    try {

        if (ServletFileUpload.isMultipartContent(request)) {
            status = "isMultiPart";
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemsList = servletFileUpload.parseRequest(request);
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

            InputStream input = null;
            Iterator it = fileItemsList.iterator();
            String result = "";
            String vocabs = null;
            int assigned = -1;

            while (it.hasNext()) {
                FileItem fileItem = (FileItem) it.next();
                result += "UpdateVocab: Form Field: " + fileItem.isFormField() + " Field name: "
                        + fileItem.getFieldName() + " Name: " + fileItem.getName() + " String: "
                        + fileItem.getString("utf-8") + "\n";
                if (fileItem.isFormField()) {
                    /* The file item contains a simple name-value pair of a form field */
                    if (fileItem.getFieldName().equals("vocab-name"))
                        vocabName = fileItem.getString();
                    else if (fileItem.getFieldName().equals("vocab-terms"))
                        vocabs = fileItem.getString("utf-8");
                    else if (fileItem.getFieldName().equals("assigned-field"))
                        assigned = Integer.parseInt(fileItem.getString());
                } else {
                    if (fileItem.getString() != null && !fileItem.getString().equals("")) {
                        @SuppressWarnings("unused")
                        String content = "nothing";
                        /* The file item contains an uploaded file */

                        /* Create new File object
                        File uploadedFile = new File("test.txt");
                        if(!uploadedFile.exists())
                           uploadedFile.createNewFile();
                        // Write the uploaded file to the system
                        fileItem.write(uploadedFile);
                        */
                        name = fileItem.getName();
                        content = fileItem.getContentType();
                        input = fileItem.getInputStream();
                    }
                }
            }
            //MetaDbHelper.note(result);
            if (vocabName != null) {
                Set<String> vocabList = new TreeSet<String>();
                if (input != null) {
                    Scanner fileSc = new Scanner(input);
                    while (fileSc.hasNextLine()) {
                        String vocabEntry = fileSc.nextLine();
                        vocabList.add(vocabEntry.trim());
                    }

                    HttpSession session = request.getSession(false);
                    if (session != null) {
                        String userName = (String) session.getAttribute("username");
                        SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                                "User " + userName + " created vocab " + vocabName);
                    }
                    status = "Vocab name: " + vocabName + ". File name: " + name + "\n";

                } else {
                    //MetaDbHelper.note(vocabs);
                    for (String vocabTerm : vocabs.split("\n"))
                        vocabList.add(vocabTerm);
                }
                if (!vocabList.isEmpty()) {
                    boolean updated = ControlledVocabDAO.addControlledVocab(vocabName, vocabList)
                            || ControlledVocabDAO.updateControlledVocab(vocabName, vocabList);
                    if (updated) {
                        status = "Vocab " + vocabName + " updated successfully ";
                        if (assigned != -1)
                            if (!AdminDescAttributesDAO.setControlledVocab(assigned, vocabName)) {
                                status = "Vocab " + vocabName + " cannot be assigned to " + assigned;
                            }

                    } else
                        status = "Vocab " + vocabName + " cannot be updated/created";
                } else
                    status = "Vocab " + vocabName + " has empty vocabList";
            }
        }
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    MetaDbHelper.note(status);
    out.print(status);
    out.flush();
}

From source file:edu.pucp.igc.piscosemanticsearch.Indexador.java

private String retomarTexto(String miArchivo) throws FileNotFoundException {
    //String rmRuta = "//Users//NuSs//Documents//workspaces//NetbeansWorkspace//SemanticSearch//src//main//resources//";
    //        FileInputStream fstream = new FileInputStream(rmRuta + miArchivo);
    //        DataInputStream = new DataInputStream(fstream);

    Scanner sc = new Scanner(new File(rmRuta + miArchivo));
    String strLinea = null;//from  w w w  .  j  a v a2 s  .c o m
    String texto = "";

    while (sc.hasNext()) {
        texto = texto.concat(sc.nextLine() + "\n");
    }
    return texto;
}

From source file:com.shoddytcg.server.GameServer.java

/**
 * Load pre-existing settings if any// www .  ja v  a 2  s  . c  om
 * NOTE: It loads the database password if available.
 * Password is line after serverName
 */
private void loadSettings() {

    File foo = new File("res/settings.txt");
    if (foo.exists()) {
        try {
            Scanner s = new Scanner(foo);
            m_dbServer = s.nextLine();
            m_dbName = s.nextLine();
            m_dbUsername = s.nextLine();
            m_serverName = s.nextLine();
            m_dbPassword = s.nextLine();
            s.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:ProgressMonitorInputStreamTest.java

/**
 * Prompts the user to select a file, loads the file into a text area, and sets it as the content
 * pane of the frame./*w  ww  .ja v  a 2 s.  c o  m*/
 */
public void openFile() throws IOException {
    int r = chooser.showOpenDialog(this);
    if (r != JFileChooser.APPROVE_OPTION)
        return;
    final File f = chooser.getSelectedFile();

    // set up stream and reader filter sequence

    FileInputStream fileIn = new FileInputStream(f);
    ProgressMonitorInputStream progressIn = new ProgressMonitorInputStream(this, "Reading " + f.getName(),
            fileIn);
    final Scanner in = new Scanner(progressIn);

    textArea.setText("");

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        protected Void doInBackground() throws Exception {
            while (in.hasNextLine()) {
                String line = in.nextLine();
                textArea.append(line);
                textArea.append("\n");
            }
            in.close();
            return null;
        }
    };
    worker.execute();
}

From source file:uk.ac.ebi.phenotype.web.util.BioMartBot.java

public String getQueryFromFile(String filename) {

    StringBuilder text = new StringBuilder();
    String NL = System.getProperty("line.separator");
    Scanner scanner = null;

    try {/*from  www  .  j a  va 2s  .co  m*/
        scanner = new Scanner(new FileInputStream(filename));

        while (scanner.hasNextLine()) {
            text.append(scanner.nextLine() + NL);
        }
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {
        scanner.close();
    }
    return text.toString();
}

From source file:nl.b3p.viewer.admin.ViewerAdminLockoutIntegrationTest.java

/**
 * This test work; but will be ignored because we need to catalina.out file
 * to check for the message and that does not seem te be generated.
 *
 * @throws IOException if any/*from   w w w  .j av a  2  s  .co  m*/
 * @throws URISyntaxException if any
 */
@Test
public void testCLockout() throws IOException, URISyntaxException {
    response = client.execute(new HttpGet(BASE_TEST_URL));
    EntityUtils.consume(response.getEntity());

    HttpUriRequest login = RequestBuilder.post().setUri(new URI(BASE_TEST_URL + "j_security_check"))
            .addParameter("j_username", "admin").addParameter("j_password", "fout").build();
    response = client.execute(login);
    EntityUtils.consume(response.getEntity());
    assertThat("Response status is OK.", response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_OK));

    // the default lockout is 5 attempt in 5 minutes
    for (int c = 1; c < 6; c++) {
        response = client.execute(login);
        EntityUtils.consume(response.getEntity());
        assertThat("Response status is OK.", response.getStatusLine().getStatusCode(),
                equalTo(HttpStatus.SC_OK));
    }
    // user 'fout' is now locked out, but we have no way to detect apart from looking at the cataline logfile,
    //   the status for a form-based login page is (and should be) 200

    LOG.info("trying one laste time with locked-out user, but correct password");
    login = RequestBuilder.post().setUri(new URI(BASE_TEST_URL + "j_security_check"))
            .addParameter("j_username", "admin").addParameter("j_password", "flamingo").build();
    response = client.execute(login);

    String body = EntityUtils.toString(response.getEntity());
    assertThat("Response status is OK.", response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_OK));

    assertNotNull("Response body mag niet null zijn.", body);
    assertTrue("Response moet 'Ongeldige logingegevens.' text hebben.",
            body.contains("Ongeldige logingegevens."));

    // there will be a message in catalina.out similar to: `WARNING: An attempt was made to authenticate the locked user "admin"`
    // problem is this is output to the console so logging is broken in tomcat plugin, so below assumption will fail and mark this test as ignored
    InputStream is = ViewerAdminLockoutIntegrationTest.class.getClassLoader()
            .getResourceAsStream("catalina.log");
    assumeNotNull("The catalina.out should privide a valid inputstream.", is);

    Scanner s = new Scanner(is);
    boolean lokkedOut = false;
    while (s.hasNextLine()) {
        final String lineFromFile = s.nextLine();
        if (lineFromFile.contains("An attempt was made to authenticate the locked user \"admin\"")) {
            lokkedOut = true;
            break;
        }
    }
    assertTrue("gebruiker 'admin' is buitengesloten", lokkedOut);
}

From source file:com.joliciel.talismane.machineLearning.ModelFactory.java

public MachineLearningModel getMachineLearningModel(ZipInputStream zis) {
    try {/*from w w  w . j a  v  a  2s.  c om*/
        MachineLearningModel machineLearningModel = null;
        ZipEntry ze = zis.getNextEntry();
        if (!ze.getName().equals("algorithm.txt")) {
            throw new JolicielException("Expected algorithm.txt as first entry in zip. Was: " + ze.getName());
        }

        // note: assuming the model type will always be the first entry
        Scanner typeScanner = new Scanner(zis, "UTF-8");
        MachineLearningAlgorithm algorithm = MachineLearningAlgorithm.MaxEnt;
        if (typeScanner.hasNextLine()) {
            String algorithmString = typeScanner.nextLine();
            try {
                algorithm = MachineLearningAlgorithm.valueOf(algorithmString);
            } catch (IllegalArgumentException iae) {
                LogUtils.logError(LOG, iae);
                throw new JolicielException("Unknown algorithm: " + algorithmString);
            }
        } else {
            throw new JolicielException("Cannot find algorithm in zip file");
        }
        switch (algorithm) {
        case MaxEnt:
            machineLearningModel = maxentService.getMaxentModel();
            break;
        case LinearSVM:
            machineLearningModel = linearSVMService.getLinearSVMModel();
            break;
        case Perceptron:
            machineLearningModel = perceptronService.getPerceptronModel();
            break;
        case PerceptronRanking:
            machineLearningModel = perceptronService.getPerceptronRankingModel();
            break;
        case OpenNLPPerceptron:
            machineLearningModel = maxentService.getPerceptronModel();
            break;
        default:
            throw new JolicielException("Machine learning algorithm not yet supported: " + algorithm);
        }

        while ((ze = zis.getNextEntry()) != null) {
            LOG.debug(ze.getName());
            machineLearningModel.loadZipEntry(zis, ze);
        } // next zip entry

        machineLearningModel.onLoadComplete();

        return machineLearningModel;
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    } finally {
        try {
            zis.close();
        } catch (IOException ioe) {
            LogUtils.logError(LOG, ioe);
        }
    }
}

From source file:ThreadedEchoServer.java

public void run() {
    try {/*w  ww.  java2s . c om*/
        try {
            InputStream inStream = incoming.getInputStream();
            OutputStream outStream = incoming.getOutputStream();

            Scanner in = new Scanner(inStream);
            PrintWriter out = new PrintWriter(outStream, true /* autoFlush */);

            out.println("Hello! Enter BYE to exit.");

            // echo client input
            boolean done = false;
            while (!done && in.hasNextLine()) {
                String line = in.nextLine();
                out.println("Echo: " + line);
                if (line.trim().equals("BYE"))
                    done = true;
            }
        } finally {
            incoming.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.maxl.java.aips2xml.Aips2Xml.java

static String convertHtmlToXml(String med_title, String html_str, String regnr_str) {
    Document mDoc = Jsoup.parse(html_str);
    mDoc.outputSettings().escapeMode(EscapeMode.xhtml);
    mDoc.outputSettings().prettyPrint(true);
    mDoc.outputSettings().indentAmount(4);

    // <div id="monographie"> -> <fi>
    mDoc.select("div[id=monographie]").tagName("fi").removeAttr("id");
    // <div class="MonTitle"> -> <title>
    mDoc.select("div[class=MonTitle]").tagName("title").removeAttr("class").removeAttr("id");
    // Beautify the title to the best of my possibilities ... still not good enough!
    String title_str = mDoc.select("title").text().trim().replaceAll("<br />", "").replaceAll("(\\t|\\r?\\n)+",
            "");/*from   www  .j  a  va 2 s. com*/
    if (!title_str.equals(med_title))
        if (SHOW_ERRORS)
            System.err.println(med_title + " differs from " + title_str);
    // Fallback solution: use title from the header AIPS.xml file - the titles look all pretty good!
    mDoc.select("title").first().text(med_title);
    // <div class="ownerCompany"> -> <owner>
    Element owner_elem = mDoc.select("div[class=ownerCompany]").first();
    if (owner_elem != null) {
        owner_elem.tagName("owner").removeAttr("class");
        String owner_str = mDoc.select("owner").text();
        mDoc.select("owner").first().text(owner_str);
    } else {
        mDoc.select("title").after("<owner></owner>");
        if (DB_LANGUAGE.equals("de"))
            mDoc.select("owner").first().text("k.A.");
        else if (DB_LANGUAGE.equals("fr"))
            mDoc.select("owner").first().text("n.s.");
    }

    // <div class="paragraph"> -> <paragraph>
    mDoc.select("div[class=paragraph]").tagName("paragraph").removeAttr("class").removeAttr("id");
    // <div class="absTitle"> -> <paragraphTitle>
    mDoc.select("div[class=absTitle]").tagName("paragraphtitle").removeAttr("class");
    // <div class="untertitle1"> -> <paragraphSubTitle>
    mDoc.select("div[class=untertitle1]").tagName("paragraphsubtitle").removeAttr("class");
    // <div class="untertitle"> -> <paragraphSubTitle>
    mDoc.select("div[class=untertitle]").tagName("paragraphsubtitle").removeAttr("class");
    // <div class="shortCharacteristic"> -> <characteristic>
    mDoc.select("div[class=shortCharacteristic]").tagName("characteristic").removeAttr("class");
    // <div class="image">
    mDoc.select("div[class=image]").tagName("image").removeAttr("class");

    // <p class="spacing1"> -> <p> / <p class="noSpacing"> -> <p>
    mDoc.select("p[class]").tagName("p").removeAttr("class");
    // <span style="font-style:italic"> -> <i>
    mDoc.select("span").tagName("i").removeAttr("style");
    // <i class="indention1"> -> <i> / <i class="indention2"> -> <b-i> 
    mDoc.select("i[class=indention1]").tagName("i").removeAttr("class");
    mDoc.select("i[class=indention2]").tagName("i").removeAttr("class");
    // mDoc.select("p").select("i").tagName("i");
    // mDoc.select("paragraphtitle").select("i").tagName("para-i");
    // mDoc.select("paragraphsubtitle").select("i").tagName("parasub-i");
    Elements elems = mDoc.select("paragraphtitle");
    for (Element e : elems) {
        if (!e.text().isEmpty())
            e.text(e.text());
    }
    elems = mDoc.select("paragraphsubtitle");
    for (Element e : elems) {
        if (!e.text().isEmpty())
            e.text(e.text());
    }

    // Here we take care of tables
    // <table class="s21"> -> <table>
    mDoc.select("table[class]").removeAttr("class");
    mDoc.select("table").removeAttr("cellspacing").removeAttr("cellpadding").removeAttr("border");
    mDoc.select("colgroup").remove();
    mDoc.select("td").removeAttr("class").removeAttr("colspan").removeAttr("rowspan");
    mDoc.select("tr").removeAttr("class");
    elems = mDoc.select("div[class]");
    for (Element e : elems) {
        if (e.text().isEmpty())
            e.remove();
    }

    mDoc.select("tbody").unwrap();
    // Remove nested table (a nasty table-in-a-table
    Elements nested_table = mDoc.select("table").select("tr").select("td").select("table");
    if (!nested_table.isEmpty()) {
        nested_table.select("table").unwrap();
    }

    // Here we take care of the images
    mDoc.select("img").removeAttr("style").removeAttr("align").removeAttr("border");

    // Subs and sups
    mDoc.select("sub[class]").tagName("sub").removeAttr("class");
    mDoc.select("sup[class]").tagName("sup").removeAttr("class");
    mDoc.select("td").select("sub").tagName("td-sub");
    mDoc.select("td").select("sup").tagName("td-sup");
    // Remove floating <td-sup> tags
    mDoc.select("p").select("td-sup").tagName("sup");
    mDoc.select("p").select("td-sub").tagName("sub");

    // Box
    mDoc.select("div[class=box]").tagName("box").removeAttr("class");

    // Insert swissmedicno5 after <owner> tag
    mDoc.select("owner").after("<swissmedicno5></swissmedicno5");
    mDoc.select("swissmedicno5").first().text(regnr_str);

    // Remove html, head and body tags         
    String xml_str = mDoc.select("body").first().html();

    //xml_str = xml_str.replaceAll("<tbody>", "").replaceAll("</tbody>", "");
    xml_str = xml_str.replaceAll("<sup> </sup>", "");
    xml_str = xml_str.replaceAll("<sub> </sub>", "");
    xml_str = xml_str.replaceAll("<p> <i>", "<p><i>");
    xml_str = xml_str.replaceAll("</p> </td>", "</p></td>");
    xml_str = xml_str.replaceAll("<p> </p>", "<p></p>"); // MUST be improved, the space is not a real space!!
    xml_str = xml_str.replaceAll("", "- ");
    xml_str = xml_str.replaceAll("<br />", "");
    xml_str = xml_str.replaceAll("(?m)^[ \t]*\r?\n", "");

    // Remove multiple instances of <p></p>
    Scanner scanner = new Scanner(xml_str);
    String new_xml_str = "";
    int counter = 0;
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (line.trim().equals("<p></p>")) {
            counter++;
        } else
            counter = 0;
        if (counter < 3)
            new_xml_str += line;
    }
    scanner.close();

    return new_xml_str;
}

From source file:imageClassify.TestForest.java

private void testFile(Path inPath, Path outPath, DataConverter converter, DecisionForest forest,
        Dataset dataset, Collection<double[]> results, Random rng) throws IOException {
    // create the predictions file
    FSDataOutputStream ofile = null;//ww  w  .  ja v a  2  s . co m

    if (outPath != null) {
        ofile = outFS.create(outPath);
    }

    FSDataInputStream input = dataFS.open(inPath);
    try {
        Scanner scanner = new Scanner(input, "UTF-8");

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.isEmpty()) {
                continue; // skip empty lines
            }

            Instance instance = converter.convert(line);
            double prediction = forest.classify(dataset, rng, instance);

            if (ofile != null) {
                ofile.writeChars(Double.toString(prediction)); // write the prediction
                ofile.writeChar('\n');
            }

            results.add(new double[] { dataset.getLabel(instance), prediction });
        }

        scanner.close();
    } finally {
        Closeables.close(input, true);
    }
}