Example usage for com.google.common.io Files toString

List of usage examples for com.google.common.io Files toString

Introduction

In this page you can find the example usage for com.google.common.io Files toString.

Prototype

public static String toString(File file, Charset charset) throws IOException 

Source Link

Usage

From source file:ninja.miserable.blossom.task.SourceReplacementTask.java

/**
 * Perform the source replacement task.//from   w ww  . jav a 2 s  . com
 *
 * @throws IOException
 */
@TaskAction
public void run() throws IOException {
    final PatternSet patternSet = new PatternSet();
    patternSet.setIncludes(this.input.getIncludes());
    patternSet.setExcludes(this.input.getExcludes());

    if (this.output.exists()) {
        // Remove the output directory if it exists to prevent any possible conflicts
        FileUtil.deleteDirectory(this.output);
    }

    this.output.mkdirs();
    this.output = this.output.getCanonicalFile();

    // Resolve global and by-file replacements
    final Map<String, String> globalReplacements = this.resolveReplacementsGlobal();
    final Multimap<String, Map<String, String>> fileReplacements = this.resolveReplacementsByFile();

    for (final DirectoryTree dirTree : this.input.getSrcDirTrees()) {
        File dir = dirTree.getDir();

        // handle non-existent source directories
        if (!dir.exists() || !dir.isDirectory()) {
            continue;
        } else {
            dir = dir.getCanonicalFile();
        }

        // this could be written as .matching(source), but it doesn't actually work
        // because later on gradle casts it directly to PatternSet and crashes
        final FileTree tree = this.getProject().fileTree(dir).matching(this.input.getFilter())
                .matching(patternSet);

        for (final File file : tree) {
            final File destination = getDestination(file, dir, this.output);
            destination.getParentFile().mkdirs();
            destination.createNewFile();

            boolean wasChanged = false;
            String text = Files.toString(file, Charsets.UTF_8);

            if (this.isIncluded(file)) {
                for (Map.Entry<String, String> entry : globalReplacements.entrySet()) {
                    text = text.replaceAll(entry.getKey(), entry.getValue());
                }

                wasChanged = true;
            }

            final String path = this.getFilePath(file);
            Collection<Map<String, String>> collection = fileReplacements.get(path);
            if (collection != null && !collection.isEmpty()) {
                for (Map<String, String> map : collection) {
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        text = text.replaceAll(entry.getKey(), entry.getValue());
                    }
                }

                wasChanged = true;
            }

            if (wasChanged) {
                Files.write(text, destination, Charsets.UTF_8);
            } else {
                Files.copy(file, destination);
            }
        }
    }
}

From source file:com.android.idegen.IntellijProject.java

private void createModulesFile(File ideaDir, Iterable<Module> modules) throws IOException {
    String modulesContent = Files.toString(
            new File(DirectorySearch.findTemplateDir(), "idea" + File.separator + MODULES_TEMPLATE_FILE_NAME),
            CHARSET);/*from  w w w  .j av a2s. c o  m*/
    StringBuilder sb = new StringBuilder();
    for (Module mod : modules) {
        File iml = mod.getImlFile();
        sb.append("      <module fileurl=\"file://").append(iml.getCanonicalPath()).append("\" filepath=\"")
                .append(iml.getCanonicalPath()).append("\" />\n");
    }
    modulesContent = modulesContent.replace("@MODULES@", sb.toString());

    File out = new File(ideaDir, "modules.xml");
    logger.info("Creating " + out.getCanonicalPath());
    Files.write(modulesContent, out, CHARSET);
}

From source file:com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewList.java

void load(File file, List<Device> deviceList) throws IOException {
    mList.clear();/*from  w  w  w . j  a v  a 2 s. co  m*/

    String xml = Files.toString(file, Charsets.UTF_8);
    Document document = DomUtilities.parseDocument(xml, true);
    if (document == null || document.getDocumentElement() == null) {
        return;
    }
    List<Element> elements = DomUtilities.getChildren(document.getDocumentElement());
    for (Element element : elements) {
        ConfigurationDescription description = ConfigurationDescription.fromXml(mProject, element, deviceList);
        if (description != null) {
            mList.add(description);
        }
    }
}

