Example usage for com.google.common.io Resources toString

List of usage examples for com.google.common.io Resources toString

Introduction

In this page you can find the example usage for com.google.common.io Resources toString.

Prototype

public static String toString(URL url, Charset charset) throws IOException 

Source Link

Document

Reads all characters from a URL into a String , using the given character set.

Usage

From source file:eu.numberfour.n4js.antlr.replacements.PlaceholderReplacer.java

/**
 * Load 'search' and 'replace' strings from a file from this class' directory.
 *///  w  w  w .  j  av  a2 s  .c om
public PlaceholderReplacer(String replacementName) throws IOException {
    String replacementBase = Replacements.class.getPackage().getName().replace(".", "/");
    this.source = replacementBase + "/" + replacementName;
    URL url = Replacements.class.getClassLoader().getResource(source);
    if (url == null) {
        throw new NullPointerException("cannot replacement :: " + source);
    }
    // normalize string to run on Windows and Mac/Unix
    String fileContents = Resources.toString(url, Charsets.UTF_8).replace("\r\n", "\n");
    String[] split = fileContents.split(SEPARATOR);
    String searchString = split[0];
    String replacementString = split[1];
    this.searchPattern = createPattern(searchString);
    this.replacement = createReplace(replacementString);
}

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

@TaskAction
public void doTask() throws IOException {
    // resolve replacements
    for (Entry<String, Object> entry : replacements.entrySet()) {
        replacements.put(entry.getKey(), Constants.resolveString(entry.getValue()).replace('\\', '/'));
    }//ww  w . j a v a  2s.c  o m

    // extract extra initscripts
    List<File> initscripts = Lists.newArrayListWithCapacity(initResources.size());
    for (int i = 0; i < initResources.size(); i++) {
        File file = new File(getTemporaryDir(), "initscript" + i);
        String thing = Resources.toString(initResources.get(i), Constants.CHARSET);

        for (Entry<String, Object> entry : replacements.entrySet()) {
            thing = thing.replace(entry.getKey(), (String) entry.getValue());
        }

        Files.write(thing, file, Constants.CHARSET);
        initscripts.add(file);
    }

    // get current Gradle instance
    Gradle gradle = getProject().getGradle();

    getProject().getLogger().lifecycle("------------------------ ");
    getProject().getLogger().lifecycle("--------SUB-CALL-------- ");
    getProject().getLogger().lifecycle("------------------------ ");

    // connect to project
    ProjectConnection connection = GradleConnector.newConnector()
            .useGradleUserHomeDir(gradle.getGradleUserHomeDir()).useInstallation(gradle.getGradleHomeDir())
            .forProjectDirectory(getProjectDir()).connect();

    //get args
    ArrayList<String> args = new ArrayList<String>(5);
    args.addAll(Splitter.on(' ').splitToList(getCallLine()));

    for (File f : initscripts) {
        args.add("-I" + f.getCanonicalPath());
    }

    // build
    connection.newBuild().setStandardOutput(System.out).setStandardInput(System.in).setStandardError(System.err)
            .withArguments(args.toArray(new String[args.size()])).setColorOutput(false).run();

    getProject().getLogger().lifecycle("------------------------ ");
    getProject().getLogger().lifecycle("------END-SUB-CALL------ ");
    getProject().getLogger().lifecycle("------------------------ ");
}

From source file:com.facebook.presto.archiveConnector.ArchiveClient.java

private static Map<String, Map<String, ArchiveTable>> lookupSchemas(URI metadataUri,
        JsonCodec<Map<String, List<ArchiveTable>>> catalogCodec) throws IOException {
    URL result = metadataUri.toURL();
    String json = Resources.toString(result, UTF_8);
    Map<String, List<ArchiveTable>> catalog = catalogCodec.fromJson(json);

    return ImmutableMap.copyOf(transformValues(catalog, resolveAndIndexTables(metadataUri)));
}

From source file:com.arpnetworking.metrics.mad.performance.FilePerfTestBase.java

/**
 * Runs a filter.//from   ww  w .j  ava  2s .com
 *
 * @param pipelineConfigurationFile Pipeline configuration file.
 * @param duration Timeout period.
 * @param variables Substitution key-value pairs into pipeline configuration file.
 * @throws IOException if configuration cannot be loaded.
 */
