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:abs.backend.erlang.ErlangTestDriver.java

/**
* Executes mainModule//w ww  .j a v a  2 s  . c  om
* 
* We replace the run script by a new version, which will write the Result
* to STDOUT Furthermore to detect faults, we have a Timeout process, which
* will kill the runtime system after 2 seconds
*/
private String run(File workDir, String mainModule) throws Exception {
    String val = null;
    File runFile = new File(workDir, "run");
    Files.write(RUN_SCRIPT, runFile, Charset.forName("UTF-8"));
    runFile.setExecutable(true);
    ProcessBuilder pb = new ProcessBuilder(runFile.getAbsolutePath(), mainModule);
    pb.directory(workDir);
    pb.redirectErrorStream(true);
    Process p = pb.start();

    Thread t = new Thread(new TimeoutThread(p));
    t.start();
    // Search for result
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while (true) {
        String line = br.readLine();
        if (line == null)
            break;
        if (line.startsWith("RES="))
            val = line.split("=")[1];
    }
    int res = p.waitFor();
    t.interrupt();
    if (res != 0)
        return null;
    return val;

}

From source file:com.android.idegen.IntellijProject.java

private void createVcsFile(File ideaDir, Iterable<Module> modules) throws IOException {
    String vcsTemplate = Files.toString(
            new File(DirectorySearch.findTemplateDir(), "idea" + File.separator + VCS_TEMPLATE_FILE_NAME),
            CHARSET);//from  w  ww.j ava2  s .  co m

    Set<String> gitRoots = new HashSet<>();
    for (Module mod : modules) {
        File dir = mod.getDir();
        // Look for git root in the module directory and its parents.
        while (dir != null) {
            File gitRoot = new File(dir, ".git");
            if (gitRoot.exists()) {
                gitRoots.add(dir.getCanonicalPath());
                break;
            } else {
                dir = dir.getParentFile();
            }
        }
    }
    StringBuilder sb = new StringBuilder();
    for (String root : gitRoots) {
        sb.append("    <mapping directory=\"").append(root).append("\" vcs=\"Git\" />\n");
    }

    vcsTemplate = vcsTemplate.replace("@VCS@", sb.toString());
    Files.write(vcsTemplate, new File(ideaDir, "vcs.xml"), CHARSET);
}

From source file:org.fusesource.process.manager.support.ProcessManagerImpl.java

@Override
public Installation installJar(final JarInstallParameters parameters) throws Exception {
    InstallScript installScript = new InstallScript() {
        @Override//from  w  w  w .  j a va  2 s .  co  m
        public void doInstall(ProcessConfig config, int id, File installDir) throws Exception {
            String name = parameters.getGroupId() + ":" + parameters.getArtifactId();
            String version = parameters.getVersion();
            if (!Strings.isNullOrEmpty(version)) {
                name += ":" + version;
            }
            config.setName(name);

            // lets untar the process launcher
            String resourceName = "process-launcher.tar.gz";
            final InputStream in = getClass().getClassLoader().getResourceAsStream(resourceName);
            Preconditions.checkNotNull(in, "Could not find " + resourceName + " on the file system");
            File tmpFile = File.createTempFile("process-launcher", ".tar.gz");
            Files.copy(new InputSupplier<InputStream>() {
                @Override
                public InputStream getInput() throws IOException {
                    return in;
                }
            }, tmpFile);
            FileUtils.extractTar(tmpFile, installDir, untarTimeout, executor);

            // lets generate the etc configs
            File etc = new File(installDir, "etc");
            etc.mkdirs();
            Files.write("", new File(etc, "config.properties"), Charsets.UTF_8);
            Files.write("", new File(etc, "jvm.config"), Charsets.UTF_8);

            JarInstaller installer = new JarInstaller(executor);
            installer.unpackJarProcess(config, id, installDir, parameters);
        }
    };
    return installViaScript(parameters.getControllerJson(), installScript);
}

From source file:com.gitblit.transport.ssh.FileKeyManager.java

/**
 * Adds a unique key to the keystore.  This function determines uniqueness
 * by disregarding the comment/description field during key comparisons.
 *///from  ww w . ja v a2  s  .c o  m