From source file:com.facebook.buck.cli.QuickstartCommand.java

/**
 * Runs the command "buck quickstart", which copies a template project into a new directory to
 * give the user a functional buck project. It copies from
 * src/com/facebook/buck/cli/quickstart/android to the directory specified. It then asks the user
 * for the location of the Android SDK so Buck cansuccessfully build the quickstart project. It
 * will fail if it cannot find the template directory or if it is unable to write to the
 * destination directory.//  w w  w.  jav  a 2 s . c  o  m
 *
 * @param options an object representing command line options
 * @return status code - zero means no problem
 * @throws IOException if the command fails to read from the template project or write to the
 *     new project
 */
@Override
int runCommandWithOptionsInternal(QuickstartCommandOptions options) throws IOException {
    String projectDir = options.getDestDir().trim();
    if (projectDir.isEmpty()) {
        projectDir = promptForPath("Enter the directory where you would like to create the " + "project: ");
    }

    File dir = new File(projectDir);
    while (!dir.isDirectory() && !dir.mkdirs() && !projectDir.isEmpty()) {
        projectDir = promptForPath("Cannot create project directory. Enter another directory: ");
        dir = new File(projectDir);
    }
    if (projectDir.isEmpty()) {
        getStdErr().println("No project directory specified. Aborting quickstart.");
        return 1;
    }

    String sdkLocation = options.getAndroidSdkDir();
    if (sdkLocation.isEmpty()) {
        sdkLocation = promptForPath("Enter your Android SDK's location: ");
    }

    File sdkLocationFile = new File(sdkLocation);
    if (!sdkLocationFile.isDirectory()) {
        getStdErr().println("WARNING: That Android SDK directory does not exist.");
    }

    sdkLocation = sdkLocationFile.getAbsoluteFile().toString();

    Path origin = PATH_TO_QUICKSTART_DIR;
    Path destination = Paths.get(projectDir);
    MoreFiles.copyRecursively(origin, destination);

    File out = new File(projectDir + "/local.properties");
    Files.write("sdk.dir=" + sdkLocation + "\n", out, StandardCharsets.UTF_8);

    getStdOut().print(Files.toString(origin.resolve("README.md").toFile(), StandardCharsets.UTF_8));
    getStdOut().flush();

    return 0;
}

From source file:org.jboss.maven.plugins.qstools.fixers.JavaSourcesFormatFixer.java

@SuppressWarnings("unchecked")
@Override//from   www  .ja  v  a  2s .  c  o m
public void fixProject(MavenProject project, Document doc) throws Exception {
    Rules rules = getConfigurationProvider().getQuickstartsRules(project.getGroupId());
    // Read DefaultEclipseSettings
    Map<String, String> options = DefaultCodeFormatterConstants.getEclipseDefaultSettings();

    // initialize the compiler settings to be able to format 1.6 code
    String compilerSource = rules.getExpectedCompilerSource();
    options.put(JavaCore.COMPILER_COMPLIANCE, compilerSource);
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, compilerSource);
    options.put(JavaCore.COMPILER_SOURCE, compilerSource);

    // Configure CodeFormatter with Eclipse XML Formatter Profile
    InputStream xmlInputStream = resources
            .getExpirationalFileInputStream(new URL(rules.getEclipseFormatterProfileLocation()));
    Document formatterSettingsDoc = PositionalXMLReader.readXML(xmlInputStream);
    NodeList settingsNodes = formatterSettingsDoc.getElementsByTagName("setting");
    for (int i = 0; i < settingsNodes.getLength(); i++) {
        Node node = settingsNodes.item(i);
        String id = node.getAttributes().getNamedItem("id").getTextContent();
        String value = node.getAttributes().getNamedItem("value").getTextContent();
        options.put(id, value);
    }

    // Instantiate the default code formatter with the given options
    CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options);

    // Apply the formatter to every Java source under the project's folder
    List<File> javaSources = FileUtils.getFiles(project.getBasedir(), "**/*.java", "");
    for (File javaSource : javaSources) {
        getLog().debug("Formating " + javaSource);
        String source = Files.toString(javaSource, Charset.forName("UTF-8"));
        TextEdit edit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, // format a compilation unit
                source, // source to format
                0, // starting position
                source.length(), // length
                0, // initial indentation
                System.getProperty("line.separator") // line separator
        );

        IDocument document = new org.eclipse.jface.text.Document(source);
        edit.apply(document);
        Files.write(document.get(), javaSource, Charset.forName("UTF-8"));
    }
}

