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.eclipse.jdt.ls.core.internal.JDTUtils.java

public static String getPackageName(IJavaProject javaProject, URI uri) {
    try {// w w  w .  ja  v a 2 s  . c o m
        File file = new File(uri);
        //FIXME need to determine actual charset from file
        String content = Files.toString(file, Charsets.UTF_8);
        return getPackageName(javaProject, content);
    } catch (Exception e) {
        JavaLanguageServerPlugin.logException("Failed to read package name from " + uri, e);
    }
    return "";
}

From source file:com.google.cloud.iot.examples.DeviceRegistryExample.java

private DeviceCredential createDeviceCredential(String publicKeyFilePath, String keyFormat) throws IOException {
    PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
    String key = Files.toString(new File(publicKeyFilePath), Charsets.UTF_8);
    publicKeyCredential.setKey(key);/*from w  w w  .j ava 2 s  .com*/
    publicKeyCredential.setFormat(keyFormat);

    DeviceCredential credential = new DeviceCredential();
    credential.setPublicKey(publicKeyCredential);
    return credential;
}

From source file:com.kaching.platform.testing.BadCodeSnippetsRunner.java

private void collectUses(String fileExtension, File f, Iterable<Snippet> patterns, Map<Snippet, Set<File>> uses,
        Map<Snippet, Pattern> compiledPatterns) throws IOException {
    if (f.isFile()) {
        if (f.getName().endsWith("." + fileExtension)) {
            String code = Files.toString(f, UTF_8);
            for (Snippet p : patterns) {
                if (compiledPatterns.get(p).matcher(code).find()) {
                    uses.get(p).add(f);/* w  ww.j a v a2 s .  c o  m*/
                }
            }
        }
    } else if (f.isDirectory()) {
        for (File c : f.listFiles()) {
            collectUses(fileExtension, c, patterns, uses, compiledPatterns);
        }
    }
}

From source file:com.opera.core.systems.OperaExtensions.java

/**
 * Install the extension by writing to widgets.dat
 *
 * @param wuid    Unique identifier of the widget.
 * @param oexpath Location of .oex file within profile
 *///  w  ww  .ja  va2s.  c  o m
private void writeOEXtoWidgetsDat(String wuid, File oexpath) throws IOException {
    // Define a path relative to the profile directory. Don't use an absolute path,
    // because that will break when used with the Remote web driver.
    String oexpathRelative = "{LargePreferences}widgets/" + oexpath.getName();

    String widgetString = Files.toString(widgetsDat, Charsets.UTF_8);
    int beforePreferencesEndTag = widgetString.lastIndexOf("</preferences>");
    if (beforePreferencesEndTag == -1) {
        throw new WebDriverException("</preferences> not found in " + widgetsDat.getPath());
    }
    String widgetDatSection = String.format(WIDGET_DAT_ITEM, wuid, oexpathRelative);
    // Insert the new <section ..> ... </section> before </preferences>
    widgetString = widgetString.substring(0, beforePreferencesEndTag) + widgetDatSection
            + widgetString.substring(beforePreferencesEndTag);
    Files.write(widgetString, widgetsDat, Charsets.UTF_8);
}

From source file:com.android.tools.idea.npw.assetstudio.assets.VectorAsset.java

/**
 * Attempt to parse an SVG file, a Vector Drawable file or a layered image based on current settings.
 *
 * @param previewWidth If set to a positive value, this will override the current output width
 *                     value (in effect, scaling the final result).
 *//*from ww  w  . ja  va 2  s. c o m*/
