Example usage for java.lang ClassLoader getResource

List of usage examples for java.lang ClassLoader getResource

Introduction

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

Prototype

public URL getResource(String name) 

Source Link

Document

Finds the resource with the given name.

Usage

From source file:eu.mihosoft.vrl.fxscad.MainController.java

/**
 * Returns the location of the Jar archive or .class file the specified
 * class has been loaded from. <b>Note:</b> this only works if the class is
 * loaded from a jar archive or a .class file on the locale file system.
 *
 * @param cls class to locate//  www  .  j ava2 s.  co  m
 * @return the location of the Jar archive the specified class comes from
 */
public static File getClassLocation(Class<?> cls) {

    //        VParamUtil.throwIfNull(cls);
    String className = cls.getName();
    ClassLoader cl = cls.getClassLoader();
    URL url = cl.getResource(className.replace(".", "/") + ".class");

    String urlString = url.toString().replace("jar:", "");

    if (!urlString.startsWith("file:")) {
        throw new IllegalArgumentException("The specified class\"" + cls.getName()
                + "\" has not been loaded from a location" + "on the local filesystem.");
    }

    urlString = urlString.replace("file:", "");
    urlString = urlString.replace("%20", " ");

    int location = urlString.indexOf(".jar!");

    if (location > 0) {
        urlString = urlString.substring(0, location) + ".jar";
    } else {
        //System.err.println("No Jar File found: " + cls.getName());
    }

    return new File(urlString);
}

From source file:com.autentia.tnt.manager.report.ReportManager.java

public static List<String> filesFromFolder(Boolean typeFile, String path) {
    File[] filesList = null;/* ww  w  .j ava2s  .c  om*/
    List<String> list = new ArrayList<String>();
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    File f = null;
    try {
        if (typeFile == true)
            f = new File(loader.getResource(path).toURI());
        else
            f = new File(path);
    } catch (Exception e) {
        log.error("Error en filesFromFolder", e);
    }
    if (f != null && f.isDirectory()) {
        filesList = f.listFiles();
        for (File file : filesList) {
            int i = file.getAbsolutePath().lastIndexOf(".");
            String format = file.getAbsolutePath().substring(i + 1);
            if (file.isFile() && (format.equals("jrxml"))) {
                list.add(path + "/" + file.getName());
            }
        }
    }
    Collections.sort(list);
    return list;
}

From source file:com.twitter.distributedlog.DLMTestUtil.java

public static ServerConfiguration loadTestBkConf() {
    ServerConfiguration conf = new ServerConfiguration();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    URL confUrl = classLoader.getResource("bk_server.conf");
    try {//from   w  w w. j  a v a  2s.c  o  m
        if (null != confUrl) {
            conf.loadConf(confUrl);
            LOG.info("loaded bk_server.conf from resources");
        }
    } catch (org.apache.commons.configuration.ConfigurationException ex) {
        LOG.warn("loading conf failed", ex);
    }
    conf.setAllowLoopback(true);
    return conf;
}

From source file:de.ingrid.portal.interfaces.impl.IBUSInterfaceImpl.java

private static String getResourceAsStream(String resource) throws Exception {
    String stripped = resource.startsWith("/") ? resource.substring(1) : resource;

    String stream = null;/* w w  w .  ja v  a 2s  .com*/
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader != null) {
        URL url = classLoader.getResource(stripped);
        if (url != null) {
            stream = url.toString();
        }
    }
    if (stream == null) {
        Environment.class.getResourceAsStream(resource);
    }
    if (stream == null) {
        URL url = Environment.class.getClassLoader().getResource(stripped);
        if (url != null) {
            stream = url.toString();
        }
    }
    if (stream == null) {
        throw new Exception(resource + " not found");
    }
    return stream;
}

From source file:org.apache.bval.jsr.xml.ValidationParser.java

static Schema getSchema(final String xsd) {
    final Schema schema = SCHEMA_CACHE.get(xsd);
    if (schema != null) {
        return schema;
    }//from ww  w. ja  v  a 2  s.com

    final ClassLoader loader = Reflection.getClassLoader(ValidationParser.class);
    final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final URL schemaUrl = loader.getResource(xsd);
    try {
        Schema s = sf.newSchema(schemaUrl);
        final Schema old = SCHEMA_CACHE.putIfAbsent(xsd, s);
        if (old != null) {
            s = old;
        }
        return s;
    } catch (SAXException e) {
        log.log(Level.WARNING, String.format("Unable to parse schema: %s", xsd), e);
        return null;
    }
}

From source file:org.ajax4jsf.renderkit.compiler.HtmlCompiler.java

