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

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

Introduction

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

Prototype

public static URL getResource(String resourceName) 

Source Link

Document

Returns a URL pointing to resourceName if the resource is found using the Thread#getContextClassLoader() context class loader .

Usage

From source file:com.torodb.mongodb.core.DefaultBuildProperties.java

public DefaultBuildProperties(String propertiesFile) {
    PropertiesConfiguration properties;/*from www.ja va  2s  . com*/
    try {
        properties = new PropertiesConfiguration(Resources.getResource(propertiesFile));
    } catch (ConfigurationException e) {
        throw new RuntimeException("Cannot read build properties file '" + propertiesFile + "'");
    }

    fullVersion = properties.getString("version");
    Matcher matcher = FULL_VERSION_PATTERN.matcher(fullVersion);
    if (!matcher.matches()) {
        throw new RuntimeException("Invalid version string '" + fullVersion + "'");
    }
    majorVersion = Integer.parseInt(matcher.group(1));
    minorVersion = Integer.parseInt(matcher.group(2));
    subVersion = matcher.group(3) != null ? Integer.parseInt(matcher.group(3)) : 0;
    extraVersion = matcher.group(4);

    // DateUtils.parseDate may be replaced by SimpleDateFormat if using Java7
    try {
        buildTime = Instant.parse(properties.getString("buildTimestamp"));
    } catch (DateTimeParseException e) {
        throw new RuntimeException("buildTimestamp property not in ISO8601 format", e);
    }

    gitCommitId = properties.getString("gitCommitId");
    gitBranch = properties.getString("gitBranch");
    gitRemoteOriginUrl = properties.getString("gitRemoteOriginURL");

    javaVersion = properties.getString("javaVersion");
    javaVendor = properties.getString("javaVendor");
    javaVmSpecificationVersion = properties.getString("javaVMSpecificationVersion");
    javaVmVersion = properties.getString("javaVMVersion");

    osName = properties.getString("osName");
    osArch = properties.getString("osArch");
    osVersion = properties.getString("osVersion");
}

From source file:org.wso2.msf4j.example.SampleClient.java

private static HttpEntity createMessageForSimpleFormStreaming() {
    HttpEntity reqEntity = null;//  ww w .  j av a 2  s  .  com
    try {
        reqEntity = MultipartEntityBuilder.create().addTextBody("name", "WSO2").addTextBody("age", "10")
                .addBinaryBody("file", new File(Resources.getResource("sample.txt").toURI()),
                        ContentType.DEFAULT_BINARY, "sample.txt")
                .build();
    } catch (URISyntaxException e) {
        log.error("Error while getting the file from resource." + e.getMessage(), e);
    }
    return reqEntity;
}

From source file:com.ning.billing.beatrix.osgi.SetupBundleWithAssertion.java

public void setupJrubyBundle() {

    try {/*from   w  ww. ja  va2  s  . c o m*/

        installJrubyJar();

        final URL resourceUrl = Resources.getResource(bundleName);
        final File unzippedRubyPlugin = unGzip(new File(resourceUrl.getFile()), rootInstallDir);

        final StringBuilder tmp = new StringBuilder(rootInstallDir.getAbsolutePath());
        tmp.append("/plugins/").append(PluginLanguage.RUBY.toString().toLowerCase());

        final File destination = new File(tmp.toString());
        if (!destination.exists()) {
            destination.mkdir();
        }

        unTar(unzippedRubyPlugin, destination);

    } catch (IOException e) {
        Assert.fail(e.getMessage());
    } catch (ArchiveException e) {
        Assert.fail(e.getMessage());
    }
}

From source file:com.facebook.buck.parser.BuckPythonProgram.java

