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.jooby.internal.ssl.PemReader.java

static List<ByteBuffer> readCertificates(final File file) throws CertificateException, IOException {
    String content = Files.toString(file, StandardCharsets.US_ASCII);

    BaseEncoding base64 = base64();//ww w  . jav  a2  s .  com
    List<ByteBuffer> certs = new ArrayList<ByteBuffer>();
    Matcher m = CERT_PATTERN.matcher(content);
    int start = 0;
    while (m.find(start)) {
        ByteBuffer buffer = ByteBuffer.wrap(base64.decode(m.group(1)));
        certs.add(buffer);

        start = m.end();
    }

    if (certs.isEmpty()) {
        throw new CertificateException("found no certificates: " + file);
    }

    return certs;
}

From source file:com.google.devtools.build.android.ResourceShrinker.java

/**
 * Remove resources (already identified by {@link #shrink(Path)}).
 *
 * <p>This task will copy all remaining used resources over from the full resource directory to a
 * new reduced resource directory. However, it can't just delete the resources, because it has no
 * way to tell aapt to continue to use the same id's for the resources. When we re-run aapt on the
 * stripped resource directory, it will assign new id's to some of the resources (to fill the
 * gaps) which means the resource id's no longer match the constants compiled into the dex files,
 * and as a result, the app crashes at runtime. <p> Therefore, it needs to preserve all id's by
 * actually keeping all the resource names. It can still save a lot of space by making these
 * resources tiny; e.g. all strings are set to empty, all styles, arrays and plurals are set to
 * not contain any children, and most importantly, all file based resources like bitmaps and
 * layouts are replaced by simple resource aliases which just point to @null.
 *
 * @param destination directory to copy resources into; if null, delete resources in place
 *//*  ww  w.  j a v a2s .  c o  m*/
private void removeUnused(Path destination) throws IOException, ParserConfigurationException, SAXException {
    assert unused != null; // should always call analyze() first
    int resourceCount = unused.size() * 4; // *4: account for some resource folder repetition
    Set<File> skip = Sets.newHashSetWithExpectedSize(resourceCount);
    Set<File> rewrite = Sets.newHashSetWithExpectedSize(resourceCount);
    for (Resource resource : unused) {
        if (resource.declarations != null) {
            for (File file : resource.declarations) {
                String folder = file.getParentFile().getName();
                ResourceFolderType folderType = ResourceFolderType.getFolderType(folder);
                if (folderType != null && folderType != ResourceFolderType.VALUES) {
                    logger.fine("Deleted unused resource " + file);
                    assert skip != null;
                    skip.add(file);
                } else {
                    // Can't delete values immediately; there can be many resources
                    // in this file, so we have to process them all
                    rewrite.add(file);
                }
            }
        }
    }
    // Special case the base values.xml folder
    File values = new File(mergedResourceDir.toFile(), FD_RES_VALUES + File.separatorChar + "values.xml");
    boolean valuesExists = values.exists();
    if (valuesExists) {
        rewrite.add(values);
    }
    Map<File, String> rewritten = Maps.newHashMapWithExpectedSize(rewrite.size());
    // Delete value resources: Must rewrite the XML files
    for (File file : rewrite) {
        String xml = Files.toString(file, UTF_8);
        Document document = XmlUtils.parseDocument(xml, true);
        Element root = document.getDocumentElement();
        if (root != null && TAG_RESOURCES.equals(root.getTagName())) {
            List<String> removed = Lists.newArrayList();
            stripUnused(root, removed);
            logger.info("Removed " + removed.size() + " unused resources from " + file + ":\n  "
                    + Joiner.on(", ").join(removed));
            String formatted = XmlPrettyPrinter.prettyPrint(document, xml.endsWith("\n"));
            rewritten.put(file, formatted);
        }
    }
    if (valuesExists) {
        String xml = rewritten.get(values);
        if (xml == null) {
            xml = Files.toString(values, UTF_8);
        }
        Document document = XmlUtils.parseDocument(xml, true);
        Element root = document.getDocumentElement();
        for (Resource resource : resources) {
            if (resource.type == ResourceType.ID && !resource.hasDefault) {
                Element item = document.createElement(TAG_ITEM);
                item.setAttribute(ATTR_TYPE, resource.type.getName());
                item.setAttribute(ATTR_NAME, resource.name);
                root.appendChild(item);
            } else if (!resource.reachable && !resource.hasDefault
                    && resource.type != ResourceType.DECLARE_STYLEABLE && resource.type != ResourceType.STYLE
                    && resource.type != ResourceType.PLURALS && resource.type != ResourceType.ARRAY
                    && resource.isRelevantType()) {
                Element item = document.createElement(TAG_ITEM);
                item.setAttribute(ATTR_TYPE, resource.type.getName());
                item.setAttribute(ATTR_NAME, resource.name);
                root.appendChild(item);
                String s = "@null";
                item.appendChild(document.createTextNode(s));
            }
        }
        String formatted = XmlPrettyPrinter.prettyPrint(document, xml.endsWith("\n"));
        rewritten.put(values, formatted);
    }
    filteredCopy(mergedResourceDir.toFile(), destination, skip, rewritten);
}

