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.sonatype.maven.polyglot.java.JavaModelReader.java

@SuppressWarnings("unchecked")
private Model compileJavaCode(String src) {

    Model model = null;//from ww w  . ja  va  2  s.  c o m

    File tempDir = Files.createTempDir();
    String randomClassName = "POM" + UUID.randomUUID().toString().replaceAll("-", "");
    String filePath = tempDir.getAbsolutePath();
    if (!filePath.endsWith("/")) {
        filePath = filePath + "/";
    }
    filePath = filePath + randomClassName + ".java";

    try {
        Files.write(replaceClassNameInSrc(src, randomClassName), new File(filePath), Charset.defaultCharset());
        log.debug("Created temp file " + filePath + " to compile POM.java");
    } catch (IOException e) {
        e.printStackTrace();
        log.debug("Error writing file " + filePath, e);
    }

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, "-parameters", "-classpath", getClassPath(), filePath);
    log.debug("Dynamically compiled class " + filePath);

    try {
        URL comiledClassFolderURL = new URL("file:" + tempDir.getAbsolutePath() + "/");

        ClassRealm systemClassLoader = (ClassRealm) getClass().getClassLoader();
        systemClassLoader.addURL(comiledClassFolderURL);

        log.debug("Added URL " + comiledClassFolderURL + " to Maven class loader to load class dynamically");

        Class<ModelFactory> pomClass = (Class<ModelFactory>) Class.forName(randomClassName, false,
                systemClassLoader);

        model = pomClass.newInstance().getModel();

    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
            | MalformedURLException e) {
        log.error("Failed to dynamically load class " + randomClassName, e);
    } finally {
        try {
            FileUtils.deleteDirectory(tempDir);
        } catch (IOException e) {
            log.error("Failed to delete temp folder " + tempDir, e);
        }
    }

    return model;
}

From source file:yarnkit.config.hocon.HoconConfig.java

@Override
public File getConfigFile(@Nonnull Map<String, LocalResource> mapping) throws IOException {
    final String serialized;
    if (mapping.isEmpty()) {
        serialized = conf.root().render(ConfigRenderOptions.concise());
    } else {//from ww w . j a  va2  s  . c om
        Map<String, String> props = YarnUtils.convertResourceMapToProperties(mapping);
        ConfigObject appended = ConfigValueFactory.fromMap(props);
        ConfigObject merged = conf.root().withValue(PATH_APP_RESOURCE_MAPPING, appended);
        serialized = merged.render(ConfigRenderOptions.concise());
    }
    LOG.info("Serialized application.conf: \n" + serialized);

    File file = File.createTempFile("application", ".conf");
    Files.write(serialized, file, Charsets.UTF_8);
    return file;
}

From source file:org.caleydo.data.importer.tcga.regular.TCGARunTask.java

protected void generateJSONReport(JsonArray detailedReports, Date analysisRun, Date dataRun,
        String runSpecificOutputPath) throws IOException {

    String reportJSONOutputPath = Settings.format(analysisRun) + ".json";

    JsonArray dataSetColors = new JsonArray();
    for (EDataSetType dataSetType : EDataSetType.values()) {
        JsonObject o = new JsonObject();
        o.addProperty(dataSetType.getName(), "#" + dataSetType.getColor().getHEX());
        dataSetColors.add(o);/* w w w.  j  a  va 2 s .  co  m*/
    }

    Gson gson = settings.getGson();
    JsonObject report = new JsonObject();
    report.add("analysisRun", gson.toJsonTree(analysisRun));
    report.add("dataRun", gson.toJsonTree(dataRun));
    report.add("details", detailedReports);
    report.addProperty("caleydoVersion", GeneralManager.VERSION.toString());
    report.add("dataSetColors", dataSetColors);

    String r = gson.toJson(report);
    Files.write(r, new File(runSpecificOutputPath, reportJSONOutputPath), Charset.forName("UTF-8"));
}

From source file:org.yes.cart.installer.ApacheTomcat7Configurer.java

private void generateSetEnv() throws IOException {
    boolean isWindows = isWindows();
    File setEnvFile = new File(tomcatHome, "bin" + File.separator + (isWindows ? "setenv.bat" : "setenv.sh"));
    Files.write(
            generateSetEnvContent(ImmutableMap.<String, String>builder().put("CATALINA_OPTS", catalinaOptions).
            /* put("JAVA_HOME", jdkHome).*/build(), isWindows), setEnvFile, Charset.forName("UTF-8"));
}

From source file:org.dllearner.algorithms.qtl.util.filters.PredicateExistenceFilterDBpedia.java

