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, String encoding) throws IOException 

Source Link

Document

Writes a String to a file creating the file if it does not exist.

Usage

From source file:gov.va.chir.tagline.dao.AnnotationsSaver.java

private void saveHeader() throws IOException {
    final StringBuilder builder = new StringBuilder();

    builder.append(DatasetUtil.DOC_ID);/* ww  w  . java  2 s.  c  om*/
    builder.append("\t");

    builder.append(ANNO_START);
    builder.append("\t");

    builder.append(ANNO_END);
    builder.append("\t");

    builder.append(ANNO_TYPE);
    builder.append(System.getProperty("line.separator"));

    FileUtils.writeStringToFile(file, builder.toString(), false);
}

From source file:it.incipict.tool.profiles.ProfilesToolTest.java

@Before
public void setUp() {
    try {/*www  .  jav  a 2  s .  c o m*/
        profileTool = new ProfilesTool();
        FileUtils.writeStringToFile(new File(KNOLEDGEBASE_FILE_PATH), profileTool.knowledgeBaseToString(),
                Charset.forName("ISO-8859-1"));
    } catch (ProfilesToolException | IOException e) {
        logger.error("error: ", e);
    }
}

From source file:de.nrw.hbz.regal.sync.ingest.DippDownloader.java

protected void downloadObject(File dir, String pid) {
    try {/*from w w  w  .  j a  v a2s  .c  om*/
        logger.debug(pid + " start download!");
        URL url = new URL(getServer() + "get/" + pid + "?xml=true");
        File file = new File(dir.getAbsolutePath() + File.separator + URLEncoder.encode(pid, "utf-8") + ".xml");
        String data = null;
        StringWriter writer = new StringWriter();
        IOUtils.copy(url.openStream(), writer);
        data = writer.toString();
        FileUtils.writeStringToFile(file, data, "utf-8");

        downloadStreams(dir, pid);
        downloadConstituent(dir, pid);
        downloadRelatedObject(dir, pid, "rel:hasPart");

        downloadRelatedObject(dir, pid, "rel:isPartOf");
        downloadRelatedObject(new File(getDownloadLocation()), pid, "rel:isMemberOf");
        downloadRelatedObject(new File(getDownloadLocation()), pid, "rel:isSubsetOf");
        downloadRelatedObject(new File(getDownloadLocation()), pid, "rel:isMemberOfCollection");
    } catch (MalformedURLException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    }

}

From source file:com.cws.esolutions.security.main.PasswordUtility.java