@Override
public boolean addKey(String username, SshKey key) {
    try {
        boolean replaced = false;
        List<String> lines = new ArrayList<String>();
        File keystore = getKeystore(username);
        if (keystore.exists()) {
            for (String entry : Files.readLines(keystore, Charsets.ISO_8859_1)) {
                String line = entry.trim();
                if (line.length() == 0) {
                    // keep blanks
                    lines.add(entry);
                    continue;
                }
                if (line.charAt(0) == '#') {
                    // keep comments
                    lines.add(entry);
                    continue;
                }

                SshKey oldKey = parseKey(line);
                if (key.equals(oldKey)) {
                    // replace key
                    lines.add(key.getPermission() + " " + key.getRawData());
                    replaced = true;
                } else {
                    // retain key
                    lines.add(entry);
                }
            }
        }

        if (!replaced) {
            // new key, append
            lines.add(key.getPermission() + " " + key.getRawData());
        }

        // write keystore
        String content = Joiner.on("\n").join(lines).trim().concat("\n");
        Files.write(content, keystore, Charsets.ISO_8859_1);

        lastModifieds.remove(keystore);
        keyCache.invalidate(username);
        return true;
    } catch (IOException e) {
        throw new RuntimeException("Cannot add ssh key", e);
    }
}

From source file:org.eclipse.andmore.gltrace.editors.StateViewPage.java

private void saveCurrentState() {
    final Shell shell = mTreeViewer.getTree().getShell();
    FileDialog fd = new FileDialog(shell, SWT.SAVE);
    fd.setFilterExtensions(new String[] { "*.txt" });
    if (sLastUsedPath != null) {
        fd.setFilterPath(sLastUsedPath);
    }//from   w  w  w. ja  va2  s . c  o m

    String path = fd.open();
    if (path == null) {
        return;
    }

    File f = new File(path);
    sLastUsedPath = f.getParent();

    // export state to f
    StatePrettyPrinter pp = new StatePrettyPrinter();
    synchronized (sGlStateLock) {
        mState.prettyPrint(pp);
    }

    try {
        Files.write(pp.toString(), f, Charsets.UTF_8);
    } catch (IOException e) {
        ErrorDialog.openError(shell, "Export GL State", "Unexpected error while writing GL state to file.",
                new Status(IStatus.ERROR, GlTracePlugin.PLUGIN_ID, e.toString()));
    }
}

From source file:org.pshdl.model.simulation.codegenerator.CCodeGenerator.java

public IHDLInterpreterFactory<NativeRunner> createInterpreter(final File tempDir) {
    try {//w  w w  .j a v  a 2  s.  co  m
        final File testCFile = new File(tempDir, "test.c");
        String _generateMainCode = this.generateMainCode();
        Files.write(_generateMainCode, testCFile, StandardCharsets.UTF_8);
        final File testRunner = new File(tempDir, "runner.c");
        final InputStream runnerStream = CCodeGenerator.class
                .getResourceAsStream("/org/pshdl/model/simulation/includes/runner.c");
        final FileOutputStream fos = new FileOutputStream(testRunner);
        try {
            ByteStreams.copy(runnerStream, fos);
        } finally {
            runnerStream.close();
            fos.close();
        }
        final File executable = new File(tempDir, "testExec");
        this.writeAuxiliaryContents(tempDir);
        String _absolutePath = tempDir.getAbsolutePath();
        String _absolutePath_1 = testCFile.getAbsolutePath();
        String _absolutePath_2 = testRunner.getAbsolutePath();
        String _absolutePath_3 = executable.getAbsolutePath();
        final ProcessBuilder builder = new ProcessBuilder(CCodeGenerator.COMPILER, "-I", _absolutePath, "-O3",
                _absolutePath_1, _absolutePath_2, "-o", _absolutePath_3);
        ProcessBuilder _directory = builder.directory(tempDir);
        ProcessBuilder _inheritIO = _directory.inheritIO();
        final Process process = _inheritIO.start();
        process.waitFor();
        int _exitValue = process.exitValue();
        boolean _notEquals = (_exitValue != 0);
        if (_notEquals) {
            throw new RuntimeException("Process did not terminate with 0");
        }
        return new IHDLInterpreterFactory<NativeRunner>() {
            public NativeRunner newInstance() {
                try {
                    String _absolutePath = executable.getAbsolutePath();
                    final ProcessBuilder execBuilder = new ProcessBuilder(_absolutePath);
                    ProcessBuilder _directory = execBuilder.directory(tempDir);
                    ProcessBuilder _redirectErrorStream = _directory.redirectErrorStream(true);
                    final Process testExec = _redirectErrorStream.start();
                    InputStream _inputStream = testExec.getInputStream();
                    OutputStream _outputStream = testExec.getOutputStream();
                    String _absolutePath_1 = executable.getAbsolutePath();
                    return new NativeRunner(_inputStream, _outputStream, CCodeGenerator.this.em, testExec, 5,
                            _absolutePath_1);
                } catch (Throwable _e) {
                    throw Exceptions.sneakyThrow(_e);
                }
            }
        };
    } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
    }
}

