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:org.trancecode.asciidoc.AsciiDoc.java

public static void toXhtml(final File sourceFile, final File targetFile) {
    final long startTime = System.currentTimeMillis();
    final File asciidocExecutable = getAsciiDocExecutable();
    try {//from ww  w . j a  va2 s . c  o m
        final PySystemState sys = new PySystemState();
        sys.argv.clear();
        sys.argv.append(new PyString(getAsciiDocExecutable().getAbsolutePath()));
        sys.argv.append(new PyString("-bxhtml11"));
        sys.argv.append(new PyString("-atoc2"));
        sys.argv.append(new PyString("-apygments"));
        sys.argv.append(new PyString("-o" + targetFile.getAbsolutePath()));
        sys.argv.append(new PyString(sourceFile.getAbsolutePath()));

        final PythonInterpreter python = new PythonInterpreter(null, sys);
        python.set("__file__", asciidocExecutable.getAbsolutePath());
        final String executableContent = Files.toString(asciidocExecutable, Charsets.UTF_8);
        python.exec(executableContent);
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    } finally {
        LOG.trace("{} executed in {} ms", asciidocExecutable, System.currentTimeMillis() - startTime);
    }
}

From source file:com.comphenix.protocol.ProtocolConfig.java

/**
 * Load the last update time stamp from the file system.
 * //from  w w w.j  ava  2 s. c  o  m
 * @return Last update time stamp.
 */
private long loadLastUpdate() {
    File dataFile = getLastUpdateFile();

    if (dataFile.exists()) {
        try {
            return Long.parseLong(Files.toString(dataFile, Charsets.UTF_8));
        } catch (NumberFormatException e) {
            plugin.getLogger().warning("Cannot parse " + dataFile + " as a number.");
        } catch (IOException e) {
            plugin.getLogger().warning("Cannot read " + dataFile);
        }
    }
    // Default last update
    return 0;
}

From source file:com.google.devtools.j2objc.GenerationBatch.java

private void processManifestFile(String filename) {
    if (filename.isEmpty()) {
        ErrorUtil.error("no @ file specified");
        return;/* w  ww .  j  a  v  a  2  s . co  m*/
    }
    File f = new File(filename);
    if (!f.exists()) {
        ErrorUtil.error("no such file: " + filename);
        return;
    }
    try {
        String fileList = Files.toString(f, Options.getCharset());
        if (fileList.isEmpty()) {
            return;
        }
        String[] files = fileList.split("\\s+"); // Split on any whitespace.
        for (String file : files) {
            processSourceFile(file);
        }
    } catch (IOException e) {
        ErrorUtil.error(e.getMessage());
    }
}

From source file:net.osten.watermap.convert.PCTReport.java

/**
 * Parse the PCT water report Google docs files.
 *
 * @return set of water reports//w  w w  . ja v a2 s  .  c om
 */
public synchronized Set<WaterReport> convert() throws IOException {
    Set<WaterReport> results = new HashSet<WaterReport>();

    log.info("dataDir=" + dataDir);

    if (waypoints.size() == 0) {
        log.warning("Waypoints empty, re-initializing...");
        initialize();
    }

    // parse json files
    if (dataDir != null) {
        for (String stateChar : stateChars) {
            for (char sectionChar : sectionChars) {
                try {
                    String fileName = "pct-" + stateChar + "-" + sectionChar + ".json";
                    File jsonFile = new File(dataDir + File.separator + fileName);
                    if (jsonFile.exists() && jsonFile.canRead()) {
                        log.info("reading json file " + jsonFile);
                        String htmlSource = Files.toString(jsonFile, Charset.forName("UTF-8"));
                        JsonParser parser = new JsonParser();
                        JsonElement root = parser.parse(htmlSource);
                        log.info("json root is obj=" + root.isJsonObject());
                        results.addAll(parseDocument(root.getAsJsonObject()));
                    }
                } catch (IOException e) {
                    log.severe(e.getLocalizedMessage());
                }
            }
        }
    }

    return results;
}

