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:de.nx42.maps4cim.ResourceLoader.java

/**
 * Reads a base64-encoded Resource from the classpath and returns it as
 * byte-array// w w  w .  j ava  2 s  .  c o  m
 * @param path the path to the resource to load
 * @return the decoded resource as byte-array
 * @throws IllegalArgumentException if the resource is not found
 * @throws IOException if the resource cannot be read as base64
 */
public static byte[] readBase64Resource(String path) throws IllegalArgumentException, IOException {
    String base64 = Resources.toString(Resources.getResource(path), Charsets.UTF_8);
    String trimmed = CharMatcher.WHITESPACE.removeFrom(base64);
    return BaseEncoding.base64().decode(trimmed);
}

From source file:net.oneandone.troilus.CassandraDB.java

/**
 * executes a CQL file. CQL processing errors will be ignored 
 * /*from   w ww .  j a v a  2  s .c o m*/
 * @param cqlFile    the CQL file name 
 * @throws IOException  if the file could not be found
 */
public void tryExecuteCqlFile(String cqlFile) {
    try {
        File file = new File(cqlFile);
        if (file.exists()) {
            tryExecuteCqls(Splitter.on(";").split(Files.toString(new File(cqlFile), Charsets.UTF_8)));
        } else {
            tryExecuteCqls(
                    Splitter.on(";").split(Resources.toString(Resources.getResource(cqlFile), Charsets.UTF_8)));
        }
    } catch (IOException ioe) {
        throw new RuntimeException(cqlFile + " not found");
    }
}

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

