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.facebook.buck.java.intellij.CompilerXml.java

/**
 * Writes the {@code compilerXml} file if and only if its content needs to be updated.
 * @return true if {@code compilerXml} was written
 */// w  w  w  .  j a  v a2s .co m
boolean write(File compilerXml) throws IOException {
    final Charset charset = Charsets.US_ASCII;

    String existingXml = null;
    if (compilerXml.exists()) {
        existingXml = Files.toString(compilerXml, charset);
    }

    String newXml = generateXml();
    boolean compilerXmlNeedsToBeWritten = !newXml.equals(existingXml);

    if (compilerXmlNeedsToBeWritten) {
        Files.write(newXml, compilerXml, charset);
    }

    return compilerXmlNeedsToBeWritten;
}

From source file:net.minecraftforge.gradle.patcher.TaskGenSubprojects.java

private static void generateRootSettings(File output, Collection<String> projects) throws IOException {
    StringBuilder builder = new StringBuilder();

    builder.append("include '");
    Joiner.on("', '").appendTo(builder, projects);
    builder.append("'");

    Files.write(builder.toString(), output, Constants.CHARSET);
}

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

/**
 * Returns the project back to its original state.
 *///from  w  ww  .j  av  a 2 s.  c o m
public void close() throws InitializationError {
    try {
        for (Map.Entry<String, String> entry : mFileContentToRestore.entrySet()) {
            Files.write(entry.getValue(), mTestProject.file(entry.getKey()), Charsets.UTF_8);
        }
    } catch (IOException e) {
        throw new InitializationError(e);
    }
    mFileContentToRestore.clear();
}

From source file:com.google.devtools.cyclefinder.CycleFinder.java

private File stripIncompatible(List<String> sourceFileNames, JdtParser parser) throws IOException {
    File strippedDir = null;// www  . j  a  v  a  2 s.  co  m
    for (int i = 0; i < sourceFileNames.size(); i++) {
        String fileName = sourceFileNames.get(i);
        RegularInputFile file = new RegularInputFile(fileName);
        String source = FileUtil.readFile(file);
        if (!source.contains("J2ObjCIncompatible")) {
            continue;
        }
        if (strippedDir == null) {
            strippedDir = Files.createTempDir();
            parser.prependSourcepathEntry(strippedDir.getPath());
        }
        org.eclipse.jdt.core.dom.CompilationUnit unit = parser.parseWithoutBindings(fileName, source);
        String qualifiedName = FileUtil.getQualifiedMainTypeName(file, unit);
        String newSource = J2ObjCIncompatibleStripper.strip(source, unit);
        String relativePath = qualifiedName.replace('.', File.separatorChar) + ".java";
        File strippedFile = new File(strippedDir, relativePath);
        Files.createParentDirs(strippedFile);
        Files.write(newSource, strippedFile, Charset.forName(options.fileEncoding()));
        sourceFileNames.set(i, strippedFile.getPath());
    }
    return strippedDir;
}

From source file:org.jetbrains.kotlin.KotlinIntegrationTestBase.java

protected void check(String baseName, String content) throws IOException {
    final File actualFile = new File(testDataDir, baseName + ".actual");
    final File expectedFile = new File(testDataDir, baseName + ".expected");

    final String normalizedContent = normalizeOutput(content);

    if (!expectedFile.isFile()) {
        Files.write(normalizedContent, actualFile, Charsets.UTF_8);
        fail("No .expected file " + expectedFile);
    } else {//from   ww w.  j av a2 s.  c om
        final String goldContent = FileUtil.loadFile(expectedFile, CharsetToolkit.UTF8, true);
        try {
            assertEquals(goldContent, normalizedContent);
            actualFile.delete();
        } catch (ComparisonFailure e) {
            Files.write(normalizedContent, actualFile, Charsets.UTF_8);
            throw e;
        }
    }
}

From source file:com.bsiag.geneclipsetoc.internal.GenerateEclipseTocUtility.java

