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.netflix.astyanax.test.EmbeddedCassandra.java

public EmbeddedCassandra(File dataDir, String clusterName, int port, int storagePort) throws IOException {
    LOG.info("Starting cassandra in dir " + dataDir);
    this.dataDir = dataDir;
    dataDir.mkdirs();//from  w ww .j  ava 2s.  c  o  m

    InputStream is = null;

    try {
        URL templateUrl = EmbeddedCassandra.class.getClassLoader().getResource("cassandra-template.yaml");
        Preconditions.checkNotNull(templateUrl, "Cassandra config template is null");
        String baseFile = Resources.toString(templateUrl, Charset.defaultCharset());

        String newFile = baseFile.replace("$DIR$", dataDir.getPath());
        newFile = newFile.replace("$PORT$", Integer.toString(port));
        newFile = newFile.replace("$STORAGE_PORT$", Integer.toString(storagePort));
        newFile = newFile.replace("$CLUSTER$", clusterName);

        File configFile = new File(dataDir, "cassandra.yaml");
        Files.write(newFile, configFile, Charset.defaultCharset());

        LOG.info("Cassandra config file: " + configFile.getPath());
        System.setProperty("cassandra.config", "file:" + configFile.getPath());

        try {
            cassandra = new CassandraDaemon();
            cassandra.init(null);
        } catch (IOException e) {
            LOG.error("Error initializing embedded cassandra", e);
            throw e;
        }
    } finally {
        Closeables.closeQuietly(is);
    }
    LOG.info("Started cassandra deamon");
}

From source file:org.icgc.dcc.release.job.annotate.snpeff.SnpEffProcess.java

@SneakyThrows
private String getConfigFile() {
    // Template/*from  w w  w  .  j a  v  a2 s.com*/
    val contents = Resources.toString(getResource("snpEff.config"), UTF_8).replace("${dataDir}",
            dataDir.getAbsolutePath());

    val configFile = File.createTempFile("snpEff", ".config");

    log.info("Creating temporary configuration file at '{}'...", configFile);
    Files.write(contents, configFile, UTF_8);

    return configFile.getAbsolutePath();
}

From source file:org.rf.ide.core.testdata.text.write.ARobotFileDumper.java

@Override
public void dump(final File robotFile, final RobotFile model) throws IOException {
    Files.write(dump(model), robotFile, Charset.forName("utf-8"));
}

From source file:com.google.devtools.j2objc.gen.ObjectiveCSourceFileGenerator.java

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

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

        Files.write(source, outputFile, Options.getCharset());
    } catch (IOException e) {
        ErrorUtil.error(e.getMessage());
    } finally {
        reset();
    }
}

From source file:br.com.objectos.blog.PostImpl.java

private void writeTo0(PostTemplate template, File destination) throws IOException {

    String html = render(template);

    DateTime date = getDate();/*  ww  w.  jav  a2s .c  om*/
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy/MM/dd");
    String directoryName = formatter.print(date);

    File directory = new File(destination, directoryName);
    directory.mkdirs();

    String title = getTitle();
    String filename = Strings.accentsToAscii(title).alphanum().whitespaceTo("_").toString().toLowerCase();

    File file = new File(directory, filename + ".html");
    Files.write(html, file, Charsets.UTF_8);

}

From source file:com.ro.ssc.app.client.controller.MainController.java

@Override
public void initialize(URL location, ResourceBundle resources) {
    log.info("Initializing main controller");
    File destDir = new File(MDB_PATH);
    if (!destDir.exists()) {
        destDir.mkdirs();//from www . j  a  v  a  2  s  .c  o  m
    } else {
        File file = new File(MDB_PATH + "/status.txt");
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            String content = Files.toString(file, Charsets.UTF_8);
            try {
                if (DateTime.parse(content, dtf).isBeforeNow()) {
                    return;
                }
            } catch (Exception e) {
            }
            log.debug("cont" + content + " file" + file);
            if (content.contains("111111111111111")) {
                Files.write(DateTime.now().toString(dtf), file, Charsets.UTF_8);

                Optional<String> result = UiCommonTools.getInstance().showExpDialogStatus("Licenta Expirata",
                        "Va rugam contactati vanzatorul softului pentru codul de deblocare ",
                        TrialKeyGenerator.generateKey(DateTime.now().toString(dtf)));
                if (result.isPresent()) {
                    if (TrialKeyValidator.decodeKey(result.get())
                            .equals(Files.toString(file, Charsets.UTF_8).concat("0"))) {
                        Files.write("NO_EXP", file, Charsets.UTF_8);

                    } else {
                        return;
                    }
                } else {
                    return;
                }
            } else if (!content.contains("NO_EXP")) {
                Files.append("1", file, Charsets.UTF_8);
            }
        } catch (FileNotFoundException ex) {
            log.error("Exception in finding file " + ex.getMessage());
        } catch (IOException ex) {
            log.error("Exception in writing file " + ex.getMessage());
        }
    }

    try {
        // load side menu
        final FXMLLoader sideMenuLoader = new FXMLLoader();
        final AnchorPane sideMenu = sideMenuLoader.load(getClass().getResourceAsStream(SIDE_MENU_LAYOUT_FILE));
        AnchorPane.setLeftAnchor(sideMenu, 0.0);
        AnchorPane.setTopAnchor(sideMenu, 0.0);
        AnchorPane.setRightAnchor(sideMenu, 0.0);
        AnchorPane.setBottomAnchor(sideMenu, 0.0);
        sideMenuContainer.getChildren().add(sideMenu);
        sideMenuContainer.getStylesheets().add(SIDE_MENU_CSS_FILE);
        ((SideMenuNoImagesController) sideMenuLoader.getController()).setMainController(this);

        // load status bar
        final FXMLLoader statusBarLoader = new FXMLLoader();
        final AnchorPane statusBar = statusBarLoader
                .load(getClass().getResourceAsStream(STATUS_BAR_LAYOUT_FILE));
        AnchorPane.setRightAnchor(statusBar, 10.0);
        statusBarContainer.getChildren().add(statusBar);
        statusBarContainer.getStylesheets().add(STATUS_BAR_CSS_FILE);

        handleSumaryViewLaunch();
    } catch (Exception ex) {
        log.error("Failed to load components", ex);
    }
}

