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.eclipse.andmore.internal.editors.layout.gle2.RenderPreviewList.java

private void save(File file) throws IOException {
    //Document document = DomUtilities.createEmptyPlainDocument();
    Document document = DomUtilities.createEmptyDocument();
    if (document != null) {
        for (ConfigurationDescription description : mList) {
            description.toXml(document);
        }//  w ww  .  j a  v a 2  s. c  o m
        String xml = EclipseXmlPrettyPrinter.prettyPrint(document, true);
        Files.write(xml, file, Charsets.UTF_8);
    }
}

From source file:com.facebook.buck.rules.GenRDotJavaStep.java

/**
 * Creates a command that will run {@code aapt} for the purpose of generating {@code R.java}.
 * @param resDirectories Directories of resource files. Will be specified with {@code -S} to
 *     {@code aapt}//from   ww  w .j  a  v  a 2 s.c om
 * @param genDirectoryPath Directory where {@code R.java} and potentially {@code R.txt} will be
 *     generated
 * @param libraryPackage Normally, {@code aapt} expects an {@code AndroidManifest.xml} so that it
 *     can extract the {@code package} attribute to determine the Java package of the generated
 *     {@code R.java} file. For this class, the client must specify the {@code package} directly
 *     rather than the path to {@code AndroidManifest.xml}. This precludes the need to keep a
 *     number of dummy {@code AndroidManifest.xml} files in the codebase.
 * @param isTempRDotJava If true, this command is being run solely for the purpose of generating
 *     {@code R.txt} (though {@code R.java} will still be generated as a side-effect). The values
 *     of the resource values in the generated {@code R.java} will be meaningless.
 *     <p>
 *     If false, this command will produce an {@code R.java} file with resource values designed to
 *     match those in an .apk that includes the resources. In this case, no {@code R.txt} will be
 *     generated.
 * @param extraLibraryPackages
 */
public GenRDotJavaStep(Set<String> resDirectories, String genDirectoryPath, String libraryPackage,
        boolean isTempRDotJava, Set<String> extraLibraryPackages) {
    this.resDirectories = ImmutableSet.copyOf(resDirectories);

    File tmpDir = Files.createTempDir();
    tmpDir.deleteOnExit();

    // TODO(mbolin): This command is run fairly frequently, often for the same value of
    // libraryPackage, so consider generating these under buck-android, parameterized by
    // libraryPackage, so that AndroidManifest.xml is only written once per package. However, one
    // must be careful when doing this when --num-threads is greater than 1.
    // Another option is to require clients to provide an AndroidManifest.xml for each
    // android_resource() rule in the codebase. This may turn out to be helpful when running the
    // Android linter because then the user will specify the min/max values of Android for a
    // library.
    File androidManifest = new File(tmpDir, "AndroidManifest.xml");
    try {
        String xml = String.format(
                "<manifest xmlns:android='http://schemas.android.com/apk/res/android' package='%s' />",
                libraryPackage);
        Files.write(xml, androidManifest, Charsets.UTF_8);
    } catch (IOException e) {
        Throwables.propagate(e);
    }
    this.androidManifestPath = androidManifest.getAbsolutePath();

    this.genDirectoryPath = Preconditions.checkNotNull(genDirectoryPath);
    this.isTempRDotJava = isTempRDotJava;
    this.extraLibraryPackages = ImmutableSet.copyOf(extraLibraryPackages);
}

From source file:com.google.devtools.j2cpp.gen.SourceFileGenerator.java

protected void save(String path) {
    try {//from   ww w .j  a v  a  2 s. c  o  m
        File outputFile = new File(outputDirectory, path);
        File dir = outputFile.getParentFile();
        if (dir != null && !dir.exists()) {
            if (!dir.mkdirs()) {
                J2ObjC.warning("cannot create output directory: " + outputDirectory);
            }
        }
        String source = builder.toString();

        // Make sure file ends with a new-line.
        if (!source.endsWith("\n")) {
            source += '\n';
        }

        Files.write(source, outputFile, Charset.defaultCharset());
    } catch (IOException e) {
        J2ObjC.error(e.getMessage());
    } finally {
        reset();
    }
}