From source file:org.everit.osgi.dev.lqmg.internal.LQMGMetadataExporter.java

private void write(final Serializer serializer, final String path, final EntityType type) throws IOException {
    File targetFile = new File(targetFolder, path);
    classes.add(targetFile.getPath());/*from www .j av a 2 s  . co m*/
    StringWriter w = new StringWriter();
    CodeWriter writer = new JavaWriter(w);
    serializer.serialize(type, SimpleSerializerConfig.DEFAULT, writer);

    // conditional creation
    boolean generate = true;
    byte[] bytes = w.toString().getBytes(sourceEncoding);
    if (targetFile.exists() && (targetFile.length() == bytes.length)) {
        String str = Files.toString(targetFile, Charset.forName(sourceEncoding));
        if (str.equals(w.toString())) {
            generate = false;
        }
    } else {
        targetFile.getParentFile().mkdirs();
    }

    if (generate) {
        Files.write(bytes, targetFile);
    }
}

From source file:google.registry.testing.AppEngineRule.java

@Override
protected void after() {
    // Resets Objectify. Although it would seem more obvious to do this at the start of a request
    // instead of at the end, this is more consistent with what ObjectifyFilter does in real code.
    ObjectifyFilter.complete();/*w ww.j av  a 2s .com*/
    helper.tearDown();
    helper = null;
    // Test that the datastore didn't need any indexes we don't have listed in our index file.
    try {
        Set<String> autoIndexes = getIndexXmlStrings(
                Files.toString(new File(temporaryFolder.getRoot(), "datastore-indexes-auto.xml"), UTF_8));
        Set<String> missingIndexes = Sets.difference(autoIndexes, MANUAL_INDEXES);
        if (!missingIndexes.isEmpty()) {
            assert_().fail("Missing indexes:\n%s", Joiner.on('\n').join(missingIndexes));
        }
    } catch (IOException e) { // This is fine; no indexes were written.
    }
}

From source file:com.hippo.leveldb.impl.VersionSet.java

public void recover() throws IOException {

    // Read "CURRENT" file, which contains a pointer to the current manifest file
    File currentFile = new File(databaseDir, Filename.currentFileName());
    Preconditions.checkState(currentFile.exists(), "CURRENT file does not exist");

    String currentName = Files.toString(currentFile, Charsets.UTF_8);
    if (currentName.isEmpty() || currentName.charAt(currentName.length() - 1) != '\n') {
        throw new IllegalStateException("CURRENT file does not end with newline");
    }/*from w  ww  .j  a v a2s.  c  om*/
    currentName = currentName.substring(0, currentName.length() - 1);

    // open file channel
    FileChannel fileChannel = new FileInputStream(new File(databaseDir, currentName)).getChannel();
    try {

        // read log edit log
        Long nextFileNumber = null;
        Long lastSequence = null;
        Long logNumber = null;
        Long prevLogNumber = null;
        Builder builder = new Builder(this, current);

        LogReader reader = new LogReader(fileChannel, throwExceptionMonitor(), true, 0);
        for (Slice record = reader.readRecord(); record != null; record = reader.readRecord()) {
            // read version edit
            VersionEdit edit = new VersionEdit(record);

            // verify comparator
            // todo implement user comparator
            String editComparator = edit.getComparatorName();
            String userComparator = internalKeyComparator.name();
            Preconditions.checkArgument(editComparator == null || editComparator.equals(userComparator),
                    "Expected user comparator %s to match existing database comparator ", userComparator,
                    editComparator);

            // apply edit
            builder.apply(edit);

            // save edit values for verification below
            logNumber = coalesce(edit.getLogNumber(), logNumber);
            prevLogNumber = coalesce(edit.getPreviousLogNumber(), prevLogNumber);
            nextFileNumber = coalesce(edit.getNextFileNumber(), nextFileNumber);
            lastSequence = coalesce(edit.getLastSequenceNumber(), lastSequence);
        }

        List<String> problems = newArrayList();
        if (nextFileNumber == null) {
            problems.add("Descriptor does not contain a meta-nextfile entry");
        }
        if (logNumber == null) {
            problems.add("Descriptor does not contain a meta-lognumber entry");
        }
        if (lastSequence == null) {
            problems.add("Descriptor does not contain a last-sequence-number entry");
        }
        if (!problems.isEmpty()) {
            throw new RuntimeException("Corruption: \n\t" + Joiner.on("\n\t").join(problems));
        }

        if (prevLogNumber == null) {
            prevLogNumber = 0L;
        }

        Version newVersion = new Version(this);
        builder.saveTo(newVersion);

        // Install recovered version
        finalizeVersion(newVersion);

        appendVersion(newVersion);
        manifestFileNumber = nextFileNumber;
        this.nextFileNumber.set(nextFileNumber + 1);
        this.lastSequence = lastSequence;
        this.logNumber = logNumber;
        this.prevLogNumber = prevLogNumber;
    } finally {
        fileChannel.close();
    }
}

