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:li.klass.fhem.error.ErrorHolder.java

private static File writeToDisk(Context context, String content) throws IOException {
    File outputDir = context.getExternalFilesDir(null);
    File outputFile = File.createTempFile("andFHEM-", ".log", outputDir);
    outputFile.setReadable(true, true);//from w  w  w  .ja v  a  2  s  .c  om
    outputFile.deleteOnExit();

    Files.write(content, outputFile, Charsets.UTF_8);

    return outputFile;
}

From source file:org.primefaces.extensions.optimizerplugin.optimizer.ClosureCompilerOptimizer.java

@Override
public void optimize(final ResourcesSetAdapter rsAdapter, final Log log) throws MojoExecutionException {
    ResourcesSetJsAdapter rsa = (ResourcesSetJsAdapter) rsAdapter;
    CompilationLevel compLevel = rsa.getCompilationLevel();
    CompilerOptions options = new CompilerOptions();
    compLevel.setOptionsForCompilationLevel(options);

    WarningLevel warnLevel = rsa.getWarningLevel();
    warnLevel.setOptionsForWarningLevel(options);
    Compiler.setLoggingLevel(Level.WARNING);

    try {/*from ww w. j  a  v  a2  s. c o m*/
        Charset cset = Charset.forName(rsa.getEncoding());

        if (rsa.getAggregation() == null) {
            // no aggregation
            for (File file : rsa.getFiles()) {
                log.info("Optimize JS file " + file.getName() + " ...");

                // statistic
                addToOriginalSize(file);

                // path of the original file
                String path = file.getCanonicalPath();

                String outputFilePath = null;
                String outputSourceMapDir = null;
                File sourceMapFile = null;
                File sourceFile;

                if (rsa.getSourceMap() != null) {
                    // setup source map
                    outputFilePath = file.getCanonicalPath();
                    outputSourceMapDir = rsa.getSourceMap().getOutputDir();
                    sourceMapFile = setupSourceMapFile(options, rsa.getSourceMap(), outputFilePath);
                    // create an empty file with ...source.js from the original one
                    sourceFile = getFileWithSuffix(path, OUTPUT_FILE_SUFFIX);

                    if (StringUtils.isNotBlank(rsa.getSuffix())) {
                        // rename original file as ...source.js
                        FileUtils.rename(file, sourceFile);
                    } else {
                        // copy content of the original file to the ...source.js
                        FileUtils.copyFile(file, sourceFile);
                    }
                } else {
                    sourceFile = file;
                }

                // compile
                List<SourceFile> interns = new ArrayList<SourceFile>();
                interns.add(SourceFile.fromFile(sourceFile, cset));
                Compiler compiler = compile(log, interns, options, rsa.isFailOnWarning());

                if (StringUtils.isNotBlank(rsa.getSuffix())) {
                    // write compiled content into the new file
                    File outputFile = getFileWithSuffix(path, rsa.getSuffix());
                    Files.write(compiler.toSource(), outputFile, cset);

                    if (sourceMapFile != null) {
                        // write sourceMappingURL into the minified file
                        writeSourceMappingURL(outputFile, sourceMapFile, rsa.getSourceMap().getSourceMapRoot(),
                                cset, log);
                    }

                    // statistic
                    addToOptimizedSize(outputFile);
                } else {
                    // path of temp. file
                    String pathOptimized = FileUtils.removeExtension(path) + OPTIMIZED_FILE_EXTENSION;

                    // create a new temp. file
                    File outputFile = new File(pathOptimized);
                    Files.touch(outputFile);

                    // write compiled content into the new file and rename it (overwrite the original file)
                    Files.write(compiler.toSource(), outputFile, cset);
                    FileUtils.rename(outputFile, file);

                    if (sourceMapFile != null) {
                        // write sourceMappingURL into the minified file
                        writeSourceMappingURL(file, sourceMapFile, rsa.getSourceMap().getSourceMapRoot(), cset,
                                log);
                    }

                    // statistic
                    addToOptimizedSize(file);
                }

                if (outputFilePath != null && sourceMapFile != null) {
                    // write the source map
                    Files.touch(sourceMapFile);
                    writeSourceMap(sourceMapFile, outputFilePath, compiler.getSourceMap(), outputSourceMapDir,
                            log);

                    // move the source file to the source map dir
                    moveToSourceMapDir(sourceFile, outputSourceMapDir, log);
                }
            }
        } else if (rsa.getAggregation().getOutputFile() != null) {
            // aggregation to one output file
            File outputFile = rsa.getAggregation().getOutputFile();
            File aggrOutputFile = aggregateFiles(rsa, cset, true);

            // statistic
            long sizeBefore = addToOriginalSize(aggrOutputFile);

            if (!rsa.getAggregation().isWithoutCompress()) {
                // compressing
                for (File file : rsa.getFiles()) {
                    log.info("Optimize JS file " + file.getName() + " ...");
                }

                String outputFilePath = null;
                File sourceMapFile = null;
                if (rsa.getSourceMap() != null) {
                    // setup source map
                    outputFilePath = outputFile.getCanonicalPath();
                    sourceMapFile = setupSourceMapFile(options, rsa.getSourceMap(), outputFilePath);
                }

                // compile
                List<SourceFile> interns = new ArrayList<SourceFile>();
                interns.add(SourceFile.fromFile(aggrOutputFile, cset));
                Compiler compiler = compile(log, interns, options, rsa.isFailOnWarning());

                // delete single files if necessary
                deleteFilesIfNecessary(rsa, log);

                // write the compiled content into a new file
                Files.touch(outputFile);
                Files.write(compiler.toSource(), outputFile, cset);

                if (outputFilePath != null && sourceMapFile != null) {
                    // write sourceMappingURL into the minified file
                    writeSourceMappingURL(outputFile, sourceMapFile, rsa.getSourceMap().getSourceMapRoot(),
                            cset, log);

                    // write the source map
                    String outputSourceMapDir = rsa.getSourceMap().getOutputDir();
                    Files.touch(sourceMapFile);
                    writeSourceMap(sourceMapFile, outputFilePath, compiler.getSourceMap(), outputSourceMapDir,
                            log);

                    // move the source file
                    moveToSourceMapDir(aggrOutputFile, outputSourceMapDir, log);
                } else {
                    // delete the temp. aggregated file ...source.js
                    if (aggrOutputFile.exists() && !aggrOutputFile.delete()) {
                        log.warn("Temporary file " + aggrOutputFile.getName() + " could not be deleted.");
                    }
                }

                // statistic
                addToOptimizedSize(sizeBefore - outputFile.length());
            } else {
                // delete single files if necessary
                deleteFilesIfNecessary(rsa, log);

                // rename aggregated file if necessary
                renameOutputFileIfNecessary(rsa, aggrOutputFile);

                // statistic
                addToOptimizedSize(sizeBefore);
            }
        } else {
            // should not happen
            log.error("Wrong plugin's internal state.");
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Resources optimization failure: " + e.getLocalizedMessage(), e);
    }
}

From source file:javasensei.util.CreateFeatures.java

public static void deleteFirstLine() throws Exception {
    StringBuilder nuevoArchivo = new StringBuilder();
    BufferedReader input = new BufferedReader(new FileReader("D:\\listaFotografias.txt"));
    input.lines().skip(1).forEachOrdered((String t) -> { //Saltamos la primera linea
        nuevoArchivo.append(t);// w  w w . j  a  va2 s  . c o  m
        nuevoArchivo.append(System.lineSeparator());
    });

    Files.write(nuevoArchivo, new File("D:\\listaFotografias.txt"), Charset.defaultCharset());
}

From source file:org.pshdl.model.simulation.codegenerator.DartCodeGenerator.java

public IHDLInterpreterFactory<NativeRunner> createInterpreter(final File tempDir) {
    try {//from w w  w  .  j a v a  2 s  .  c om
        IHDLInterpreterFactory<NativeRunner> _xblockexpression = null;
        {
            final String dartCode = this.generateMainCode();
            final File binDir = new File(tempDir, "bin");
            boolean _mkdirs = binDir.mkdirs();
            boolean _not = (!_mkdirs);
            if (_not) {
                throw new IllegalArgumentException(("Failed to create Directory " + binDir));
            }
            File _file = new File(binDir, "dut.dart");
            Files.write(dartCode, _file, StandardCharsets.UTF_8);
            final File testRunnerDir = new File(DartCodeGenerator.TESTRUNNER_DIR);
            final File testRunner = new File(testRunnerDir, "bin/darttestrunner.dart");
            String _name = testRunner.getName();
            File _file_1 = new File(binDir, _name);
            Files.copy(testRunner, _file_1);
            final File yaml = new File(testRunnerDir, "pubspec.yaml");
            String _name_1 = yaml.getName();
            File _file_2 = new File(tempDir, _name_1);
            Files.copy(yaml, _file_2);
            File _file_3 = new File(binDir, "packages");
            Path _path = _file_3.toPath();
            File _file_4 = new File(testRunnerDir, "packages");
            Path _path_1 = _file_4.toPath();
            java.nio.file.Files.createSymbolicLink(_path, _path_1);
            File _file_5 = new File(tempDir, "packages");
            Path _path_2 = _file_5.toPath();
            File _file_6 = new File(testRunnerDir, "packages");
            Path _path_3 = _file_6.toPath();
            java.nio.file.Files.createSymbolicLink(_path_2, _path_3);
            _xblockexpression = new IHDLInterpreterFactory<NativeRunner>() {
                public NativeRunner newInstance() {
                    try {
                        String _name = testRunner.getName();
                        String _plus = ("bin/" + _name);
                        ProcessBuilder _processBuilder = new ProcessBuilder(DartCodeGenerator.DART_EXEC, _plus,
                                DartCodeGenerator.this.unitName, DartCodeGenerator.this.library);
                        ProcessBuilder _directory = _processBuilder.directory(tempDir);
                        ProcessBuilder _redirectErrorStream = _directory.redirectErrorStream(true);
                        final Process dartRunner = _redirectErrorStream.start();
                        InputStream _inputStream = dartRunner.getInputStream();
                        OutputStream _outputStream = dartRunner.getOutputStream();
                        return new NativeRunner(_inputStream, _outputStream, DartCodeGenerator.this.em,
                                dartRunner, 5, ((("Dart " + DartCodeGenerator.this.library) + ".")
                                        + DartCodeGenerator.this.unitName));
                    } catch (Throwable _e) {
                        throw Exceptions.sneakyThrow(_e);
                    }
                }
            };
        }
        return _xblockexpression;
    } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
    }
}