protected void benchmark(final String pipelineConfigurationFile, final Duration duration,
        final ImmutableMap<String, String> variables) throws IOException {
    // Replace any variables in the configuration file
    String configuration = Resources.toString(Resources.getResource(pipelineConfigurationFile), Charsets.UTF_8);
    for (final Map.Entry<String, String> entry : variables.entrySet()) {
        configuration = configuration.replace(entry.getKey(), entry.getValue());
    }

    // Load the specified stock configuration
    final PipelineConfiguration stockPipelineConfiguration = new StaticConfiguration.Builder()
            .addSource(new JsonNodeLiteralSource.Builder().setSource(configuration).build())
            .setObjectMapper(PipelineConfiguration.createObjectMapper(_injector)).build()
            .getRequiredAs(PipelineConfiguration.class);

    // Canary tracking
    LOGGER.info(String.format("Expected canaries; periods=%s", stockPipelineConfiguration.getPeriods()));
    final CountDownLatch latch = new CountDownLatch(stockPipelineConfiguration.getPeriods().size());
    final Set<Period> periods = Sets.newConcurrentHashSet();

    // Create custom "canary" sink
    final ListeningSink sink = new ListeningSink((periodicData) -> {
        if (periodicData != null) {
            for (final String metricName : periodicData.getData().keys()) {
                if (TestFileGenerator.CANARY.equals(metricName)) {
                    if (periods.add(periodicData.getPeriod())) {
                        LOGGER.info(String.format("Canary flew; filter=%s, period=%s", this.getClass(),
                                periodicData.getPeriod()));
                        latch.countDown();
                    }
                }
            }
        }
        return null;
    });

    // Add the custom "canary" sink
    final List<Sink> benchmarkSinks = Lists.newArrayList(stockPipelineConfiguration.getSinks());
    benchmarkSinks.add(sink);

    // Create the custom configuration
    final PipelineConfiguration benchmarkPipelineConfiguration = OvalBuilder.<PipelineConfiguration, PipelineConfiguration.Builder>clone(
            stockPipelineConfiguration).setSinks(benchmarkSinks).build();

    // Instantiate the pipeline
    final Pipeline pipeline = new Pipeline(benchmarkPipelineConfiguration);

    // Execute the pipeline until the canary flies the coop
    try {
        LOGGER.debug(String.format("Launching pipeline; configuration=%s", pipelineConfigurationFile));
        final Stopwatch timer = Stopwatch.createUnstarted();
        timer.start();
        pipeline.launch();

        if (!latch.await(duration.getMillis(), TimeUnit.MILLISECONDS)) {
            LOGGER.error("Test timed out");
            throw new RuntimeException("Test timed out");
        }

        timer.stop();
        LOGGER.info(String.format("Performance filter result; filter=%s, seconds=%s", this.getClass(),
                timer.elapsed(TimeUnit.SECONDS)));

    } catch (final InterruptedException e) {
        Thread.interrupted();
        throw new RuntimeException("Test interrupted");
    } finally {
        pipeline.shutdown();
    }
}

From source file:com.mgmtp.perfload.perfalyzer.reporting.email.EmailSkeleton.java