public synchronized File buildBundle(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 w w.  j  av  a 2 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 buildBundle or not
    if (cacheKeyBuilder.toString().equals(bundleCacheKey) && currentCacheBundle.isFile() && !forceRefresh) {
        return currentCacheBundle;
    }

    // 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 = "bundles" + idx++;
        loadJsImport.append("import " + className + " from \"" + moduleNameVersion[0] + "\"\n");

        loadJsRegister.append(HELIUM_BUNDLES_VAR + ".push({\n");
        loadJsRegister.append("id: \"" + moduleNameVersion[0] + "\",\n");
        loadJsRegister.append("name: \"" + pkg.getName() + "\",\n");
        loadJsRegister.append("icon: " + gson.toJson(pkg.getIcon()) + ",\n");
        loadJsRegister.append("type: \"" + pkg.getType() + "\",\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());

    copyFrameworkModuleToInstallPath(npmPackageCopyFilter);

    try {
        out.reset();
        npmCommand("install --loglevel=error");
    } catch (TaskRunnerException e) {
        // ignore `(empty)` warning
        String cause = new String(out.toByteArray());
        if (!cause.contains("(empty)")) {
            throw new IOException(cause);
        }
    }

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

    String bundleStdoutResult = new String(out.toByteArray());

    File heliumBundle = new File(workingDirectory, HELIUM_BUNDLE);
    if (!heliumBundle.isFile()) {
        throw new IOException("Can't create bundle: \n" + bundleStdoutResult);
    }

    WebpackResult result = getWebpackResultFromOutput(bundleStdoutResult);
    if (result.errors.length > 0) {
        heliumBundle.delete();
        throw new IOException(result.errors[0]);
    }

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

From source file:net.chris54721.infinitycubed.utils.Utils.java

public static String toString(URL url) throws IOException {
    return Resources.toString(url, Charsets.UTF_8);
}

From source file:com.wx3.galacdecks.networking.HttpHandler.java

public HttpHandler(NettyWebSocketServer server) {
    this.server = server;

    URL url = Resources.getResource("index.html");

    try {/*from  ww w .ja v a2s. c om*/
        this.webpage = Resources.toString(url, Charsets.UTF_8);
    } catch (IOException e) {
        this.webpage = "No default webpage for this WebSocketServer";
    }
}

From source file:integration.BaseRestTestHelper.java

/**
 * Use this method to load a json file from the classpath.
 * <p>/*  w ww. j  ava 2s .  c  o m*/
 *     It will be looked for relative to the caller's object's class.
 * </p>
 * For example if you have a class in the package <code>integration.system.users</code> and call <code>jsonResource("abc.json")</code>
 * on the instance of your test class (i.e. <code>this</code>), it will look for a file in <code>resources/integration/system/inputs/abc.json</code>.
 * <p>
 *     If the file does not exist or cannot be read, a {@link java.lang.IllegalStateException} will be raised which should cause your test to fail.
 * </p>
 * @param relativeFileName the name of the file relative to the caller's class.
 * @return the bytes in that file.
 */
protected String jsonResource(String relativeFileName) {
    final URL resource = Resources.getResource(this.getClass(), relativeFileName);
    if (resource == null) {
        throw new IllegalStateException(
                "Unable to find JSON resource " + relativeFileName + " for test. This is a bug.");
    }
    try {
        return Resources.toString(resource, Charset.defaultCharset());
    } catch (IOException e) {
        throw new IllegalStateException(
                "Unable to read JSON resource " + relativeFileName + " for test. This is a bug.");
    }
}

From source file:org.onosproject.drivers.netconf.TemplateManager.java

/**
 * Loads the named templates into the template manager.
 *
 * @param reference//from   ww  w. ja  va  2  s .c o  m
 *            the class reference from which to load resources
 * @param pattern
 *            pattern to convert template name to resource path
 * @param templateNames
 *            list of template to load
 */
public void load(Class<? extends Object> reference, String pattern, String... templateNames) {
    for (String name : templateNames) {
        String key = name;
        String resource;

        // If the template name begins with a '/', then assume it is a full path
        // specification
        if (name.charAt(0) == '/') {
            int start = name.lastIndexOf('/') + 1;
            int end = name.lastIndexOf('.');
            if (end == -1) {
                key = name.substring(start);
            } else {
                key = name.substring(start, end);
            }
            resource = name;
        } else {
            resource = String.format(pattern, name);
        }

        log.debug("LOAD TEMPLATE: '{}' as '{}' from '{}", name, key, resource);

        try {
            templates.put(name,
                    Resources.toString(Resources.getResource(reference, resource), StandardCharsets.UTF_8));

        } catch (IOException ioe) {
            log.error("Unable to load NETCONF request template '{}' from '{}'", key, resource, ioe);
        }
    }
}

From source file:net.fabricmc.installer.installer.MultiMCInstaller.java

private static String readBaseJson() throws IOException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    String string = Resources.toString(classLoader.getResource("multimcPatch.json"), StandardCharsets.UTF_8);
    return string;
}

From source file:com.netflix.exhibitor.core.rest.UIResource.java

@Path("{file:.*}")
@GET//from w w  w . j  a  v a  2s  .c  o m
public Response getResource(@PathParam("file") String fileName) throws IOException {
    if (fileName.startsWith(jQueryUiPrefix)) {
        String stripped = fileName.substring(jQueryUiPrefix.length());
        fileName = "css/jquery/" + context.getExhibitor().getJQueryStyle().name().toLowerCase() + "/"
                + stripped;
    }

    URL resource;
    try {
        resource = Resources.getResource("com/netflix/exhibitor/core/ui/" + fileName);
    } catch (IllegalArgumentException dummy) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
    String resourceFile = resource.getFile();
    String contentType;
    if (resourceFile.endsWith(".png")) {
        contentType = "image/png"; // not in default mime types
    } else if (resourceFile.endsWith(".js")) {
        contentType = "text/javascript"; // not in default mime types
    } else if (resourceFile.endsWith(".css")) {
        contentType = "text/css"; // not in default mime types
    } else {
        contentType = fileTypeMap.getContentType(resourceFile);
    }
    Object entity;
    if (contentType.startsWith("text/")) {
        entity = Resources.toString(resource, Charset.forName("UTF-8"));
    } else {
        entity = Resources.toByteArray(resource);
    }
    return Response.ok(entity).type(contentType).build();
}

From source file:org.jclouds.abiquo.domain.ConfigResources.java

private static String readLicense(final String filename) {
    URL url = ConfigResources.class.getResource("/" + filename);
    try {/*from w ww .  jav a  2  s. com*/
        return Resources.toString(url, Charset.defaultCharset());
    } catch (IOException e) {
        throw new RuntimeException("Could not read file " + filename);
    }
}