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.android.build.gradle.integration.instant.InstantRunTestUtils.java

public static void printBuildInfoFile(@Nullable InstantRun instantRunModel) {
    if (instantRunModel == null) {
        System.err.println("Cannot print build info file as model is null");
        return;/*from w w  w  .j  a  v  a 2 s .  c  o m*/
    }
    try {
        System.out.println("------------ build info file ------------\n"
                + Files.toString(instantRunModel.getInfoFile(), Charsets.UTF_8)
                + "---------- end build info file ----------\n");
    } catch (IOException e) {
        System.err.println("Unable to print build info xml file: \n" + Throwables.getStackTraceAsString(e));
    }
}

From source file:org.freeeed.main.FileProcessor.java

private void prepareImageSrcForUI(String htmlFileName, String docName) throws IOException {
    File htmlFile = new File(htmlFileName);
    String htmlContent = Files.toString(htmlFile, Charset.defaultCharset());
    String replaceWhat = "SRC=\"" + Pattern.quote(docName) + "_html_";
    String replacement = "SRC=\"filedownload.html?action=exportHtmlImage&docPath=" + docName + "_html_";
    htmlContent = htmlContent.replaceAll(replaceWhat, replacement);

    Files.write(htmlContent, htmlFile, Charset.defaultCharset());
}

From source file:com.github.pires.example.App.java

public void execute(String... args) throws Exception {
    parser = new CmdLineParser(this);
    parser.setUsageWidth(80);/*from  ww w.  j a  va  2  s.c o m*/
    try {
        parser.parseArgument(args);
        action = Action.valueOf(args[4].toUpperCase());
        switch (action) {
        case ADD:
            groupName = args[5];
            break;
        case EXEC:
            groupName = args[5];
            command = args[6];
            break;
        case RUN:
            groupName = args[5];
            filePath = args[6];
            break;
        case DESTROY:
            groupName = args[5];
            nodeId = args[6];
        }
    } catch (Exception e) {
        log.error("There was an error while parsing parameters.. ", e);
        printUsage();
        System.exit(1);
    }

    // show help, if requested
    if (help) {
        printUsage();
        System.exit(1);
    } else {
        // get private-key
        final String credentials = getPrivateKeyFromFile(pkPath);
        // prepare credentials
        LoginCredentials login = getLoginForCommandExecution(action);
        ComputeService compute = initComputeService(account, credentials);

        // go
        int error = 0;
        try {
            switch (action) {
            case ADD:
                log.info(">> adding node to group {}", groupName);

                // Build Debian image in europe-west1-a zone
                TemplateBuilder templateBuilder = compute.templateBuilder();
                templateBuilder.fromImage(compute.getImage("debian-7-wheezy-v20140408"));
                templateBuilder.locationId("europe-west1-a");
                templateBuilder.fastest();

                // this will create a user with the same name as you on the
                // node. ex. you can connect via ssh publicip
                Statement bootInstructions = AdminAccess.standard();
                templateBuilder.options(runScript(bootInstructions));

                NodeMetadata node = getOnlyElement(
                        compute.createNodesInGroup(groupName, 1, templateBuilder.build()));
                log.info("<< node {}: {}", node.getId(),
                        concat(node.getPrivateAddresses(), node.getPublicAddresses()));
                break;

            case EXEC:
                log.info(">> running {} on group {} as {}", command, groupName, login.identity);

                // when you run commands, you can pass options to decide whether to
                // run it as root, supply or own credentials vs from cache, and wrap
                // in an init script vs directly invoke
                Map<? extends NodeMetadata, ExecResponse> responses = compute.runScriptOnNodesMatching(
                        inGroup(groupName), exec(command),
                        overrideLoginCredentials(login).runAsRoot(false).wrapInInitScript(false));

                for (Entry<? extends NodeMetadata, ExecResponse> response : responses.entrySet()) {
                    log.info("<< node {}: {}", response.getKey().getId(), concat(
                            response.getKey().getPrivateAddresses(), response.getKey().getPublicAddresses()));
                    log.info("<<     {}", response.getValue());
                }
                break;

            case RUN:
                final File file = new File("TODO_FILE_PATH");
                log.info(">> running {} on group {} as {}", file, groupName, login.identity);

                // when running a sequence of commands, you probably want to have
                // jclouds use the default behavior, which is to fork a background
                // process.
                responses = compute.runScriptOnNodesMatching(inGroup(groupName),
                        Files.toString(file, Charsets.UTF_8), overrideLoginCredentials(login).runAsRoot(false)
                                .nameTask("_" + file.getName().replaceAll("\\..*", "")));

                for (Entry<? extends NodeMetadata, ExecResponse> response : responses.entrySet()) {
                    log.info("<< node {}: {}", response.getKey().getId(), concat(
                            response.getKey().getPrivateAddresses(), response.getKey().getPublicAddresses()));
                    log.info("<<     {}", response.getValue());
                }
                break;

            case DESTROY:
                log.info(">> destroying node [{}] in group [{}]", nodeId, groupName);
                // you can use predicates to select which nodes you wish to destroy.
                Set<? extends NodeMetadata> destroyed = compute.destroyNodesMatching(
                        Predicates.<NodeMetadata>and(not(TERMINATED), inGroup(groupName), withIds(nodeId)));
                log.info("<< destroyed noded {}", destroyed);
                break;
            case LISTIMAGES:
                // list images
                Set<? extends Image> images = compute.listImages();
                log.info(">> No of images {}", images.size());
                for (Image img : images) {
                    log.info(">>>>  {}", img);
                }
                break;

            case LISTNODES:
                Set<? extends ComputeMetadata> nodes1 = compute.listNodes();
                log.info(">> No of unfiltered nodes/instances {}", nodes1.size());
                for (ComputeMetadata nodeData : nodes1) {
                    log.info(">>>> {}", (NodeMetadata) nodeData);
                }

                final String region = "europe-west1-a";
                final String group = "instance";
                final String tagKey = "type";
                final String tagValue = "hz-nodes";
                Predicate filter = Predicates.<NodeMetadata>and(locationId(region), inGroup(group),
                        hasTagKeyWithTagValue(tagKey, tagValue));
                Set<? extends ComputeMetadata> nodes2 = compute.listNodesDetailsMatching(filter);
                log.info(">> No of filtered nodes/instances {}", nodes2.size());
                for (ComputeMetadata nodeData : nodes2) {
                    log.info("-----> {}", (NodeMetadata) nodeData);
                }

                break;
            }
        } catch (RunNodesException e) {
            log.error("error adding node to group {}", groupName, e);
            error = 1;
        } catch (RunScriptOnNodesException e) {
            log.error("error executing {} on group {}", command, groupName, e);
            error = 1;
        } catch (Exception e) {
            log.error("error: ", e);
            error = 1;
        } finally {
            compute.getContext().close();
            System.exit(error);
        }
    }

}

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