public static void main(final String[] args) {
    final String methodName = PasswordUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {// w  ww .ja v  a  2  s. co  m
        DEBUGGER.debug("Value: {}", methodName);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(PasswordUtility.CNAME, options, true);

        System.exit(1);
    }

    BufferedReader bReader = null;
    BufferedWriter bWriter = null;

    try {
        // load service config first !!
        SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG,
                false);

        if (DEBUG) {
            DEBUGGER.debug("Options options: {}", options);

            for (String arg : args) {
                DEBUGGER.debug("Value: {}", arg);
            }
        }

        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
            DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions());
            DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList());
        }

        final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData();
        final SecurityConfig secConfig = secConfigData.getSecurityConfig();
        final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo();
        final SystemConfig systemConfig = secConfigData.getSystemConfig();

        if (DEBUG) {
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
            DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig);
            DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig);
            DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig);
        }

        if (commandLine.hasOption("encrypt")) {
            if ((StringUtils.isBlank(repoConfig.getPasswordFile()))
                    || (StringUtils.isBlank(repoConfig.getSaltFile()))) {
                System.err.println("The password/salt files are not configured. Entries will not be stored!");
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            final String entryName = commandLine.getOptionValue("entry");
            final String username = commandLine.getOptionValue("username");
            final String password = commandLine.getOptionValue("password");
            final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
                DEBUGGER.debug("String password: {}", password);
                DEBUGGER.debug("String salt: {}", salt);
            }

            final String encodedSalt = PasswordUtils.base64Encode(salt);
            final String encodedUserName = PasswordUtils.base64Encode(username);
            final String encryptedPassword = PasswordUtils.encryptText(password, salt,
                    secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                    secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                    systemConfig.getEncoding());
            final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword);

            if (DEBUG) {
                DEBUGGER.debug("String encodedSalt: {}", encodedSalt);
                DEBUGGER.debug("String encodedUserName: {}", encodedUserName);
                DEBUGGER.debug("String encodedPassword: {}", encodedPassword);
            }

            if (commandLine.hasOption("store")) {
                try {
                    new File(passwordFile.getParent()).mkdirs();
                    new File(saltFile.getParent()).mkdirs();

                    boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile();

                    if (DEBUG) {
                        DEBUGGER.debug("saltFileExists: {}", saltFileExists);
                    }

                    // write the salt out first
                    if (!(saltFileExists)) {
                        throw new IOException("Unable to create salt file");
                    }

                    boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile();

                    if (!(passwordFileExists)) {
                        throw new IOException("Unable to create password file");
                    }

                    if (commandLine.hasOption("replace")) {
                        File[] files = new File[] { saltFile, passwordFile };

                        if (DEBUG) {
                            DEBUGGER.debug("File[] files: {}", (Object) files);
                        }

                        for (File file : files) {
                            if (DEBUG) {
                                DEBUGGER.debug("File: {}", file);
                            }

                            String currentLine = null;
                            File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile");

                            if (DEBUG) {
                                DEBUGGER.debug("File tmpFile: {}", tmpFile);
                            }

                            bReader = new BufferedReader(new FileReader(file));
                            bWriter = new BufferedWriter(new FileWriter(tmpFile));

                            while ((currentLine = bReader.readLine()) != null) {
                                if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) {
                                    bWriter.write(currentLine + System.getProperty("line.separator"));
                                    bWriter.flush();
                                }
                            }

                            bWriter.close();

                            FileUtils.deleteQuietly(file);
                            FileUtils.copyFile(tmpFile, file);
                            FileUtils.deleteQuietly(tmpFile);
                        }
                    }

                    FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt
                            + System.getProperty("line.separator"), true);
                    FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + ","
                            + encodedPassword + System.getProperty("line.separator"), true);
                } catch (IOException iox) {
                    ERROR_RECORDER.error(iox.getMessage(), iox);
                }
            }

            System.out.println("Entry Name " + entryName + " stored.");
        }

        if (commandLine.hasOption("decrypt")) {
            String saltEntryName = null;
            String saltEntryValue = null;
            String decryptedPassword = null;
            String passwordEntryName = null;

            if ((StringUtils.isEmpty(commandLine.getOptionValue("entry"))
                    && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) {
                throw new ParseException("No entry or username was provided to decrypt.");
            }

            if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) {
                throw new ParseException("no entry provided to decrypt");
            }

            String entryName = commandLine.getOptionValue("entry");
            String username = commandLine.getOptionValue("username");

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) {
                throw new IOException(
                        "Unable to read configured password/salt file. Please check configuration and/or permissions.");
            }

            for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) {
                saltEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String saltEntryName: {}", saltEntryName);
                }

                if (StringUtils.equals(saltEntryName, entryName)) {
                    saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    break;
                }
            }

            if (StringUtils.isEmpty(saltEntryValue)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) {
                passwordEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName);
                }

                if (StringUtils.equals(passwordEntryName, saltEntryName)) {
                    String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue,
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            systemConfig.getEncoding());

                    break;
                }
            }

            if (StringUtils.isEmpty(decryptedPassword)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            System.out.println(decryptedPassword);
        } else if (commandLine.hasOption("encode")) {
            System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0)));
        } else if (commandLine.hasOption("decode")) {
            System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0)));
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        System.err.println("An error occurred during processing: " + iox.getMessage());
        System.exit(1);
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
        System.exit(1);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
        System.exit(1);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
        System.exit(1);
    } finally {
        try {
            if (bReader != null) {
                bReader.close();
            }

            if (bWriter != null) {
                bReader.close();
            }
        } catch (IOException iox) {
        }
    }

    System.exit(0);
}

From source file:koper.demo.dataevent.listener.OrderListener.java

