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:com.google.caliper.runner.worker.WorkerRunner.java

/**
 * Formats an error message for throwing or logging, adding the path to the worker output file to
 * the message. The given {@code baseMessageFormat} must include a "%s" to allow the worker name
 * to be added.//from ww  w  . ja  v a2 s  .c  o m
 */
private String formatError(String baseMessageFormat, Object... args) {
    String baseMessage = String.format(baseMessageFormat, args);
    if (printWorkerLog) {
        try {
            worker.outputLogger().flush();
            String logContent = Files.toString(outputFile, UTF_8);
            return baseMessage + " Worker log follows:\n\n" + logContent;
        } catch (IOException ignore) {
            // fall through to printing the path
        }
    }

    return baseMessage + String.format(" Inspect %s to see any worker output.", outputFile);
}

From source file:com.pivotal.hawq.mapreduce.MRFormatTestUtils.java

/**
 * Replace all path locations in metadata file to use local path.
 * @param metadataFile the file to transform
 * @throws IOException/*  w  w w  . ja va  2s  . c  o m*/
 */
public static void transformMetadata(File metadataFile) throws IOException {
    String content = Files.toString(metadataFile, Charsets.UTF_8);
    // replace all lines like
    // - path: /hawq-data/gpseg0/16385/119737/134935.1
    // to
    // - path: test-data/hawq-data/gpseg0/16385/119737/134935.1
    content = PATH_PATTERN.matcher(content).replaceAll("$1" + TEST_FOLDER + "$2");
    Files.write(content.getBytes(), metadataFile);
}

From source file:com.github.nethad.clustermeister.api.impl.KeyPairCredentials.java

/**
 * Get the private key./*from   w  w w. ja  va2s  .c o m*/
 * 
 * @return  the private key as a String.
 * @throws IOException  
 *      when an error occurs while reading from {@link #privateKeySource}. 
 */
public String getPrivateKey() throws IOException {
    return Files.toString(privatekeySource, charset);
}

From source file:net.minecraftforge.gradle.patcher.TaskGenPatches.java

public void processFile(String relative, InputStream original, InputStream changed) throws IOException {
    getLogger().debug("Diffing: " + relative);

    File patchFile = new File(getPatchDir(), relative + ".patch").getCanonicalFile();

    if (changed == null) {
        getLogger().debug("    Changed File does not exist");
        return;// w  w w.  ja  v a2 s .  c  o m
    }

    // We have to cache the bytes because diff reads the stream twice.. why.. who knows.
    byte[] oData = ByteStreams.toByteArray(original);
    byte[] cData = ByteStreams.toByteArray(changed);

    Diff diff = Diff.diff(new InputStreamReader(new ByteArrayInputStream(oData), Charsets.UTF_8),
            new InputStreamReader(new ByteArrayInputStream(cData), Charsets.UTF_8), false);

    if (!relative.startsWith("/"))
        relative = "/" + relative;

    if (!diff.isEmpty()) {
        String unidiff = diff.toUnifiedDiff(originalPrefix + relative, changedPrefix + relative,
                new InputStreamReader(new ByteArrayInputStream(oData), Charsets.UTF_8),
                new InputStreamReader(new ByteArrayInputStream(cData), Charsets.UTF_8), 3);
        unidiff = unidiff.replace("\r\n", "\n"); //Normalize lines
        unidiff = unidiff.replace("\n" + Hunk.ENDING_NEWLINE + "\n", "\n"); //We give 0 shits about this.

        String olddiff = "";
        if (patchFile.exists()) {
            olddiff = Files.toString(patchFile, Charsets.UTF_8);
        }

        if (!olddiff.equals(unidiff)) {
            getLogger().debug("Writing patch: " + patchFile);
            patchFile.getParentFile().mkdirs();
            Files.touch(patchFile);
            Files.write(unidiff, patchFile, Charsets.UTF_8);
        } else {
            getLogger().debug("Patch did not change");
        }
        created.add(patchFile);
    }
}

From source file:com.twitter.common.args.OptionInfo.java

private String getArgFileContent(String optionName, String argFilePath) throws IllegalArgumentException {
    if (argFilePath.isEmpty()) {
        throw new IllegalArgumentException(
                String.format("Invalid null/empty value for argument '%s'.", optionName));
    }//  w  w  w . jav  a  2s .  co  m

    try {
        return Files.toString(new File(argFilePath), Charsets.UTF_8);
    } catch (IOException e) {
        throw new IllegalArgumentException(
                String.format("Unable to read argument '%s' value from file '%s'.", optionName, argFilePath),
                e);
    }
}

From source file:com.android.ide.eclipse.auidt.internal.wizards.templates.TemplateManager.java

@Nullable
public TemplateMetadata getTemplate(File templateDir) {
    if (mTemplateMap != null) {
        TemplateMetadata metadata = mTemplateMap.get(templateDir);
        if (metadata != null) {
            return metadata;
        }//from  w w w.j ava2s  . 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);
                mTemplateMap.put(templateDir, metadata);
                return metadata;
            }
        }
    } catch (IOException e) {
        AdtPlugin.log(e, null);
    }

    return null;
}

