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.andmore.internal.wizards.templates.TemplateManager.java

@Nullable
TemplateMetadata getTemplate(File templateDir) {
    if (mTemplateMap != null) {
        TemplateMetadata metadata = mTemplateMap.get(templateDir);
        if (metadata != null) {
            return metadata;
        }/*w  w w  . ja v a  2 s .  c  o m*/
    } else {
        mTemplateMap = Maps.newHashMap();
    }

    try {
        File templateFile = new File(templateDir, TEMPLATE_XML);
        if (templateFile.isFile()) {
            String xml = Files.toString(templateFile, Charsets.UTF_8);
            Document doc = DomUtilities.parseDocument(xml, true);
            if (doc != null && doc.getDocumentElement() != null) {
                TemplateMetadata metadata = new TemplateMetadata(doc);
                if (EXCLUDED_CATEGORIES.contains(metadata.getCategory())
                        || EXCLUDED_FORMFACTORS.contains(metadata.getFormFactor())) {
                    return null;
                }
                mTemplateMap.put(templateDir, metadata);
                return metadata;
            }
        }
    } catch (IOException e) {
        AndmoreAndroidPlugin.log(e, null);
    }

    return null;
}

From source file:com.google.dart.tools.debug.core.coverage.CoverageManager.java

private static Map<IFile, List<SourceRange>> parseCoverageFile(UriToFileResolver uriToFileResolver,
        IContainer container, File jsonFile) throws Exception {
    Map<IFile, TreeMap<Integer, Integer>> filesHitMaps = Maps.newHashMap();
    Map<IFile, List<SourceRange>> filesMarkerRanges = Maps.newHashMap();
    String fileString = Files.toString(jsonFile, Charsets.UTF_8);
    JSONObject rootObject = new JSONObject(fileString);
    JSONArray coverageArray = rootObject.getJSONArray("coverage");
    for (int i = 0; i < coverageArray.length(); i++) {
        JSONObject coverageEntry = coverageArray.getJSONObject(i);
        // prepare IFile
        IFile file = getFile(uriToFileResolver, container, coverageEntry);
        if (file == null) {
            continue;
        }//from   w  ww . ja  v a2s . co m
        // prepare hit map
        TreeMap<Integer, Integer> hitMap = parseHitMap(coverageEntry);
        if (hitMap == null) {
            continue;
        }
        // merge hit maps
        TreeMap<Integer, Integer> hitMapOld = filesHitMaps.get(file);
        if (hitMapOld != null) {
            Set<Entry<Integer, Integer>> entrySet = hitMapOld.entrySet();
            for (Entry<Integer, Integer> entry : entrySet) {
                int line = entry.getKey();
                int hitsOld = entry.getValue();
                Integer hits = hitMap.get(line);
                if (hits != null) {
                    hitMap.put(line, hitsOld + hits.intValue());
                } else {
                    hitMap.put(line, hitsOld);
                }
            }
        }
        filesHitMaps.put(file, hitMap);
    }
    // add marker ranges
    for (Entry<IFile, TreeMap<Integer, Integer>> entry : filesHitMaps.entrySet()) {
        IFile file = entry.getKey();
        TreeMap<Integer, Integer> hitMap = entry.getValue();
        filesMarkerRanges.put(file, createMarkerRanges(file, hitMap));
    }
    //
    return filesMarkerRanges;
}

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

/** Patch the device to add an ES256 key for authentication. */
public void patchEs256ForAuth(String deviceId, String publicKeyFilePath) throws IOException {
    String devicePath = registryPath + "/devices/" + deviceId;
    PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
    String key = Files.toString(new File(publicKeyFilePath), Charsets.UTF_8);
    publicKeyCredential.setKey(key);/*from   w  ww.j  a v a2 s.c o m*/
    publicKeyCredential.setFormat("ES256_PEM");

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

    Device device = new Device();
    device.setCredentials(Arrays.asList(credential));

    Device patchedDevice = service.projects().locations().registries().devices().patch(devicePath, device)
            .setFields("credentials").execute();

    System.out.println("Patched device is " + patchedDevice.toPrettyString());
}

From source file:org.apache.hive.ptest.execution.context.CloudComputeService.java

public static Credentials getCredentialsFromJsonKeyFile(String filename) throws IOException {
    String fileContents = Files.toString(new File(filename), UTF_8);
    Supplier<Credentials> credentialSupplier = new GoogleCredentialsFromJson(fileContents);
    return credentialSupplier.get();
}

From source file:org.attribyte.essem.sysmon.linux.BlockDevices.java

/**
 * Gets the block size for a device.//from w  w  w.  java 2s . c  om
 * @param name The device name.
 * @return The block size.
 */
