Example usage for com.google.common.io Files write

List of usage examples for com.google.common.io Files write

Introduction

In this page you can find the example usage for com.google.common.io Files write.

Prototype

public static void write(CharSequence from, File to, Charset charset) throws IOException 

Source Link

Usage

From source file:org.jvnet.hudson.plugins.periodicbackup.Util.java

/**
 *
 * Creates the backupObject File from given BackupObject, fileNameBase and destination path
 *
 * @param backupObject BackupObject given to be serialized
 * @param destinationDir String with path to the directory where the file will be created
 * @param fileNameBase first part of the filename
 * @return serialized BackupObject File/* ww w.ja v a2 s .  co  m*/
 * @throws IOException If an IO problem occurs
 */
public static File createBackupObjectFile(BackupObject backupObject, String destinationDir, String fileNameBase)
        throws IOException {
    File backupObjectFile = new File(destinationDir, createFileName(fileNameBase, BackupObject.EXTENSION));
    String xml = backupObject.getAsString();
    System.out.println("[INFO] Building BackupObject file: " + backupObjectFile.getAbsolutePath());
    Files.write(xml, backupObjectFile, Charsets.UTF_8);
    return backupObjectFile;
}

From source file:com.github.enr.markdownj.extras.FileUtils.java

/**
 * Writes a string to the specified file using the specified encoding.
 * /*w  ww.ja v  a2 s . co m*/
 * If the file path doesn't exist, it's created.
 * If the file exists, it is overwritten.
 * 
 * @param filePath the path to the file.
 * @param text the string to write.
 * @throws IOException
 */
public static void writeFile(String filePath, String text, String encoding) throws IOException {
    File file = new File(filePath);
    File parent = file.getParentFile();
    if (!parent.exists()) {
        parent.mkdirs();
    }
    Charset charset = charsetForNameOrDefault(encoding);
    Files.write(text, file, charset);
}

From source file:org.polimi.zarathustra.DifferenceHelper.java

/**
 * Saves a text representation of the differences in a file.
 *///from w ww  . jav a 2  s  . c om
public static void dumpDifferences(List<Difference> differences, String filePath) throws IOException {
    StringBuilder sb = new StringBuilder();
    RulesJsonSerializer serializer = new RulesJsonSerializer(filePath + ".json");

    for (Difference difference : differences) {
        sb.append("--- Difference " + difference.getId() + " at "
                + difference.getTestNodeDetail().getXpathLocation() + " ---\n" + difference.toString())
                .append("\n\n");
    }
    File dumpFile = new File(filePath);
    Files.write(sb.toString(), dumpFile, Charsets.UTF_8);
    serializer.printDifferencesToFile(differences);
}

From source file:io.macgyver.core.scheduler.MacGyverTask.java

@Override
public void execute(TaskExecutionContext context) throws RuntimeException {

    try {/*from  w  ww  .ja  v  a2 s  .c  om*/
        if (logger.isDebugEnabled()) {
            logger.debug("execute {} context={}", this, context);
        }

        if (config.has("script")) {
            ScriptExecutor se = new ScriptExecutor();

            Map<String, Object> args = createArgsFromConfig();

            se.run(config.path("script").asText(), args, true);
        } else if (config.has("inlineScript")) {

            String language = config.path("inlineScriptLanguage").asText("groovy");

            String n = UUID.randomUUID().toString() + "." + language;

            File tempScriptsDir = new File(Bootstrap.getInstance().getScriptsDir().getAbsolutePath(), "temp");
            tempScriptsDir.mkdirs();

            File scriptFile = new File(tempScriptsDir, n);

            try {
                String scriptBody = config.path("inlineScript").asText();
                if (logger.isInfoEnabled()) {
                    logger.info("executing inline script: {}", scriptBody);
                }
                Files.write(scriptBody, scriptFile, Charsets.UTF_8);

                ScriptExecutor se = new ScriptExecutor();

                Map<String, Object> args = createArgsFromConfig();

                se.run("temp/" + n, args, true);
            } finally {
                if (scriptFile.exists()) {
                    try {
                        scriptFile.delete();
                    } catch (Exception e) {
                        logger.warn("could not delete file: {}", scriptFile);
                    }
                }
            }

        }
    } catch (IOException e) {
        throw new MacGyverException(e);
    }
}

From source file:se.kth.karamel.backend.ClusterDefinitionService.java

public static void saveYaml(String yaml) throws KaramelException {
    try {//from w ww.j  av a2s .  c om
        YamlCluster cluster = yamlToYamlObject(yaml);
        String name = cluster.getName().toLowerCase();
        File folder = new File(Settings.CLUSTER_ROOT_PATH(name));
        if (!folder.exists()) {
            folder.mkdirs();
        }
        File file = new File(Settings.CLUSTER_YAML_PATH(name));
        Files.write(yaml, file, Charset.forName("UTF-8"));
    } catch (IOException ex) {
        throw new KaramelException("Could not convert yaml to java ", ex);
    }
}

