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:com.autentia.common.util.FileSystemUtils.java

/**
 * Devuelve la ruta absoluta hasta el directorio a partir del cual se puede obtener la clase. Si la clase est en un
 * .class se obtiene la ruta hasta el directorio donde empezar el paquete de la clase (es decir los directorios
 * com/foo/barr/... no estaran incluidos en el resultado). Si la clase est en un .jar se obtiene la ruta donde
 * est el jar.//w  w  w.j ava  2 s  .com
 * <p>
 * Para encontrar la clase se busacara haciendo un <code>getResource()</code> a la propia clase que se quiere
 * localizar.
 * <p>
 * El directorio que se devuelve termina con el caracter separador de directorios (segn la plataforma).
 * 
 * @param clazz clase que se pretende localizar.
 * @return ruta absoluta hasta el directorio donde se puede localizar la clase.
 */
public static String getPathToClassOrJar(Class<?> clazz) {
    // 
    // No utilizamos el separador del sistema porque en Windows y, al menos, bajo Tomcat,
    // el mtodo class.getResource() espera como parmetro el separador de unix.
    // 
    final String PATH_SEPARATOR = "/";
    String cn = PATH_SEPARATOR + clazz.getName().replace('.', PATH_SEPARATOR.charAt(0)) + ".class";
    final URL url = clazz.getResource(cn);
    String path = url.getPath();
    final int indexOfClass = path.indexOf(cn);
    final int indexOfClassMinusOne = indexOfClass - 1;

    // La URL que define donde est una clase es del estilo:
    // * file:/...class
    // * jar:file:/...jar!/...class
    // Con URL.getPath() se obtiene una cadena que ya tiene quitado el primer protocolo (file: o jar:).
    final int begin;
    final int end;
    if (path.charAt(indexOfClassMinusOne) == '!') {
        // La clase est en un jar, as que quitamos el protocolo 'file:' del principio,
        // y el nombre del jar del final
        begin = path.indexOf(':') + 1;
        end = path.lastIndexOf(PATH_SEPARATOR, indexOfClassMinusOne) + 1;
    } else {
        begin = 0;
        end = indexOfClass + 1;
    }
    path = path.substring(begin, end);
    return getCannonicalPath(path);
}

From source file:com.asakusafw.testdriver.compiler.util.DeploymentUtil.java

/**
 * Find library file/directory from an element class.
 * @param aClass element class in target library
 * @return target file/directory, or {@code null} if not found
 * @throws IllegalArgumentException if some parameters were {@code null}
 *///from w  w  w  .  j av  a 2 s .  c o  m
public static File findLibraryPathFromClass(Class<?> aClass) {
    if (aClass == null) {
        throw new IllegalArgumentException("aClass must not be null"); //$NON-NLS-1$
    }
    int start = aClass.getName().lastIndexOf('.') + 1;
    String name = aClass.getName().substring(start);
    URL resource = aClass.getResource(name + ".class");
    if (resource == null) {
        LOG.warn("Failed to locate the class file: {}", aClass.getName());
        return null;
    }
    String protocol = resource.getProtocol();
    if (protocol.equals("file")) {
        try {
            File file = new File(resource.toURI());
            return toClassPathRoot(aClass, file);
        } catch (URISyntaxException e) {
            LOG.warn(
                    MessageFormat.format(
                            "Failed to locate the library path (cannot convert to local file): {0}", resource),
                    e);
            return null;
        }
    }
    if (protocol.equals("jar")) {
        String path = resource.getPath();
        return toClassPathRoot(aClass, path);
    } else {
        LOG.warn("Failed to locate the library path (unsupported protocol {}): {}", resource, aClass.getName());
        return null;
    }
}

From source file:com.bjond.utilities.MiscUtils.java

/**
 * The file resource must be encoded in UTF-8.   
 * /*from w w w. j av a  2  s  .com*/
 * @param myClass Class associated with the resource (resource just have to in the same package as this class, I think).
 * @param resourceName filename of the resource.
 * @return Content of the file read in string.
 * @throws IOException If any IO error occurs reading contents from Resource. Such as the resource not found.
 */
public static String readContentsFromResource(@SuppressWarnings("rawtypes") Class myClass, String resourceName)
        throws IOException {
    val rsc = myClass.getResource(resourceName);
    val path = rsc.getPath();
    val file = new File(path);
    return Files.toString(file, Charset.forName("UTF-8"));
}

From source file:de.alpharogroup.lang.ClassUtils.java

/**
 * Gives the url from the path back.//from w  w  w.j ava2  s  .  com
 *
 * @param clazz
 *            The class-object.
 * @param path
 *            The path.
 * @return 's the url from the path.
 */