From source file:com.facebook.buck.cli.QuickstartCommand.java

/**
 * Runs the command "buck quickstart", which copies a template project into a new directory to
 * give the user a functional buck project. It copies from
 * src/com/facebook/buck/cli/quickstart/android to the directory specified. It then asks the user
 * for the location of the Android SDK so Buck cansuccessfully build the quickstart project. It
 * will fail if it cannot find the template directory or if it is unable to write to the
 * destination directory.//from   w w  w.j  ava2s. c o  m
 *
 * @param options an object representing command line options
 * @return status code - zero means no problem
 * @throws IOException if the command fails to read from the template project or write to the
 *     new project
 */
@Override
int runCommandWithOptionsInternal(QuickstartCommandOptions options) throws IOException {
    String projectDir = options.getDestDir().trim();
    if (projectDir.isEmpty()) {
        projectDir = promptForPath("Enter the directory where you would like to create the " + "project: ");
    }

    File dir = new File(projectDir);
    while (!dir.isDirectory() && !dir.mkdirs() && !projectDir.isEmpty()) {
        projectDir = promptForPath("Cannot create project directory. Enter another directory: ");
        dir = new File(projectDir);
    }
    if (projectDir.isEmpty()) {
        getStdErr().println("No project directory specified. Aborting quickstart.");
        return 1;
    }

    String sdkLocation = options.getAndroidSdkDir();
    if (sdkLocation.isEmpty()) {
        sdkLocation = promptForPath("Enter your Android SDK's location: ");
    }

    File sdkLocationFile = new File(sdkLocation);
    if (!sdkLocationFile.isDirectory()) {
        getStdErr().println("WARNING: That Android SDK directory does not exist.");
    }

    sdkLocation = sdkLocationFile.getAbsoluteFile().toString();

    Path origin = PATH_TO_QUICKSTART_DIR;
    Path destination = Paths.get(projectDir);
    MoreFiles.copyRecursively(origin, destination);

    File out = new File(projectDir + "/local.properties");
    Files.write("sdk.dir=" + sdkLocation + "\n", out, StandardCharsets.UTF_8);

    getStdOut().print(Files.toString(origin.resolve("README.md").toFile(), StandardCharsets.UTF_8));
    getStdOut().flush();

    return 0;
}

From source file:org.t3as.snomedct.service.SnomedCoderService.java

/**
 * Accepts a JSON object with text and possible options for the analysis.
 *///from   w  ww  .  ja v  a2 s. com
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
public static Collection<Utterance> mapTextWithOptions(final AnalysisRequest r) throws IOException,
        InterruptedException, JAXBException, SQLException, ParserConfigurationException, SAXException {

    System.out.println(r);

    // metamap options
    final Collection<Option> opts = new ArrayList<>();
    final Set<String> optionNames = new HashSet<>();
    for (final String o : r.getOptions()) {
        final Option opt = MetaMapOptions.strToOpt(o);
        if (opt != null) {
            optionNames.add(opt.name());
            if (!opt.useProcessorDefault())
                opts.add(opt);
        }
    }
    // always make sure we have a restrict_to_sources option
    if (!optionNames.contains(new RestrictToSources().name()))
        opts.add(new RestrictToSources());

    // tmp files for metamap in/out
    final File infile = File.createTempFile("metamap-input-", ".txt");
    final File outfile = File.createTempFile("metamap-output-", ".xml");
    final String s = r.getText() + (r.getText().endsWith("\n") ? "" : "\n");
    final String ascii = MetaMap.decomposeToAscii(URLDecoder.decode(s, "UTF-8"));
    Files.write(ascii, infile, Charsets.UTF_8);
    // we don't want too much data for a free service
    if (infile.length() > MAX_DATA_BYTES) {
        throw new WebApplicationException(Response.status(Responses.NOT_ACCEPTABLE)
                .entity("Too much data, currently limited to " + MAX_DATA_BYTES + " bytes.").type("text/plain")
                .build());
    }

    // process the data with MetaMap
    final MetaMap metaMap = new MetaMap(PUBLIC_MM_DIR, opts);
    if (!metaMap.process(infile, outfile)) {
        throw new WebApplicationException(Response.status(INTERNAL_SERVER_ERROR)
                .entity("Processing failed, aborting.").type("text/plain").build());
    }

    // look up the SNOMED codes from the UMLS CUI code/description combinations returned by MetaMap
    final MMOs root = JaxbLoader.loadXml(outfile);
    try (final SnomedLookup snomedLookup = new SnomedLookup(DB_PATH)) {
        snomedLookup.enrichXml(root);
    }

    //noinspection ResultOfMethodCallIgnored
    infile.delete();
    //noinspection ResultOfMethodCallIgnored
    outfile.delete();

    return destructiveFilter(root);
}