From source file:org.jclouds.examples.rackspace.cloudservers.CreateServerWithKeyPair.java

/**
 * Create a public key in the cloud and write the private key file to the local working directory.
 *///from w ww .  ja  va 2 s .  c  o m
private KeyPair createKeyPair() throws IOException {
    System.out.format("  Create Key Pair%n");

    KeyPairApi keyPairApi = novaApi.getKeyPairApi(REGION).get();
    KeyPair keyPair = keyPairApi.create(NAME);

    Files.write(keyPair.getPrivateKey(), keyPairFile, UTF_8);

    System.out.format("    Wrote %s%n", keyPairFile.getAbsolutePath());

    return keyPair;
}

From source file:com.sk89q.worldguard.commands.WorldGuardCommands.java

@Command(aliases = { "report" }, desc = "Writes a report on WorldGuard", flags = "p", max = 0)
@CommandPermissions({ "worldguard.report" })
public void report(CommandContext args, final Actor sender) throws CommandException, AuthorizationException {
    ReportList report = new ReportList("Report");
    worldGuard.getPlatform().addPlatformReports(report);
    report.add(new SystemInfoReport());
    report.add(new ConfigReport());
    String result = report.toString();

    try {/*ww w  .j av  a 2 s.com*/
        File dest = new File(worldGuard.getPlatform().getConfigDir().toFile(), "report.txt");
        Files.write(result, dest, Charset.forName("UTF-8"));
        sender.print("WorldGuard report written to " + dest.getAbsolutePath());
    } catch (IOException e) {
        throw new CommandException("Failed to write report: " + e.getMessage());
    }

    if (args.hasFlag('p')) {
        sender.checkPermission("worldguard.report.pastebin");
        ActorCallbackPaste.pastebin(worldGuard.getSupervisor(), sender, result, "WorldGuard report: %s.report",
                worldGuard.getExceptionConverter());
    }
}

From source file:com.android.ide.eclipse.gltrace.editors.StateViewPage.java

private void saveCurrentState() {
    final Shell shell = mTreeViewer.getTree().getShell();
    FileDialog fd = new FileDialog(shell, SWT.SAVE);
    fd.setFilterExtensions(new String[] { "*.txt" });
    if (sLastUsedPath != null) {
        fd.setFilterPath(sLastUsedPath);
    }/*from  w w  w .  ja  v a 2s .  c  o m*/

    String path = fd.open();
    if (path == null) {
        return;
    }

    File f = new File(path);
    sLastUsedPath = f.getParent();

    // export state to f
    StatePrettyPrinter pp = new StatePrettyPrinter();
    synchronized (sGlStateLock) {
        mState.prettyPrint(pp);
    }

    try {
        Files.write(pp.toString(), f, Charsets.UTF_8);
    } catch (IOException e) {
        ErrorDialog.openError(shell, "Export GL State", "Unexpected error while writing GL state to file.",
                new Status(Status.ERROR, GlTracePlugin.PLUGIN_ID, e.toString()));
    }
}