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:io.viewserver.server.steps.ViewServerSteps.java

private DataSource getDataSource(String dataSourceFile) throws IOException {
    JacksonSerialiser serialiser = new JacksonSerialiser();
    String json = Resources.toString(Resources.getResource(dataSourceFile), Charsets.UTF_8);
    DataSource dataSource = serialiser.deserialise(json, DataSource.class);
    return dataSource;
}

From source file:com.google.template.soy.data.SanitizedContents.java

/**
 * Loads assumed-safe content from a Java resource.
 *
 * This performs ZERO VALIDATION of the data, and takes you on your word that the input is valid.
 * We assume that resources should be safe because they are part of the binary, and therefore not
 * attacker controlled, unless the source code is compromised (in which there's nothing we can
 * do)./*from   w  w  w  .j  av a2  s  .  c o  m*/
 *
 * @param contextClass Class relative to which to load the resource.
 * @param resourceName The name of the resource, relative to the context class.
 * @param charset The character set to use, usually Charsets.UTF_8.
 * @param kind The content kind of the resource.
 */
public static SanitizedContent fromResource(Class<?> contextClass, String resourceName, Charset charset,
        ContentKind kind) throws IOException {
    pretendValidateResource(resourceName, kind);
    return SanitizedContent.create(
            Resources.toString(Resources.getResource(contextClass, resourceName), charset), kind,
            // Text resources are usually localized, so one might think that the locale direction should
            // be assumed for them. We do not do that because:
            // - We do not know the locale direction here.
            // - Some messages do not get translated.
            // - This method currently can't be used for text resources (see pretendValidateResource()).
            getDefaultDir(kind));
}

From source file:com.thoughtworks.selenium.webdriven.JavascriptLibrary.java