From source file:scoutdoc.main.converter.ScoutDocConverter.java

public void execute(Task t) throws IOException {
    Preconditions.checkArgument(t.getInputPages().size() > 0, "InputPages needs to contain at least one page");

    MediaWikiLanguageExt markupLanguage = new MediaWikiLanguageExt();

    markupLanguage.getTemplateProviders().add(new IgnoreTemplateProvider("ScoutPage")); //Could also use: markupLanguage.setTemplateExcludes("ScoutPage")
    markupLanguage.getTemplateProviders().add(new PagesTemplateProvider());
    markupLanguage.setInternalLinkPattern(ProjectProperties.getWikiServerInternalLinkPattern());

    MarkupParser markupParser = new MarkupParser();
    markupParser.setMarkupLanguage(markupLanguage);

    List<ConversionItem> items = new ArrayList<ConversionItem>();
    ConversionItem firstItem = new ConversionItem();
    firstItem.inputPage = Pages.normalize(t.getInputPages().get(0));
    firstItem.outputFileName = "index.html";
    firstItem.outputTitle = t.getOutputTitle();
    firstItem.includeToc = t.getInputPages().size() > 1;
    firstItem.firstLevel = true;//w  w w. java 2  s.  co m
    items.add(firstItem);

    for (int i = 1; i < t.getInputPages().size(); i++) {
        Page p = Pages.normalize(t.getInputPages().get(i));
        ConversionItem item = new ConversionItem();
        item.inputPage = p;
        item.outputFileName = String.format("%02d", i) + "_" + PageUtility.toBasePageNamee(p).toLowerCase()
                + ".html";
        item.outputTitle = PageUtility.toBasePageName(p);
        item.includeToc = true;
        item.firstLevel = false;
        items.add(item);
    }

    markupLanguage.setPageMapping(new PageMapper(items));

    OutlineParser outlineParser = new OutlineParser();
    outlineParser.setMarkupLanguage(markupLanguage);

    OutlineItem rootItem = outlineParser.createRootItem();
    OutlineItem firstLevel = rootItem;

    for (int j = 0; j < items.size(); j++) {
        ConversionItem item = items.get(j);

        System.out.println("============");
        System.out.println("Page: " + item.inputPage.getName());
        System.out.println("outputFileName: " + item.outputFileName);

        item.inputContent = Files.toString(new File(PageUtility.toFilePath(item.inputPage)), CHARSET);

        item.outputFile = new File(ProjectProperties.getFolderWikiDist() + ProjectProperties.getFileSeparator()
                + t.getOutputFolder() + ProjectProperties.getFileSeparator() + item.outputFileName);
        Files.createParentDirs(item.outputFile);
        System.out.println("outputFile: " + item.outputFile);

        File apiFile = PageUtility.toApiFile(item.inputPage);
        Collection<Page> images = ApiFileUtility.parseImages(apiFile);

        StringWriter out = new StringWriter();
        HtmlDocumentBuilderExt htmlDocumentBuilder = new HtmlDocumentBuilderExt(out);
        htmlDocumentBuilder.setPrependImagePrefix(ProjectProperties.getRelPathNavImagesDist());
        htmlDocumentBuilder.setDefaultAbsoluteLinkTarget("doc_external");
        htmlDocumentBuilder.setItems(items);
        htmlDocumentBuilder.setCurrentItemIndex(j);

        markupParser.setBuilder(htmlDocumentBuilder);

        markupLanguage.setPageName(item.inputPage.getName());
        Set<String> imageNames = new HashSet<String>();
        for (Page image : images) {
            imageNames.add(PageUtility.toPageNamee(image));
        }
        markupLanguage.setImageNames(imageNames);

        markupParser.parse(item.inputContent);

        String htmlContent = out.toString();
        Files.write(htmlContent, item.outputFile, CHARSET);

        if (item.includeToc) {
            item.outlineItem = computeOutline(outlineParser, item);
            if (item.firstLevel) {
                rootItem.getChildren().add(item.outlineItem);
                firstLevel = item.outlineItem;
            } else {
                firstLevel.getChildren().add(item.outlineItem);
            }
        } else {
            item.outlineItem = new OutlineItem(rootItem, 1, "id", 1, 1, item.outputTitle);
            item.outlineItem.setResourcePath(item.outputFile.getAbsolutePath());
            if (item.firstLevel) {
                firstLevel = item.outlineItem;
            }
        }

        File toFolder = computeImagesFolder(t);
        for (Page image : images) {
            File imageFile = PageUtility.toImageFile(image);
            if (imageFile.exists()) {
                Files.copy(imageFile, new File(toFolder, PageUtility.convertToInternalName(image.getName())));
            } else {
                System.err.println("Requested imageFile does not exist. Page: " + image.toString());
            }

        }
    }

    MarkupToEclipseToc eclipseToc = new MarkupToEclipseToc() {
        @Override
        protected String computeFile(OutlineItem item) {
            if (item != null && item.getResourcePath() != null) {
                return tail(item.getResourcePath(), ProjectProperties.getFileSeparator());
            }
            return super.computeFile(item);
        }
    };
    eclipseToc.setBookTitle(t.getOutputTitle());
    eclipseToc.setHelpPrefix(CharMatcher.anyOf(String.valueOf(ProjectProperties.getFileSeparator()))
            .replaceFrom(t.getOutputFolder(), "/"));
    eclipseToc.setHtmlFile("index.html");
    String tocContent = eclipseToc.createToc(rootItem);

    File tocOutputFile = new File(ProjectProperties.getFolderWikiDist() + ProjectProperties.getFileSeparator()
            + t.getOutputTocFile());
    Files.write(tocContent, tocOutputFile, CHARSET);

    //If more than one page, copy navigation images.
    if (t.getInputPages().size() > 1) {
        File fromFolder = new File(ProjectProperties.getFolderNavImagesSource());
        File toFolder = computeImagesFolder(t);
        Files.copy(new File(fromFolder, ProjectProperties.IMAGE_HOME),
                new File(toFolder, ProjectProperties.IMAGE_HOME));
        Files.copy(new File(fromFolder, ProjectProperties.IMAGE_NEXT),
                new File(toFolder, ProjectProperties.IMAGE_NEXT));
        Files.copy(new File(fromFolder, ProjectProperties.IMAGE_PREV),
                new File(toFolder, ProjectProperties.IMAGE_PREV));
    }
}

