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

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

Introduction

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

Prototype

public static void writeStringToFile(File file, String data) throws IOException 

Source Link

Document

Writes a String to a file creating the file if it does not exist using the default encoding for the VM.

Usage

From source file:com.example.todo.selenium.RestLog.java

public void saveForced(StringWriter writer, String subTitle) {

    if (StringUtils.isEmpty(subTitle)) {
        subTitle = "";
    } else {//from   w w  w.  j  av a 2  s . c o m
        subTitle = "-" + subTitle;
    }

    int sequenceNo = sequence.incrementAndGet();
    String evidenceFile = String.format("rest_communi_%03d%s.txt", sequenceNo, subTitle);
    File pageSourceFile = new File(evidenceSavingDirectory, evidenceFile);

    try {
        FileUtils.writeStringToFile(pageSourceFile, writer.toString());

    } catch (IOException e) {
        logger.error(e.toString());
    }

}

From source file:com.cloud.utils.ProcessUtilTest.java

@Test(expected = ConfigurationException.class)
public void pidCheckBadPid() throws ConfigurationException, IOException {
    Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
    FileUtils.writeStringToFile(pidFile, "intentionally not number");
    ProcessUtil.pidCheck(pidFile.getParent(), pidFile.getName());
}

From source file:com.sangupta.codefix.FixCopyright.java

protected String processEachFile(File file) throws IOException {
    // read contents
    String contents = FileUtils.readFileToString(file).trim();

    // check if file contains comments or not
    boolean hasCopyright = CopyrightHelper.checkCopyrightExists(contents);

    if (!hasCopyright) {
        // append the copyright and move on
        contents = this.copyrightNotice + SYSTEM_NEW_LINE + contents;
        FileUtils.writeStringToFile(file, contents);
        return "adding copyright";
    }//ww w.  ja  v  a  2 s  . c om

    // remove comment
    int index = CopyrightHelper.findCopyrightEnd(contents);
    if (index == -1) {
        System.out.println("No proper ending of comment detected, skipping!");
    }

    contents = contents.substring(index + 1);
    contents = this.copyrightNotice + SYSTEM_NEW_LINE + StringUtils.stripStart(contents, null);
    FileUtils.writeStringToFile(file, contents);
    return "copyright updated!";
}

From source file:com.smash.revolance.ui.database.FileSystemStorageTests.java

@Test
public void storageShouldHandleFileAddedDirectlyInTheRootFolder() throws IOException, StorageException {
    File file = new File(dbRoot, "key");

    // Create the file since it does not exists yet!
    FileUtils.writeStringToFile(file, "data");

    String content = storage.retrieve("key");

    assertThat(content, is("data"));
}

From source file:com.splunk.shuttl.testutil.TUtilsMBean.java

private static void writeXmlBoilerPlateWithNamespaceToFile(String namespace, File confFile) {
    try {// ww  w.  j a v a2  s.com
        FileUtils.writeStringToFile(confFile, TUtilsMBean.XML_HEADER + "<ns2:" + namespace
                + " xmlns:ns2=\"com.splunk.shuttl.server.model\">\n" + "</ns2:" + namespace + ">\n");
    } catch (IOException e) {
        TUtilsTestNG.failForException("Could not write contents to file", e);
    }
}

From source file:de.christian_klisch.software.servercontrol.service.impl.AbstractCommandProcessor.java

