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:com.google.devtools.javatools.transform.SourceTransformer.java

/**
 * Applies source transform {@literal task}s to each file in {@literal paths}, writing output
 * files for each one according to the {@literal outputFileFunction}.
 *
 * @throws IOException if a filesystem error occurs
 * @throws JavaParseException if source failed to parse
 *//*from  w w  w  .j av a 2  s.  c  o m*/
public void transform(Iterable<String> paths) throws IOException {
    for (String path : paths) {
        String fileContent = Files.toString(new File(path), Charsets.UTF_8);
        for (SourceTransformTask task : tasks) {
            CompilationUnitTree tree = parse(fileContent);
            fileContent = task.transform(tree, fileContent);
        }

        File outFile = new File(outputFileFunction.apply(path));
        Files.createParentDirs(outFile);
        Files.write(fileContent, outFile, Charsets.UTF_8);
    }
}

From source file:co.cask.cdap.etl.mock.batch.MockExternalSource.java

/**
 * Used to write the input records for the pipeline run. Should be called after the pipeline has been created.
 *
 * @param fileName file to write the records into
 * @param records records that should be the input for the pipeline
 *///from www.j a  v  a 2  s .  c o  m
public static void writeInput(String fileName, Iterable<StructuredRecord> records) throws Exception {
    String output = Joiner.on("\n").join(Iterables.transform(records, new Function<StructuredRecord, String>() {
        @Override
        public String apply(StructuredRecord input) {
            return GSON.toJson(input);
        }
    }));
    Files.write(output, new File(fileName), Charsets.UTF_8);
}

From source file:org.deephacks.tools4j.config.internal.core.xml.XmlSchemaManager.java