From source file:com.axelor.tools.x2j.Generator.java

private void expand(File outputPath, Collection<Entity> items, boolean doLookup) throws IOException {

    if (items == null || items.isEmpty()) {
        return;/*w w  w  .  j av a  2  s .  c  o m*/
    }

    final List<Entity> all = new ArrayList<>(items);
    final Entity first = all.get(0);

    final String ns = first.getNamespace();
    final String name = first.getName();

    // prepend all lookup entities
    if (doLookup && lookup.get(name) != null) {
        all.addAll(0, lookup.get(name));
    }

    // check that all entities have same namespace
    for (Entity it : all) {
        if (!ns.equals(it.getNamespace())) {
            throw new IllegalArgumentException(
                    String.format("Invalid namespace: %s.%s != %s.%s", ns, name, it.getNamespace(), name));
        }
    }

    final Entity entity = all.remove(0);
    final Repository repository = entity.getRepository();

    final File entityFile = this.file(outputPath, entity.getFile());
    final File repoFile = repository == null ? null : this.file(outputPath, repository.getFile());

    long lastModified = entity.getLastModified();

    for (Entity it : all) {
        if (lastModified < it.getLastModified()) {
            lastModified = it.getLastModified();
        }
    }

    if (lastModified < entityFile.lastModified()) {
        return;
    }

    for (Entity it : all) {
        entity.merge(it);
    }

    entityFile.getParentFile().mkdirs();
    if (repoFile != null) {
        repoFile.getParentFile().mkdirs();
    }

    String[] existing = { entity.getName() + ".java", entity.getName() + ".groovy" };

    for (String fname : existing) {
        File ex = this.file(entityFile.getParentFile(), fname);
        if (ex.exists()) {
            ex.delete();
        }
    }

    log.info("Generating: " + entityFile.getPath());
    String code = Expander.expand(entity, false);
    Files.write(Utils.stringTrailing(code), entityFile, Charsets.UTF_8);

    if (repoFile == null)
        return;

    log.info("Generating: " + repoFile.getPath());
    String repo = Expander.expand(entity, true);
    Files.write(Utils.stringTrailing(repo), repoFile, Charsets.UTF_8);
}

From source file:org.gradle.nativeplatform.test.xctest.tasks.InstallXCTestBundle.java

private void installToDir(final File bundleDir, final File bundleFile) throws IOException {
    getFileOperations().sync(new Action<CopySpec>() {
        @Override/*from   ww  w .ja  v  a2 s  .co  m*/
        public void execute(CopySpec copySpec) {
            copySpec.from(bundleFile, new Action<CopySpec>() {
                @Override
                public void execute(CopySpec copySpec) {
                    copySpec.into("Contents/MacOS");
                }
            });

            copySpec.into(bundleDir);
        }
    });

    File outputFile = new File(bundleDir, "Contents/Info.plist");

    Files.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
            + "<plist version=\"1.0\">\n" + "<dict/>\n" + "</plist>", outputFile, Charset.forName("UTF-8"));

    getProject().exec(new Action<ExecSpec>() {
        @Override
        public void execute(ExecSpec execSpec) {
            execSpec.setWorkingDir(bundleDir);
            execSpec.executable(getSwiftStdlibToolLocator().find());
            execSpec.args("--copy", "--scan-executable", bundleFile.getAbsolutePath(), "--destination",
                    new File(bundleDir, "Contents/Frameworks").getAbsolutePath(), "--platform", "macosx",
                    "--resource-destination", new File(bundleDir, "Contents/Resources").getAbsolutePath(),
                    "--scan-folder", new File(bundleDir, "Contents/Frameworks").getAbsolutePath());
        }
    }).assertNormalExitValue();
}

