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.aimdek.ccm.util.CommonUtil.java

/**
 * Gets the resource full file path./* ww  w. j  av  a  2  s .  c o  m*/
 *
 * @param anyClass
 *            the any class
 * @param filePath
 *            the file path
 * @return the resource full file path
 */
public static String getResourceFullFilePath(Class<?> anyClass, String filePath) {

    return anyClass.getResource(filePath).getPath();

}

From source file:com.vmware.admiral.closures.util.ClosureUtils.java

public static byte[] loadDockerImageData(String dockerImageName, String folderFilter, Class<?> resourceClass) {
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    try {//from ww w  .  j a v  a 2  s . c  om
        URL dirURL = resourceClass.getResource("/" + folderFilter);
        logInfo("Reading image data %s from: %s ", dockerImageName, dirURL);

        String extractImageName = extractImageName(dockerImageName);
        String folderNameFilter = folderFilter + extractImageName;
        buildTarData(dirURL, folderNameFilter, byteOutputStream);

        return byteOutputStream.toByteArray();
    } catch (Exception ex) {
        Utils.logWarning("Unable to load docker image data! Reason: ", ex);
    } finally {
        try {
            byteOutputStream.close();
        } catch (IOException e) {
            // not interested
        }
    }
    return new byte[] {};
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.standalone.ServerDetector.java

private static Boolean _detect(String className) {
    try {/*from w  ww  .  j  a v  a 2 s .co  m*/
        ClassLoader.getSystemClassLoader().loadClass(className);

        return Boolean.TRUE;
    } catch (ClassNotFoundException cnfe) {
        ServerDetector sd = _instance;

        Class<?> c = sd.getClass();

        if (c.getResource(className) != null) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }
}

From source file:com.bfd.harpc.common.configure.PathUtils.java

/**
 * ??URL?class/*from  www. j av  a  2  s . co  m*/
 * <p>
 * <b>NOTE:</b><br />
 * warfile:/path/my-app/calsses/ <br />
 * jarfile:/path/my-app/my-app.jar.
 * 
 * @return URL
 */
public static URL getCodeLocation(Class<?> clazz) {
    URL codeLocation = null;
    // If CodeSource didn't work, Class.getResource
    // instead.
    URL r = clazz.getResource("");
    synchronized (r) {
        String s = r.toString();
        Pattern jrare = Pattern.compile("jar:\\s?(.*)!/.*");
        Matcher m = jrare.matcher(s);
        if (m.find()) { // the code is run from a jar file.
            s = m.group(1);
        } else {
            String p = clazz.getPackage().getName().replace('.', '/');
            s = s.substring(0, s.lastIndexOf(p));
        }
        try {
            codeLocation = new URL(s);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }
    return codeLocation;
}

From source file:be.i8c.sag.util.FileUtils.java

/**
 * Get the File that represents the location of this jar that contains the clazz.
 *
 * Note: The file may be a directory when you are running this
 * code from your IDE or without packing it into a jar.
 *
 * @param clazz A class that is located in the jar file.
 * @return A File that represents the location of the jar that contains the clazz.
 *//*from   ww w  .j ava2s. c  om*/
public static File getJarFile(Class<?> clazz) {
    String className = clazz.getSimpleName() + ".class";
    String classPath = "/" + clazz.getName().replace('.', '/') + ".class";

    URL generatorFileUrl = clazz.getResource(className);

    // We want to remove the last instance of the internal class path
    String jarPath = new StringBuilder(new StringBuilder(generatorFileUrl.getPath()).reverse().toString()
            .replaceFirst(new StringBuilder(classPath).reverse().toString(), "")).reverse().toString();

    // Remove the file:/ and the '!' at the end of the path.
    // This only needs to be done if it's a file
    jarPath = jarPath.replaceAll("^file:/", "");
    jarPath = jarPath.replaceAll("!$", "");

    return new File(jarPath);
}

From source file:com.validation.manager.core.tool.Tool.java

public static ImageIcon createImageIcon(String path, String description, Class relativeTo) {
    URL imgURL = relativeTo == null ? Tool.class.getResource(path) : relativeTo.getResource(path);
    return imgURL == null ? null : new ImageIcon(imgURL, description);
}

From source file:com.github.thesmartenergy.sparql.generate.jena.engine.TestBase.java

static void setUpClass(Class clazz) throws Exception {
    LOG = Logger.getLogger(clazz);
    LOG.debug(clazz.getName());/*from w w w.  j  a  v a 2s .c  om*/
    String dir = clazz.getSimpleName();
    dir = Character.toLowerCase(dir.charAt(0)) + (dir.length() > 1 ? dir.substring(1) : "");
    examplePath = clazz.getResource("/" + dir);

    exampleDir = new File(examplePath.toURI());

    // read location-mapping
    URI confUri = exampleDir.toURI().resolve("configuration.ttl");
    Model conf = RDFDataMgr.loadModel(confUri.toString());

    // initialize file manager
    fileManager = FileManager.makeGlobal();
    Locator loc = new LocatorFile(exampleDir.toURI().getPath());
    LocationMapper mapper = new LocationMapper(conf);
    fileManager.addLocator(loc);
    fileManager.setLocationMapper(mapper);
}

From source file:jfix.util.Reflections.java

/**
 * Returns all instanceable (sub-)classes of given type in given package.
 *//*from  w w w .  j av a2 s.  co  m*/
public static <E> E[] find(Class<E> classType, Package pckage) {
    File directory;
    try {
        String name = "/" + pckage.getName().replace('.', '/');
        directory = new File(classType.getResource(name).toURI());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    List<E> result = new ArrayList<>();
    if (directory.exists()) {
        String[] files = directory.list();
        for (int i = 0; i < files.length; i++) {
            if (files[i].endsWith(".class")) {
                String classname = files[i].substring(0, files[i].length() - 6);
                try {
                    Object o = Class.forName(pckage.getName() + "." + classname).newInstance();
                    if (classType.isInstance(o)) {
                        result.add((E) o);
                    }
                } catch (ClassNotFoundException cnfex) {
                    System.err.println(cnfex);
                } catch (InstantiationException iex) {
                } catch (IllegalAccessException iaex) {
                }
            }
        }
    }
    result.sort(new Comparator<Object>() {
        public int compare(Object o1, Object o2) {
            return o1.getClass().getSimpleName().compareTo(o2.getClass().getSimpleName());
        }
    });
    return result.toArray((E[]) Array.newInstance(classType, result.size()));
}

From source file:fm.last.commons.io.LastFileUtils.java

/**
 * Searches for a file on local filesytem, classpath etc.
 * //from   ww  w.ja va  2  s  .c o m
 * @param fileName Name of file to find.
 * @param classToLoadFrom Class to use as a base for finding the file via it's classloader, if necessary.
 * @return The file if found on the file system.
 * @throws FileNotFoundException If the File could not be found.
 */
public static File getFile(String fileName, Class<?> classToLoadFrom) throws FileNotFoundException {
    File file = new File(fileName); // first try the path directly
    if (!file.exists()) {
        URL fileURL = classToLoadFrom.getResource(fileName);// next try the class's classpath
        if (fileURL == null) {
            fileURL = classToLoadFrom.getClassLoader().getResource(fileName);// next try the class' classloader's classpath
            if (fileURL == null) {
                fileURL = ClassLoader.getSystemClassLoader().getResource(fileName); // finally try the system classloader's
                // classpath
                if (fileURL == null) {
                    throw new FileNotFoundException(
                            "Could not find " + fileName + " on path, classpath " + "or system classpath");
                }
            }
        }
        file = new File(fileURL.getFile());
    }
    log.debug("Path to file located is " + file.getAbsolutePath());
    return file;
}

From source file:Main.java

public static BufferedImage getUIImage(Class c, String name) {

    try {//  w w w .j a v a 2 s  .c  o  m
        String id = c + " - " + name;
        WeakReference wr = (WeakReference) UIImagesReferences.get(id);

        if (wr != null) {
            BufferedImage img = (BufferedImage) wr.get();
            if (img != null) {
                return img;
            }
        }
        BufferedImage img = ImageIO.read(c.getResource(name));

        UIImagesReferences.put(id, new WeakReference(img));

        return img;
    } catch (Exception e) {
        throw new RuntimeException("error loading " + c + " " + name, e);
    }

}