Example usage for org.apache.commons.io FileUtils readLines

List of usage examples for org.apache.commons.io FileUtils readLines

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils readLines.

Prototype

public static List readLines(File file) throws IOException 

Source Link

Document

Reads the contents of a file line by line to a List of Strings using the default encoding for the VM.

Usage

From source file:br.com.involves.converter.ConverterTest.java

@Test
public void testListConverterToJson() throws IllegalArgumentException, IllegalAccessException, IOException {
    JsonConverter converter = new JsonConverter();
    File expected = new File("src/test/resources/listPersonExpected.json");
    File output = folder.newFile("listPersonOutput.json");

    Address address1 = new Address("Rua Jos", "39", "So Jos");
    Address address2 = new Address("Rua Joo", "100", "Florianpolis");
    List<Address> listAddress = new ArrayList<>();
    listAddress.add(address1);/* w ww. jav a 2 s .com*/
    listAddress.add(address2);

    Person person1 = new Person("Fernando", 28, 'M', listAddress, new double[] { 8.0, 6.0, 10.0 });
    Person person2 = new Person("Maria", 30, 'F', listAddress, new double[] { 0.0, 2.0, 5.0 });
    List<Person> personList = new ArrayList<>();
    personList.add(person1);
    personList.add(person2);

    converter.convert(personList, output);

    Assert.assertTrue(output.exists());
    Assert.assertEquals(FileUtils.readLines(expected), FileUtils.readLines(output));
}

From source file:hu.bme.mit.sette.tools.catg.CatgParser.java