From source file:org.apache.gora.goraci.rackspace.RackspaceOrchestration.java

private static void performRackspaceOrchestration(Properties properties)
        throws InstantiationException, IllegalAccessException, IOException {
    rsContinent = DataStoreFactory.findProperty(properties, MemStore.class.newInstance(), RS_CONTINENT,
            "rackspace-cloudservers-us");
    rsUser = DataStoreFactory.findProperty(properties, MemStore.class.newInstance(), RS_USERNAME, "asf-gora");
    rsApiKey = DataStoreFactory.findProperty(properties, MemStore.class.newInstance(), RS_APIKEY, null);
    rsRegion = DataStoreFactory.findProperty(properties, MemStore.class.newInstance(), RS_REGION, "DFW");
    String rsFlavourId = DataStoreFactory.findProperty(properties, MemStore.class.newInstance(), RS_FLAVORID,
            null);/*from   w  ww . j av a2  s  .co m*/
    String rsImageId = DataStoreFactory.findProperty(properties, MemStore.class.newInstance(), RS_IMAGEID,
            null);
    int numServers = Integer.parseInt(
            DataStoreFactory.findProperty(properties, MemStore.class.newInstance(), RS_NUM_SERVERS, "10"));
    String serverName = DataStoreFactory.findProperty(properties, MemStore.class.newInstance(), RS_SERVERNAME,
            "goraci_test_server");

    novaApi = ContextBuilder.newBuilder(rsContinent).credentials(rsUser, rsApiKey).buildApi(NovaApi.class);
    LOG.info("Defining Rackspace cloudserver continent as: {}, and region: {}.", rsContinent, rsRegion);

    //Choose operating system
    ImageApi imageApi = novaApi.getImageApi(rsRegion);
    Image image = imageApi.get(rsImageId);
    //Choose hardware configuration
    FlavorApi flavorApi = novaApi.getFlavorApi(rsRegion);
    Flavor flavor = flavorApi.get(rsFlavourId);
    LOG.info("Defining Rackspace cloudserver flavors as: {}, with image id's {}", rsFlavourId, rsImageId);

    //Manage keypairs
    KeyPairApi keyPairApi = novaApi.getKeyPairApi(rsRegion).get();

    File keyPairFile = null;
    String publicKey = null;
    //Use your own .pub key which should be on CP
    if (DataStoreFactory.findBooleanProperty(properties, MemStore.class.newInstance(), RS_PUBKEY, "true")) {
        keyPairFile = new File("~/.ssh/id_rsa.pub");
        LOG.info("Uploading local public key from ~/.ssh/id_rsa.pub to Rackspace...");
    } else {
        //obtain existing key from Rackspace
        if (keyPairApi.get("goraci-keypair") != null) {
            publicKey = keyPairApi.get("goraci-keypair").getPublicKey();
            LOG.info("Obtained existing public key 'goraci-keypair' from Rackspace...");
        } else {
            //have Rackspace generate us a key
            LOG.info("Generating local keypair 'goraci-keypair' and uploading to Rackspace...");
            KeyPair keyPair = keyPairApi.create("goraci-keypair");
            keyPairFile = new File("/target/goraci-keypair.pem");
            try {
                Files.write(keyPair.getPrivateKey(), keyPairFile, Charsets.UTF_8);
            } catch (IOException e) {
                throw new IOException(e);
            }
            try {
                publicKey = Files.toString(keyPairFile, Charsets.UTF_8);
            } catch (IOException e) {
                throw new IOException(e);
            }
            keyPairApi.createWithPublicKey("goraci-keypair", publicKey);
        }
    }

    ServerApi serverApi = novaApi.getServerApi(rsRegion);
    CreateServerOptions options = CreateServerOptions.Builder.keyPairName("goraci-keypair");
    ServerCreated serverCreated = null;
    for (int i = 0; i < numServers; i++) {
        if (serverName != null) {
            serverCreated = serverApi.create(serverName + i, rsImageId, rsFlavourId, options);

        } else {
            serverCreated = serverApi.create("goraci_test_server" + i, image.getId(), flavor.getId(), options);
        }
        ServerPredicates.awaitActive(serverApi).apply(serverCreated.getId());
        LOG.info("Provisioned node {} of {} with name {}", new Object[] { i + 1, numServers, serverName + i });
    }

}

From source file:com.coinblesk.client.backup.BackupRestoreDialogFragment.java