From source file:org.eclipse.xtext.xbase.lib.ArithmeticExtensionGenerator.java

public void generate() {
    try {//  w ww.  ja v  a 2s  .  c  o m
        final String path = "../org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/";
        File _file = new File(path);
        _file.mkdirs();
        for (final String type : this.types) {
            {
                String _className = this.className(type);
                String _plus = (path + _className);
                String _plus_1 = (_plus + ".java");
                final File file = new File(_plus_1);
                CharSequence _xifexpression = null;
                boolean _exists = file.exists();
                if (_exists) {
                    String _xblockexpression = null;
                    {
                        final String content = Files.toString(file, Charsets.ISO_8859_1);
                        StringConcatenation _builder = new StringConcatenation();
                        String _startMarker = this.startMarker();
                        int _indexOf = content.indexOf(_startMarker);
                        String _substring = content.substring(0, _indexOf);
                        _builder.append(_substring, "");
                        _builder.newLineIfNotEmpty();
                        _builder.append("\t");
                        CharSequence _generateAllOperations = this.generateAllOperations(type);
                        _builder.append(_generateAllOperations, "\t");
                        _builder.newLineIfNotEmpty();
                        String _endMarker = this.endMarker();
                        int _indexOf_1 = content.indexOf(_endMarker);
                        String _endMarker_1 = this.endMarker();
                        int _length = _endMarker_1.length();
                        int _plus_2 = (_indexOf_1 + _length);
                        String _substring_1 = content.substring(_plus_2);
                        _builder.append(_substring_1, "");
                        _xblockexpression = _builder.toString();
                    }
                    _xifexpression = _xblockexpression;
                } else {
                    _xifexpression = this.generate(type);
                }
                final CharSequence newContent = _xifexpression;
                final StringConcatenation result = new StringConcatenation("\n");
                result.append(newContent);
                Files.write(result, file, Charsets.ISO_8859_1);
            }
        }
    } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
    }
}