private static int getBlockSize(final String name) {

    File file = new File("/sys/block/" + name + "/queue/physical_block_size");
    if (!file.exists()) {
        int end = name.length() - 1;
        while (end > 0 && Character.isDigit(name.charAt(end)))
            end--;
        file = new File("/sys/block/" + name.substring(0, end + 1) + "/queue/physical_block_size");
    }

    if (!file.exists()) {
        return 0;
    }

    try {
        return Integer.parseInt(Files.toString(file, Charsets.US_ASCII).trim());
    } catch (IOException ioe) {
        return 0;
    } catch (NumberFormatException nfe) {
        nfe.printStackTrace();
        return 0;
    }
}

From source file:com.eucalyptus.util.Mbeans.java

public static void register(final Object obj) {
    if (jmxBuilder == null) {
        return;//from w ww  .jav a2 s  .  c  om
    } else {
        Class targetType = obj.getClass();
        if (targetType.isAnonymousClass()) {
            targetType = (targetType.getSuperclass() != null ? targetType.getSuperclass()
                    : targetType.getInterfaces()[0]);
        }
        String exportString = "jmx.export{ bean( " + " target: obj, "
                + " name: obj.class.package.name+\":type=${obj.class.simpleName}\","
                + " desc: \"${obj.toString()}\"" + " ) }";
        for (Class c : Classes.ancestors(targetType)) {
            File jmxConfig = SubDirectory.MANAGEMENT.getChildFile(c.getCanonicalName());
            if (jmxConfig.exists()) {
                LOG.trace("Trying to read jmx config file: " + jmxConfig.getAbsolutePath());
                try {
                    exportString = Files.toString(jmxConfig, Charset.defaultCharset());
                    LOG.trace("Succeeded reading jmx config file: " + jmxConfig.getAbsolutePath());
                    break;
                } catch (IOException ex) {
                    LOG.error(ex, ex);
                }
            }
        }
        //TODO:GRZE:load class specific config here
        try {
            LOG.trace("Exporting MBean: " + obj);
            LOG.trace("Exporting MBean: " + exportString);
            List<GroovyMBean> mbeans = (List<GroovyMBean>) Groovyness.eval(exportString, new HashMap() {
                {
                    put("jmx", jmxBuilder);
                    put("obj", obj);
                }
            });
            for (GroovyMBean mbean : mbeans) {
                LOG.trace("MBean server: default=" + mbean.server().getDefaultDomain() + " all="
                        + Arrays.asList(mbean.server().getDomains()));
                LOG.trace("Exported MBean: " + mbean);
            }
        } catch (ScriptExecutionFailedException ex) {
            LOG.error("Exporting MBean failed: " + ex.getMessage(), ex);
        } catch (IOException ex) {
            LOG.error("Error after export MBean: " + ex.getMessage(), ex);
        }
    }
}

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

/** Create a device that is authenticated using ES256. */
public static void createDeviceWithEs256(String deviceId, String publicKeyFilePath, String projectId,
        String cloudRegion, String registryName) throws GeneralSecurityException, IOException {
    GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new RetryHttpInitializerWrapper(credential);
    final CloudIot service = new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory,
            init).setApplicationName(APP_NAME).build();

    final String registryPath = "projects/" + projectId + "/locations/" + cloudRegion + "/registries/"
            + registryName;/*from  ww  w. java2s  .  com*/

    PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
    final String key = Files.toString(new File(publicKeyFilePath), Charsets.UTF_8);
    publicKeyCredential.setKey(key);
    publicKeyCredential.setFormat("ES256_PEM");

    DeviceCredential devCredential = new DeviceCredential();
    devCredential.setPublicKey(publicKeyCredential);

    System.out.println("Creating device with id: " + deviceId);
    Device device = new Device();
    device.setId(deviceId);
    device.setCredentials(Arrays.asList(devCredential));

    Device createdDevice = service.projects().locations().registries().devices().create(registryPath, device)
            .execute();

    System.out.println("Created device: " + createdDevice.toPrettyString());
}

From source file:com.axelor.studio.service.ViewRemovalService.java

