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:ec.nbdemetra.common.TxtTsSave.java

@OnAnyThread
private static void store(TsCollection[] data, File file, OptionsBean options, ProgressHandle ph)
        throws IOException {
    ph.start();/*w w w . j a va  2 s  .c o  m*/
    ph.progress("Loading time series");
    TsCollection content = TsFactory.instance.createTsCollection();
    for (TsCollection col : data) {
        col.load(TsInformationType.All);
        content.quietAppend(col);
    }

    ph.progress("Creating content");
    TxtTssTransferHandler handler = new TxtTssTransferHandler();
    Config config = handler.getConfig().toBuilder().put("beginPeriod", options.beginPeriod)
            .put("showDates", options.showDates).put("showTitle", options.showTitle)
            .put("vertical", options.vertical).build();
    handler.setConfig(config);
    String stringContent = handler.tsCollectionToString(content);

    ph.progress("Writing file");
    Files.write(stringContent, file, StandardCharsets.UTF_8);
}

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

static void generate(Orchestrator orchestrator, String language, String repositoryKey,
        ImmutableMap<String, ImmutableMap<String, String>> rulesParameters, Set<String> excluded,
        Set<String> subsetOfEnabledRules, Set<String> activatedRuleKeys) {
    try {//from  ww  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)
                    || (!subsetOfEnabledRules.isEmpty() && !subsetOfEnabledRules.contains(key))) {
                continue;
            }
            activatedRuleKeys.add(key);
            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, StandardCharsets.UTF_8);
        orchestrator.getServer().restoreProfile(FileLocation.of(file));
        file.delete();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.shmsoft.dmass.main.WindowsReduce.java

@Override
protected void cleanup(Reducer.Context context) throws IOException, InterruptedException {

    if (!Project.getProject().isMetadataCollectStandard()) {
        // write summary headers with all metadata
        Files.append("\n" + columnMetadata.delimiterSeparatedHeaders(), new File(metadataOutputFileName),
                Charset.defaultCharset());
    }//from   ww  w  . ja va 2  s . c o m

    zipFileWriter.closeZip();
    Stats.getInstance().setJobFinished();
    String outputSuccess = Project.getProject().getResultsDir() + "/_SUCCESS";
    Files.write("", new File(outputSuccess), Charset.defaultCharset());
}

From source file:org.sonar.plugins.pmd.PmdConfiguration.java

private File writeToWorkingDirectory(String content, String fileName) throws IOException {
    File file = new File(fileSystem.workDir(), fileName);
    Files.write(content, file, Charsets.UTF_8);
    return file;// w ww  .  j  a  va  2s .  co  m
}

From source file:com.cloudera.oryx.kmeans.computation.local.KMeansLocalGenerationRunner.java

@Override
protected void runSteps() throws IOException, InterruptedException, JobException {
    String instanceDir = getInstanceDir();
    int generationID = getGenerationID();
    String generationPrefix = Namespaces.getInstanceGenerationPrefix(instanceDir, generationID);

    File currentInboundDir = Files.createTempDir();
    currentInboundDir.deleteOnExit();/* w w  w .j  a  v a2 s.  c o m*/
    File tempOutDir = Files.createTempDir();
    tempOutDir.deleteOnExit();

    try {
        Store store = Store.get();
        store.downloadDirectory(generationPrefix + "inbound/", currentInboundDir);
        Summary summary = new Summarize(currentInboundDir).call();
        if (summary == null) {
            // No summary created, bail out.
            return;
        }
        List<List<RealVector>> foldVecs = new Standarize(currentInboundDir, summary).call();
        List<List<WeightedRealVector>> weighted = new WeightedPointsByFold(foldVecs).call();
        List<KMeansEvaluationData> evalData = new ClusteringEvaluation(weighted).call();
        ClusteringModelBuilder b = new ClusteringModelBuilder(summary);
        DataDictionary dictionary = b.getDictionary();
        List<Model> models = Lists.newArrayList();
        List<String> stats = Lists.newArrayList();
        for (KMeansEvaluationData data : evalData) {
            stats.add(data.getClusterValidityStatistics().toString());
            ClusteringModel cm = b.build(data.getName(generationPrefix), data.getBest());
            models.add(cm);
        }
        Files.write(Joiner.on("\n").join(stats) + '\n', new File(tempOutDir, "cluster_stats.csv"),
                Charsets.UTF_8);
        KMeansPMML.write(new File(tempOutDir, "model.pmml.gz"), dictionary, models);
        store.uploadDirectory(generationPrefix, tempOutDir, false);
    } catch (ExecutionException ee) {
        throw new JobException(ee.getCause());
    } finally {
        IOUtils.deleteRecursively(tempOutDir);
    }
}

From source file:org.eclipse.wst.jsdt.nodejs.core.api.projects.MEANProject.java

/**
 * Initialize the content of the project.
 *///from w w w  .jav  a  2 s.  c  om