@Override
protected void parseSnippet(Snippet snippet, SnippetInputsXml inputsXml) throws Exception {
    File outputFile = RunnerProjectUtils.getSnippetOutputFile(getRunnerProjectSettings(), snippet);
    File errorFile = RunnerProjectUtils.getSnippetErrorFile(getRunnerProjectSettings(), snippet);

    if (errorFile.exists()) {
        // TODO enhance this section and make it more clear

        List<String> lines = FileUtils.readLines(errorFile);

        String firstLine = lines.get(0);

        if (firstLine.startsWith("Exception in thread \"main\"")) {
            Pattern p = Pattern.compile("Exception in thread \"main\" ([a-z0-9\\._]+).*",
                    Pattern.CASE_INSENSITIVE);

            Matcher m = p.matcher(firstLine);
            if (m.matches()) {
                String exceptionType = m.group(1);

                if (exceptionType.equals("java.lang.NoClassDefFoundError")) {
                    inputsXml.setResultType(ResultType.NA);
                } else if (exceptionType.equals("java.lang.VerifyError")) {
                    inputsXml.setResultType(ResultType.EX);
                } else if (exceptionType.endsWith("Exception")) {
                    // enhance
                    inputsXml.setResultType(ResultType.EX);
                } else {
                    System.err.println(snippet.getMethod());
                    System.err.println("NOT HANDLED TYPE: " + exceptionType);
                }//  www .j a v a  2s .  c om
            } else {
                System.err.println(snippet.getMethod());
                System.err.println("NO MATCH");
            }
        } else if (firstLine.startsWith("java.lang.ArrayIndexOutOfBoundsException")) {
            inputsXml.setResultType(ResultType.EX);
        } else if (firstLine.startsWith("WARNING: !!!!!!!!!!!!!!!!! Prediction failed !!!!!!!!!!!!!!!!!")) {
            // TODO enhance (it was just warning)
            inputsXml.setResultType(ResultType.S);
        }

        // if (firstLine
        // .startsWith("Exception in thread \"main\" java.lang.NoClassDefFoundError"))
        // {
        // inputsXml.setResultType(ResultType.NA);
        // return;
        // } else if (firstLine
        // .startsWith("Exception in thread \"main\" java.lang.StringIndexOutOfBoundsException"))
        // {
        // inputsXml.setResultType(ResultType.EX);
        // return;
        // }// else if(firstLine.startsWith("))

        // TODO enhance error message

        // this is debug (only if unhandled error)
        if (inputsXml.getResultType() == null) {
            System.err.println("=============================");
            System.err.println(snippet.getMethod());
            System.err.println("=============================");

            for (String line : lines) {
                System.err.println(line);
            }
            System.err.println("=============================");
        }
    } else {
        // TODO enhance this section
        inputsXml.setResultType(ResultType.S);

        // collect inputs
        List<String> lines = FileUtils.readLines(outputFile);
        if (!lines.get(0).startsWith("Now testing ")) {
            throw new RuntimeException("File beginning problem: " + outputFile);
        }

        Pattern p = Pattern.compile("\\[Input (\\d+)\\]");
        Pattern p2 = Pattern.compile("  (\\w+) param(\\d+) = (.*)");

        int inputNumber = 1;

        for (int i = 1; i < lines.size(); inputNumber++) {
            String line = lines.get(i);

            Matcher m = p.matcher(line);
            if (m.matches()) {
                if (!m.group(1).equals(String.valueOf(inputNumber))) {
                    System.err.println("Current input should be: " + inputNumber);
                    System.err.println("Current input line: " + line);
                    throw new RuntimeException("File input problem (" + line + "): " + outputFile);
                }

                // find end of generated input
                int nextInputLine = -1;
                for (int j = i + 1; j < lines.size(); j++) {
                    if (p.matcher(lines.get(j)).matches()) {
                        nextInputLine = j;
                        break;
                    }
                }

                if (nextInputLine < 0) {
                    // EOF
                    nextInputLine = lines.size();
                }

                int paramCount = snippet.getMethod().getParameterTypes().length;

                InputElement ie = new InputElement();

                for (int j = 0; j < paramCount; j++) {
                    String l = lines.get(i + 1 + j + 1);
                    Matcher m2 = p2.matcher(l);

                    if (m2.matches()) {
                        String type = m2.group(1);
                        String value = m2.group(3);

                        ParameterElement pe = new ParameterElement();

                        if (type.equals("String")) {
                            pe.setType(ParameterType.EXPRESSION);
                            pe.setValue("\"" + value + "\"");
                        } else {
                            pe.setType(ParameterType.fromString(type));
                            pe.setValue(value);
                        }

                        ie.getParameters().add(pe);
                    } else {
                        throw new RuntimeException("File input problem (" + l + "): " + outputFile);
                    }
                }

                inputsXml.getGeneratedInputs().add(ie);

                i = nextInputLine;

                // TODO now NOT dealing with result and exception
            } else {
                throw new RuntimeException("File input problem (" + line + "): " + outputFile);
            }
        }
    }

}

From source file:de.codecentric.batch.test.FlatFileJobTest.java

@Test
public void runXmlJob() throws Exception {
    File file = new File("target/out-xmlconfig.txt");
    file.delete();//ww  w  .j a va  2s  .com
    jobOperator.start("flatFileJobXml", "");
    while (jobRepository.getLastJobExecution("flatFileJobXml", new JobParameters()).getStatus().isRunning()) {
        Thread.sleep(100);
    }
    assertEquals(BatchStatus.COMPLETED,
            jobRepository.getLastJobExecution("flatFileJobXml", new JobParameters()).getStatus());
    assertEquals(10, FileUtils.readLines(file).size());
}

From source file:ml.shifu.guagua.mapreduce.example.sum.SumTest.java