private void restore() {
    final String password = txtPassword.getText().toString();
    final File selectedBackupFile = (File) backupFilesList.getSelectedItem();
    clearPasswordInput();/*from w w w.java 2s . com*/
    checkState(password != null && password.length() > 0);
    checkState(selectedBackupFile != null && selectedBackupFile.exists());

    try {
        final String encryptedBackup = Files.toString(selectedBackupFile, Charsets.UTF_8);
        final byte[] decryptedBackup = EncryptionUtils.decryptBytes(encryptedBackup, password.toCharArray());
        Log.d(TAG, String.format("Decrypted backup file: [%s] (%d bytes)", selectedBackupFile,
                decryptedBackup.length));

        // before we extract the backup, we do a cleanup.
        cleanupBeforeRestore();

        extractZip(decryptedBackup);

        cleanupAfterRestore();

    } catch (Exception e) {
        Log.w(TAG, "Could not restore backup: ", e);
        String errorMsg = e.getMessage() != null ? e.getMessage() : "(unknown)";
        new AlertDialog.Builder(this.getContext()).setTitle(R.string.fragment_backup_restore_failed_title)
                .setMessage(getString(R.string.fragment_backup_restore_failed_message, errorMsg))
                .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create().show();
    }
}

From source file:org.mayocat.theme.internal.DefaultThemeFileResolver.java

/**
 * Tries to get template content for a certain theme and breakpoint. Tries in order : - tenant theme folder in
 * persistent directory (example : data/tenants/thetenant/themes/thetheme/[breakpoint/]filename - global theme
 * folder in persistent directory (example : data/themes/thetheme/[breakpoint/]filename) - classpath (example uri :
 * /themes/thetheme/[breakpoint/]filename) For each step, checks the breakpoint (if set) and fallback on the
 * no-breakpoint file//from w  ww . ja  va  2  s  .c  o  m
 *
 * @param theme the theme for which to try and get the template content
 * @param name the name of the template to get
 * @param breakpoint the breakpoint for which to get the template content
 * @return the content of the template, or null if not found
 * @throws IOException when there is an IO exception getting the content
 */
private String getTemplateContent(Theme theme, String name, Optional<Breakpoint> breakpoint)
        throws IOException {
    ThemeResource resource = this.getResource(theme, name, breakpoint);
    if (resource == null) {
        return null;
    }

    switch (resource.getType()) {
    default:
    case FILE:
        return Files.toString(resource.getPath().toFile(), Charsets.UTF_8);
    case CLASSPATH_RESOURCE:
        return Resources.toString(Resources.getResource(resource.getPath().toString()), Charsets.UTF_8);
    }
}

From source file:com.android.tools.idea.templates.recipe.RecipeContext.java

/**
 * Merges the given source file into the given destination file (or it just copies it over if
 * the destination file does not exist).
 * <p/>/*from   w  ww.java 2  s  .co m*/
 * Only XML and Gradle files are currently supported.
 */
public void merge(@NotNull File from, @NotNull File to) {
    try {
        String targetText = null;

        to = getTargetFile(to);
        if (!(hasExtension(to, DOT_XML) || hasExtension(to, DOT_GRADLE))) {
            throw new RuntimeException("Only XML or Gradle files can be merged at this point: " + to);
        }

        if (to.exists()) {
            targetText = Files.toString(to, Charsets.UTF_8);
        } else if (to.getParentFile() != null) {
            //noinspection ResultOfMethodCallIgnored
            checkedCreateDirectoryIfMissing(to.getParentFile());
        }

        if (targetText == null) {
            // The target file doesn't exist: don't merge, just copy
            boolean instantiate = hasExtension(from, DOT_FTL);
            if (instantiate) {
                instantiate(from, to);
            } else {
                copyTemplateResource(from, to);
            }
            return;
        }

        String sourceText;
        from = getSourceFile(from);
        if (hasExtension(from, DOT_FTL)) {
            // Perform template substitution of the template prior to merging
            myLoader.setTemplateFile(from);
            sourceText = processFreemarkerTemplate(myFreemarker, myParamMap, from);
        } else {
            sourceText = readTextFile(from);
            if (sourceText == null) {
                return;
            }
        }

        String contents;
        if (to.getName().equals(GRADLE_PROJECT_SETTINGS_FILE)) {
            contents = RecipeMergeUtils.mergeGradleSettingsFile(sourceText, targetText);
            myNeedsGradleSync = true;
        } else if (to.getName().equals(SdkConstants.FN_BUILD_GRADLE)) {
            contents = GradleFileMerger.mergeGradleFiles(sourceText, targetText, myProject);
            myNeedsGradleSync = true;
        } else if (hasExtension(to, DOT_XML)) {
            contents = RecipeMergeUtils.mergeXml(myProject, sourceText, targetText, to);
        } else {
            throw new RuntimeException("Only XML or Gradle settings files can be merged at this point: " + to);
        }

        writeFile(this, contents, to);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (TemplateException e) {
        throw new RuntimeException(e);
    }
}