From source file:com.qualinsight.plugins.sonarqube.smell.plugin.extension.SmellMeasurer.java

private static String getFileAsString(final File file, final Charset charset) {
    try {/*from  w ww .ja  v a2 s  .c  o m*/
        return Files.toString(file, charset);
    } catch (final IOException e) {
        LOGGER.warn("A problem occured while reading file.", e);
        return EMPTY_FILE_CONTENT;
    }
}

From source file:org.arbeitspferde.groningen.utility.Process.java

/**
 * @param processId the PID of the target process.
 * @return the {@class ProcessInfo} instance or {@code null} if process information can not be
 *         obtained./*w  ww  .  ja  va 2s.c  om*/
 */
public static final ProcessInfo getProcessInfo(int processId) {
    File statStream = null;
    ProcessInfo info = null;
    FileReader statReader = null;
    BufferedReader statDataReader = null;
    try {
        statStream = new File("/proc/" + Integer.toString(processId) + "/stat");
        statReader = new FileReader(statStream);
        statDataReader = new BufferedReader(statReader);
    } catch (FileNotFoundException e) {
        log.log(Level.WARNING, "PID file doesn't exist: " + "/proc/" + Integer.toString(processId) + "/stat");
        return info;
    }
    try {
        String line = statDataReader.readLine();
        Matcher matcher = STAT_FILE_FORMAT.matcher(line);
        if (matcher.find()) {
            String commandLine = Files.toString(new File("/proc/" + Integer.toString(processId) + "/cmdline"),
                    StandardCharsets.UTF_8);
            // TODO(drk): read the start time from the stat file.
            info = new ProcessInfo(processId, Integer.parseInt(matcher.group(4)),
                    statStream.lastModified() / 1000, commandLine);
        }
    } catch (IOException e) {
        log.log(Level.WARNING, "Error reading the stream: " + e);
    } finally {
        try {
            statReader.close();
            statDataReader.close();
        } catch (IOException e) {
            log.log(Level.WARNING, "Cannot close the stream");
        }
    }
    return info;
}

From source file:com.bsiag.htmltools.internal.PublishUtility.java

/**
 * Take a single HTML file and publish it to the outFolder.
 * Images and CSS resources are moved, HTML is formatted.
 *
 * @param inFolder/*from   w  w w .  ja va2  s. co  m*/
 *          root folder where the input HTML file is located.
 * @param outFolder
 *          directory where the post-processed HTML file is saved.
 * @param cssReplacement
 * @param pageList
 * @param root
 * @param fixXrefLinks
 *          tells if the cross references links should be fixed as described here
 *          https://github.com/asciidoctor/asciidoctor/issues/858
 * @param fixExternalLinks
 *          add taget="_blank" on links starting with http(s):// or ftp://
 * @throws IOException
 */