@Override
protected void build() {
    String css = null;//  w ww .  jav  a 2s  .c om
    try {
        css = Resources.toString(Resources.getResource("email/email.css"), Charsets.UTF_8);
    } catch (IOException ex) {
        log.error("Could not read CSS for e-mail", ex);
    }

    raw("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

    //@formatter:off

    html();
    head();
    title().text("perfAlyzer Report").end();
    meta().httpEquiv("Content-Type").content("text/html; charset=UTF-8").end();
    if (css != null) {
        style().type("text/css").text(SystemUtils.LINE_SEPARATOR + css).end();
    }
    end();
    body();
    div().id("content");
    h1().text("perfAlyzer E-mail Report").end();
    div();
    table();
    tbody();
    tr();
    th().text(resourceBundle.getString("overview.testplan")).end();
    td().text(testMetadata.getTestPlanFile()).end();
    end();
    tr();
    th().text(resourceBundle.getString("overview.start")).end();
    td().text(dateTimeFormatter.format(testMetadata.getTestStart())).end();
    end();
    tr();
    th().text(resourceBundle.getString("overview.end")).end();
    td().text(dateTimeFormatter.format(testMetadata.getTestEnd())).end();
    end();
    tr();
    th().text(resourceBundle.getString("overview.duration")).end();
    td().text(testMetadata.getTestDuration()).end();
    end();
    tr();
    th().text(resourceBundle.getString("overview.operations")).end();
    td().text(on(", ").join(testMetadata.getOperations())).end();
    end();
    tr();
    th().text(resourceBundle.getString("overview.comment")).end();
    td().text(testMetadata.getTestComment()).end();
    end();
    tr();
    th().text(resourceBundle.getString("overview.rawResultsDir")).end();
    td().text(testMetadata.getRawResultsDir()).end();
    end();
    tr();
    th().text(resourceBundle.getString("overview.perfloadVersion")).end();
    td().text(testMetadata.getPerfLoadVersion()).end();
    end();
    if (linkToReport != null) {
        tr();
        th().text(resourceBundle.getString("report.link")).end();
        td().a().href(linkToReport).text(linkToReport).alt("Link to perfAlyzer Report").end().end();
        end();
    }
    end();
    end();
    end();
    br();
    addDataTable(data, true);
    for (Entry<String, List<? extends List<String>>> entry : comparisonData.entrySet()) {
        br();
        h2().text("Comparison - " + entry.getKey()).end();
        addDataTable(entry.getValue(), false);
    }
    end();
    end();
    end();

    //@formatter:on
}

From source file:com.facebook.buck.lua.AbstractLuaScriptStarter.java

private String getPureStarterTemplate() {
    try {/*from  w  w  w.j  a  v  a 2s  . c  om*/
        return Resources.toString(Resources.getResource(STARTER), Charsets.UTF_8);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.netflix.simianarmy.chaos.ScriptChaosType.java

/**
 * Runs the script.//from w w  w.j  a  v a 2 s  . c  o  m
 */
@Override
public void apply(ChaosInstance instance) {
    LOGGER.info("Running script for {} on instance {}", getKey(), instance.getInstanceId());

    SshClient ssh = instance.connectSsh();

    String filename = getKey().toLowerCase() + ".sh";
    URL url = Resources.getResource(ScriptChaosType.class, "/scripts/" + filename);
    String script;
    try {
        script = Resources.toString(url, Charsets.UTF_8);
    } catch (IOException e) {
        throw new IllegalStateException("Error reading script resource", e);
    }

    ssh.put("/tmp/" + filename, script);
    ExecResponse response = ssh.exec("/bin/bash /tmp/" + filename);
    if (response.getExitStatus() != 0) {
        LOGGER.warn("Got non-zero output from running script: {}", response);
    }
    ssh.disconnect();
}

From source file:org.sonar.plugins.javascript.rules.JavaScriptRulesDefinition.java

@Nullable
private static String readRuleDefinitionResource(String fileName) {
    URL resource = JavaScriptRulesDefinition.class
            .getResource("/org/sonar/l10n/javascript/rules/javascript/" + fileName);
    if (resource == null) {
        return null;
    }/*from  ww w.  j  ava  2s .c o  m*/
    try {
        return Resources.toString(resource, Charsets.UTF_8);
    } catch (IOException e) {
        throw new IllegalStateException("Failed to read: " + resource, e);
    }
}

From source file:com.facebook.buck.features.lua.AbstractLuaScriptStarter.java

private String getPureStarterTemplate() {
    try {/*  w w  w .  ja v a  2  s. c o  m*/
        return Resources.toString(Resources.getResource(AbstractLuaScriptStarter.class, STARTER),
                Charsets.UTF_8);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.google.gapid.views.Licenses.java

protected static String readLicenses(boolean html) {
    try {/* ww  w  .j a v  a 2s.c  om*/
        String result = Resources.toString(Resources.getResource("text/licenses.html"), UTF_8);
        if (html) {
            // Linkify links.
            result = result.replaceAll("(https?://[^\\s]+(?:[^\\s.,;:!?'\"()\\[\\]{}]))",
                    "<a href='$1'>$1</a>");
        } else {
            // De-HTML the text.
            result = result.replaceAll("<[^>]+>", "");
        }
        return result;
    } catch (IOException | IllegalArgumentException e) {
        LOG.log(SEVERE, "Failed to load the licenses", e);
        return "Failed to load the licenses.";
    }
}