protected void execute(Task task) {
    Command v = (Command) task;/*from   w w w  . j ava 2 s  .  com*/
    String returnvalue = "";
    long timestamp = new Date().getTime();

    try {
        java.lang.Process p = null;
        if (((CommandView) v).getTargetOS().equals(LINOS)) {
            FileUtils.writeStringToFile(new File(SCRIPTDIR + timestamp + SCRIPTFILELIN), v.getCommand());
            if (((CommandView) v).getSshserver() != null && !((CommandView) v).getSshserver().isEmpty()) {
                returnvalue = this.executeOnSSH((Command) v, timestamp + SCRIPTFILELIN);
                new File(SCRIPTDIR + timestamp + SCRIPTFILELIN).delete();
            } else {
                Runtime.getRuntime().exec("chmod 775 " + SCRIPTDIR + timestamp + SCRIPTFILELIN);
                p = Runtime.getRuntime().exec(SCRIPTDIR + timestamp + SCRIPTFILELIN);
                p.waitFor();
                new File(SCRIPTDIR + timestamp + SCRIPTFILELIN).delete();
            }
        }
        if (((CommandView) v).getTargetOS().equals(WINOS)) {
            FileUtils.writeStringToFile(new File(SCRIPTDIR + timestamp + SCRIPTFILEWIN), v.getCommand());
            if (((CommandView) v).getSshserver() != null && !((CommandView) v).getSshserver().isEmpty()) {
                returnvalue = this.executeOnSSH((Command) v, timestamp + SCRIPTFILEWIN);
                new File(SCRIPTDIR + timestamp + SCRIPTFILEWIN).delete();
            } else {
                p = Runtime.getRuntime().exec(SCRIPTDIR + timestamp + SCRIPTFILEWIN);
                p.waitFor();
                new File(SCRIPTDIR + timestamp + SCRIPTFILEWIN).delete();
            }
        }

        if (p != null) {
            returnvalue = IOUtils.toString(p.getInputStream(), "UTF-8");
            if (returnvalue != null) {
                returnvalue = returnvalue.trim();
                returnvalue = returnvalue.replaceAll("[\\r\\n]", "");
            }
        }
        if (returnvalue != null && !returnvalue.isEmpty()) {
            returnvalue = returnvalue.trim();
            returnvalue = returnvalue.replaceAll("[\\r\\n]", "");
        }

    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    v.setLastExecute(new GregorianCalendar());
    v.setLastResult(returnvalue);
}

From source file:net.jperf.LogParserTest.java

public void testLogParserMain() throws Exception {
    PrintStream realOut = System.out;
    ByteArrayOutputStream fakeOut = new ByteArrayOutputStream();
    System.setOut(new PrintStream(fakeOut, true));
    try {/*from   w ww.  j  a v  a 2 s . c  om*/
        //usage
        realOut.println("-- Usage Test --");
        LogParser.runMain(new String[] { "--help" });
        realOut.println(fakeOut.toString());
        assertTrue(fakeOut.toString().indexOf("Usage") >= 0);
        fakeOut.reset();

        //log on std in, write to std out
        InputStream realIn = System.in;
        ByteArrayInputStream fakeIn = new ByteArrayInputStream(testLog.getBytes());
        System.setIn(fakeIn);
        try {
            realOut.println("-- Std in -> Std out Test --");
            LogParser.runMain(new String[0]);
            realOut.println(fakeOut.toString());
            assertTrue(fakeOut.toString().indexOf("tag") >= 0 && fakeOut.toString().indexOf("tag2") >= 0
                    && fakeOut.toString().indexOf("tag3") >= 0);
            fakeOut.reset();
        } finally {
            System.setIn(realIn);
        }

        //Log from a file
        FileUtils.writeStringToFile(new File("./target/logParserTest.log"), testLog);

        //log from file, write to std out
        realOut.println("-- File in -> Std out Test --");
        LogParser.runMain(new String[] { "./target/logParserTest.log" });
        realOut.println(fakeOut.toString());
        assertTrue(fakeOut.toString().indexOf("tag") >= 0 && fakeOut.toString().indexOf("tag2") >= 0
                && fakeOut.toString().indexOf("tag3") >= 0);
        fakeOut.reset();

        //CSV format test
        realOut.println("-- File in -> Std out Test with CSV --");
        LogParser.runMain(new String[] { "-f", "csv", "./target/logParserTest.log" });
        realOut.println(fakeOut.toString());
        assertTrue(fakeOut.toString().indexOf("\"tag\",") >= 0 && fakeOut.toString().indexOf("\"tag2\",") >= 0
                && fakeOut.toString().indexOf("\"tag3\",") >= 0);
        fakeOut.reset();

        //log from file, write to file
        realOut.println("-- File in -> File out Test --");
        LogParser.runMain(new String[] { "-o", "./target/statistics.out", "./target/logParserTest.log" });
        String statsOut = FileUtils.readFileToString(new File("./target/statistics.out"));
        realOut.println(statsOut);
        assertTrue(
                statsOut.indexOf("tag") >= 0 && statsOut.indexOf("tag2") >= 0 && statsOut.indexOf("tag3") >= 0);

        //log from file, write to file, different timeslice
        realOut.println("-- File in -> File out with different timeslice Test --");
        LogParser.runMain(new String[] { "-o", "./target/statistics.out", "--timeslice", "120000",
                "./target/logParserTest.log" });
        statsOut = FileUtils.readFileToString(new File("./target/statistics.out"));
        realOut.println(statsOut);
        assertTrue(
                statsOut.indexOf("tag") >= 0 && statsOut.indexOf("tag2") >= 0 && statsOut.indexOf("tag3") >= 0);

        //missing param test
        realOut.println("-- Missing param test --");
        assertEquals(1, LogParser.runMain(new String[] { "./target/logParserTest.log", "-o" }));

        //unknown arg test
        realOut.println("-- Unknown arg test --");
        assertEquals(1, LogParser.runMain(new String[] { "./target/logParserTest.log", "--foo" }));
        realOut.println(fakeOut);
        assertTrue(fakeOut.toString().indexOf("Unknown") >= 0);

        //graphing test
        realOut.println("-- File in -> File out with graphing --");
        LogParser.runMain(new String[] { "-o", "./target/statistics.out", "-g", "./target/perfGraphs.out",
                "./src/test/resources/net/jperf/dummyLog.txt" });
        statsOut = FileUtils.readFileToString(new File("./target/statistics.out"));
        realOut.println(statsOut);
        String graphsOut = FileUtils.readFileToString(new File("./target/perfGraphs.out"));
        realOut.println(graphsOut);
        assertTrue(graphsOut.indexOf("chtt=TPS") > 0 && graphsOut.indexOf("chtt=Mean") > 0);
    } finally {
        System.setOut(realOut);
    }
}

From source file:com.gargoylesoftware.htmlunit.libraries.MooTools121Test.java

/**
 * @throws Exception if an error occurs// ww w .j a va2  s  .c om
 */
@Test
@Tries(3)
@SuppressWarnings("unchecked")
public void mooTools() throws Exception {
    final String resource = "libraries/mootools/1.2.1/Specs/index.html";
    final URL url = getClass().getClassLoader().getResource(resource);
    assertNotNull(url);

    client_ = getWebClient();
    final HtmlPage page = client_.getPage(url);

    final HtmlElement progress = page.getElementById("progress");
    client_.waitForBackgroundJavaScriptStartingBefore(2000 * 100);

    final String prevProgress = progress.asText();

    FileUtils.writeStringToFile(new File("/tmp/mootols.html"), page.asXml());
    final String xpath = "//ul[@class='specs']/li[@class!='success']";
    final List<HtmlElement> failures = (List<HtmlElement>) page.getByXPath(xpath);
    if (!failures.isEmpty()) {
        final StringBuilder sb = new StringBuilder();
        for (HtmlElement failure : failures) {
            sb.append(failure.asXml()).append("\n\n");
        }
        throw new AssertionFailedError(sb.toString());
    }

    assertEquals("364", page.getElementById("total_examples").asText());
    assertEquals("0", page.getElementById("total_failures").asText());
    assertEquals("0", page.getElementById("total_errors").asText());
    assertEquals("100", prevProgress);
}

From source file:gov.nih.nci.cacis.common.schematron.SchematronValidatorTest.java

/**
 * checks xsd validation with invalid xml
 * @throws IOException - exception thrown if any
 *//*from  www .ja  va 2s .c  o m*/
@Test
public void validateInValidXML() throws IOException {
    final String validXmlFile = getClass().getClassLoader().getResource("schematron-failure-test.xml")
            .getFile();
    final String xmlString = FileUtils.readFileToString(new File(validXmlFile));
    Assert.assertNotNull(xmlString);
    final String output = validator.validate(xmlString);
    FileUtils.writeStringToFile(new File("output.txt"), output);
    Assert.assertNotNull(output);
    final String expOutputFile = getClass().getClassLoader().getResource("schematron-failure-test-output.txt")
            .getFile();
    final String expOutput = FileUtils.readFileToString(new File(expOutputFile));
    Assert.assertEquals(expOutput, output);
}

From source file:com.ikanow.aleph2.analytics.spark.utils.SparkPyTechnologyUtils.java

/** Write the script to a temp file
 * @param bucket//  w w  w .  j av  a  2  s. co m
 * @param job
 * @param script
 * @throws IOException 
 */
public static String writeUserPythonScriptTmpFile(final String signature,
        final Either<String, String> script_or_resource) throws IOException {
    final String tmp_dir = System.getProperty("java.io.tmpdir");
    final String filename = tmp_dir + "/user_py_script" + signature + ".py";

    final String script = script_or_resource
            .<String>either(l -> l,
                    fj.data.Java8.Function_F(Lambdas.wrap_u(r -> IOUtils.toString(
                            Thread.currentThread().getContextClassLoader().getResourceAsStream(r),
                            Charsets.UTF_8))));

    FileUtils.writeStringToFile(new File(filename), script);

    return filename;
}