Example usage for java.lang Class getResource

List of usage examples for java.lang Class getResource

Introduction

In this page you can find the example usage for java.lang Class getResource.

Prototype

@CallerSensitive
public URL getResource(String name) 

Source Link

Document

Finds a resource with a given name.

Usage

From source file:org.piwigo.remotesync.api.util.FileUtil.java

public static File getFile(Class<?> clazz, String resourceName, boolean checkExistence) {
    try {//from   www  . ja  v  a  2 s  . c  om
        URL resource = clazz.getResource(resourceName);

        if (resource == null)
            throw new IllegalStateException("Unable to find resource with name " + resourceName);

        String filePath = URLDecoder.decode(resource.getPath(), "UTF-8");

        File file = new File(filePath);
        if (checkExistence && !file.exists())
            throw new FileNotFoundException("Unable to find file with name " + resourceName);

        return file;
    } catch (Exception exception) {
        logger.debug(exception.getMessage(), exception);
        return null;
    }
}

From source file:org.rhq.enterprise.server.plugins.rhnhosted.xmlrpc.RhnCommTest.java

/**
 * method to find a file relative to the calling class.  primarily
 * useful when writing tests that need access to external data.
 * this lets you put the data relative to the test class file.
 *
 * @param path the path, relative to caller's location
 * @return URL a URL referencing the file
 * @throws ClassNotFoundException if the calling class can not be found
 * (i.e., should not happen)// w w w .j ava  2 s .c o m
 */
public static URL findTestData(String path) throws ClassNotFoundException {
    Throwable t = new Throwable();
    StackTraceElement[] ste = t.getStackTrace();

    String className = ste[1].getClassName();
    Class clazz = Class.forName(className);

    URL ret = clazz.getResource(path);
    return ret;
}

From source file:org.romaframework.aspect.reporting.jr.JRDesignHelper.java

private static InputStream getImageByAspect(String name, String aspectName) {
    final Class<?> toSave = Class.class;

    String customPath = Roma.component(TemplateManager.class).getCustomPath();

    String path;/*from  w w  w.ja  va  2 s  .  co m*/
    if (customPath == null) {
        path = Roma.component(ApplicationConfiguration.class).getApplicationPackage();
    } else {
        path = customPath;
    }
    String packageFile = path + DOT + aspectName + ".image";
    packageFile = Utility.getResourcePath(packageFile);
    log.info(_LOG_JRDESIGN_HELPER + "getImage: " + Utility.PATH_SEPARATOR + packageFile + Utility.PATH_SEPARATOR
            + name);
    URL url = toSave.getResource(Utility.PATH_SEPARATOR + packageFile + Utility.PATH_SEPARATOR + name);

    try {
        InputStream stream = EMPTYSTREAM;
        VirtualFile file = VirtualFileFactory.getInstance().getFile(url);
        if (file != null) {
            stream = file.getInputStream();
        } else {
            log.warn(_LOG_JRDESIGN_HELPER + "getImage: url : " + url);
            log.warn(_LOG_JRDESIGN_HELPER + "cannot find image " + Utility.PATH_SEPARATOR + packageFile
                    + Utility.PATH_SEPARATOR + name);
        }
        log.debug(_LOG_JRDESIGN_HELPER + "getImage: " + stream);
        return stream;
    } catch (Throwable e) {
        log.error("Unable to get image " + name + " cause: " + e, e);
        return null;
    }
}

From source file:org.sakuli.AbstractLogAwareTest.java

public static String getResource(String resourceName, Class<?> resourceClass) {
    try {/*from  w  ww  .  java 2s . com*/
        return Paths.get(resourceClass.getResource(resourceName).toURI()).toString();
    } catch (URISyntaxException | NullPointerException e) {
        LOGGER.error("could not resolve resource '{}' from classpath '{}'", resourceName, e);
        return null;
    }
}

From source file:org.sakuli.utils.ResourceHelper.java