From source file:com.google.gms.googleservices.GoogleServicesTask.java

@TaskAction
public void action() throws IOException {
    if (!quickstartFile.isFile()) {
        getLogger().warn("File " + quickstartFile.getName() + " is missing from module root folder."
                + " The Google Quickstart Plugin cannot function without it.");

        // Skip the rest of the actions because it would not make sense if `quickstartFile` is missing.
        return;//from   w  w w  .  j av a 2  s. c  o m
    }

    // delete content of outputdir.
    deleteFolder(intermediateDir);
    if (!intermediateDir.mkdirs()) {
        throw new GradleException("Failed to create folder: " + intermediateDir);
    }

    JsonElement root = new JsonParser().parse(Files.newReader(quickstartFile, Charsets.UTF_8));

    if (!root.isJsonObject()) {
        throw new GradleException("Malformed root json");
    }

    JsonObject rootObject = root.getAsJsonObject();

    Map<String, String> resValues = new TreeMap<String, String>();

    handleProjectNumber(rootObject, resValues);

    JsonObject clientObject = getClientForPackageName(rootObject);

    if (clientObject != null) {
        handleAnalytics(clientObject, resValues);
        handleAdsService(clientObject, resValues);
    } else {
        getLogger().warn("No matching client found for package name '" + packageName + "'");
    }

    // write the values file.
    File values = new File(intermediateDir, "values");
    if (!values.exists() && !values.mkdirs()) {
        throw new GradleException("Failed to create folder: " + values);
    }

    Files.write(getValuesContent(resValues), new File(values, "values.xml"), Charsets.UTF_8);
}

From source file:pl.lstypka.jevidence.core.io.FileUtils.java

public void saveString(String value, String destination) {
    try {/*  www . j  av a 2  s  . c  o  m*/
        Files.write(value, new File(destination), Charset.forName("UTF-8"));
    } catch (IOException e) {
        throw new JEvidenceException("Exception occurred while saving records", e);
    }
}

From source file:org.jclouds.examples.rackspace.cloudfiles.UploadObjectsWithServiceNet.java

/**
 * Upload an object from a File using the Swift API.
 *///  www  . j  ava 2  s .c  o  m
private void uploadObjectFromFile() throws IOException {
    System.out.format("Upload Object From File%n");

    String filename = "uploadObjectFromFile";
    String suffix = ".txt";

    File tempFile = File.createTempFile(filename, suffix);

    try {
        Files.write("uploadObjectFromFile", tempFile, Charsets.UTF_8);

        ByteSource byteSource = Files.asByteSource(tempFile);
        Payload payload = Payloads.newByteSourcePayload(byteSource);

        cloudFiles.getObjectApi(REGION, CONTAINER).put(filename + suffix, payload);

        System.out.format("  %s%s%n", filename, suffix);
    } finally {
        tempFile.delete();
    }
}

From source file:fr.xebia.workshop.continuousdelivery.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 www.  j  av a 2  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 = "ContinuousDeliveryWorkshopLab_" + 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);
            }
        }
        // SETUP WITH LINKS TO DIFFERENT LABS WIKI PAGE
        try {
            Map<String, Object> rootMap = Maps.newHashMap();
            rootMap.put("infrastructure", infrastructure);
            String templatePath = TEMPLATE_ROOT_PATH + SETUP_TEMPLATE_NAME + ".ftl";
            rootMap.put("generator", "This page has been generaterd by '{{{" + getClass()
                    + "}}}' with template '{{{" + templatePath + "}}}' on the " + new DateTime());
            rootMap.put("generatedWikiPageNames", generatedForTeam);
            String page = FreemarkerUtils.generate(rootMap, templatePath);
            String wikiPageName = "ContinuousDeliveryWorkshopLab_" + infrastructure.getIdentifier() + "_"
                    + SETUP_TEMPLATE_NAME;
            wikiPageName = wikiPageName.replace('-', '_');

            File wikiPageFile = new File(wikiBaseFolder, wikiPageName + ".wiki");
            Files.write(page, wikiPageFile, Charsets.UTF_8);

            generatedWikiPageNames.add(wikiPageName);
            setupGeneratedWikiPageNames.add(wikiPageName);

            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) {
        indexPageWriter.println(" # [ContinuousDeliveryWorkshopLab_" + teamInfrastructure.getIdentifier() + "_"
                + SETUP_TEMPLATE_NAME + "]");
        for (String wikiPage : teamsPages.get(teamInfrastructure)) {
            indexPageWriter.println("  * [" + wikiPage + "]");
        }
    }
    /*
     * for (String wikiPage : setupGeneratedWikiPageNames) { indexPageWriter.println(" # [" + wikiPage + "]"); }
     */
    String indexPageName = "ContinuousDeliveryWorkshopLab";
    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));
}