From source file:com.google.dart.java2dart.engine.MainAnalysisServer.java

private static void applyEdits(File file, List<Edit> edits) throws IOException {
    // sort in descending order
    Collections.sort(edits, new Comparator<Edit>() {
        @Override//  w  ww  .j  a va2s.c  o m
        public int compare(Edit o1, Edit o2) {
            return o2.offset - o1.offset;
        }
    });
    // apply to file
    String content = Files.toString(file, Charsets.UTF_8);
    for (Edit edit : edits) {
        content = content.substring(0, edit.offset) + edit.replacement
                + content.substring(edit.offset + edit.length);
    }
    Files.write(content, file, Charsets.UTF_8);
}

From source file:com.google.javascript.jscomp.NpmCommandLineRunner.java

JsonObject getPackageJson(File packageJsonFile) throws IOException, JsonParseException {
    if (!packageJsonFile.isFile()) {
        throw new IOException("No package.json file at " + packageJsonFile.getAbsoluteFile());
    }/*from  ww w.  jav  a 2  s  .  c om*/

    return new JsonParser().parse(Files.toString(packageJsonFile, Charset.forName(flags.charset)))
            .getAsJsonObject();
}

From source file:org.apache.kylin.dict.lookup.cache.RocksDBLookupTableCache.java

@Override
public CacheState getCacheState(ExtTableSnapshotInfo extTableSnapshotInfo) {
    String resourcePath = extTableSnapshotInfo.getResourcePath();
    if (inBuildingTables.containsKey(resourcePath)) {
        return CacheState.IN_BUILDING;
    }/* w w  w .jav a 2  s  . c  o m*/
    File stateFile = getCacheStateFile(
            getSnapshotCachePath(extTableSnapshotInfo.getTableName(), extTableSnapshotInfo.getId()));
    if (!stateFile.exists()) {
        return CacheState.NONE;
    }
    try {
        String stateString = Files.toString(stateFile, Charsets.UTF_8);
        return CacheState.valueOf(stateString);
    } catch (IOException e) {
        logger.error("error when read state file", e);
    }
    return CacheState.NONE;
}

From source file:com.axelor.studio.service.builder.ViewBuilderService.java

/**
 * Write view and action xml into new viewFile.
 * /*  www . j  a  va 2  s .  c o m*/
 * @param name
 *            Name of model
 * @param views
 *            List of AbstractView of models.
 * @param actions
 *            List of Actions of model.
 * @throws IOException
 * @throws JAXBException
 */
public void writeView(File viewDir, String name, AbstractView view, List<Action> actions)
        throws IOException, JAXBException {

    ObjectViews objectViews = new ObjectViews();

    File viewFile = new File(viewDir, name + ".xml");
    if (viewFile.exists()) {
        String xml = Files.toString(viewFile, Charsets.UTF_8);
        if (!Strings.isNullOrEmpty(xml)) {
            objectViews = XMLViews.fromXML(xml);
        }
    }

    if (objectViews == null) {
        objectViews = new ObjectViews();
    }

    if (view != null) {
        List<AbstractView> views = filterOldViews(view, objectViews.getViews());
        objectViews.setViews(views);
    }

    if (actions != null && !actions.isEmpty()) {
        actions = filterOldActions(actions, objectViews.getActions());
        objectViews.setActions(actions);
    }

    if (view != null || (actions != null && !actions.isEmpty())) {
        XMLViews.marshal(objectViews, new FileWriter(viewFile));
    }

}