public void initialize() {
    Map<String, CharSequence> path2content = new HashMap<String, CharSequence>();
    path2content.putAll(this.getAppContents());
    path2content.putAll(this.getServerContents());

    Set<Entry<String, CharSequence>> entries = path2content.entrySet();
    for (Entry<String, CharSequence> entry : entries) {
        try {
            File outputFile = new File(this.directory, entry.getKey());
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }
            Files.write(entry.getValue(), outputFile, Charset.forName(UTF8));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.android.build.gradle.integration.common.fixture.app.LargeTestProject.java

private static void createSettingsGradle(@NonNull GradleModule project, @NonNull File location)
        throws IOException {
    StringBuilder builder = new StringBuilder();
    buildSettingsGradle(project, builder);

    Files.write(builder.toString(), new File(location, "settings.gradle"), Charset.defaultCharset());
}

From source file:fr.xebia.workshop.bigdata.DocumentationGenerator.java

public void generateDocs(WorkshopInfrastructure workshopInfrastructure, String baseWikiFolder)
        throws IOException {
    File wikiBaseFolder = new File(baseWikiFolder);
    if (wikiBaseFolder.exists()) {
        logger.debug("Delete wiki folder {}", wikiBaseFolder);
        wikiBaseFolder.delete();//  w  w w. j  ava2  s.c om
    }
    wikiBaseFolder.mkdirs();

    Map<String, String> wikiPageNamesByTeamIdentifier = Maps.newHashMap();

    for (String teamIdentifier : workshopInfrastructure.getTeamIdentifiers()) {

        Map<String, Object> rootMap = Maps.newHashMap();
        rootMap.put("infrastructure", workshopInfrastructure);
        rootMap.put("teamIdentifier", teamIdentifier);
        String templatePath = "/fr/xebia/workshop/bigdata/bigdatalab.md.ftl";
        rootMap.put("generator", "This page has been generaterd by '{{{" + getClass()
                + "}}}' with template '{{{" + templatePath + "}}}' on the " + new DateTime());
        String page = FreemarkerUtils.generate(rootMap, templatePath);
        String wikiPageName = "Lab_team_" + teamIdentifier;
        wikiPageNamesByTeamIdentifier.put(teamIdentifier, wikiPageName);
        File wikiPageFile = new File(wikiBaseFolder, wikiPageName + ".md");
        Files.write(page, wikiPageFile, Charsets.UTF_8);
        logger.debug("Generated file {}", wikiPageFile.getAbsoluteFile());
    }

    StringWriter indexPageStringWriter = new StringWriter();
    PrintWriter indexPageWriter = new PrintWriter(indexPageStringWriter);

    indexPageWriter.println("# Labs Per Team");

    for (String teamIdentifier : new TreeSet<String>(workshopInfrastructure.getTeamIdentifiers())) {
        indexPageWriter.println("* [Lab for team " + teamIdentifier + "]"
                + "(https://github.com/xebia-france/flume-hadoop-workshop/wiki/"
                + wikiPageNamesByTeamIdentifier.get(teamIdentifier) + ")");
    }

    String indexPageName = "Home";
    Files.write(indexPageStringWriter.toString(), new File(baseWikiFolder, indexPageName + ".md"),
            Charsets.UTF_8);

    System.out.println("GENERATED WIKI PAGES TO BE COMMITTED IN XEBIA-FRANCE GITHUB");
    System.out.println("=================================================================");
    System.out.println();
    System.out.println("Base folder: " + baseWikiFolder);
    System.out.println("All the files in " + baseWikiFolder
            + " must be committed in https://github.com/xebia-france/flume-hadoop-workshop/wiki/");
    System.out.println("Index page: " + indexPageName);
    System.out.println("Per team pages: \n\t"
            + Joiner.on("\n\t").join(new TreeSet<String>(wikiPageNamesByTeamIdentifier.values())));
}

From source file:com.facebook.buck.parcelable.GenParcelable.java

@Override
public List<Step> getBuildSteps(final BuildContext buildContext, BuildableContext buildableContext) {
    Step step = new Step() {

        @Override/*from ww  w.  j a va2  s.  c  o m*/
        public int execute(ExecutionContext executionContext) {
            for (SourcePath sourcePath : srcs) {
                Path src = sourcePath.resolve();
                File file = executionContext.getProjectFilesystem().getFileForRelativePath(src);
                try {
                    // Generate the Java code for the Parcelable class.
                    ParcelableClass parcelableClass = Parser.parse(file);
                    String generatedJava = new Generator(parcelableClass).generate();

                    // Write the generated Java code to a file.
                    File outputPath = getOutputPathForParcelableClass(parcelableClass).toFile();
                    Files.createParentDirs(outputPath);
                    Files.write(generatedJava, outputPath, Charsets.UTF_8);
                } catch (IOException e) {
                    executionContext.logError(e, "Error creating parcelable from file: %s", src);
                    return 1;
                }
            }
            return 0;
        }

        @Override
        public String getShortName() {
            return "gen_parcelable";
        }

        @Override
        public String getDescription(ExecutionContext context) {
            return "gen_parcelable";
        }
    };

    return ImmutableList.of(step);
}

From source file:org.itcollege.valge.licenseaudit.LicenseAuditMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {/*  w w  w .  j ava 2s.  c o  m*/
        List<Dependency> allDeps = this.loadAllDependencies(project, localRepository, remoteRepositories,
                mavenProjectBuilder);
        List<Scope> scopes = this.getScopesInfo(allDeps);
        List<Dependency> bundledDeps = this.filterScopes(allDeps);

        ConfigData config = loadConfiguration();
        List<License> licenses = this.groupByLicenses(bundledDeps, config);

        for (License lic : licenses) {
            if (config.approved.contains(lic.name)) {
                lic.status = "approved";
            } else if (config.rejected.contains(lic.name)) {
                lic.status = "rejected";
            }
        }

        String content = getHtmlContent(
                new ReportData(new Project(this.project, scopes), licenses, bundledScopes), config);

        Files.write(content, new File(getOutputDir(), "report.html"), Charset.defaultCharset());
    } catch (Exception e) {
        throw new MojoExecutionException("License audit failed", e);
    }
}