@Test
public void testSumApp() throws IOException {
    Properties props = new Properties();
    props.setProperty(GuaguaConstants.MASTER_COMPUTABLE_CLASS, SumMaster.class.getName());
    props.setProperty(GuaguaConstants.WORKER_COMPUTABLE_CLASS, SumWorker.class.getName());
    props.setProperty(GuaguaConstants.GUAGUA_ITERATION_COUNT, "10");
    props.setProperty(GuaguaConstants.GUAGUA_MASTER_RESULT_CLASS, LongWritable.class.getName());
    props.setProperty(GuaguaConstants.GUAGUA_WORKER_RESULT_CLASS, LongWritable.class.getName());

    props.setProperty(GuaguaConstants.GUAGUA_MASTER_INTERCEPTERS, SumOutput.class.getName());

    props.setProperty(GuaguaConstants.GUAGUA_INPUT_DIR, getClass().getResource("/sum").toString());

    props.setProperty("guagua.sum.output", SUM_OUTPUT);

    GuaguaUnitDriver<GuaguaWritableAdapter<LongWritable>, GuaguaWritableAdapter<LongWritable>> driver = new GuaguaMRUnitDriver<GuaguaWritableAdapter<LongWritable>, GuaguaWritableAdapter<LongWritable>>(
            props);//from ww w  .ja v a  2  s. co  m

    driver.run();

    Assert.assertEquals(15345 + "",
            FileUtils.readLines(new File(System.getProperty("user.dir") + File.separator + SUM_OUTPUT)).get(0));
}

From source file:de.tuberlin.dima.aim3.assignment1.BookAndAuthorJoinTest.java

void testJoin(Tool bookAndAuthorJoin, boolean mapOnly) throws Exception {
    File authorsFile = getTestTempFile("authors.tsv");
    File booksFile = getTestTempFile("books.tsv");
    File outputDir = getTestTempDir("output");
    outputDir.delete();/*from  ww w  . ja va2 s  . co  m*/

    writeLines(authorsFile, readLines("/assignment1/authors.tsv"));
    writeLines(booksFile, readLines("/assignment1/books.tsv"));

    Configuration conf = new Configuration();

    bookAndAuthorJoin.setConf(conf);
    bookAndAuthorJoin.run(new String[] { "--authors", authorsFile.getAbsolutePath(), "--books",
            booksFile.getAbsolutePath(), "--output", outputDir.getAbsolutePath() });

    String outputFilename = mapOnly ? "part-m-00000" : "part-r-00000";

    File outputFile = new File(outputDir, outputFilename);
    System.out.println(FileUtils.readLines(outputFile));
    Multimap<String, Book> booksByAuthors = readBooksByAuthors(outputFile);

    assertTrue(booksByAuthors.containsKey("Charles Bukowski"));
    assertTrue(booksByAuthors.get("Charles Bukowski")
            .contains(new Book("Confessions of a Man Insane Enough to Live with Beasts", 1965)));
    assertTrue(booksByAuthors.get("Charles Bukowski").contains(new Book("Hot Water Music", 1983)));

    assertTrue(booksByAuthors.containsKey("Fyodor Dostoyevsky"));
    assertTrue(booksByAuthors.get("Fyodor Dostoyevsky").contains(new Book("Crime and Punishment", 1866)));
    assertTrue(booksByAuthors.get("Fyodor Dostoyevsky").contains(new Book("The Brothers Karamazov", 1880)));

}

From source file:api.behindTheName.BehindTheNameApi.java

private void Search(final HashSet<String> set, int counter, final PeopleNameOption option,
        final ProgressCallback callback) {
    final int c = counter;
    callback.onProgressUpdate(behindTheNameProgressValues[c]);
    if (!set.isEmpty())
        callback.onProgress(new TreeSet<>(set));

    Platform.runLater(new Runnable() {

        @Override// ww w.j a v  a2  s  .  com
        public void run() {
            String nation = genres.get(option.genre);
            String gender = getGenderKey(option.gender);
            String url = "http://www.behindthename.com/api/random.php?number=6&usage=" + nation + "&gender="
                    + gender + "&key=" + BEHIND_THE_NAME_KEY;

            final File file = new File("Temp.xml");
            try {
                URL u = new URL(url);
                FileUtils.copyURLToFile(u, file);

                List<String> lines = FileUtils.readLines(file);
                for (String s : lines) {
                    if (s.contains("<name>")) {
                        s = s.substring(s.indexOf(">") + 1, s.lastIndexOf("</"));
                        set.add(s);
                    }
                }

            } catch (MalformedURLException ex) {
                Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
            }

            try {
                Thread.sleep(250);
            } catch (InterruptedException ex) {
                Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
            }

            if (set.size() == MAX_SIZE || c == MAX_SEARCH - 1 || set.isEmpty()) {
                callback.onProgressUpdate(1.0f);

                return;
            }

            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    Search(set, c + 1, option, callback);
                }
            });

        }
    });

}