public static void generate(File rootInFolder, List<String> pages, String helpPrefix, File outTocFile,
        File outContextsFile, List<HelpContext> inContexts) throws IOException {
    if (!rootInFolder.exists() || !rootInFolder.isDirectory()) {
        throw new IllegalStateException(
                "Folder rootInFolder '" + rootInFolder.getAbsolutePath() + "' not found.");
    }/*from w w  w  . j a  va2s  .  com*/
    if (pages == null || pages.isEmpty()) {
        throw new IllegalArgumentException("pages can not be null, it should contains at least one element");
    }
    if (outTocFile == null) {
        throw new IllegalStateException("File outTocFile is not set.");
    }
    if (inContexts != null && inContexts.size() > 0 && outContextsFile == null) {
        throw new IllegalStateException(
                "File outContextsFile is not set (but there are '" + inContexts.size() + "' HelpContexts)");
    }

    //Prepare the rootInFolder list (this will check that the files exist)
    List<File> inFiles = new ArrayList<File>();
    for (String p : pages) {
        if (p != null && p.length() > 0) {
            inFiles.add(computeFile(rootInFolder, p));
        }
    }

    //Prepare the topicFileMap (this will check that the files exist)
    Map<File, String> topicFileMap = new HashMap<>();
    if (inContexts != null) {
        for (HelpContext hc : inContexts) {
            if (hc.getTopicPages() != null) {
                for (String p : hc.getTopicPages()) {
                    topicFileMap.put(computeFile(rootInFolder, p), null);
                }
            }
        }
    }

    Map<Integer, OutlineItemEx> nodeMap = new HashMap<Integer, OutlineItemEx>();
    for (int i = 0; i < inFiles.size(); i++) {
        File inFile = inFiles.get(i);

        String html = Files.toString(inFile, Charsets.UTF_8);
        String filePath = calculateFilePath(rootInFolder, inFile);
        Document doc = Jsoup.parse(html);

        computeOutlineNodes(nodeMap, doc, filePath);

        if (topicFileMap.containsKey(inFile)) {
            topicFileMap.put(inFile, findFirstHeader(doc));
        }
    }

    //Loop over the topicFileMap and verify that all values are set.
    for (File inFile : topicFileMap.keySet()) {
        if (topicFileMap.get(inFile) == null) {
            String html = Files.toString(inFile, Charsets.UTF_8);
            Document doc = Jsoup.parse(html);
            topicFileMap.put(inFile, findFirstHeader(doc));
        }
    }

    OutlineItemEx root = nodeMap.get(ROOT_LEVEL);
    if (root == null) {
        throw new IllegalStateException("No header found in the html files");
    }

    //Compute Toc File and write it
    MarkupToEclipseToc eclipseToc = new MarkupToEclipseToc() {
        @Override
        protected String computeFile(OutlineItem item) {
            if (item instanceof OutlineItemEx && ((OutlineItemEx) item).getFilePath() != null) {
                return ((OutlineItemEx) item).getFilePath();
            }
            return super.computeFile(item);
        }
    };
    eclipseToc.setBookTitle(root.getLabel());
    eclipseToc.setHtmlFile(root.getFilePath());
    eclipseToc.setHelpPrefix(helpPrefix);
    String tocContent = eclipseToc.createToc(root);
    Files.createParentDirs(outTocFile);
    Files.write(tocContent, outTocFile, Charsets.UTF_8);

    //Compute Contexts File and write it
    if (inContexts != null && inContexts.size() > 0) {
        List<Context> outContexts = computeContexts(rootInFolder, helpPrefix, inContexts, topicFileMap);
        String contextsContent = ContextUtility.toXml(outContexts);
        Files.createParentDirs(outContextsFile);
        Files.write(contextsContent, outContextsFile, Charsets.UTF_8);
    }
}

From source file:eu.numberfour.n4js.antlr.delimiters.DebugAntlrGeneratorFragment.java