From source file:com.vexsoftware.votifier.NuVotifierBukkit.java

@Override
public void onEnable() {
    NuVotifierBukkit.instance = this;

    // Set the plugin version.
    version = getDescription().getVersion();

    if (!getDataFolder().exists()) {
        getDataFolder().mkdir();//from  w ww .  j  a va  2 s . c o  m
    }

    // Handle configuration.
    File config = new File(getDataFolder() + "/config.yml");
    YamlConfiguration cfg;
    File rsaDirectory = new File(getDataFolder() + "/rsa");

    /*
     * Use IP address from server.properties as a default for
     * configurations. Do not use InetAddress.getLocalHost() as it most
     * likely will return the main server address instead of the address
     * assigned to the server.
     */
    String hostAddr = Bukkit.getServer().getIp();
    if (hostAddr == null || hostAddr.length() == 0)
        hostAddr = "0.0.0.0";

    /*
     * Create configuration file if it does not exists; otherwise, load it
     */
    if (!config.exists()) {
        try {
            // First time run - do some initialization.
            getLogger().info("Configuring Votifier for the first time...");

            // Initialize the configuration file.
            config.createNewFile();

            // Load and manually replace variables in the configuration.
            String cfgStr = new String(ByteStreams.toByteArray(getResource("bukkitConfig.yml")),
                    StandardCharsets.UTF_8);
            String token = TokenUtil.newToken();
            cfgStr = cfgStr.replace("%default_token%", token).replace("%ip%", hostAddr);
            Files.write(cfgStr, config, StandardCharsets.UTF_8);

            /*
             * Remind hosted server admins to be sure they have the right
             * port number.
             */
            getLogger().info("------------------------------------------------------------------------------");
            getLogger()
                    .info("Assigning NuVotifier to listen on port 8192. If you are hosting Craftbukkit on a");
            getLogger().info("shared server please check with your hosting provider to verify that this port");
            getLogger().info("is available for your use. Chances are that your hosting provider will assign");
            getLogger().info("a different port, which you need to specify in config.yml");
            getLogger().info("------------------------------------------------------------------------------");
            getLogger().info("Your default NuVotifier token is " + token + ".");
            getLogger().info("You will need to provide this token when you submit your server to a voting");
            getLogger().info("list.");
            getLogger().info("------------------------------------------------------------------------------");
        } catch (Exception ex) {
            getLogger().log(Level.SEVERE, "Error creating configuration file", ex);
            gracefulExit();
            return;
        }
    }

    // Load configuration.
    cfg = YamlConfiguration.loadConfiguration(config);

    /*
     * Create RSA directory and keys if it does not exist; otherwise, read
     * keys.
     */
    try {
        if (!rsaDirectory.exists()) {
            rsaDirectory.mkdir();
            keyPair = RSAKeygen.generate(2048);
            RSAIO.save(rsaDirectory, keyPair);
        } else {
            keyPair = RSAIO.load(rsaDirectory);
        }
    } catch (Exception ex) {
        getLogger().log(Level.SEVERE, "Error reading configuration file or RSA tokens", ex);
        gracefulExit();
        return;
    }

    debug = cfg.getBoolean("debug", false);

    boolean setUpPort = cfg.getBoolean("enableExternal", true); //Always default to running the external port

    if (setUpPort) {
        // Load Votifier tokens.
        ConfigurationSection tokenSection = cfg.getConfigurationSection("tokens");

        if (tokenSection != null) {
            Map<String, Object> websites = tokenSection.getValues(false);
            for (Map.Entry<String, Object> website : websites.entrySet()) {
                tokens.put(website.getKey(), KeyCreator.createKeyFrom(website.getValue().toString()));
                getLogger().info("Loaded token for website: " + website.getKey());
            }
        } else {
            String token = TokenUtil.newToken();
            tokenSection = cfg.createSection("tokens");
            tokenSection.set("default", token);
            tokens.put("default", KeyCreator.createKeyFrom(token));
            try {
                cfg.save(config);
            } catch (IOException e) {
                getLogger().log(Level.SEVERE, "Error generating Votifier token", e);
                gracefulExit();
                return;
            }
            getLogger().info("------------------------------------------------------------------------------");
            getLogger().info("No tokens were found in your configuration, so we've generated one for you.");
            getLogger().info("Your default Votifier token is " + token + ".");
            getLogger().info("You will need to provide this token when you submit your server to a voting");
            getLogger().info("list.");
            getLogger().info("------------------------------------------------------------------------------");
        }

        // Initialize the receiver.
        final String host = cfg.getString("host", hostAddr);
        final int port = cfg.getInt("port", 8192);
        if (debug)
            getLogger().info("DEBUG mode enabled!");

        final boolean disablev1 = cfg.getBoolean("disable-v1-protocol");
        if (disablev1) {
            getLogger().info("------------------------------------------------------------------------------");
            getLogger().info("Votifier protocol v1 parsing has been disabled. Most voting websites do not");
            getLogger().info("currently support the modern Votifier protocol in NuVotifier.");
            getLogger().info("------------------------------------------------------------------------------");
        }

        serverGroup = new NioEventLoopGroup(1);

        new ServerBootstrap().channel(NioServerSocketChannel.class).group(serverGroup)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        channel.attr(VotifierSession.KEY).set(new VotifierSession());
                        channel.attr(VotifierPlugin.KEY).set(NuVotifierBukkit.this);
                        channel.pipeline().addLast("greetingHandler", new VotifierGreetingHandler());
                        channel.pipeline().addLast("protocolDifferentiator",
                                new VotifierProtocolDifferentiator(false, !disablev1));
                        channel.pipeline().addLast("voteHandler",
                                new VoteInboundHandler(NuVotifierBukkit.this));
                    }
                }).bind(host, port).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            serverChannel = future.channel();
                            getLogger()
                                    .info("Votifier enabled on socket " + serverChannel.localAddress() + ".");
                        } else {
                            SocketAddress socketAddress = future.channel().localAddress();
                            if (socketAddress == null) {
                                socketAddress = new InetSocketAddress(host, port);
                            }
                            getLogger().log(Level.SEVERE, "Votifier was not able to bind to " + socketAddress,
                                    future.cause());
                        }
                    }
                });
    } else {
        getLogger().info(
                "You have enableExternal set to false in your config.yml. NuVotifier will NOT listen to votes coming in from an external voting list.");
    }

    ConfigurationSection forwardingConfig = cfg.getConfigurationSection("forwarding");
    if (forwardingConfig != null) {
        String method = forwardingConfig.getString("method", "none").toLowerCase(); //Default to lower case for case-insensitive searches
        if ("none".equals(method)) {
            getLogger().info(
                    "Method none selected for vote forwarding: Votes will not be received from a forwarder.");
        } else if ("pluginmessaging".equals(method)) {
            String channel = forwardingConfig.getString("pluginMessaging.channel", "NuVotifier");
            try {
                forwardingMethod = new BukkitPluginMessagingForwardingSink(this, channel, this);
                getLogger().info("Receiving votes over PluginMessaging channel '" + channel + "'.");
            } catch (RuntimeException e) {
                getLogger().log(Level.SEVERE,
                        "NuVotifier could not set up PluginMessaging for vote forwarding!", e);
            }
        } else {
            getLogger().severe(
                    "No vote forwarding method '" + method + "' known. Defaulting to noop implementation.");
        }
    }
}

