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.getobjects.jetty.WOJettyRunner.java

/**
 * This prepares and configures the Jetty server. It sets up the Servlet
 * context and configuration to point to the WOServletAdaptor class.
 * <p>/*  ww  w .  jav a2 s.  co m*/
 * Flow:
 * <ol>
 *   <li>a jetty.Server object is setup with a port
 *   <li>a servlet.Context object is attached to the server with the appname
 *   <li>a ServletHolder objects is created as a factory for WOServletAdaptor
 *       and holds all the 'init parameters' (properties)
 *   <li>the ServletHolder is added to the servlet.Context (as / which is
 *       /AppName/ with the prefix of the Context itself)
 * </ol>
 * Note: no WO objects are instantiated at this point.
 * <p>
 * Finally the app can have a public 'www' directory with static resources
 * (either as a 'www' subpackage, or pointed to by WOProjectDirectory, or
 * in the current directory).<br>
 * All files/dirs within that are publically exposed in the Jetty root (NOT
 * below the app entry point, e.g.: /images/banner.gif).
 */
public void initWithProperties(final Properties _properties) {
    String appClassName = _properties.getProperty("WOAppClass");
    String appName = _properties.getProperty("WOAppName");

    if (appClassName == null)
        appClassName = appName;

    Class appClass = NSJavaRuntime.NSClassFromString(appClassName);
    if (appClass == null) {
        this.log.warn("did not find application class: " + appClassName);
        appClass = WOApplication.class;
    }

    String shortAppName = appName;
    if (shortAppName == null)
        shortAppName = appClass.getSimpleName();

    /* Map 'www' directory inside the application package */
    final URL rsrcBase = appClass.getResource("www");

    this.log.debug("setting up Jetty ...");

    int port = UObject.intValue(_properties.get("WOPort"));
    this.server = new Server(port);
    this.log.debug(shortAppName + " starts on port: " + port);

    /* Create a Jetty Context. "org.mortbay.jetty.servlet.Context" manages
     * a (or many?) ServletContexts in Jetty.
     *
     * Note that we map the whole context to the appname!
     */
    final Context root = new Context(this.server, "/" + shortAppName,
            Context.NO_SESSIONS | Context.NO_SECURITY);

    /* add a Servlet to the container */

    //root.addServlet("org.mortbay.servlet.Dump", "/Dump/*");

    /* a ServletHolder wraps a Servlet configuration in Jetty */
    ServletHolder servletHolder = new ServletHolder(WOServletAdaptor.class);
    servletHolder.setName(shortAppName);
    servletHolder.setInitParameter("WOAppName", shortAppName);
    servletHolder.setInitParameter("WOAppClass", appClass.getName());

    for (Object pName : _properties.keySet()) {
        final String value = _properties.getProperty((String) pName);
        servletHolder.setInitParameter((String) pName, value);
    }

    this.prepareServletHolder(root, servletHolder, shortAppName);

    /* This makes the Servlet being initialize on startup (instead of first
     * request).
     */
    servletHolder.setInitOrder(10); /* positive values: init asap */

    /* add Servlet to the Jetty Context */

    root.addServlet(servletHolder, "/");
    this.log.debug("mapped application to URL: /" + shortAppName);

    /* add resource handler (directly expose 'www' directory to Jetty) */

    this.addResourceHandler(rsrcBase, _properties);

    /* done */

    this.log.debug("finished setting up Servlets.");
    this.applicationURL = "http://localhost:" + port + "/" + shortAppName;
    this.log.info("Application URL is " + this.applicationURL);

    this.autoOpenInBrowser = UObject.boolValue(_properties.getProperty("WOAutoOpenInBrowser", "false"));
}

From source file:org.graphwalker.Util.java

public static Logger setupLogger(@SuppressWarnings("rawtypes") final Class classParam) {
    Logger logger = Logger.getLogger(classParam);
    if (new File("graphwalker.properties").canRead()) {
        PropertyConfigurator.configure("graphwalker.properties");
    } else {//w ww.ja  va 2 s . c  o  m
        PropertyConfigurator
                .configure(classParam.getResource("/org/graphwalker/resources/graphwalker.properties"));
    }
    return logger;
}

From source file:org.guzz.util.PropertyUtil.java

/**
 * Load properties from classpath.//  w  w  w .ja  v a 2s  .c om
 * @param clazz relative class
 * @param resName resource file name
 * @return return null if failed.
 */
public static Properties loadFromResource(Class clazz, String resName) {
    URL resUrl = clazz.getResource(resName);

    if (resUrl == null) {
        log.debug("resource not available! resName: " + resName);
        return null;
    }

    InputStream fis = null;

    try {
        fis = resUrl.openStream();
        Properties props = new Properties();
        props.load(fis);
        return props;
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.error("erron on load resource, url:[" + resUrl + "], msg:" + e);
        }
    } finally {
        CloseUtil.close(fis);
    }

    return null;
}

From source file:org.hibernate.search.test.util.impl.ClasspathResourceAsFile.java

public ClasspathResourceAsFile(Class<?> clazz, String path, File parentDirectory) {
    this.url = clazz.getResource(path);
    this.parentDirectory = parentDirectory;
}

From source file:org.hippoecm.repository.util.RepoUtils.java