@NotNull
private ParseResult tryParse(int previewWidth, boolean allowPropertyOverride) {
    StringBuilder errorBuffer = new StringBuilder();

    File path = myPath.get();
    if (!path.exists() || path.isDirectory()) {
        return ParseResult.INVALID;
    }

    String xmlFileContent = null;
    FileType fileType = myFileType.get();

    if (fileType.equals(FileType.SVG)) {
        OutputStream outStream = new ByteArrayOutputStream();
        String errorLog = Svg2Vector.parseSvgToXml(path, outStream);
        errorBuffer.append(errorLog);
        xmlFileContent = outStream.toString();
    } else if (fileType.equals(FileType.LAYERED_IMAGE)) {
        try {
            xmlFileContent = new LayeredImageConverter().toVectorDrawableXml(path);
        } catch (IOException e) {
            errorBuffer.append(e.getMessage());
        }
    } else {
        try {
            xmlFileContent = Files.toString(path, Charsets.UTF_8);
        } catch (IOException e) {
            errorBuffer.append(e.getMessage());
        }
    }

    BufferedImage image = null;
    int originalWidth = 0;
    int originalHeight = 0;
    if (xmlFileContent != null) {
        Document vdDocument = VdPreview.parseVdStringIntoDocument(xmlFileContent, errorBuffer);
        if (vdDocument != null) {
            VdPreview.SourceSize vdOriginalSize = VdPreview.getVdOriginalSize(vdDocument);
            originalWidth = vdOriginalSize.getWidth();
            originalHeight = vdOriginalSize.getHeight();

            if (allowPropertyOverride) {
                String overriddenXml = overrideXmlFileContent(vdDocument, vdOriginalSize, errorBuffer);
                if (overriddenXml != null) {
                    xmlFileContent = overriddenXml;
                }
            }

            if (previewWidth <= 0) {
                previewWidth = myOutputWidth.get() > 0 ? myOutputWidth.get() : originalWidth;
            }

            final VdPreview.TargetSize imageTargetSize = VdPreview.TargetSize.createSizeFromWidth(previewWidth);
            image = VdPreview.getPreviewFromVectorXml(imageTargetSize, xmlFileContent, errorBuffer);
        }
    }

    if (image == null) {
        errorBuffer.insert(0, ERROR_EMPTY_PREVIEW + "\n");
        return new ParseResult(errorBuffer.toString());
    } else {
        return new ParseResult(errorBuffer.toString(), image, originalWidth, originalHeight, xmlFileContent);
    }
}

From source file:net.minecraftforge.gradle.tasks.PatchSourcesTask.java

private void inject(FileCollection injects, final Map<String, String> sourceMap,
        final Map<String, byte[]> resourceMap) throws IOException {
    FileVisitor visitor = new FileVisitor() {

        @Override// w ww  .  j a  v a2 s .  c  o  m
        public void visitDir(FileVisitDetails arg0) {
            // nope.
        }

        @Override
        public void visitFile(FileVisitDetails details) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            details.copyTo(stream);
            // BAOS dont need to be clsoed.

            byte[] array = stream.toByteArray();
            String path = details.getRelativePath().getPathString().replace('\\', '/');

            if (details.getName().endsWith(".java")) {
                sourceMap.put(path, new String(array, Constants.CHARSET));
            } else {
                resourceMap.put(path, array);
            }
        }

    };

    for (File inject : injects) {
        if (inject.isDirectory()) {
            getProject().fileTree(inject).visit(visitor);
        } else if (inject.getName().endsWith(".jar") || inject.getName().endsWith(".zip")) {
            (new ZipFileTree(inject)).visit(visitor);
        } else if (inject.getName().endsWith(".java")) {
            sourceMap.put(inject.getName(), Files.toString(inject, Constants.CHARSET));
        } else {
            resourceMap.put(inject.getName(), Files.toByteArray(inject));
        }
    }
}

From source file:com.google.devtools.build.lib.util.ResourceUsage.java

/**
 * Returns the current cpu utilization of the current process with the given
 * id in jiffies. The returned array contains the following information: The
 * 1st entry is the number of jiffies that the process has executed in user
 * mode, and the 2nd entry is the number of jiffies that the process has
 * executed in kernel mode. Reads /proc/self/stat to obtain this information.
 *
 * @param processId the process id or <code>self</code> for the current
 *        process.//from  w  w  w. j  a va 2  s .  c o  m
 */
private static long[] getCurrentCpuUtilizationInJiffies(String processId) {
    try {
        File file = new File("/proc/" + processId + "/stat");
        if (file.isDirectory()) {
            return new long[2];
        }
        Iterator<String> stat = WHITESPACE_SPLITTER.split(Files.toString(file, US_ASCII)).iterator();
        for (int i = 0; i < 13; ++i) {
            stat.next();
        }
        long token13 = Long.parseLong(stat.next());
        long token14 = Long.parseLong(stat.next());
        return new long[] { token13, token14 };
    } catch (NumberFormatException | IOException e) {
        return new long[2];
    }
}