private Map<String, Schema> readValues() {
    String dirValue = PROP.get(XML_CONFIG_SCHEMA_FILE_STORAGE_DIR_PROP);
    if (dirValue == null || "".equals(dirValue)) {
        dirValue = System.getProperty("java.io.tmpdir");
    }/*w  ww .j  a va  2s . c o  m*/
    File file = new File(new File(dirValue), XML_SCHEMA_FILE_NAME);

    try {
        if (!file.exists()) {
            Files.write("<schema-xml></schema-xml>", file, Charset.defaultCharset());
        }
        FileInputStream in = new FileInputStream(file);
        JAXBContext context = JAXBContext.newInstance(XmlSchemas.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        XmlSchemas schemas = (XmlSchemas) unmarshaller.unmarshal(in);
        return schemas.getSchemas();

    } catch (JAXBException e) {
        throw new RuntimeException(e);
    } catch (FileNotFoundException e) {
        throw CFG202_XML_SCHEMA_FILE_MISSING(file);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.opennms.newts.cassandra.NewtsInstance.java

public static CQLDataSet getDataSet(String keyspace, int replicationFactor) {
    try {/*from ww  w.  ja  va 2  s. c  o m*/
        //  Concatenate the schema strings
        String schemasString = "";
        for (Schema schema : schemaLoader) {
            schemasString += CharStreams.toString(new InputStreamReader(schema.getInputStream()));
        }

        // Replace the placeholders
        schemasString = schemasString.replace(KEYSPACE_PLACEHOLDER, keyspace);
        schemasString = schemasString.replace(REPLICATION_FACTOR_PLACEHOLDER,
                Integer.toString(replicationFactor));

        // Split the resulting script back into lines
        String lines[] = schemasString.split("\\r?\\n");

        // Remove duplicate CREATE KEYSPACE statements;
        StringBuffer sb = new StringBuffer();
        boolean foundCreateKeyspace = false;
        boolean skipNextLine = false;
        for (String line : lines) {
            if (line.startsWith("CREATE KEYSPACE")) {
                if (!foundCreateKeyspace) {
                    foundCreateKeyspace = true;
                    sb.append(line);
                    sb.append("\n");
                } else {
                    skipNextLine = true;
                }
            } else if (skipNextLine) {
                skipNextLine = false;
            } else {
                sb.append(line);
                sb.append("\n");
            }
        }

        // Write the results to disk
        File schemaFile = File.createTempFile("schema-", ".cql", new File("target"));
        schemaFile.deleteOnExit();
        Files.write(sb.toString(), schemaFile, Charsets.UTF_8);
        return new FileCQLDataSet(schemaFile.getAbsolutePath(), false, true, keyspace);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.eclipse.xtext.generator.AbstractGeneratorFragment.java

/**
 * @since 2.7//from  w  w w  .j av a 2 s.c  om
 */
protected void writeStringIntoFile(String filename, String content, Charset encoding) {
    try {
        Files.write(content, new File(filename), encoding);
    } catch (IOException e) {
        throw new WrappedException(e);
    }
}

From source file:brooklyn.entity.rebind.persister.MementoFileWriterSync.java

public void write(T val) {
    try {//from  www  .  j  ava 2 s  .  c o m
        lock.writeLock().lockInterruptibly();
    } catch (InterruptedException e) {
        throw Exceptions.propagate(e);
    }
    try {
        Stopwatch stopwatch = Stopwatch.createStarted();

        // Write to the temp file, then atomically move it to the permanent file location
        Files.write(serializer.toString(val), tmpFile, Charsets.UTF_8);
        Files.move(tmpFile, file);
        modCount.incrementAndGet();

        if (LOG.isTraceEnabled())
            LOG.trace("Wrote {}, took {}; modified file {} times",
                    new Object[] { file, Time.makeTimeStringRounded(stopwatch), modCount });
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    } finally {
        lock.writeLock().unlock();
    }
}

From source file:org.glowroot.container.impl.LocalContainer.java

public LocalContainer(@Nullable File dataDir, boolean useFileDb, int port, boolean shared,
        Map<String, String> extraProperties) throws Exception {
    if (dataDir == null) {
        this.dataDir = TempDirs.createTempDir("glowroot-test-datadir");
        deleteDataDirOnClose = true;/*from w w w  .  j a  v  a  2 s  .c  o m*/
    } else {
        this.dataDir = dataDir;
        deleteDataDirOnClose = false;
    }
    this.shared = shared;
    File configFile = new File(this.dataDir, "config.json");
    if (!configFile.exists()) {
        Files.write("{\"ui\":{\"port\":" + port + "}}", configFile, Charsets.UTF_8);
    }
    Map<String, String> properties = Maps.newHashMap();
    properties.put("data.dir", this.dataDir.getAbsolutePath());
    properties.put("internal.logging.spy", "true");
    if (!useFileDb) {
        properties.put("internal.h2.memdb", "true");
    }
    properties.putAll(extraProperties);
    try {
        MainEntryPoint.start(properties);
    } catch (org.glowroot.GlowrootModule.StartupFailedException e) {
        throw new StartupFailedException(e);
    }
    JavaagentMain.setTraceStoreThresholdMillisToZero();
    final GlowrootModule glowrootModule = MainEntryPoint.getGlowrootModule();
    checkNotNull(glowrootModule);
    IsolatedWeavingClassLoader.Builder loader = IsolatedWeavingClassLoader.builder();
    AdviceCache adviceCache = glowrootModule.getTransactionModule().getAdviceCache();
    loader.setShimTypes(adviceCache.getShimTypes());
    loader.setMixinTypes(adviceCache.getMixinTypes());
    List<Advice> advisors = Lists.newArrayList();
    advisors.addAll(adviceCache.getAdvisors());
    loader.setAdvisors(advisors);
    loader.setWeavingTimerService(glowrootModule.getTransactionModule().getWeavingTimerService());
    loader.setTimerWrapperMethods(
            glowrootModule.getConfigModule().getConfigService().getAdvancedConfig().timerWrapperMethods());
    loader.addBridgeClasses(AppUnderTest.class, AppUnderTestServices.class);
    loader.addExcludePackages("org.glowroot.api", "org.glowroot.advicegen", "org.glowroot.collector",
            "org.glowroot.common", "org.glowroot.config", "org.glowroot.jvm", "org.glowroot.local",
            "org.glowroot.shaded", "org.glowroot.transaction", "org.glowroot.weaving", "com.google.common");
    isolatedWeavingClassLoader = loader.build();
    httpClient = new HttpClient(glowrootModule.getUiModule().getPort());
    configService = new ConfigService(httpClient, new GetUiPortCommand() {
        @Override
        public int getUiPort() throws Exception {
            // TODO report checker framework issue that checkNotNull needed here
            // in addition to above
            checkNotNull(glowrootModule);
            return glowrootModule.getUiModule().getPort();
        }
    });
    traceService = new TraceService(httpClient);
    this.glowrootModule = glowrootModule;
}

From source file:pt.up.fe.specs.library.IoUtils.java

/**
 * Helper method for Guava Files.write, which uses the default Charset and
 * throws an unchecked exception./*from w  w w  .  j a  v  a  2  s . c  o m*/
 * 
 * @param contents
 * @param file
 */
public static void write(CharSequence contents, File file) {
    try {
        Files.write(contents, file, Charset.defaultCharset());
    } catch (IOException e) {
        throw new RuntimeException("Could not write file '" + file + "'", e);
    }
}

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

public void generateDocs(Collection<TeamInfrastructure> teamsInfrastructures, String baseWikiFolder)
        throws IOException {
    File wikiBaseFolder = new File(baseWikiFolder);
    if (wikiBaseFolder.exists()) {
        logger.debug("Delete wiki folder {}", wikiBaseFolder);
        wikiBaseFolder.delete();//from w ww.  j  av a2  s .c  o  m
    }
    wikiBaseFolder.mkdirs();

    List<String> generatedWikiPageNames = Lists.newArrayList();
    List<String> setupGeneratedWikiPageNames = Lists.newArrayList();
    HashMap<TeamInfrastructure, List<String>> teamsPages = Maps.newHashMap();

    for (TeamInfrastructure infrastructure : teamsInfrastructures) {
        List<String> generatedForTeam = Lists.newArrayList();
        for (String template : TEMPLATE_LAB_NAMES) {
            try {
                Map<String, Object> rootMap = Maps.newHashMap();
                rootMap.put("infrastructure", infrastructure);
                String templatePath = TEMPLATE_ROOT_PATH + template + ".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 = "OSMonitoringLabs_" + infrastructure.getIdentifier() + "_" + template;
                wikiPageName = wikiPageName.replace('-', '_');
                generatedWikiPageNames.add(wikiPageName);
                generatedForTeam.add(wikiPageName);
                File wikiPageFile = new File(wikiBaseFolder, wikiPageName + ".wiki");
                Files.write(page, wikiPageFile, Charsets.UTF_8);
                logger.debug("Generated file {}", wikiPageFile);
            } catch (Exception e) {
                logger.error("Exception generating doc for {}", infrastructure, e);
            }
        }

        teamsPages.put(infrastructure, generatedForTeam);
    }

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

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

    List<TeamInfrastructure> teams = new ArrayList<TeamInfrastructure>(teamsPages.keySet());

    Collections.sort(teams);

    for (TeamInfrastructure teamInfrastructure : teams) {

        for (String wikiPage : teamsPages.get(teamInfrastructure)) {
            indexPageWriter.println("  * [" + wikiPage + "]");
        }
    }
    /*
     * for (String wikiPage : setupGeneratedWikiPageNames) { indexPageWriter.println(" # [" + wikiPage + "]"); }
     */
    String indexPageName = "OS-Monitoring";
    Files.write(indexPageStringWriter.toString(), new File(baseWikiFolder, indexPageName + ".wiki"),
            Charsets.UTF_8);

    System.out.println("GENERATED WIKI PAGES TO BE COMMITTED IN XEBIA-FRANCE GOOGLE CODE");
    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://xebia-france.googlecode.com/svn/wiki");
    System.out.println("Index page: " + indexPageName);
    System.out.println("Per team pages: \n\t" + Joiner.on("\n\t").join(generatedWikiPageNames));
}

From source file:org.glowroot.agent.config.ConfigFileUtil.java

public static void writeToFileIfNeeded(File file, ObjectNode rootObjectNode, List<String> keyOrder,
        boolean logStartupMessageInstead) throws IOException {
    String content = writeConfigAsString(rootObjectNode, keyOrder);
    String existingContent = "";
    if (file.exists()) {
        existingContent = Files.toString(file, UTF_8);
        if (content.equals(existingContent)) {
            // it's nice to preserve the correct modification stamp on the file to track when it
            // was last really changed
            return;
        }/*from  w  w w.j  ava  2  s. c  om*/
    }
    if (!logStartupMessageInstead) {
        Files.write(content, file, UTF_8);
    } else if (!normalize(content).equals(normalize(existingContent))) {
        startupLogger.info("tried to update {} during startup but the agent is running with"
                + " config.readOnly=true, you can prevent this message from re-occurring by"
                + " manually updating the file with these contents:\n{}", file.getName(), content);
    }
}