From source file:massbank.svn.SVNUtils.java

/**
 * /*from w ww  . j av  a2s .co  m*/
 */
public static String[] getLicenseOKFileList(String[] paths) {
    List<String> licenseOKList = new ArrayList();
    for (int i = 0; i < paths.length; i++) {
        String filePath = paths[i];
        boolean found = false;
        try {
            List<String> lines = FileUtils.readLines(new File(filePath));
            for (int l = 0; l < lines.size(); l++) {
                String line = lines.get(l);
                if (line.startsWith("LICENSE: CC")) {
                    found = true;
                    break;
                } else if (line.startsWith("CH$NAME")) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (found) {
            licenseOKList.add(filePath);
        }
    }
    return (String[]) licenseOKList.toArray(new String[] {});
}

From source file:de.tudarmstadt.ukp.dkpro.tc.examples.io.ReutersCorpusReader.java

@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
    super.initialize(context);

    goldLabelMap = new HashMap<String, List<String>>();

    try {/*w ww .  j a v a 2 s.c  o m*/
        URL resourceUrl = ResourceUtils.resolveLocation(goldLabelFile, this, context);

        for (String line : FileUtils.readLines(new File(resourceUrl.toURI()))) {
            String[] parts = line.split(" ");

            if (parts.length < 2) {
                throw new IOException("Wrong file format in line: " + line);
            }
            String fileId = parts[0].split("/")[1];

            List<String> labels = new ArrayList<String>();
            for (int i = 1; i < parts.length; i++) {
                labels.add(parts[i]);
            }

            goldLabelMap.put(fileId, labels);
        }
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    } catch (URISyntaxException ex) {
        throw new ResourceInitializationException(ex);
    }
}

From source file:com.bluexml.side.portal.alfresco.reverse.reverser.LayoutReverser.java

public LayoutReverser(File page, Portal p, String layoutName) throws IOException {
    this.pageFile = page;
    this.readLines = FileUtils.readLines(page);
    this.p = p;//from   ww  w .  java  2s  .  c  om
    extractedLayout = PortalFactory.eINSTANCE.createPortalLayout();
    extractedLayout.setName(layoutName);
    p.getLayoutSet().add(extractedLayout);
}

From source file:com.impetus.ankush.agent.service.provider.PIDServiceStatusProvider.java

/**
 * Method to get service status using the process id.
 *//*  w  w w. j a v a 2 s. c  o  m*/
@Override
public Map<String, Boolean> getServiceStatus(List<ComponentService> services) {
    // Service status map
    Map<String, Boolean> status = new HashMap<String, Boolean>();

    // iterate over the services for getting service status.
    for (ComponentService service : services) {
        try {
            // Get pid file path
            String pidFile = service.getParameters().get(KEY_PID_FILE);
            // create file object
            File file = new File(pidFile);
            // check file exists or not
            if (file.exists()) {
                // Get file string

                List<String> lines = FileUtils.readLines(file);
                // if content is empty
                if (lines == null || lines.isEmpty()) {
                    status.put(service.getRole(), false);
                } else {
                    // if pid exists
                    Result result = CommandExecutor.executeCommand(COMMAND_PS_P + lines.get(0));
                    // setting service status.
                    status.put(service.getRole(), result.getExitVal() == 0);
                }
            } else {
                status.put(service.getRole(), false);
            }
        } catch (Exception e) {
            // logging error in agent log
            LOGGER.error(e.getMessage(), e);
            // setting service status as false.
            status.put(service.getRole(), false);
        }
    }
    // return service status.
    return status;
}