/**
 * @param clazz the class object for which to obtain a reference to the manifest
 * @return the URL of the manifest found, or {@code null} if it could not be obtained
 *///  w w w.j  a  v a2 s . co m
public static URL getManifestURL(Class clazz) {
    try {
        final StringBuilder sb = new StringBuilder();
        final String[] classElements = clazz.getName().split("\\.");
        for (int i = 0; i < classElements.length - 1; i++) {
            sb.append("../");
        }
        sb.append("META-INF/MANIFEST.MF");
        final URL classResource = clazz.getResource(classElements[classElements.length - 1] + ".class");
        if (classResource != null) {
            return new URL(classResource, new String(sb));
        }
    } catch (MalformedURLException ignore) {
    }
    return null;
}

From source file:org.jahia.services.htmlvalidator.WAIValidatorTest.java

private String[] getResourceListing(Class clazz, String path) throws URISyntaxException, IOException {
    URL dirURL = clazz.getResource(path);
    if (dirURL != null && dirURL.getProtocol().equals("file")) {
        /* A file path: easy enough */
        return new File(dirURL.toURI()).list();
    }/*w ww .j a  v  a 2  s .co m*/

    if (dirURL == null) {
        /*
        * In case of a jar file, we can't actually find a directory.
        * Have to assume the same jar as clazz.
        */
        String me = clazz.getName().replace(".", "/") + ".class";
        dirURL = clazz.getClassLoader().getResource(me);
    }

    if (dirURL.getProtocol().equals("jar")) {
        /* A JAR path */
        String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
        JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
        Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
        Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory
        while (entries.hasMoreElements()) {
            String name = entries.nextElement().getName();
            if (name.startsWith(path)) { //filter according to the path
                result.add(name);
            }
        }
        return result.toArray(new String[result.size()]);
    }

    throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}

From source file:org.jboss.datavirt.commons.config.ConfigurationFactory.java

/**
 * Shared method used to locate and load configuration information from a number of
 * places, aggregated into a single {@link Configuration} instance.
 * @param configFileOverride/*from   w w  w. ja v a 2  s . com*/
 * @param standardConfigFileName
 * @param refreshDelay
 * @param defaultConfigPath
 * @param defaultConfigLoader
 * @throws ConfigurationException
 */
public static Configuration createConfig(String configFileOverride, String standardConfigFileName,
        Long refreshDelay, String defaultConfigPath, Class<?> defaultConfigLoader) {
    registerGlobalLookups();
    try {
        CompositeConfiguration config = new CompositeConfiguration();
        config.addConfiguration(new SystemPropertiesConfiguration());
        URL url = findConfig(configFileOverride, standardConfigFileName);
        if (url != null) {
            PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration(url);
            FileChangedReloadingStrategy fileChangedReloadingStrategy = new FileChangedReloadingStrategy();
            fileChangedReloadingStrategy.setRefreshDelay(refreshDelay);
            propertiesConfiguration.setReloadingStrategy(fileChangedReloadingStrategy);
            config.addConfiguration(propertiesConfiguration);
        }
        if (defaultConfigPath != null) {
            config.addConfiguration(
                    new PropertiesConfiguration(defaultConfigLoader.getResource(defaultConfigPath)));
        }
        return config;
    } catch (ConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jbpm.bpel.wsdl.xml.WsdlUtil.java

public static Definition readResource(Class clazz, String resource) throws WSDLException {
    return factory.newWSDLReader().readWSDL(clazz.getResource(resource).toExternalForm());
}

From source file:org.jbpm.bpel.xml.util.XmlUtil.java

public static DOMSource parseResource(String resource, Class cl) throws SAXException, IOException {
    URL resourceURL = cl.getResource(resource);
    Element elem = parseResource(resource, resourceURL);
    return new DOMSource(elem, resourceURL.toExternalForm());
}

From source file:org.jcurl.demo.tactics.JCurlShotPlanner.java

/**
 * Setting the internal field {@link #document} directly (bypassing
 * {@link #setDocument(URL)}) is used to deplay the document loading until
 * {@link #ready()}./*from w  w w .ja va2s.  c  o m*/
 */
@Override
protected void initialize(final String[] as) {
    if ("Linux".equals(System.getProperty("os.name")))
        getContext().getResourceManager().setPlatform("linux");

    final Class<?> mc = this.getClass();
    {
        final ResourceMap r = Application.getInstance().getContext().getResourceMap();
        initialScene = mc.getResource("/" + r.getResourcesDir() + r.getString("Application.defaultDocument"));
        templateScene = mc.getResource("/" + r.getResourcesDir() + r.getString("Application.templateDocument"));
    }

    // schedule the document to load in #ready()
    document = initialScene;
    for (final String p : as) {
        // ignore javaws parameters
        if ("-open".equals(p) || "-print".equals(p))
            continue;
        try {
            document = new URL(p);
            break;
        } catch (final MalformedURLException e) {
            final File f = new File(p);
            if (f.canRead())
                try {
                    document = f.toURL();
                    break;
                } catch (final MalformedURLException e2) {
                    log.warn("Cannot load '" + p + "'.", e);
                }
            else
                log.warn("Cannot load '" + p + "'.", e);
        }
    }
}