public static URL getResource(final Class<?> clazz, final String path) {
    URL url = clazz.getResource(path);
    if (null == url) {
        url = ClassUtils.getClassLoader().getResource(path);
    }
    return url;
}

From source file:org.hawkular.wildfly.agent.itest.util.AbstractITest.java

public static String readNode(Class<?> caller, String nodeFileName) throws IOException {
    URL url = caller.getResource(caller.getSimpleName() + "." + nodeFileName);
    if (url != null) {
        StringBuilder result = new StringBuilder();
        try (Reader r = new InputStreamReader(url.openStream(), "utf-8")) {
            char[] buff = new char[1024];
            int len = 0;
            while ((len = r.read(buff, 0, buff.length)) != -1) {
                result.append(buff, 0, len);
            }/* w w w .ja va  2  s  .c  o m*/
        }
        return result.toString();
    } else {
        return null;
    }
}

From source file:de.alpharogroup.lang.ClassExtensions.java

/**
 * Gives the URL from the resource. Wrapes the Class.getResource(String)-method.
 *
 * @param <T>/*from w w w  . j  a  va  2 s. c o  m*/
 *            the generic type
 * @param name
 *            The name from the resource.
 * @param obj
 *            The Object.
 * @return The resource or null if the resource does not exists.
 */
public static <T> URL getResource(final String name, final T obj) {
    final Class<?> clazz = obj.getClass();
    URL url = clazz.getResource(name);
    if (url == null) {
        url = getResource(clazz, name);
    }
    return url;
}

From source file:de.alpharogroup.lang.ClassExtensions.java

/**
 * Gives the url from the path back.//from w w w.jav a2 s  .c o  m
 *
 * @param clazz
 *            The class-object.
 * @param path
 *            The path.
 * @return 's the url from the path.
 */
public static URL getResource(final Class<?> clazz, final String path) {
    URL url = clazz.getResource(path);
    if (url == null) {
        url = ClassExtensions.getClassLoader().getResource(path);
    }
    return url;
}

From source file:de.alpharogroup.lang.ClassExtensions.java

/**
 * Gives the url from the path back.//from w  w  w .  ja  v  a  2 s .c  om
 *
 * @param clazz
 *            The class-object.
 * @return 's the url from the path.
 */
public static URL getResource(final Class<?> clazz) {
    final String path = ClassExtensions.getPath(clazz);
    URL url = clazz.getResource(path);
    if (url == null) {
        url = ClassExtensions.getClassLoader().getResource(path);
    }
    return url;
}

From source file:org.hawkular.wildfly.agent.itest.util.AbstractITest.java

public static void writeNode(Class<?> caller, ModelNode node, String nodeFileName)
        throws UnsupportedEncodingException, FileNotFoundException {
    URL callerUrl = caller.getResource(caller.getSimpleName() + ".class");
    if (!callerUrl.getProtocol().equals("file")) {
        throw new IllegalStateException(AbstractITest.class.getName()
                + ".store() works only if the caller's class file is loaded using a file:// URL.");
    }/*from ww  w  .  j av  a 2 s. c  o  m*/
    String callerUrlPath = callerUrl.getPath();

    String nodePath = callerUrlPath.replaceAll("\\.class$", "." + nodeFileName);
    nodePath = nodePath.replace("/target/test-classes/", "/src/test/resources/");
    System.out.println("Storing a node to [" + nodePath + "]");

    File outputFile = new File(nodePath);
    if (!outputFile.getParentFile().exists()) {
        outputFile.getParentFile().mkdirs();
    }

    try (PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "utf-8"))) {
        node.writeString(out, false);
    }
}

From source file:com.trsst.Common.java

public static Attributes getManifestAttributes() {
    Attributes result = null;/*from   w ww .  j a  va 2 s .  c  om*/
    Class<Common> clazz = Common.class;
    String className = clazz.getSimpleName() + ".class";
    URL classPath = clazz.getResource(className);
    if (classPath == null || !classPath.toString().startsWith("jar")) {
        // Class not from JAR
        return null;
    }
    String classPathString = classPath.toString();
    String manifestPath = classPathString.substring(0, classPathString.lastIndexOf("!") + 1)
            + "/META-INF/MANIFEST.MF";
    try {
        Manifest manifest = new Manifest(new URL(manifestPath).openStream());
        result = manifest.getMainAttributes();
    } catch (MalformedURLException e) {
        log.error("Could not locate manifest: " + manifestPath);
    } catch (IOException e) {
        log.error("Could not open manifest: " + manifestPath);
    }
    return result;
}