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.eclipse.mylyn.commons.sdk.util.CommonTestUtil.java

private static File getFileFromNotRunningPlatform(String filename, Class<?> clazz)
        throws UnsupportedEncodingException, IOException {
    URL localURL = clazz.getResource("");
    String path = URLDecoder.decode(localURL.getFile(), Charset.defaultCharset().name());
    int i = path.indexOf("!");
    if (i != -1) {
        int j = path.lastIndexOf(File.separatorChar, i);
        if (j != -1) {
            path = path.substring(0, j) + File.separator;
        } else {//from  w ww . java 2s . co m
            throw new AssertionFailedError(
                    "Unable to determine location for '" + filename + "' at '" + path + "'");
        }
        // class file is nested in jar, use jar path as base
        if (path.startsWith("file:")) {
            path = path.substring(5);
        }
        return new File(path + filename);
    } else {
        // remove all package segments from name
        String directory = clazz.getName().replaceAll("[^.]", "");
        directory = directory.replaceAll(".", "../");
        if (path.contains("/bin/")) {
            // account for bin/ when running from Eclipse workspace
            directory += "../";
        } else if (path.contains("/target/classes/")) {
            // account for bin/ when running from Eclipse workspace
            directory += "../../";
        }
        filename = path + (directory + filename).replaceAll("/", Matcher.quoteReplacement(File.separator));
        return new File(filename).getCanonicalFile();
    }
}

From source file:org.eclipse.skalli.commons.XMLUtils.java

/**
 * Reads and parses an XML document from a resource file loaded with
 * the bundle classloader of the given class.
 *
 * @param c  the class.// w w w . j ava 2  s  . c om
 * @param filename  the path and filename of the requested resource relative to the bundle root
 * of the bundle containg the given class.
 *
 * @return  an XML document parsed from the given file, or <code>null</code> if the requested
 * resource was not found.
 *
 * @throws SAXException  if a parsing error occurd.
 * @throws IOException  if an i/o error occured.
 * @throws ParserConfigurationException  a serious serious configuration error occured.
 */
public static Document documentFromResource(Class<?> c, String filename)
        throws SAXException, IOException, ParserConfigurationException {
    URL urlBefore = c.getResource(filename);
    if (urlBefore == null) {
        return null;
    }
    InputStream isBefore = null;
    try {
        isBefore = urlBefore.openStream();
        DocumentBuilder docBuilder = getDocumentBuilder();
        Document doc = docBuilder.parse(isBefore);
        return doc;
    } finally {
        if (isBefore != null) {
            isBefore.close();
        }
    }
}

From source file:org.eclipse.skalli.core.rest.RestAPISmokeTest.java