/**
 * Compile XML from resource in classpath. Resource always readed
 * as UTF-8 text , to avoid xml declarations.
 * @param resource - absolute path to resource
 * @return compiled XML, or Exception-generated stub, if parsing error occurs.
 *//* ww  w. ja  v  a2  s.c  om*/
public static PreparedTemplate compileResource(String resource) {
    HtmlCompiler compiler = new HtmlCompiler();
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    InputStream input = URLToStreamHelper.urlToStreamSafe(loader.getResource(resource));
    // Since parsing exceptions handled by compiler, we can not check parameter.
    PreparedTemplate compile = compiler.compile(input, resource);
    if (null != input) {
        try {
            input.close();
        } catch (IOException e) {
            // can be ignored
        }
    }
    return compile;
}

From source file:org.apache.cassandra.utils.FBUtilities.java

public static String resourceToFile(String filename) throws ConfigurationException {
    ClassLoader loader = PropertyFileSnitch.class.getClassLoader();
    URL scpurl = loader.getResource(filename);
    if (scpurl == null)
        throw new ConfigurationException("unable to locate " + filename);

    return scpurl.getFile();
}

From source file:net.jradius.server.config.Configuration.java

private static void setGeneralOptions() {
    debug = xmlCfg.getConfigBoolean("debug");
    timeoutSeconds = xmlCfg.getConfigInt("timeout");

    List children = root.getChildren("chain-catalog");

    HierarchicalConfiguration.Node node;
    for (Iterator i = children.iterator(); i.hasNext();) {
        node = (HierarchicalConfiguration.Node) i.next();
        xmlCfg.setRoot(node);//w  w w  .jav a2 s.c  o m

        String catalogURL = xmlCfg.getConfigString("name");

        if (catalogURL != null) {
            try {
                ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                RadiusLog.debug("Loading Chains URL: " + catalogURL);
                parser.parse(classLoader.getResource(catalogURL));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        xmlCfg.setRoot(root);
    }
}

From source file:org.jboss.as.test.integration.web.sso.SSOTestBase.java

public static WebArchive createSsoWar(String warName) {
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    String resourcesLocation = "org/jboss/as/test/integration/web/sso/resources/";

    WebArchive war = ShrinkWrap.create(WebArchive.class, warName);
    war.setWebXML(tccl.getResource(resourcesLocation + "web-form-auth.xml"));
    war.addAsWebInfResource(tccl.getResource(resourcesLocation + "jboss-web.xml"), "jboss-web.xml");

    war.addAsWebResource(tccl.getResource(resourcesLocation + "error.html"), "error.html");
    war.addAsWebResource(tccl.getResource(resourcesLocation + "index.html"), "index.html");
    war.addAsWebResource(tccl.getResource(resourcesLocation + "index.jsp"), "index.jsp");
    war.addAsWebResource(tccl.getResource(resourcesLocation + "login.html"), "login.html");

    war.addClass(EJBServlet.class);
    war.addClass(LogoutServlet.class);

    return war;/*  w ww.  ja  va 2 s  .  c om*/
}

From source file:org.apache.axis2.util.Loader.java

/**
 * Searches for <code>resource</code> in different
 * places. The search order is as follows:
 * <ol>/*  w  w w.  j  a  v a  2  s  .com*/
 * <p><li>Search for <code>resource</code> using the thread context
 * class loader under Java2. If that fails, search for
 * <code>resource</code> using the class loader that loaded this
 * class (<code>Loader</code>).
 * <p><li>Try one last time with
 * <code>ClassLoader.getSystemResource(resource)</code>, that is is
 * using the system class loader in JDK 1.2 and virtual machine's
 * built-in class loader in JDK 1.1.
 * </ol>
 * <p/>
 *
 * @param resource
 * @return Returns URL
 */
static public URL getResource(String resource) {
    ClassLoader classLoader = null;
    URL url = null;
    try {
        // We could not find resource. Ler us now try with the
        // classloader that loaded this class.
        classLoader = getTCL();
        if (classLoader != null) {
            log.debug("Trying to find [" + resource + "] using " + classLoader + " class loader.");
            url = classLoader.getResource(resource);
            if (url != null) {
                return url;
            }
        }
    } catch (Throwable t) {
        log.warn("Caught Exception while in Loader.getResource. This may be innocuous.", t);
    }

    // Last ditch attempt: get the resource from the class path. It
    // may be the case that clazz was loaded by the Extentsion class
    // loader which the parent of the system class loader. Hence the
    // code below.
    log.debug("Trying to find [" + resource + "] using ClassLoader.getSystemResource().");
    return ClassLoader.getSystemResource(resource);
}