/** Create a new instance by layout the files in a temporary directory. */
public static BuckPythonProgram newInstance(TypeCoercerFactory typeCoercerFactory,
        ImmutableSet<BaseDescription<?>> descriptions, boolean cleanupEnabled) throws IOException {

    Path pythonPath;/*from w w w  . j ava  2  s .  c  o m*/

    if (PATH_TO_PYTHON_DSL.isEmpty()) {
        try {
            URL url = Resources.getResource("buck_parser");

            if ("jar".equals(url.getProtocol())) {
                // Buck is being executed from a JAR file. Extract the jar file from the resource path,
                // and verify it is correct.
                // When python attempts to import `buck_parser`, it will see the jar file, and load it via
                // zipimport, and look into the `buck_parser` directory in the root of the jar.
                JarURLConnection connection = (JarURLConnection) url.openConnection();
                Preconditions.checkState(connection.getEntryName().equals("buck_parser"),
                        "buck_parser directory should be at the root of the jar file.");
                URI jarFileURI = connection.getJarFileURL().toURI();
                pythonPath = Paths.get(jarFileURI);
            } else if ("file".equals(url.getProtocol())) {
                // Buck is being executed from classpath on disk. Set the parent directory as the python
                // path.
                // When python attempts to import `buck_parser`, it will look for a `buck_parser` child
                // directory in the given path.
                pythonPath = Paths.get(url.toURI()).getParent();
            } else {
                throw new IllegalStateException(
                        "buck_python resource directory should reside in a local directory or in a jar file. "
                                + "Got: " + url);
            }
        } catch (URISyntaxException e) {
            throw new IllegalStateException("Failed to determine location of buck_parser python package", e);
        }
    } else {
        pythonPath = Paths.get(PATH_TO_PYTHON_DSL);
    }

    Path generatedRoot = Files.createTempDirectory("buck_python_program");
    LOG.debug("Writing python rules stub to %s.", generatedRoot);
    try (Writer out = Files.newBufferedWriter(generatedRoot.resolve("generated_rules.py"), UTF_8)) {
        out.write("from buck_parser.buck import *\n\n");
        BuckPyFunction function = new BuckPyFunction(typeCoercerFactory, CoercedTypeCache.INSTANCE);
        for (BaseDescription<?> description : descriptions) {
            try {
                out.write(function.toPythonFunction(DescriptionCache.getRuleType(description),
                        description.getConstructorArgType()));
                out.write('\n');
            } catch (RuntimeException e) {
                throw new BuckUncheckedExecutionException(e, "When writing python function for %s.",
                        description.getClass().getName());
            }
        }
    }

    String pathlibDir = PATH_TO_PATHLIB_PY.getParent().toString();
    String watchmanDir = PATH_TO_PYWATCHMAN.toString();
    String typingDir = PATH_TO_TYPING.toString();
    String sixDir = PATH_TO_SIX_PY.getParent().toString();
    try (Writer out = Files.newBufferedWriter(generatedRoot.resolve("__main__.py"), UTF_8)) {
        out.write(Joiner.on("\n").join("from __future__ import absolute_import, print_function", "import sys",
                "PY2 = sys.version_info[0] == 2",
                "sys.path.insert(0, "
                        + Escaper.escapeAsPythonString(MorePaths.pathWithUnixSeparators(pathlibDir)) + ")",
                "sys.path.insert(0, "
                        + Escaper.escapeAsPythonString(MorePaths.pathWithUnixSeparators(watchmanDir)) + ")",
                "if PY2:",
                "    sys.path.insert(0, "
                        + Escaper.escapeAsPythonString(MorePaths.pathWithUnixSeparators(typingDir)) + ")",
                "sys.path.insert(0, " + Escaper.escapeAsPythonString(MorePaths.pathWithUnixSeparators(sixDir))
                        + ")",
                // Path to the bundled python code.
                "sys.path.insert(0, "
                        + Escaper.escapeAsPythonString(MorePaths.pathWithUnixSeparators(pythonPath)) + ")",
                // Path to the generated rules stub.
                "sys.path.insert(0, "
                        + Escaper.escapeAsPythonString(MorePaths.pathWithUnixSeparators(generatedRoot)) + ")",
                "if __name__ == '__main__':", "    try:", "        from buck_parser import buck",
                "        buck.main()", "    except KeyboardInterrupt:",
                "        print('Killed by User', file=sys.stderr)", ""));
    }

    LOG.debug("Created temporary buck.py instance at %s.", generatedRoot);
    return new BuckPythonProgram(generatedRoot, cleanupEnabled);
}