public void onInsertOrder(Order order, DataEvent dataEvent) {
    // ??/*from   www  .j  a va  2  s  . c om*/
    File output = new File("output.txt");
    try {
        FileUtils.writeStringToFile(output,
                "\norderNo : " + order.getOrderNo() + ", create time : " + order.getCreatedTime(), true);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // ?
    MsgBean<String, String> msgBean = dataEvent.getMsgBean();
    long receive = msgBean.getReceiveUseTime();
    long consume = msgBean.getConsumeUseTime();
    sumReceiveTime.getAndAdd(receive);
    sumConsumeTime.getAndAdd(consume - receive);

    long cnt = msgCount.incrementAndGet();
    if (cnt % WRITE_PERIOD == 0)
        writeFile(file);
}

From source file:com.uwsoft.editor.proxy.SceneDataManager.java

public SceneVO createNewScene(String name) {
    SceneVO vo = new SceneVO();
    vo.sceneName = name;/*from   w  w  w  .ja  va  2  s.c om*/
    ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
    try {
        String projPath = projectManager.getCurrentProjectPath();
        FileUtils.writeStringToFile(new File(projPath + "/project.dt"),
                projectManager.currentProjectInfoVO.constructJsonString(), "utf-8");
        FileUtils.writeStringToFile(new File(projPath + "/scenes/" + vo.sceneName + ".dt"),
                vo.constructJsonString(), "utf-8");
        projectManager.currentProjectInfoVO.scenes.add(vo);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return vo;
}

From source file:com.thoughtworks.go.config.materials.mercurial.HgMaterialDockerTest.java

@Test
public void shouldRefreshWorkingDirectoryIfUsernameInUrlChanges() throws Exception {
    HgMaterial material = new HgMaterial("http://user1:password@localhost:9999", null);
    final List<Modification> modifications = material.latestModification(workingFolder,
            new TestSubprocessExecutionContext());
    final File unversionedFile = new File(workingFolder, "unversioned.txt");
    FileUtils.writeStringToFile(unversionedFile, "something", UTF_8);
    assertTrue(unversionedFile.exists());

    material = new HgMaterial("http://user2:password@localhost:9999", null);
    material.modificationsSince(workingFolder, new StringRevision(modifications.get(0).getRevision()),
            new TestSubprocessExecutionContext());
    assertFalse(unversionedFile.exists());
}

From source file:com.hotels.plunger.TapDataReaderTest.java

@Test
public void readLocal() throws IOException {
    File tsvFile = temporaryFolder.newFile("data.tsv");
    FileUtils.writeStringToFile(tsvFile, "1\thello\tX\n2\taloha\tY\n", Charset.forName("UTF-8"));

    cascading.tap.local.FileTap fileTap = new cascading.tap.local.FileTap(
            new cascading.scheme.local.TextDelimited(fields), tsvFile.getAbsolutePath());

    Data actual = new TapDataReader(fileTap).read();

    assertThat(actual, is(expected));//from  www  .j  a  v  a2s .  c o  m
}

From source file:github.srlee309.lessWrongBookCreator.bookGeneration.HtmlOutputFileCreator.java

protected void writeStringToFile(String filePath, String fileContent) {
    try {//from ww w .j av a2  s  .  c  o m
        FileUtils.writeStringToFile(new File(filePath), fileContent, "UTF-8");
    } catch (IOException ex) {
        logger.error("", ex);
    }
}

From source file:jp.primecloud.auto.common.component.FreeMarkerGeneratorTest.java

@Test
public void test1() throws Exception {
    Map<String, Object> rootMap = new HashMap<String, Object>();
    rootMap.put("aaa", "AAA");
    rootMap.put("bbb", "BBB");
    rootMap.put("enable", Boolean.TRUE);
    rootMap.put("num", 12345.6789);

    Model model = new Model();
    model.setEnabled(true);/*from  w  w  w  .  j  av  a 2s  . c  o  m*/
    rootMap.put("model", model);

    String data = generator.generate("test1.ftl", rootMap);

    File file = new File("target/tmp/test1.txt");
    FileUtils.writeStringToFile(file, data, "UTF-8");
}