String readScriptImpl(String script) {
    URL url = getClass().getResource(script);

    if (url == null) {
        throw new RuntimeException("Cannot locate " + script);
    }/*from   ww  w . ja  v a  2  s  .  com*/

    try {
        return Resources.toString(url, Charsets.UTF_8);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.optimizely.ab.event.internal.serializer.SerializerTestUtils.java

static String generateConversionJson() throws IOException {
    String conversionJson = Resources.toString(Resources.getResource("serializer/conversion.json"),
            Charsets.UTF_8);/*from w  w w.  jav  a 2s .co m*/
    return conversionJson.replaceAll("\\s+", "");
}

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

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

From source file:com.cognifide.aemrules.extensions.RulesLoader.java

protected String getDescriptionFromResources(String ruleKey) {
    String result = null;//w w w  .  ja  va  2  s. co  m
    try {
        String path = String.format("/rules/%s.md", ruleKey);
        URL url = Resources.getResource(RulesLoader.class, path);
        result = Resources.toString(url, Charsets.UTF_8);
    } catch (IOException | IllegalArgumentException e) {
        LOG.error("Cannot read resource file with rule description.", e);
    }
    return result;
}

From source file:org.eclipse.scada.configuration.setup.common.lib.SerialToNetworkHandler.java

protected StringReader makeScript(final Map<String, String> properties, final String resourceName)
        throws IOException {
    return new StringReader(StringReplacer.replace(
            Resources.toString(this.getClass().getResource(resourceName), StandardCharsets.UTF_8),
            StringReplacer.newSource(properties), PATTERN));
}

From source file:org.solrsystem.ingest.Main.java

private static AbstractMap<String, Object> usage(String[] args) throws IOException {
    URL usage = Resources.getResource("usage.docopts.txt");
    String usageStr = Resources.toString(usage, Charset.forName("UTF-8"));
    @SuppressWarnings("unchecked")
    AbstractMap<String, Object> result = clj.docopt(usageStr, args);
    if (result != null) {
        for (String s : result.keySet()) {
            log.debug("{}:{}", s, result.get(s));
        }/*from w w w  . ja  v a2  s . c o  m*/
    }
    if (result == null || result.get("--help") != null) {
        System.out.println(usageStr);
        System.exit(1);
    }
    return result;
}

From source file:com.jaeksoft.searchlib.crawler.web.browser.BrowserDriver.java

private final synchronized static String getXPath() throws IOException {
    if (XPATH_SCRIPT != null)
        return XPATH_SCRIPT;
    URL url = Resources.getResource("/com/jaeksoft/searchlib/crawler/web/browser/get_xpath.js");
    String content = Resources.toString(url, Charsets.UTF_8);
    BufferedReader br = new BufferedReader(new StringReader(content));
    StringBuilder sb = new StringBuilder();
    String line;/*from  www.  j a  v  a2  s  . c  om*/
    while ((line = br.readLine()) != null)
        sb.append(line.trim());
    br.close();
    XPATH_SCRIPT = sb.toString();
    return XPATH_SCRIPT;
}

From source file:org.apache.zeppelin.helium.HeliumVisualizationFactory.java

public synchronized File bundle(List<HeliumPackage> pkgs, boolean forceRefresh) throws IOException {
    // package.json
    URL pkgUrl = Resources.getResource("helium/package.json");
    String pkgJson = Resources.toString(pkgUrl, Charsets.UTF_8);
    StringBuilder dependencies = new StringBuilder();
    StringBuilder cacheKeyBuilder = new StringBuilder();

    FileFilter npmPackageCopyFilter = new FileFilter() {
        @Override//from w ww .  ja v  a2 s. c  om
        public boolean accept(File pathname) {
            String fileName = pathname.getName();
            if (fileName.startsWith(".") || fileName.startsWith("#") || fileName.startsWith("~")) {
                return false;
            } else {
                return true;
            }
        }
    };

    for (HeliumPackage pkg : pkgs) {
        String[] moduleNameVersion = getNpmModuleNameAndVersion(pkg);
        if (moduleNameVersion == null) {
            logger.error("Can't get module name and version of package " + pkg.getName());
            continue;
        }
        if (dependencies.length() > 0) {
            dependencies.append(",\n");
        }
        dependencies.append("\"" + moduleNameVersion[0] + "\": \"" + moduleNameVersion[1] + "\"");
        cacheKeyBuilder.append(pkg.getName() + pkg.getArtifact());

        File pkgInstallDir = new File(workingDirectory, "node_modules/" + pkg.getName());
        if (pkgInstallDir.exists()) {
            FileUtils.deleteDirectory(pkgInstallDir);
        }

        if (isLocalPackage(pkg)) {
            FileUtils.copyDirectory(new File(pkg.getArtifact()), pkgInstallDir, npmPackageCopyFilter);
        }
    }
    pkgJson = pkgJson.replaceFirst("DEPENDENCIES", dependencies.toString());

    // check if we can use previous bundle or not
    if (cacheKeyBuilder.toString().equals(bundleCacheKey) && currentBundle.isFile() && !forceRefresh) {
        return currentBundle;
    }

    // webpack.config.js
    URL webpackConfigUrl = Resources.getResource("helium/webpack.config.js");
    String webpackConfig = Resources.toString(webpackConfigUrl, Charsets.UTF_8);

    // generate load.js
    StringBuilder loadJsImport = new StringBuilder();
    StringBuilder loadJsRegister = new StringBuilder();

    long idx = 0;
    for (HeliumPackage pkg : pkgs) {
        String[] moduleNameVersion = getNpmModuleNameAndVersion(pkg);
        if (moduleNameVersion == null) {
            continue;
        }

        String className = "vis" + idx++;
        loadJsImport.append("import " + className + " from \"" + moduleNameVersion[0] + "\"\n");

        loadJsRegister.append("visualizations.push({\n");
        loadJsRegister.append("id: \"" + moduleNameVersion[0] + "\",\n");
        loadJsRegister.append("name: \"" + pkg.getName() + "\",\n");
        loadJsRegister.append("icon: " + gson.toJson(pkg.getIcon()) + ",\n");
        loadJsRegister.append("class: " + className + "\n");
        loadJsRegister.append("})\n");
    }

    FileUtils.write(new File(workingDirectory, "package.json"), pkgJson);
    FileUtils.write(new File(workingDirectory, "webpack.config.js"), webpackConfig);
    FileUtils.write(new File(workingDirectory, "load.js"), loadJsImport.append(loadJsRegister).toString());

    // install tabledata module
    File tabledataModuleInstallPath = new File(workingDirectory, "node_modules/zeppelin-tabledata");
    if (tabledataModulePath != null) {
        if (tabledataModuleInstallPath.exists()) {
            FileUtils.deleteDirectory(tabledataModuleInstallPath);
        }
        FileUtils.copyDirectory(tabledataModulePath, tabledataModuleInstallPath, npmPackageCopyFilter);
    }

    // install visualization module
    File visModuleInstallPath = new File(workingDirectory, "node_modules/zeppelin-vis");
    if (visualizationModulePath != null) {
        if (visModuleInstallPath.exists()) {
            // when zeppelin-vis and zeppelin-table package is published to npm repository
            // we don't need to remove module because npm install command will take care
            // dependency version change. However, when two dependencies are copied manually
            // into node_modules directory, changing vis package version results inconsistent npm
            // install behavior.
            //
            // Remote vis package everytime and let npm download every time bundle as a workaround
            FileUtils.deleteDirectory(visModuleInstallPath);
        }
        FileUtils.copyDirectory(visualizationModulePath, visModuleInstallPath, npmPackageCopyFilter);
    }

    out.reset();
    try {
        npmCommand("install");
        npmCommand("run bundle");
    } catch (TaskRunnerException e) {
        throw new IOException(new String(out.toByteArray()));
    }

    File visBundleJs = new File(workingDirectory, "vis.bundle.js");
    if (!visBundleJs.isFile()) {
        throw new IOException("Can't create visualization bundle : \n" + new String(out.toByteArray()));
    }

    WebpackResult result = getWebpackResultFromOutput(new String(out.toByteArray()));
    if (result.errors.length > 0) {
        visBundleJs.delete();
        throw new IOException(result.errors[0]);
    }

    synchronized (this) {
        currentBundle.delete();
        FileUtils.moveFile(visBundleJs, currentBundle);
        bundleCacheKey = cacheKeyBuilder.toString();
    }
    return currentBundle;
}