private ObjectViews getObjectViews(File viewDir, String model) {

    if (modelMap.containsKey(model)) {
        return modelMap.get(model);
    }// ww  w  .j  ava 2s  .  c  o m

    try {
        File viewFile = new File(viewDir, model + ".xml");
        if (viewFile.exists()) {
            String xml = Files.toString(viewFile, Charsets.UTF_8);
            ObjectViews objectViews = XMLViews.fromXML(xml);
            modelMap.put(model, objectViews);
            return objectViews;
        }
    } catch (IOException | JAXBException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.google.testing.pogen.GenerateCommand.java

/**
 * Parses the specified template file and generates a modified template file and skeleton test
 * code.//  ww w . j  av  a2 s  . c o  m
 * 
 * @param templateFile the template file to be modified
 * @param rootInputDir the root input directory of template files
 * @param codeOutDir the output directory of skeleton test code
 * @param parser the parser to parse template files
 * @param updater the updater to update template files
 * @param generator the generator to generate skeleton test code
 * @throws IOException if errors occur in reading and writing files
 * @throws TemplateParseException if the specified template is in bad format
 * @throws PageObjectUpdateException if the existing test code doesn't have generated code
 */
private void parseAndGenerate(File templateFile, File rootInputDir, File codeOutDir, TemplateParser parser,
        TemplateUpdater updater, TestCodeGenerator generator)
        throws IOException, TemplateParseException, PageObjectUpdateException {
    Preconditions.checkNotNull(templateFile);
    Preconditions.checkNotNull(rootInputDir);
    Preconditions.checkNotNull(codeOutDir);
    Preconditions.checkArgument(!Strings.isNullOrEmpty(packageName));
    Preconditions.checkNotNull(parser);

    if (verbose) {
        System.out.println(templateFile.getAbsolutePath() + " ... ");
    }
    File orgTemplateFile = backupFile(templateFile);
    String pageName = NameConverter.getJavaClassName(getFileNameWithoutExtension(templateFile));
    // Read template file
    String template = Files.toString(orgTemplateFile, Charset.defaultCharset());
    // Parse template extracting template variables
    TemplateInfo templateInfo = parser.parse(template);
    if (verbose) {
        System.out.print(".");
    }
    // Generate modified template
    String modifiedTemplate = updater.generate(templateInfo);
    if (verbose) {
        System.out.print(".");
    }

    // Construct path of skeleton test code
    URI relativeDirUri = rootInputDir.toURI().relativize(templateFile.getParentFile().toURI());
    String relativeDirPath = relativeDirUri.toString();
    if (relativeDirPath.endsWith("/")) {
        relativeDirPath = relativeDirPath.substring(0, relativeDirPath.length() - 1);
    }
    if (!Strings.isNullOrEmpty(relativeDirPath)) {
        relativeDirPath = File.separatorChar + relativeDirPath;
    }
    String packagePrefix = relativeDirPath.replace('/', '.');
    File actualDir = new File(codeOutDir.getPath() + relativeDirPath);
    actualDir.mkdirs();

    // Generate skeleton test code
    File codeFile = new File(actualDir, pageName + "Page.java");
    if (codeFile.exists() && !codeFile.canWrite()) {
        throw new FileProcessException("No permission for writing the specified file", codeFile);
    }

    // @formatter:off
    String testCode = codeFile.exists()
            ? generator.update(templateInfo, Files.toString(codeFile, Charset.defaultCharset()))
            : generator.generate(templateInfo, packageName + packagePrefix, pageName);
    // @formatter:on
    if (verbose) {
        System.out.print(".");
    }
    // Write generated template and skeleton test code
    Files.write(modifiedTemplate, templateFile, Charset.defaultCharset());
    if (verbose) {
        System.out.print(".");
    }
    Files.write(testCode, codeFile, Charset.defaultCharset());
    if (verbose) {
        System.out.println("\n" + templateFile.getAbsolutePath() + " processed successfully");
    }
}

From source file:com.android.tools.idea.rendering.ProjectCallback.java

@Nullable
private ILayoutPullParser getParser(@NotNull String layoutName, @Nullable File xml) {
    if (layoutName.equals(myLayoutName)) {
        ILayoutPullParser parser = myLayoutEmbeddedParser;
        // The parser should only be used once!! If it is included more than once,
        // subsequent includes should just use a plain pull parser that is not tied
        // to the XML model
        myLayoutEmbeddedParser = null;/*  ww  w  . j  a  v a 2s  . c  o  m*/
        return parser;
    }

    // For included layouts, create a ContextPullParser such that we get the
    // layout editor behavior in included layouts as well - which for example
    // replaces <fragment> tags with <include>.
    if (xml != null && xml.isFile()) {
        ContextPullParser parser = new ContextPullParser(this);
        try {
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
            String xmlText = Files.toString(xml, Charsets.UTF_8);
            parser.setInput(new StringReader(xmlText));
            return parser;
        } catch (XmlPullParserException e) {
            LOG.error(e);
        } catch (FileNotFoundException e) {
            // Shouldn't happen since we check isFile() above
        } catch (IOException e) {
            LOG.error(e);
        }
    }

    return null;
}