From source file:org.owasp.webgoat.plugin.BlindSendFileAssignment.java

@PostConstruct
@SneakyThrows/*from  www .j  a v a  2s .c  o  m*/
public void createSecretFileWithRandomContents() {
    File targetDirectory = new File(webGoatHomeDirectory, "/XXE");
    if (!targetDirectory.exists()) {
        targetDirectory.mkdir();
    }
    Files.write(CONTENTS, new File(targetDirectory, "secret.txt"), Charsets.UTF_8);
}

From source file:org.apache.brooklyn.core.mgmt.persist.FileBasedStoreObjectAccessor.java

@Override
public void put(String val) {
    try {/*from   www .j  a  v  a  2  s  .  c o m*/
        if (val == null)
            val = "";
        FileUtil.setFilePermissionsTo600(tmpFile);
        Files.write(val, tmpFile, Charsets.UTF_8);
        FileBasedObjectStore.moveFile(tmpFile, file);
    } catch (IOException e) {
        throw Exceptions
                .propagate("Problem writing data to file " + file + " (via temporary file " + tmpFile + ")", e);
    } catch (InterruptedException e) {
        throw Exceptions.propagate(e);
    }
}

From source file:com.github.rinde.rinsim.scenario.measure.MetricsIO.java

/**
 * Writes the provided list of times to a file. The output format is as
 * follows://  w w  w.  j a  v  a2s.  c  o  m
 *
 * <pre>
 * {@code length}
 * {@code time 1}
 * {@code time 2}
 * ..
 * {@code time n}
 * </pre>
 *
 * @param length The length of the scenario: [0,length)
 * @param times The arrival times of events, for each time it holds that 0
 *          &#8804; time &lt; length.
 * @param f The file to write to.
 */
public static void writeTimes(double length, List<? extends Number> times, File f) {
    try {
        Files.createParentDirs(f);
        Files.write(
                new StringBuilder().append(length).append(System.lineSeparator())
                        .append(Joiner.on(System.lineSeparator()).join(times)).append(System.lineSeparator()),
                f, Charsets.UTF_8);
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.sonar.web.it.ProfileGenerator.java

static void generate(Orchestrator orchestrator, String language, String repositoryKey,
        ImmutableMap<String, ImmutableMap<String, String>> rulesParameters, Set<String> excluded) {
    try {//  w w w  .  j a v a2 s  .c o  m
        StringBuilder sb = new StringBuilder().append("<profile>").append("<name>rules</name>")
                .append("<language>").append(language).append("</language>").append("<alerts>")
                .append("<alert>").append("<metric>blocker_violations</metric>")
                .append("<operator>&gt;</operator>").append("<warning></warning>").append("<error>0</error>")
                .append("</alert>").append("<alert>").append("<metric>info_violations</metric>")
                .append("<operator>&gt;</operator>").append("<warning></warning>").append("<error>0</error>")
                .append("</alert>").append("</alerts>").append("<rules>");

        List<String> ruleKeys = Lists.newArrayList();
        String json = new HttpRequestFactory(orchestrator.getServer().getUrl()).get("/api/rules/search",
                ImmutableMap.<String, Object>of("languages", language, "repositories", repositoryKey, "ps",
                        "1000"));
        @SuppressWarnings("unchecked")
        List<Map> jsonRules = (List<Map>) ((Map) JSONValue.parse(json)).get("rules");
        for (Map jsonRule : jsonRules) {
            String key = (String) jsonRule.get("key");
            ruleKeys.add(key.split(":")[1]);
        }

        for (String key : ruleKeys) {
            if (excluded.contains(key)) {
                continue;
            }
            sb.append("<rule>").append("<repositoryKey>").append(repositoryKey).append("</repositoryKey>")
                    .append("<key>").append(key).append("</key>").append("<priority>INFO</priority>");
            if (rulesParameters.containsKey(key)) {
                sb.append("<parameters>");
                for (Map.Entry<String, String> parameter : rulesParameters.get(key).entrySet()) {
                    sb.append("<parameter>").append("<key>").append(parameter.getKey()).append("</key>")
                            .append("<value>").append(parameter.getValue()).append("</value>")
                            .append("</parameter>");
                }
                sb.append("</parameters>");
            }
            sb.append("</rule>");
        }

        sb.append("</rules>").append("</profile>");

        File file = File.createTempFile("profile", ".xml");
        Files.write(sb, file, Charsets.UTF_8);
        orchestrator.getServer().restoreProfile(FileLocation.of(file));
        file.delete();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:br.com.objectos.jabuticava.debs.Caracteristica.java

public void writeTo(File file) {
    try {
        Files.write(text, file, CHARSET);
    } catch (IOException e) {
    }
}