From source file:com.google.devtools.treeshaker.TreeShaker.java

private File stripIncompatible(List<String> sourceFileNames, Parser parser) throws IOException {
    File strippedDir = null;//from   ww w .  jav  a2  s  . c o m
    for (int i = 0; i < sourceFileNames.size(); i++) {
        String fileName = sourceFileNames.get(i);
        RegularInputFile file = new RegularInputFile(fileName);
        String source = j2objcOptions.fileUtil().readFile(file);
        if (!source.contains("J2ObjCIncompatible")) {
            continue;
        }
        if (strippedDir == null) {
            strippedDir = Files.createTempDir();
            parser.prependSourcepathEntry(strippedDir.getPath());
        }
        Parser.ParseResult parseResult = parser.parseWithoutBindings(file, source);
        String qualifiedName = parseResult.mainTypeName();
        parseResult.stripIncompatibleSource();
        String relativePath = qualifiedName.replace('.', File.separatorChar) + ".java";
        File strippedFile = new File(strippedDir, relativePath);
        Files.createParentDirs(strippedFile);
        Files.write(parseResult.getSource(), strippedFile, j2objcOptions.fileUtil().getCharset());
        sourceFileNames.set(i, strippedFile.getPath());
    }
    return strippedDir;
}

From source file:com.proofpoint.zookeeper.ConnectionState.java