From source file:org.artifactory.support.core.collectors.analysis.ThreadDumpCollector.java

/**
 * Produces thread dump and saves it to the corresponding file
 *
 * @param id an ordered id of the collected dump
 *
 * @return {@link StringBuilderWrapper}// ww  w. j  a  v a 2s . com
 */
private boolean createDump(File tmpDir, Optional<Short> id) {
    try {
        getLog().debug("Producing thread dump {}", id.isPresent() ? id.get() : 1);
        StringBuilderWrapper td = new StringBuilderWrapper(threadDumper.dumpThreads());
        Files.write(td, getOutputFile(tmpDir, id), Charsets.UTF_8);
    } catch (IOException e) {
        getLog().error("Creating thread dump has failed: " + e.getMessage());
        getLog().debug("Cause: {}", e);
        return false;
    }
    return true;
}

From source file:com.sk89q.worldedit.command.WorldEditCommands.java

@Command(aliases = { "report" }, desc = "Writes a report on WorldEdit", flags = "p", max = 0)
@CommandPermissions({ "worldedit.report" })
public void report(Actor actor, CommandContext args) throws WorldEditException {
    ReportList report = new ReportList("Report");
    report.add(new SystemInfoReport());
    report.add(new ConfigReport());
    String result = report.toString();

    try {//  ww  w . ja v a 2 s  . co  m
        File dest = new File(we.getWorkingDirectoryFile(we.getConfiguration().saveDir), "report.txt");
        Files.write(result, dest, Charset.forName("UTF-8"));
        actor.print("WorldEdit report written to " + dest.getAbsolutePath());
    } catch (IOException e) {
        actor.printError("Failed to write report: " + e.getMessage());
    }

    if (args.hasFlag('p')) {
        actor.checkPermission("worldedit.report.pastebin");
        ActorCallbackPaste.pastebin(we.getSupervisor(), actor, result, "WorldEdit report: %s.report",
                WorldEdit.getInstance().getPlatformManager().getCommandManager().getExceptionConverter());
    }
}

From source file:com.netflix.exhibitor.core.processes.StandardProcessOperations.java

@Override
public void startInstance() throws Exception {
    Details details = new Details(exhibitor);
    String javaEnvironmentScript = exhibitor.getConfigManager().getConfig()
            .getString(StringConfigs.JAVA_ENVIRONMENT);
    String log4jProperties = exhibitor.getConfigManager().getConfig().getString(StringConfigs.LOG4J_PROPERTIES);

    prepConfigFile(details);/*from  w ww  . j  a  v a 2 s  .c o  m*/
    if ((javaEnvironmentScript != null) && (javaEnvironmentScript.trim().length() > 0)) {
        File envFile = new File(details.configDirectory, "java.env");
        Files.write(javaEnvironmentScript, envFile, Charset.defaultCharset());
    }

    if ((log4jProperties != null) && (log4jProperties.trim().length() > 0)) {
        File log4jFile = new File(details.configDirectory, "log4j.properties");
        Files.write(log4jProperties, log4jFile, Charset.defaultCharset());
    }

    ProcessBuilder builder = buildZkServerScript("start");

    exhibitor.getProcessMonitor().monitor(ProcessTypes.ZOOKEEPER, builder.start(), null,
            ProcessMonitor.Mode.LEAVE_RUNNING_ON_INTERRUPT, ProcessMonitor.Streams.BOTH);

    exhibitor.getLog().add(ActivityLog.Type.INFO, "Process started via: " + builder.command().get(0));
}