@Nullable
TemplateMetadata getTemplate(File templateDir) {
    if (mTemplateMap != null) {
        TemplateMetadata metadata = mTemplateMap.get(templateDir);
        if (metadata != null) {
            return metadata;
        }//from w w  w .j  a v  a  2s.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.flume.test.util.SyslogAgent.java

public void runKeepFieldsTest() throws Exception {
    /* Create expected output and log message */
    String logMessage = "<34>1 Oct 11 22:14:15 mymachine su: Test\n";
    String expectedOutput = "su: Test\n";
    if (keepFields.equals("true") || keepFields.equals("all")) {
        expectedOutput = logMessage;//from  ww w.j  a v  a 2  s.c  om
    } else if (!keepFields.equals("false") && !keepFields.equals("none")) {
        if (keepFields.indexOf("hostname") != -1) {
            expectedOutput = "mymachine " + expectedOutput;
        }
        if (keepFields.indexOf("timestamp") != -1) {
            expectedOutput = "Oct 11 22:14:15 " + expectedOutput;
        }
        if (keepFields.indexOf("version") != -1) {
            expectedOutput = "1 " + expectedOutput;
        }
        if (keepFields.indexOf("priority") != -1) {
            expectedOutput = "<34>" + expectedOutput;
        }
    }
    LOGGER.info("Created expected output: " + expectedOutput);

    /* Send test message to agent */
    sendMessage(logMessage);

    /* Wait for output file */
    int numberOfListDirAttempts = 0;
    while (sinkOutputDir.listFiles().length == 0) {
        if (++numberOfListDirAttempts >= DEFAULT_ATTEMPTS) {
            throw new AssertionError("FILE_ROLL sink hasn't written any files after " + DEFAULT_ATTEMPTS
                    + " attempts with " + DEFAULT_TIMEOUT + " ms timeout.");
        }

        TimeUnit.MILLISECONDS.sleep(DEFAULT_TIMEOUT);
    }

    // Only 1 file should be in FILE_ROLL sink's dir (rolling is disabled)
    File[] sinkOutputDirChildren = sinkOutputDir.listFiles();
    Assert.assertEquals("Expected FILE_ROLL sink's dir to have only 1 child," + " but found "
            + sinkOutputDirChildren.length + " children.", 1, sinkOutputDirChildren.length);

    /* Wait for output file stats to be as expected. */
    File outputDirChild = sinkOutputDirChildren[0];
    int numberOfStatsAttempts = 0;
    while (outputDirChild.length() != expectedOutput.length()) {
        if (++numberOfStatsAttempts >= DEFAULT_ATTEMPTS) {
            throw new AssertionError("Expected output and FILE_ROLL sink's" + " lengths did not match after "
                    + DEFAULT_ATTEMPTS + " attempts with " + DEFAULT_TIMEOUT + " ms timeout.");
        }

        TimeUnit.MILLISECONDS.sleep(DEFAULT_TIMEOUT);
    }

    File actualOutput = sinkOutputDirChildren[0];
    if (!Files.toString(actualOutput, Charsets.UTF_8).equals(expectedOutput)) {
        LOGGER.error("Actual output doesn't match expected output.\n");
        LOGGER.debug("Output: " + Files.toString(actualOutput, Charsets.UTF_8));
        throw new AssertionError("FILE_ROLL sink's actual output doesn't " + "match expected output.");
    }
}

From source file:io.hops.hopsworks.api.certs.CertSigningService.java

private CsrDTO signCSR(String hostId, String commandId, String csr, boolean rotation, boolean isAppCertificate)
        throws AppException {
    try {//from  www  .  java 2s .co m
        // If there is a certificate already for that host, rename it to .TO_BE_REVOKED.COMMAND_ID
        // When AgentResource has received a successful response for the key rotation, revoke and delete it
        if (rotation) {
            File certFile = Paths.get(settings.getIntermediateCaDir(), "certs",
                    hostId + CertificatesMgmService.CERTIFICATE_SUFFIX).toFile();
            if (certFile.exists()) {
                File destination = Paths
                        .get(settings.getIntermediateCaDir(), "certs",
                                hostId + serviceCertificateRotationTimer.getToBeRevokedSuffix(commandId))
                        .toFile();
                try {
                    FileUtils.moveFile(certFile, destination);
                } catch (FileExistsException ex) {
                    FileUtils.deleteQuietly(destination);
                    FileUtils.moveFile(certFile, destination);
                }
            }
        }
        String agentCert = opensslOperations.signCertificateRequest(csr, true, true, isAppCertificate);
        File caCertFile = Paths.get(settings.getIntermediateCaDir(), "certs", "ca-chain.cert.pem").toFile();
        String caCert = Files.toString(caCertFile, Charset.defaultCharset());
        return new CsrDTO(caCert, agentCert, settings.getHadoopVersionedDir());
    } catch (IOException ex) {
        String errorMsg = "Error while signing CSR for host " + hostId + " Reason: " + ex.getMessage();
        logger.log(Level.SEVERE, errorMsg, ex);
        throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), errorMsg);
    }
}