private String getResource(Class<?> c, String filename) throws IOException {
    URL bundleURL = c.getResource(filename);
    if (bundleURL == null) {
        return null;
    }/* w  w  w  . j  a  v  a2 s .  com*/
    InputStream in = null;
    try {
        String content = IOUtils.toString(bundleURL.openStream(), "UTF-8");
        return StringUtils.replace(content, "${PORT1}", Integer.toString(port));
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:org.eclipse.wb.internal.core.utils.ui.DrawUtils.java

/**
 * @return the {@link Image} loaded relative to given {@link Class}.
 *//*from   ww  w . j a v  a2s.  com*/
public static Image loadImage(Class<?> clazz, String path) {
    try {
        URL resource = clazz.getResource(path);
        if (resource != null) {
            InputStream stream = resource.openStream();
            try {
                return new Image(null, stream);
            } finally {
                IOUtils.closeQuietly(stream);
            }
        }
    } catch (Throwable e) {
    }
    return null;
}

From source file:org.failearly.dataset.internal.resource.DataSetResourceFactory.java

private static boolean doesNotExistResource(Class<?> testClass, String resourceName) {
    return null == testClass.getResource(resourceName);
}

From source file:org.fuin.utils4j.Utils4J.java

/**
 * Get the path to a resource located in the same package as a given class.
 * //  www .j a  v a  2 s.c  o m
 * @param clasz
 *            Class with the same package where the resource is located -
 *            Cannot be <code>null</code>.
 * @param name
 *            Filename of the resource - Cannot be <code>null</code>.
 * 
 * @return Resource URL.
 */
public static URL getResource(final Class clasz, final String name) {
    checkNotNull("clasz", clasz);
    checkNotNull("name", name);
    final String nameAndPath = "/" + getPackagePath(clasz) + "/" + name;
    return clasz.getResource(nameAndPath);
}

From source file:org.getobjects.appserver.core.WOResourceManager.java

/**
 * This is the primary method to locate a component and return a
 * WOComponentDefinition describing it. The definition is just a blueprint,
 * not an actual instance of the component.
 * <p>//from  w  w  w . j av  a 2 s.co m
 * The method calls load() on the definition, this will actually load the
 * template of the component.
 * <p>
 * All the caching is done by the wrapping method.
 *
 * @param _name  - the name of the component to load (eg 'Main')
 * @param _langs - the languages to check
 * @param _rm    - the RM used to lookup classes
 * @return a WOComponentDefinition which represents the specific component
 */
public IWOComponentDefinition definitionForComponent(String _name, String[] _langs, WOResourceManager _rm) {
    /*
     * Note: a 'package component' is a component which has its own package,
     *       eg: org.opengroupware.HomePage with subelements 'HomePage.class',
     *       'HomePage.html' and 'HomePage.wod'.
     */
    // TODO: complete me
    URL templateData = null;
    String type = "WOx";
    String rsrcName = _name != null ? _name.replace('.', '/') : null;
    boolean debugOn = log.isDebugEnabled();

    if (debugOn)
        log.debug("make cdef for component: " + _name);

    Class cls = this.lookupComponentClass(_name);
    if (cls == null) { /* we do not serve this class */
        if (debugOn)
            log.debug("rm does not serve the class, check for templates: " + _name);

        /* check whether its a component w/o a class */
        templateData = this.urlForResourceNamed(rsrcName + ".wox", _langs);
        if (templateData == null) {
            type = "WOWrapper";
            templateData = this.urlForResourceNamed(rsrcName + ".html", _langs);
        }

        if (templateData == null)
            return null; /* did not find a template */

        if (debugOn)
            log.debug("  found a class-less component: " + _name);
        cls = WOComponent.class; // TODO: we might want to use a different class
    }
    if (debugOn)
        log.debug("  comp class: " + cls);

    /* this is a bit hackish ;-), but well, ... */
    boolean isPackageComponent = false;
    String className = cls.getName();
    if (className.endsWith("." + _name + ".Component"))
        isPackageComponent = true;
    else if (className.endsWith("." + _name + "." + _name))
        isPackageComponent = true;

    if (debugOn) {
        if (isPackageComponent)
            log.debug("  found a package component: " + className);
        else
            log.debug("  component is not a pkg one: " + _name + "/" + className);
    }

    /* def */

    IWOComponentDefinition cdef = new WOComponentDefinition(_name, cls);

    /* find template */

    URL wodData = null;

    if (!isPackageComponent) {
        if (templateData == null)
            templateData = this.urlForResourceNamed(rsrcName + ".wox", _langs);
        if (templateData == null) {
            templateData = this.urlForResourceNamed(rsrcName + ".html", _langs);
            type = "WOWrapper";
        }

        if ("WOWrapper".equals(type))
            wodData = this.urlForResourceNamed(rsrcName + ".wod", _langs);
    } else {
        // Note: we directly access the class resources. Not sure yet whether
        //       this is a good idea or whether we should instantiate a new
        //       WOClassResourceManager for resource lookup?
        //       This resource manager could also be set as the components
        //       resource manager?
        // TODO: localization?
        templateData = cls.getResource(_name + ".wox");
        if (templateData == null)
            templateData = cls.getResource("Component.wox");

        if (templateData == null) {
            type = "WOWrapper";
            templateData = cls.getResource(_name + ".html");
            wodData = cls.getResource(_name + ".wod");

            if (debugOn)
                log.debug("in " + cls + " lookup " + _name + ".html: " + templateData);

            if (templateData == null)
                templateData = cls.getResource("Component.html");
            if (wodData == null)
                wodData = cls.getResource("Component.wod");
        }
    }

    if (templateData == null) {
        if (debugOn)
            log.debug("component has no template: " + _name);
        return cdef;
    }

    /* load it */

    if (!cdef.load(type, templateData, wodData, _rm)) {
        log.error("failed to load template.");
        return null;
    }
    return cdef;
}

From source file:org.getobjects.appserver.products.WOPackageLinker.java

public boolean linkFramework(String _pkg) {
    if (_pkg == null)
        return false;
    if (_pkg.length() == 0)
        return false;

    /* avoid load cycles */
    if (this.packagesInLoad.contains(_pkg))
        return true;
    this.packagesInLoad.add(_pkg);

    this.log.debug("  link framework: " + _pkg);

    // TBD: use active loader?
    final ClassLoader loader = this.getClass().getClassLoader();

    /* load all classes of the framework to let us cache the dynamic elements */

    /* first lookup base class for package (used as the hook) */
    // Note: the new 'package-info.java' doesn't contain a class

    Class pkgbase = null;
    try {/*from w w w.  ja  v  a  2  s .  c  o  m*/
        pkgbase = Class.forName(_pkg + "." + "WOFramework", true, loader);
    } catch (ClassNotFoundException e) {
        this.log.debug("    did not find package base class", null /* e2 */);
    }

    if (pkgbase == null) {
        this.log.warn("    could not link package: " + _pkg);
        return false;
    }
    this.log.debug("    using base class:" + pkgbase);

    /* link */

    final WOPackageLinker linker = new WOPackageLinker(this.enableCaching, this.goProductManager);
    linker.linkClass(pkgbase);

    /* next check whether the package wants to link something */

    // TODO: check whether this works properly
    URL deplink = pkgbase.getResource(goLinkFile);
    if (deplink == null)
        deplink = pkgbase.getResource(jopeLinkFile);
    if (deplink != null) {
        this.log.debug("    linking framework dependencies ...");
        linker.linkWithSpecification(deplink);
    }

    /* link system frameworks */
    // TODO: we get an runaway when calling this, find out why
    // String sysbase = WOApplication.class.getPackage().getName();
    // linker.linkFramework(sysbase + ".elements");
    // linker.linkFramework(sysbase);

    /* retrieve the resulting resource manager */
    final WOResourceManager rm = linker.resourceManager();
    if (rm instanceof WOCompoundResourceManager) {
        final WOCompoundResourceManager crm = (WOCompoundResourceManager) rm;
        for (WOResourceManager erm : crm.resourceManagers())
            this.addResourceManager(erm);
    } else
        this.addResourceManager(rm);

    /* register the product as a GoClass */

    if (this.goProductManager != null) {
        if (!this.goProductManager.loadProduct(null, _pkg)) {
            this.log.warn("could not register linked framework as a product: " + _pkg);
        }
    }

    return true;
}

From source file:org.getobjects.eoaccess.EODatabase.java

/**
 * This method first derives the model name from the given class. If the
 * class ends with 'Database', this is replace with 'Model.xml'. For example:
 * 'OGoDatabase' gives 'OGoModel.xml'.//  w  ww.  j  a va  2  s  .c  o  m
 * The model is the loaded.
 */
public static EOAdaptor dbAdaptorForURL(Class _cls, String _dbURL) {
    if (_cls == null) {
        log.error("got no EODatabase class to create the adaptor for:" + _dbURL);
        return null;
    }
    if (_dbURL == null) {
        log.error("got no URL create the adaptor for:" + _cls);
        return null;
    }

    /* derive model name (eg OGoDatabase => OGoModel.xml) */

    String modelName = _cls.getSimpleName();
    if (modelName.endsWith("Database"))
        modelName = modelName.substring(0, modelName.length() - 8);
    modelName += "Model.xml";

    /* load model */

    URL modelURL = _cls.getResource(modelName);
    EOModel modelPattern = null;
    try {
        if (modelURL != null)
            modelPattern = EOModel.loadModel(modelURL);
        else
            log.warn("did not find database model resource: " + modelName);
    } catch (Exception e) {
        log.error("could not load database model " + modelName, e);
        return null;
    }

    /* setup adaptor */

    EOAdaptor adaptor = EOAdaptor.adaptorWithURL(_dbURL, modelPattern);
    if (adaptor == null) {
        log.error("got no adaptor for DB URL: " + _dbURL);
        return null;
    }

    if (!adaptor.testConnect()) {
        log.error("adaptor could not connect to DB URL: " + _dbURL);
        return null;
    }

    /* make adaptor fetch the model from the database (if necessary) */

    EOModel model = adaptor.model();
    if (model == null) {
        log.error("adaptor could not retrieve model for DB URL: " + _dbURL);
        return null;
    }

    return adaptor;
}

From source file:org.getobjects.foundation.NSPropertyListParser.java

/**
 * Parse a plist from a Java class resource (MyClass.getResource()).
 *
 * @param _baseClass    - Java class to use as a lookup base
 * @param _resourceName - name of the resource
 * @return a plist object, or null on error
 *//*  www.j a  va 2  s.c o  m*/
public static Object parse(final Class _baseClass, String _resourceName) {
    if (_baseClass == null || _resourceName == null)
        return null;

    if (_resourceName.lastIndexOf('.') == -1)
        _resourceName += ".plist";
    final URL url = _baseClass.getResource(_resourceName);
    if (url == null) {
        plistLog.error("did not find resource in class " + _baseClass + " : " + _resourceName);
        return null;
    }

    final NSPropertyListParser parser = new NSPropertyListParser();
    final Object plist = parser.parse(url);

    if (plist == null) {
        plistLog.error("could not load plist resource: " + url, parser.lastException());
        return null;
    }
    return plist;
}