private static void publishHtmlFile(File inFolder, File inFile, File outFolder,
        Map<String, File> cssReplacement, List<File> pageList, RootItem root, boolean fixXrefLinks,
        boolean fixExternalLinks) throws IOException {
    File outFile = new File(outFolder, inFile.getName());
    String html = Files.toString(inFile, Charsets.UTF_8);

    Document doc = Jsoup.parse(html);
    doc.outputSettings().charset("ASCII");

    if (pageList != null && pageList.size() > 1) {
        fixNavigation(doc, inFile, pageList, root);
    }

    if (fixXrefLinks) {
        fixListingLink(doc);
        fixFigureLink(doc);
        fixTableLink(doc);
    }

    if (fixExternalLinks) {
        fixExternalLinks(doc);
    }

    Files.createParentDirs(outFile);
    moveAndCopyImages(doc, inFolder, outFolder, IMAGES_SUB_PATH);

    moveAndCopyCss(doc, inFolder, outFolder, CSS_SUB_PATH, cssReplacement);

    String content = trimTrailingWhitespaces(doc.toString());
    Files.write(content, outFile, Charsets.UTF_8);
}

From source file:org.eclipse.andmore.internal.editors.layout.gle2.RenderPreviewList.java

void load(File file, Collection<Device> deviceList) throws IOException {
    mList.clear();//from   w ww.j a  v a2s.c o  m

    String xml = Files.toString(file, Charsets.UTF_8);
    Document document = DomUtilities.parseDocument(xml, true);
    if (document == null || document.getDocumentElement() == null) {
        return;
    }
    List<Element> elements = DomUtilities.getChildren(document.getDocumentElement());
    for (Element element : elements) {
        ConfigurationDescription description = ConfigurationDescription.fromXml(mProject, element, deviceList);
        if (description != null) {
            mList.add(description);
        }
    }
}

From source file:io.prestosql.cli.Console.java

public boolean run() {
    ClientSession session = clientOptions.toClientSession();
    boolean hasQuery = !isNullOrEmpty(clientOptions.execute);
    boolean isFromFile = !isNullOrEmpty(clientOptions.file);

    if (!hasQuery && !isFromFile) {
        AnsiConsole.systemInstall();/*from   w  ww .j a va  2  s .  com*/
    }

    initializeLogging(clientOptions.logLevelsFile);

    String query = clientOptions.execute;
    if (hasQuery) {
        query += ";";
    }

    if (isFromFile) {
        if (hasQuery) {
            throw new RuntimeException("both --execute and --file specified");
        }
        try {
            query = Files.toString(new File(clientOptions.file), UTF_8);
            hasQuery = true;
        } catch (IOException e) {
            throw new RuntimeException(
                    format("Error reading from file %s: %s", clientOptions.file, e.getMessage()));
        }
    }

    // abort any running query if the CLI is terminated
    AtomicBoolean exiting = new AtomicBoolean();
    ThreadInterruptor interruptor = new ThreadInterruptor();
    CountDownLatch exited = new CountDownLatch(1);
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        exiting.set(true);
        interruptor.interrupt();
        awaitUninterruptibly(exited, EXIT_DELAY.toMillis(), MILLISECONDS);
    }));

    try (QueryRunner queryRunner = new QueryRunner(session, clientOptions.debug,
            Optional.ofNullable(clientOptions.socksProxy), Optional.ofNullable(clientOptions.httpProxy),
            Optional.ofNullable(clientOptions.keystorePath),
            Optional.ofNullable(clientOptions.keystorePassword),
            Optional.ofNullable(clientOptions.truststorePath),
            Optional.ofNullable(clientOptions.truststorePassword),
            Optional.ofNullable(clientOptions.accessToken), Optional.ofNullable(clientOptions.user),
            clientOptions.password ? Optional.of(getPassword()) : Optional.empty(),
            Optional.ofNullable(clientOptions.krb5Principal),
            Optional.ofNullable(clientOptions.krb5RemoteServiceName),
            Optional.ofNullable(clientOptions.krb5ConfigPath),
            Optional.ofNullable(clientOptions.krb5KeytabPath),
            Optional.ofNullable(clientOptions.krb5CredentialCachePath),
            !clientOptions.krb5DisableRemoteServiceHostnameCanonicalization)) {
        if (hasQuery) {
            return executeCommand(queryRunner, query, clientOptions.outputFormat, clientOptions.ignoreErrors,
                    clientOptions.progress);
        }

        runConsole(queryRunner, exiting);
        return true;
    } finally {
        exited.countDown();
        interruptor.close();
    }
}