From source file:com.torodb.BuildProperties.java

BuildProperties(String propertiesFile) {
    PropertiesConfiguration properties;/*www . jav a 2 s .  c  om*/
    try {
        properties = new PropertiesConfiguration(Resources.getResource(propertiesFile));
    } catch (ConfigurationException e) {
        throw new RuntimeException("Cannot read build properties file '" + propertiesFile + "'");
    }

    fullVersion = properties.getString("version");
    Matcher matcher = FULL_VERSION_PATTERN.matcher(fullVersion);
    if (!matcher.matches()) {
        throw new RuntimeException("Invalid version string '" + fullVersion + "'");
    }
    majorVersion = Integer.parseInt(matcher.group(1));
    minorVersion = Integer.parseInt(matcher.group(2));
    subVersion = matcher.group(3) != null ? Integer.parseInt(matcher.group(3)) : 0;
    extraVersion = matcher.group(4);

    // DateUtils.parseDate may be replaced by SimpleDateFormat if using Java7
    try {
        buildTime = DateUtils.parseDate(properties.getString("build.timestamp"),
                new String[] { ISO8601_FORMAT_STRING });
    } catch (ParseException e) {
        throw new RuntimeException("build.timestamp property not in ISO8601 format");
    }

    gitCommitId = properties.getString("git.commit.id");
    gitBranch = properties.getString("git.branch");
    gitRemoteOriginUrl = properties.getString("git.remote.origin.url");

    javaVersion = properties.getString("java.version");
    javaVendor = properties.getString("java.vendor");
    javaVMSpecificationVersion = properties.getString("java.vm.specification.version");
    javaVMVersion = properties.getString("java.vm.version");

    osName = properties.getString("os.name");
    osArch = properties.getString("os.arch");
    osVersion = properties.getString("os.version");
}

From source file:at.ac.univie.isc.asio.io.Classpath.java

/**
 * Load a resource from the classpath and wrap it as a {@code ByteSource}.
 *
 * @param name name of the resource/*from  ww w. j a v a 2  s  .c om*/
 * @return the wrapped resource
 * @throws java.lang.IllegalArgumentException if the resource is not found
 */
@Nonnull
public static ByteSource load(@Nonnull final String name) throws IllegalArgumentException {
    Preconditions.checkArgument(!name.startsWith("/"),
            "illegal resource name <%s> - resource names may not have a leading slash, they are implicitly absolute",
            name);
    final URL url = Resources.getResource(name);
    return Resources.asByteSource(url);
}

From source file:com.proofpoint.platform.BundlerPackager.java