From source file:org.eclipse.andmore.ddms.systrace.SystraceOutputParser.java

public static String getCss(File assetsFolder) {
    try {//w w  w . j  a va  2  s.c o m
        return String.format("<style type=\"text/css\">%s</style>",
                Files.toString(new File(assetsFolder, "style.css"), Charsets.UTF_8));
    } catch (IOException e) {
        return "";
    }
}

From source file:org.ftc.opmodes.xNetworkAnalyzer.java

@Override
public void init(RobotContext ctx) throws Exception {
    wifiChannelMap = HashBiMap.create();
    wifiChannelMap.put(2412, "2.4G Ch1");
    wifiChannelMap.put(2417, "2.4G Ch2");
    wifiChannelMap.put(2422, "2.4G Ch3");
    wifiChannelMap.put(2427, "2.4G Ch4");
    wifiChannelMap.put(2432, "2.4G Ch5");
    wifiChannelMap.put(2437, "2.4G Ch6");
    wifiChannelMap.put(2442, "2.4G Ch7");
    wifiChannelMap.put(2447, "2.4G Ch8");
    wifiChannelMap.put(2452, "2.4G Ch9");
    wifiChannelMap.put(2457, "2.4G Ch10");
    wifiChannelMap.put(2462, "2.4G Ch11");
    wifiChannelMap.put(2467, "2.4G Ch12");
    wifiChannelMap.put(2472, "2.4G Ch13");
    wifiChannelMap.put(2484, "2.4G Ch14");

    wifi = (WifiManager) appContext().getSystemService(Context.WIFI_SERVICE);
    appContext().registerReceiver(new BroadcastReceiver() {
        @Override/*w ww .  j  ava 2 s .  c o m*/
        public void onReceive(Context context, Intent intent) {
            LinkedList<ScanResult> results = new LinkedList<>(wifi.getScanResults());
            scanResults(results);
        }
    }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

    wifi.startScan();

    try {
        String absolutePath = appContext().getFilesDir().getAbsolutePath() + "/";
        RunShellCommand cmd = new RunShellCommand();
        String output;
        if ((output = cmd.run(
                String.format("cp /data/misc/wifi/p2p_supplicant.conf %sp2p_supplicant.conf \n", absolutePath)))
                        .length() > 0) {
            log().e(this.getClass().getSimpleName(), "Cannot copy p2p file" + output);
            operChannel = output;
        }

        String fileData = Files.toString(new File(absolutePath + "p2p_supplicant.conf"),
                Charset.defaultCharset());
        String[] datas = fileData.split("/n");
        for (String data : datas) {
            if (data.contains("p2p_oper_channel")) {
                operChannel = data.substring(data.indexOf("="));
            }
        }
    } catch (FileNotFoundException ex) {
        if (operChannel.equals("")) {
            operChannel = ex.getMessage();
        }
    }
}

From source file:net.minecraftforge.gradle.user.TaskSourceCopy.java

@SuppressWarnings("unchecked")
@TaskAction/*from   www .  ja  v  a2  s.c o m*/
public void doTask() throws IOException {
    // get the include/exclude patterns from the source (this is different than what's returned by getFilter)
    PatternSet patterns = new PatternSet();
    patterns.setIncludes(source.getIncludes());
    patterns.setExcludes(source.getExcludes());

    // get output
    File out = getOutput();
    if (out.exists())
        deleteDir(out);

    out.mkdirs();
    out = out.getCanonicalFile();

    // resolve replacements
    HashMap<String, String> repl = new HashMap<String, String>(replacements.size());
    for (Entry<String, Object> e : replacements.entrySet()) {
        if (e.getKey() == null || e.getValue() == null)
            continue; // we dont deal with nulls.

        Object val = e.getValue();
        while (val instanceof Closure)
            val = ((Closure<Object>) val).call();

        repl.put(Pattern.quote(e.getKey()), val.toString());
    }

    getLogger().debug("REPLACE >> " + repl);

    // start traversing tree
    for (DirectoryTree dirTree : source.getSrcDirTrees()) {
        File dir = dirTree.getDir();
        getLogger().debug("PARSING DIR >> " + dir);

        // handle nonexistant srcDirs
        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
        FileTree tree = getProject().fileTree(dir).matching(source.getFilter()).matching(patterns);

        for (File file : tree) {
            File dest = getDest(file, dir, out);
            dest.getParentFile().mkdirs();
            dest.createNewFile();

            if (isIncluded(file)) {
                getLogger().debug("PARSING FILE IN >> " + file);
                String text = Files.toString(file, Charsets.UTF_8);

                for (Entry<String, String> entry : repl.entrySet())
                    text = text.replaceAll(entry.getKey(), entry.getValue());

                getLogger().debug("PARSING FILE OUT >> " + dest);
                Files.write(text, dest, Charsets.UTF_8);
            } else {
                Files.copy(file, dest);
            }
        }
    }
}

From source file:org.apache.aurora.scheduler.SchedulerModule.java

private static Optional<String> readTierFile() {
    if (TIER_CONFIG_FILE.hasAppliedValue()) {
        try {//www.jav  a  2 s  .com
            return Optional.of(Files.toString(TIER_CONFIG_FILE.get(), StandardCharsets.UTF_8));
        } catch (IOException e) {
            LOG.error("Error loading tier configuration file.");
            throw Throwables.propagate(e);
        }
    }

    return Optional.<String>absent();
}

From source file:org.apache.s4.fixtures.CommTestUtils.java

public static String readFile(File f) throws IOException {
    return Files.toString(f, Charset.defaultCharset());

}