/**
 * Resolves a resource from the Classpath.
 *
 * @param classDef          a instance of {@link Class}
 * @param classPathResource resource string like e.g. "/filename.file".
 * @param exceptionMessage  custom exception message, if file couldn't resolved.
 * @return a {@link Path} object of the classpath resource.
 * @throws NoSuchFileException//from   w  w w .j  a  v a2  s  .  c o  m
 */
public static Path getClasspathResource(Class<?> classDef, String classPathResource, String exceptionMessage)
        throws NoSuchFileException {
    try {
        return Paths.get(classDef.getResource(classPathResource).toURI());
    } catch (FileSystemNotFoundException | URISyntaxException | NullPointerException e) {
        NoSuchFileException exc = new NoSuchFileException(classPathResource, null, exceptionMessage);
        exc.addSuppressed(e);
        throw exc;
    }
}

From source file:org.sandsoft.cymric.util.Commons.java

/**
 * Create a new custom pane from FXML data. <br>
 * Restraints: Name and package of FXML file should be the same as
 * <code>resourceClass</code>. <code>resourceClass</code> should extend
 * <code>BorderPane</code> or one of its descendents.
 *
 * @param resourceClass Pane class in which data to be loaded.
 * @return Pane type object containing loaded node.
 *///from   w  ww  .  j  a  v  a2 s  .co m
public static Pane loadPaneFromFXML(Class resourceClass) throws IOException {
    //init loader           
    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(resourceClass.getResource(resourceClass.getSimpleName() + ".fxml"));

    //load fxml
    Node node = (Node) loader.load();
    BorderPane control = (BorderPane) loader.getController();

    BorderPane.setAlignment(node, Pos.CENTER);
    control.setCenter(node);

    return control;
}

From source file:org.sipfoundry.sipxconfig.test.TestHelper.java

/**
* Retrieves the file corresponding to the class resource
*
* @param klass/*from  ww w.j  ava 2  s .c om*/
* @param resource resource name relative to class
* @return file that can be opened and used to read resource
*/
public static File getResourceAsFile(Class klass, String resource) {
    URL url = klass.getResource(resource);
    return new File(url.getFile());
}

From source file:org.springframework.boot.gradle.testkit.GradleBuild.java

private URL getScriptForTestClass(Class<?> testClass) {
    return testClass.getResource(testClass.getSimpleName() + ".gradle");
}

From source file:org.syncany.operations.plugin.PluginOperation.java

private File getJarFile(Plugin plugin) {
    Class<? extends Plugin> pluginClass = plugin.getClass();
    URL pluginClassLocation = pluginClass.getResource('/' + pluginClass.getName().replace('.', '/') + ".class");
    String pluginClassLocationStr = pluginClassLocation.toString();

    logger.log(Level.INFO, "Plugin class is at " + pluginClassLocationStr);

    if (pluginClassLocationStr.startsWith("jar:file:")) {
        int indexStartAfterSchema = "jar:file:".length();
        int indexEndAtExclamationPoint = pluginClassLocationStr.indexOf("!");
        File pluginJarFile = new File(
                pluginClassLocationStr.substring(indexStartAfterSchema, indexEndAtExclamationPoint));

        logger.log(Level.INFO, "Plugin is in JAR at " + pluginJarFile);
        return pluginJarFile;
    } else {/*from   w w  w  .  java  2s .c o m*/
        logger.log(Level.INFO, "Plugin is not in a JAR file. Probably in test environment.");
        return null;
    }
}

From source file:org.unitils.core.util.FileResolver.java

protected URI resolveOnClasspath(Class<?> testClass, String fullFileName) {
    URL fileUrl = testClass.getResource('/' + fullFileName);
    if (fileUrl == null) {
        throw new UnitilsException("File with name " + fullFileName + " cannot be found.");
    }//  w  ww. j  a  va  2  s  .c  om
    try {
        return toUri(fullFileName, fileUrl);
    } catch (URISyntaxException e) {
        throw new UnitilsException("File with name " + fullFileName + " cannot be found.", e);
    }
}