private void analyze() {
    Set<Node> existentialMeaninglessProperties = new TreeSet<>(new NodeComparator());

    StringBuilder sb = new StringBuilder();
    // check data properties
    String query = "SELECT ?p ?range WHERE {?p a owl:DatatypeProperty . ?p rdfs:range ?range .}";

    QueryExecution qe = ks.getQueryExecutionFactory().createQueryExecution(query);
    ResultSet rs = qe.execSelect();
    while (rs.hasNext()) {
        QuerySolution qs = rs.next();//from w w  w .  j  av a 2  s. c  om

        Resource property = qs.getResource("p");
        Resource range = qs.getResource("range");

        //         if(range.equals(XSD.xdouble)) {
        existentialMeaninglessProperties.add(property.asNode());
        //         }
    }
    qe.close();
    for (Node p : existentialMeaninglessProperties) {
        sb.append(p).append("\n");
    }
    existentialMeaninglessProperties.clear();
    sb.append("\n\n");

    // check object properties
    query = "SELECT ?p WHERE {?p a owl:ObjectProperty .}";

    qe = ks.getQueryExecutionFactory().createQueryExecution(query);
    rs = qe.execSelect();
    while (rs.hasNext()) {
        QuerySolution qs = rs.next();

        Resource property = qs.getResource("p");
        existentialMeaninglessProperties.add(property.asNode());

    }
    qe.close();

    for (Node p : existentialMeaninglessProperties) {
        sb.append(p).append("\n");
    }
    try {
        Files.write(sb.toString(), new File("dbpedia_meaningless_properties.txt"), Charsets.UTF_8);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.springframework.data.release.io.Workspace.java

private void writeContentToFile(String name, Project project, String content) throws IOException {

    File file = getFile(name, project);
    Files.write(content, file, UTF_8);
}

From source file:cc.kave.commons.pointsto.stores.ProjectUsageStore.java

private void storeCache() throws IOException {
    Path cacheFile = baseDir.resolve(CACHE_FILENAME);

    try (Stream<String> lines = projectDirToStore.keySet().stream()
            .map(p -> baseDir.relativize(p).toString())) {
        Files.write(cacheFile, (Iterable<String>) lines::iterator, StandardCharsets.UTF_8);
    }/*from   w  w  w.  ja v a2 s .  com*/
    cacheInvalidated = false;
}

From source file:org.apache.s4.fixtures.CommTestUtils.java

public static void writeStringToFile(String s, File f) throws IOException {
    Files.write(s, f, Charset.defaultCharset());
}

From source file:com.facebook.buck.shell.GenerateShellScriptStep.java

@Override
public int execute(ExecutionContext context) {
    List<String> lines = Lists.newArrayList();
    // Run with -e so the script will fail if any of the steps fail.
    lines.add("#!/bin/bash");
    lines.add("set -e");

    // This script can be cached and used on machines other than the one where it was created. That
    // means it can't contain any absolute filepaths. Expose the absolute filepath of the root of
    // the project as $BUCK_REAL_ROOT, determined at runtime.
    int levelsBelowRoot = outputFile.getNameCount() - 1;
    String pathBackToRoot = Joiner.on("/").join(Collections.nCopies(levelsBelowRoot, ".."));
    lines.add(String.format("BUCK_REAL_ROOT=\"$(cd `dirname $0`/%s; pwd)\"", pathBackToRoot));

    // Create a tmp directory that will be deleted when this script exits. This ensures that
    // scriptToRun doesn't leak any state onto the filesystem from run to run.
    lines.add("BUCK_TMP_ROOT=`mktemp -d -t sh_binary.XXXXXXXXXX`");
    lines.add("trap \"chmod -R 755 $BUCK_TMP_ROOT " + "&& rm -rf $BUCK_TMP_ROOT\" EXIT HUP INT TERM");

    // Navigate to the tmp directory.
    lines.add("cd $BUCK_TMP_ROOT");

    // Symlink the resources to the $BUCK_TMP_ROOT directory.
    String scriptToRunEscapedRelativePath = Escaper.escapeAsBashString(scriptToRun);
    lines.add("SCRIPT_TO_RUN=" + scriptToRunEscapedRelativePath);
    createSymlinkCommands(resources, lines);

    // Make everything in $BUCK_TMP_ROOT read-only.
    lines.add("find $BUCK_TMP_ROOT -type d -exec chmod 555 {} \\;");
    lines.add("find $BUCK_TMP_ROOT -type f -exec chmod 444 {} \\;");

    // Forward the args to this generated script to scriptToRun and execute it. Expose the temporary
    // directory to the scriptToRun as $BUCK_PROJECT_ROOT. Run all this inside the temporary
    // directory, so we don't leak absolute filepaths from the repo.
    lines.add("BUCK_PROJECT_ROOT=$BUCK_TMP_ROOT \"$BUCK_TMP_ROOT/$SCRIPT_TO_RUN\" \"$@\"");

    // Write the contents to the file.
    File output = context.getProjectFilesystem().getFileForRelativePath(outputFile.toString());
    try {//  w  w  w.ja va 2  s  . co m
        Files.write(Joiner.on('\n').join(lines) + '\n', output, Charsets.UTF_8);
    } catch (IOException e) {
        e.printStackTrace(context.getStdErr());
        return 1;
    }

    // Make sure the file is executable.
    if (output.setExecutable(/* executable */ true, /* ownerOnly */ false)) {
        return 0;
    } else {
        context.getConsole().printErrorText("Failed to set file as executable: " + output);
        return 1;
    }
}

From source file:com.github.rinde.jaamas17.VanLonHolvoetResultWriter.java

void writeBidComputationTimeMeasurements(SimulationResult result) {
    if (!(result.getResultObject() instanceof SimResult)) {
        return;/*from  w  w  w. ja va2  s  .  c  om*/
    }
    final SimResult info = (SimResult) result.getResultObject();
    final TimeMeasurements measurements = info.getTimeMeasurements().get();

    if (measurements.getAuctionEvents().isEmpty() || measurements.getBidTimeMeasurements().isEmpty()
            || measurements.getRpTimeMeasurements().isEmpty()) {
        return;
    }
    final SimArgs simArgs = result.getSimArgs();
    final Scenario scenario = simArgs.getScenario();

    final String id = Joiner.on("-").join(simArgs.getMasConfig().getName(), scenario.getProblemClass().getId(),
            scenario.getProblemInstanceId(), simArgs.getRandomSeed(), simArgs.getRepetition());

    final File statsDir = new File(experimentDirectory, "computation-time-stats");
    statsDir.mkdirs();

    if (!measurements.getAuctionEvents().isEmpty()) {
        final File auctionsFile = new File(statsDir, id + "-auctions.csv");
        final StringBuilder auctionContents = new StringBuilder();
        auctionContents.append("auction_start,auction_end,num_bids").append(System.lineSeparator());
        for (final AuctionEvent e : measurements.getAuctionEvents()) {
            Joiner.on(",").appendTo(auctionContents, e.getAuctionStartTime(), e.getTime(), e.getNumBids());
            auctionContents.append(System.lineSeparator());
        }
        try {
            Files.write(auctionContents, auctionsFile, Charsets.UTF_8);
        } catch (final IOException e) {
            throw new IllegalStateException(e);
        }
    }

    if (!measurements.getBidTimeMeasurements().isEmpty()) {
        final File compFile = new File(statsDir, id + "-bid-computations.csv");
        final ImmutableListMultimap<Bidder<?>, SolverTimeMeasurement> bidMeasurements = measurements
                .getBidTimeMeasurements();
        final StringBuilder compContents = new StringBuilder();
        compContents.append("bidder_id,comp_start_sim_time,route_length,duration_ns")
                .append(System.lineSeparator());
        int bidderId = 0;
        for (final Bidder<?> bidder : bidMeasurements.keySet()) {
            final List<SolverTimeMeasurement> ms = bidMeasurements.get(bidder);
            for (final SolverTimeMeasurement m : ms) {
                final int routeLength = m.input().getVehicles().get(0).getRoute().get().size();

                Joiner.on(",").appendTo(compContents, bidderId, m.input().getTime(), routeLength,
                        m.durationNs());
                compContents.append(System.lineSeparator());
            }
            bidderId++;
        }
        try {
            Files.write(compContents, compFile, Charsets.UTF_8);
        } catch (final IOException e1) {
            throw new IllegalStateException(e1);
        }
    }

    if (!measurements.getRpTimeMeasurements().isEmpty()) {
        final File rpCompFile = new File(statsDir, id + "-rp-computations.csv");
        final ImmutableListMultimap<RoutePlanner, SolverTimeMeasurement> solMeasurements = measurements
                .getRpTimeMeasurements();
        final StringBuilder compContents = new StringBuilder();
        compContents.append("route_planner_id,comp_start_sim_time,route_length,duration_ns")
                .append(System.lineSeparator());
        int rpId = 0;
        for (final RoutePlanner rp : solMeasurements.keySet()) {
            final List<SolverTimeMeasurement> ms = solMeasurements.get(rp);
            for (final SolverTimeMeasurement m : ms) {
                final int routeLength = m.input().getVehicles().get(0).getRoute().get().size();

                Joiner.on(",").appendTo(compContents, rpId, m.input().getTime(), routeLength, m.durationNs());
                compContents.append(System.lineSeparator());
            }
            rpId++;
        }
        try {
            Files.write(compContents, rpCompFile, Charsets.UTF_8);
        } catch (final IOException e1) {
            throw new IllegalStateException(e1);
        }
    }

    // clear measurements to avoid filling memory
    info.getTimeMeasurements().clear();
}