public void execute() throws MojoExecutionException, MojoFailureException {
    URL bundlerLib = Resources.getResource("bundler/lib");
    checkNotNull(bundlerLib,/*from  ww w.j  a  v  a  2  s .com*/
            "Couldn't find a gem repo that contains bundler.  Please ensure the Bundler Packaging plugin is properly built.");

    String gemfileLocation = locateFileInProjectRoot("Gemfile");
    String gemfileLockLocation = locateFileInProjectRoot("Gemfile.lock");

    Ruby runtime = JavaEmbedUtils.initialize(ImmutableList.of(bundlerLib.getPath()), createRuntimeConfig());
    RubyObjectAdapter adapter = JavaEmbedUtils.newObjectAdapter();

    IRubyObject gemRepositoryBuilder = createNewGemRepositoryBuilder(runtime);

    String gemrepoTempDirectoryPath = createTemporaryDirectory();

    IRubyObject response = null;
    try {
        response = adapter.callMethod(gemRepositoryBuilder, "build_repository_using_bundler",
                new IRubyObject[] { javaToRuby(runtime, gemrepoTempDirectoryPath),
                        javaToRuby(runtime, gemfileLocation), javaToRuby(runtime, gemfileLockLocation) });
    } catch (Exception e) {
        throw new MojoExecutionException(
                "Gem repo jar was not properly constructed.  Please check the output for errors.  "
                        + "Try running bundle install manually to verify the contents of the Gemfile.  ["
                        + gemfileLocation + "]",
                e);

    }

    String gemrepoGeneratedLocation = response.asJavaString();

    try {
        deleteRecursively(new File(gemrepoGeneratedLocation + "/bin"));
    } catch (IOException e) {
        //If it fails, no big deal, we eliminate the whole repo later on.
    }
    try {
        deleteRecursively(new File(gemrepoGeneratedLocation + "/cache"));
    } catch (IOException e) {
        //If it fails, no big deal, we eliminate the whole repo later on.
    }
    try {
        deleteRecursively(new File(gemrepoGeneratedLocation + "/doc"));
    } catch (IOException e) {
        //If it fails, no big deal, we eliminate the whole repo later on.
    }

    generateJarFile(new File(gemrepoGeneratedLocation), gemfileLocation);

    try {
        deleteRecursively(new File(gemrepoTempDirectoryPath));
    } catch (IOException e) {
        throw new MojoExecutionException("Error trying to delete temporary directory for the gems, "
                + "please ensure the plugin is properly built and the temporary directory ["
                + gemrepoTempDirectoryPath + "] is writeable.");
    }
}

From source file:com.mapr.synth.samplers.FileSampler.java

@SuppressWarnings({ "UnusedDeclaration" })
public void setResource(String lookup) throws IOException {
    if (lookup.matches(".*\\.json")) {
        readJsonData(Resources.newInputStreamSupplier(Resources.getResource(lookup)));
    } else {/*from  www  .java  2  s .co m*/
        List<String> lines = Resources.readLines(Resources.getResource(lookup), Charsets.UTF_8);
        readDelimitedData(lookup, lines);
    }

    setupIndex();
}

From source file:org.hawkular.metrics.clients.ptrans.ExecutableITestBase.java

@Before
public void before() throws Exception {
    ptransConfFile = temporaryFolder.newFile();
    try (FileOutputStream out = new FileOutputStream(ptransConfFile)) {
        Resources.copy(Resources.getResource("ptrans.conf"), out);
    }//  w  ww  .j  av  a 2 s .com

    ptransOut = temporaryFolder.newFile();
    ptransErr = temporaryFolder.newFile();

    ptransPidFile = temporaryFolder.newFile();

    ptransProcessBuilder = new ProcessBuilder();
    ptransProcessBuilder.directory(temporaryFolder.getRoot());
    ptransProcessBuilder.redirectOutput(ptransOut);
    ptransProcessBuilder.redirectError(ptransErr);

    ptransProcessBuilder.command(JAVA, "-jar", PTRANS_ALL);
}

From source file:com.selesse.tailerswift.gui.view.AboutFrame.java

private String getOpenSourceLicenseText() {
    String licenseText = "";
    URL guavaUrl = Resources.getResource("licenses/guava.txt");
    URL slf4jUrl = Resources.getResource("licenses/slf4j.txt");

    try {/*from  w w  w.  j  a v  a  2s.c  om*/
        String guavaContents = Resources.toString(guavaUrl, Charsets.UTF_8);
        String slf4jContents = Resources.toString(slf4jUrl, Charsets.UTF_8);

        licenseText = guavaContents + "\n\n" + slf4jContents;
    } catch (IOException e) {
        LOGGER.error("Could not open license", e);
    }

    return licenseText;
}