From source file:com.android.idegen.Module.java

public void buildImlFile() throws IOException {
    String imlTemplate = Files.toString(new File(DirectorySearch.findTemplateDir(), IML_TEMPLATE_FILE_NAME),
            IntellijProject.CHARSET);/*from  w  w  w  .j a  v  a 2 s.c om*/

    String facetXml = "";
    if (isAndroidModule()) {
        facetXml = buildAndroidFacet();
    }
    imlTemplate = imlTemplate.replace("@FACETS@", facetXml);

    String moduleDir = getDir().getCanonicalPath();

    StringBuilder sourceDirectories = new StringBuilder();
    sourceDirectories.append("    <content url=\"file://$MODULE_DIR$\">\n");
    ImmutableList<File> srcDirs = getSourceDirs();
    for (File src : srcDirs) {
        String relative = src.getCanonicalPath().substring(moduleDir.length());
        boolean isTestSource = false;
        // This covers directories like .../test[s]/...
        if (relative.matches(".*/tests?/.*")) {
            isTestSource = true;
        }
        sourceDirectories.append("      <sourceFolder url=\"file://$MODULE_DIR$").append(relative)
                .append("\" isTestSource=\"").append(isTestSource).append("\" />\n");
    }
    ImmutableList<File> excludeDirs = getExcludeDirs();
    for (File src : excludeDirs) {
        String relative = src.getCanonicalPath().substring(moduleDir.length());
        sourceDirectories.append("      <excludeFolder url=\"file://$MODULE_DIR$").append(relative)
                .append("\"/>\n");
    }
    sourceDirectories.append("    </content>\n");

    // Intermediates.
    sourceDirectories.append(buildIntermediates());

    imlTemplate = imlTemplate.replace("@SOURCES@", sourceDirectories.toString());

    StringBuilder moduleDependencies = new StringBuilder();
    for (String dependency : getAllDependencies()) {
        Module module = moduleCache.getAndCacheByDir(new File(dependency));
        moduleDependencies.append("    <orderEntry type=\"module\" module-name=\"").append(module.getName())
                .append("\" />\n");
    }
    imlTemplate = imlTemplate.replace("@MODULE_DEPENDENCIES@", moduleDependencies.toString());

    imlFile = new File(moduleDir, getName() + ".iml");
    logger.info("Creating " + imlFile.getCanonicalPath());
    Files.write(imlTemplate, imlFile, IntellijProject.CHARSET);
}

From source file:terrastore.store.js.JSInvoker.java

private String loadFunction(String declaration) throws IOException {
    String separator = System.getProperty("file.separator");
    File f = IOUtils.getFileFromTerrastoreHome(JAVASCRIPT_DIR + separator + declaration);
    return Files.toString(f, Charset.forName("UTF-8"));
}

From source file:com.facebook.buck.testutil.integration.ProjectWorkspace.java

public String getFileContents(String pathRelativeToProjectRoot) throws IOException {
    return Files.toString(getFile(pathRelativeToProjectRoot), Charsets.UTF_8);
}

From source file:com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTransferCases2.java

public void filesToStringReturnNonNull() throws IOException {
    // BUG: Diagnostic contains: (Non-null)
    triggerNullnessChecker(Files.toString(new File("/dev/null"), UTF_8));
}