private void writeSessionId() {
    if (config.getSessionStorePath() != null) {
        ZookeeperSessionID session = new ZookeeperSessionID();
        session.setPassword(zookeeper.getSessionPasswd());
        session.setSessionId(zookeeper.getSessionId());
        ObjectMapper mapper = new ObjectMapper();
        try {/*from  ww  w  .  ja  v  a  2s  . co  m*/
            String sessionSpec = mapper.writeValueAsString(session);
            Files.write(sessionSpec, new File(config.getSessionStorePath()), Charsets.UTF_8);
        } catch (IOException e) {
            log.warn(e, "Couldn't write session info to: %s", config.getSessionStorePath());
        }
    }
}

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

/**
 * Handle a client object for analytics (@xml/global_tracker)
 * @param clientObject the client Json object.
 * @throws IOException//w  w w  . j  av  a  2s . co  m
 */
private void handleAnalytics(JsonObject clientObject, Map<String, String> resValues) throws IOException {
    JsonObject analyticsService = getServiceByName(clientObject, "analytics_service");
    if (analyticsService == null)
        return;

    JsonObject analyticsProp = analyticsService.getAsJsonObject("analytics_property");
    if (analyticsProp == null)
        return;

    JsonPrimitive trackingId = analyticsProp.getAsJsonPrimitive("tracking_id");
    if (trackingId == null)
        return;

    resValues.put("ga_trackingId", trackingId.getAsString());

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

    Files.write(getGlobalTrackerContent(trackingId.getAsString()), new File(xml, "global_tracker.xml"),
            Charsets.UTF_8);
}

From source file:org.jcruncher.less.LessProcessor.java

private void processItem(Item item) throws IOException {
    StringBuilder contentSB = new StringBuilder();
    System.out.print("less - processing to " + item.dest.getName() + " (");
    int c = 0;// www.j a  v  a  2 s  .com
    boolean printFileName = true;
    if (item.sources.size() > 4) {
        System.out.print(item.sources.size() + " files");
        printFileName = false;
    }
    for (File file : item.sources) {
        String content = compile(file);
        if (printFileName) {
            System.out.print(((c > 0) ? "," : "") + file.getName());
        }
        contentSB.append(content).append("\n");
        c++;
    }

    if (item.dest.getParentFile() != null && !item.dest.getParentFile().exists()) {
        item.dest.getParentFile().mkdirs();
    }
    Files.write(contentSB.toString(), item.dest, Charsets.UTF_8);
    System.out.println(") DONE");
}