@SuppressWarnings("resource")
private void prettyPrint(String absoluteGrammarFileName, String encoding) {
    try {/*from  w  ww  .  j  a v a 2s .co  m*/
        String content = Files.toString(new File(absoluteGrammarFileName), Charset.forName(encoding));
        final ILineSeparatorInformation unixLineSeparatorInformation = new ILineSeparatorInformation() {
            @Override
            public String getLineSeparator() {
                return NewlineNormalizer.UNIX_LINE_DELIMITER;
            }
        };
        Injector injector = new SimpleAntlrStandaloneSetup() {
            @Override
            public Injector createInjector() {
                return Guice.createInjector(new SimpleAntlrRuntimeModule() {
                    @Override
                    public void configure(Binder binder) {
                        super.configure(binder);
                        binder.bind(ILineSeparatorInformation.class).toInstance(unixLineSeparatorInformation);
                    }

                    @Override
                    public Class<? extends IFormatter> bindIFormatter() {
                        return PlatformIndependantFormatter.class;
                    }
                });
            }
        }.createInjectorAndDoEMFRegistration();
        XtextResource resource = injector.getInstance(XtextResource.class);
        resource.setURI(URI.createFileURI(absoluteGrammarFileName));

        // no need to close StringInputStream since it doesn't allocate resources
        resource.load(new StringInputStream(content, encoding),
                Collections.singletonMap(XtextResource.OPTION_ENCODING, encoding));
        if (!resource.getErrors().isEmpty()) {
            throw new RuntimeException(resource.getErrors().toString());
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(content.length());
        resource.save(outputStream, SaveOptions.newBuilder().format().getOptions().toOptionsMap());
        String postprocessContent = new NewlineNormalizer()
                .toUnixLineDelimiter(new String(outputStream.toByteArray(), encoding));
        Files.write(postprocessContent, new File(absoluteGrammarFileName), Charset.forName(encoding));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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

public JavaagentContainer(@Nullable File dataDir, boolean useFileDb, int port, boolean shared,
        boolean captureConsoleOutput, boolean viewerMode, List<String> extraJvmArgs) throws Exception {
    if (dataDir == null) {
        this.dataDir = TempDirs.createTempDir("glowroot-test-datadir");
        deleteDataDirOnClose = true;//from www .j  av a 2s.c o m
    } else {
        this.dataDir = dataDir;
        deleteDataDirOnClose = false;
    }
    this.shared = shared;
    // need to start socket listener before spawning process so process can connect to socket
    serverSocket = new ServerSocket(0);
    File configFile = new File(this.dataDir, "config.json");
    if (!configFile.exists()) {
        Files.write("{\"ui\":{\"port\":" + port + "}}", configFile, Charsets.UTF_8);
    }
    List<String> command = buildCommand(serverSocket.getLocalPort(), this.dataDir, useFileDb, viewerMode,
            extraJvmArgs);
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.redirectErrorStream(true);
    final Process process = processBuilder.start();
    consolePipeExecutorService = Executors.newSingleThreadExecutor();
    InputStream in = process.getInputStream();
    // process.getInputStream() only returns null if ProcessBuilder.redirectOutput() is used
    // to redirect output to a file
    checkNotNull(in);
    consoleOutputPipe = new ConsoleOutputPipe(in, System.out, captureConsoleOutput);
    consolePipeExecutorService.submit(consoleOutputPipe);
    this.process = process;
    Socket socket = serverSocket.accept();
    ObjectOutputStream objectOut = new ObjectOutputStream(socket.getOutputStream());
    ObjectInputStream objectIn = new ObjectInputStream(socket.getInputStream());
    final SocketCommander socketCommander = new SocketCommander(objectOut, objectIn);
    int uiPort;
    try {
        uiPort = getUiPort(socketCommander);
    } catch (StartupFailedException e) {
        // clean up and re-throw
        socketCommander.sendCommand(SocketCommandProcessor.SHUTDOWN);
        socketCommander.close();
        process.waitFor();
        serverSocket.close();
        consolePipeExecutorService.shutdownNow();
        throw e;
    }
    httpClient = new HttpClient(uiPort);
    configService = new ConfigService(httpClient, new GetUiPortCommand() {
        @Override
        public int getUiPort() throws Exception {
            return JavaagentContainer.getUiPort(socketCommander);
        }
    });
    traceService = new TraceService(httpClient);
    shutdownHook = new ShutdownHookThread(socketCommander);
    this.socketCommander = socketCommander;
    // unfortunately, ctrl-c during maven test will kill the maven process, but won't kill the
    // forked surefire jvm where the tests are being run
    // (http://jira.codehaus.org/browse/SUREFIRE-413), and so this hook won't get triggered by
    // ctrl-c while running tests under maven
    Runtime.getRuntime().addShutdownHook(shutdownHook);
}

From source file:org.glowroot.agent.webdriver.tests.WebDriverSetup.java

private static WebDriverSetup createSetup(boolean shared) throws Exception {
    int uiPort = getAvailablePort();
    File baseDir = Files.createTempDir();
    File configFile = new File(baseDir, "config.json");
    Files.write("{\"ui\":{\"port\":" + uiPort + "}}", configFile, Charsets.UTF_8);
    Container container;/* w w w.  j  a  va  2s  .  c  o  m*/
    if (Containers.useJavaagent()) {
        container = new JavaagentContainer(baseDir, true, false,
                ImmutableList.of("-Dglowroot.collector.host="));
    } else {
        container = new LocalContainer(baseDir, true, ImmutableMap.of("glowroot.collector.host", ""));
    }
    if (SauceLabs.useSauceLabs()) {
        return new WebDriverSetup(container, uiPort, shared, null, null);
    } else {
        SeleniumServer seleniumServer = new SeleniumServer();
        seleniumServer.start();
        // currently tests fail with default nativeEvents=true
        // (can't select radio buttons on capture point page)
        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability("nativeEvents", false);
        // single webdriver instance for much better performance
        WebDriver driver;
        if (USE_LOCAL_IE) {
            driver = new InternetExplorerDriver(capabilities);
        } else {
            driver = new FirefoxDriver(capabilities);
        }
        // 768 is bootstrap media query breakpoint for screen-sm-min
        // 992 is bootstrap media query breakpoint for screen-md-min
        // 1200 is bootstrap media query breakpoint for screen-lg-min
        driver.manage().window().setSize(new Dimension(1200, 800));
        return new WebDriverSetup(container, uiPort, shared, seleniumServer, driver);
    }
}

From source file:eu.stratosphere.api.java.tuple.TupleGenerator.java

private static void insertCodeIntoFile(String code, File file) throws IOException {
    String fileContent = Files.toString(file, Charsets.UTF_8);
    Scanner s = new Scanner(fileContent);

    StringBuilder sb = new StringBuilder();
    String line = null;//www. j av  a  2s.co m

    boolean indicatorFound = false;

    // add file beginning
    while (s.hasNextLine() && (line = s.nextLine()) != null) {
        sb.append(line + "\n");
        if (line.contains(BEGIN_INDICATOR)) {
            indicatorFound = true;
            break;
        }
    }

    if (!indicatorFound) {
        System.out.println("No indicator found in '" + file + "'. Will skip code generation.");
        s.close();
        return;
    }

    // add generator signature
    sb.append("\t// GENERATED FROM " + TupleGenerator.class.getName() + ".\n");

    // add tuple dependent code
    sb.append(code + "\n");

    // skip generated code
    while (s.hasNextLine() && (line = s.nextLine()) != null) {
        if (line.contains(END_INDICATOR)) {
            sb.append(line + "\n");
            break;
        }
    }

    // add file ending
    while (s.hasNextLine() && (line = s.nextLine()) != null) {
        sb.append(line + "\n");
    }
    s.close();
    Files.write(sb.toString(), file, Charsets.UTF_8);
}