From source file:com.zack6849.alphabot.api.PermissionManager.java

public void save() {
    System.out.println("Saving....");
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonParser parser = new JsonParser();
    String json = null;/*w  w  w.j  a va 2s  .c o  m*/
    try {
        json = Files.toString(new File("permissions.json"),
                Charset.isSupported("UTF-8") ? Charset.forName("UTF-8") : Charset.defaultCharset());
        JsonElement jelement = parser.parse(json);
        JsonObject output = jelement.getAsJsonObject();
        HashMap<String, String> masks = new HashMap<String, String>();
        for (Group g : getGroups()) {
            if (!g.getName().equalsIgnoreCase("default")) {
                for (User u : g.getUsers().keySet()) {
                    if (!masks.containsKey(g.getUsers().get(u))) {
                        masks.put(g.getUsers().get(u), g.getName());
                    }
                }
            }
        }
        JsonElement obj = output.get("users");
        Set<Map.Entry<String, JsonElement>> users = output.get("users").getAsJsonObject().entrySet();
        Iterator it = users.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            masks.put(entry.getKey().toString().replaceAll("\"", ""),
                    entry.getValue().toString().replaceAll("\"", ""));
        }
        for (String s : masks.keySet()) {
            obj.getAsJsonObject().remove(s);
            obj.getAsJsonObject().addProperty(s, masks.get(s));
        }
        JsonObject gr = output.get("groups").getAsJsonObject();
        for (Group g : groups) {
            gr.remove(g.getName());
            //temporary group object to store the "new" group object
            //loop through all permissions in the actual group, and if the permission is inherited, then remove it.
            List<String> permissions = new ArrayList<String>();
            Iterator<Permission> iter = g.getPermissions().iterator();
            while (iter.hasNext()) {
                Permission perm = iter.next();
                if (!perm.isInheirited()) {
                    permissions.add(perm.getPermission());
                }
            }
            JsonObject group = parser.parse(gson.toJson(g)).getAsJsonObject();
            group.remove("permissions");
            group.add("permissions", parser.parse(gson.toJson(permissions)));
            group.remove("inheritance");
            group.add("inheritance", parser.parse(gson.toJson(g.getInheritance())));
            gr.add(g.getName(), group);
        }
        output.remove("groups");
        output.add("groups", gr);
        output.remove("users");
        output.add("users", obj);
        Files.write(gson.toJson(output), new File("permissions.json"),
                Charset.isSupported("UTF-8") ? Charset.forName("UTF-8") : Charset.defaultCharset());
        System.out.println("6");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.palantir.atlasdb.shell.AtlasShellConnectionDialogModel.java

@SuppressWarnings("unchecked")
public static Map<String, DbConnectionInfo> readConnections() {
    if (!FILE.exists()) {
        return ImmutableMap.of();
    }//from w  w w  .  jav a  2 s .  com
    try {
        Gson gson = new Gson();
        Type collectionType = new TypeToken<Map<String, DbConnectionInfo>>() { /* empty */
        }.getType();
        return (Map<String, DbConnectionInfo>) gson.fromJson(Files.toString(FILE, Charsets.UTF_8),
                collectionType);
    } catch (IOException e) {
        throw Throwables.throwUncheckedException(e);
    }
}

From source file:sourcecodefilter.ExitCode.java

static Set<String> parseSerializationRelevantClassNames(File baseDir) {
    File xstreamConfigurationSourceFile = new File(baseDir, "org/catrobat/catroid/io/StorageHandler.java");
    if (!(xstreamConfigurationSourceFile.exists())) {
        throw new RuntimeException(
                "Serialization configuration source must exist: " + xstreamConfigurationSourceFile.toString());
    }//from   www. j av a 2  s .  c om
    Set<String> classNames = new HashSet<>(ADDITIONAL_SERIALIZATION_CLASSES);
    try {
        String fileContent = Files.toString(xstreamConfigurationSourceFile, Charsets.UTF_8);
        Pattern serializedClassNamePattern = Pattern.compile("(?:xstream\\..*?)(\\w+)(?:\\.class)");
        Matcher matcher = serializedClassNamePattern.matcher(fileContent);
        while (matcher.find()) {
            classNames.add(matcher.group(1));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return classNames;
}