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:org.jboss.as.test.integration.security.CustomLoginModuleTestCase.java

@Deployment
public static WebArchive deployment() {
    // FIXME hack to get things prepared before the deployment happens
    try {//from  w  ww.ja v a  2s. co  m
        final ModelControllerClient client = ModelControllerClient.Factory
                .create(InetAddress.getByName("localhost"), 9999);
        // create required security domains
        createSecurityDomains(client);
    } catch (Exception e) {
        // ignore
    }

    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    URL webxml = tccl.getResource("web-secure.war/web.xml");
    WebArchive war = create("custom-login-module.war", SecuredServlet.class, webxml);
    WebSecurityPasswordBasedBase.printWar(war);
    return war;
}

From source file:com.netsteadfast.greenstep.bsc.util.BscReportSupportUtils.java

public static byte[] getByteIconBase(String mode, float target, float min, float score, String kpiCompareType,
        String kpiManagement, float kpiQuasiRange) throws Exception {
    byte[] datas = null;
    SysExpressionVO sysExpression = exprThreadLocal04.get();
    if (null == sysExpression) {
        return datas;
    }/*from w  w  w . ja  v  a  2  s.co  m*/
    Map<String, Object> parameters = new HashMap<String, Object>();
    Map<String, Object> results = new HashMap<String, Object>();
    parameters.put("mode", mode);
    parameters.put("target", target);
    parameters.put("min", min);
    parameters.put("score", score);
    parameters.put("compareType", kpiCompareType);
    parameters.put("management", kpiManagement);
    parameters.put("quasiRange", kpiQuasiRange);
    results.put("icon", " ");
    ScriptExpressionUtils.execute(sysExpression.getType(), sysExpression.getContent(), results, parameters);
    String iconResource = (String) results.get("icon");
    ClassLoader classLoader = BscReportSupportUtils.class.getClassLoader();
    datas = IOUtils.toByteArray(classLoader.getResource(iconResource).openStream());
    return datas;
}

From source file:ResourcesUtils.java

/**
 * Returns the URL of the resource on the classpath
 * /*  ww w .j  a v a 2s .  c  om*/
 * @param loader
 *            The classloader used to load the resource
 * @param resource
 *            The resource to find
 * @throws IOException
 *             If the resource cannot be found or read
 * @return The resource
 */
public static URL getResourceURL(ClassLoader loader, String resource) throws IOException {
    URL url = null;
    if (loader != null) {
        url = loader.getResource(resource);
    }
    if (url == null) {
        url = ClassLoader.getSystemResource(resource);
    }
    if (url == null) {
        throw new IOException("Could not find resource " + resource);
    }
    return url;
}

From source file:com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.java

/**
 * Loads up a resource from the classpath as a byte array.
 * @param path path of resource/*from  ww w.j  a  v a 2s. c  om*/
 * @return contents of resource
 * @throws IOException if any IO error occurs
 * @throws IllegalArgumentException if {@code path} cannot be found
 */
public static byte[] getResource(String path) throws IOException {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL url = cl.getResource(path);
    Validate.isTrue(url != null);
    try (InputStream in = url.openStream()) {
        return IOUtils.toByteArray(in);
    }
}

From source file:org.jboss.as.test.integration.security.CustomLoginModuleTestCase.java

/**
 * Base method to create a {@link WebArchive}
 *
 * @param name Name of the war file/*from  www.j  ava  2  s.  c  om*/
 * @param servletClass a class that is the servlet
 * @param webxml {@link URL} to the web.xml. This can be null
 * @return
 */
public static WebArchive create(String name, Class<?> servletClass, URL webxml) {
    WebArchive war = ShrinkWrap.create(WebArchive.class, name);
    war.addClass(servletClass);

    ClassLoader tccl = Thread.currentThread().getContextClassLoader();

    war.addAsWebResource(tccl.getResource("web-secure.war/login.jsp"), "login.jsp");
    war.addAsWebResource(tccl.getResource("web-secure.war/error.jsp"), "error.jsp");
    war.addAsWebInfResource(tccl.getResource("custom-login-module.war/jboss-web.xml"), "jboss-web.xml");
    war.addClass(CustomTestLoginModule.class);

    if (webxml != null) {
        war.setWebXML(webxml);
    }

    return war;
}

From source file:com.liferay.portal.util.InitUtil.java

public static synchronized void init() {
    if (_initialized) {
        return;//from   ww w.ja  v  a 2 s.co  m
    }

    StopWatch stopWatch = null;

    if (_PRINT_TIME) {
        stopWatch = new StopWatch();

        stopWatch.start();
    }

    // Set the default locale used by Liferay. This locale is no longer set
    // at the VM level. See LEP-2584.

    String userLanguage = SystemProperties.get("user.language");
    String userCountry = SystemProperties.get("user.country");
    String userVariant = SystemProperties.get("user.variant");

    LocaleUtil.setDefault(userLanguage, userCountry, userVariant);

    // Set the default time zone used by Liferay. This time zone is no
    // longer set at the VM level. See LEP-2584.

    String userTimeZone = SystemProperties.get("user.timezone");

    TimeZoneUtil.setDefault(userTimeZone);

    // Shared class loader

    try {
        Thread currentThread = Thread.currentThread();

        PortalClassLoaderUtil.setClassLoader(currentThread.getContextClassLoader());
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Log4J

    if (GetterUtil.getBoolean(SystemProperties.get("log4j.configure.on.startup"), true)) {

        ClassLoader classLoader = InitUtil.class.getClassLoader();

        Log4JUtil.configureLog4J(classLoader.getResource("META-INF/portal-log4j.xml"));
        try {
            Log _log = LogFactoryUtil.getLog(InitUtil.class);

            String configName = "META-INF/portal-log4j-ext.xml";
            Enumeration<URL> configs = classLoader.getResources(configName);
            if (_log.isDebugEnabled() && !configs.hasMoreElements()) {
                _log.debug("No " + configName + " has been found");
            }
            while (configs.hasMoreElements()) {
                URL config = configs.nextElement();
                Log4JUtil.configureLog4J(config);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Shared log

    try {
        LogFactoryUtil.setLogFactory(new Log4jLogFactoryImpl());
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Cache registry

    CacheRegistryUtil.setCacheRegistry(new CacheRegistryImpl());

    // Configuration factory

    ConfigurationFactoryUtil.setConfigurationFactory(new ConfigurationFactoryImpl());

    // Data source factory

    DataSourceFactoryUtil.setDataSourceFactory(new DataSourceFactoryImpl());

    // DB factory

    DBFactoryUtil.setDBFactory(new DBFactoryImpl());

    // Java properties

    JavaProps.isJDK5();

    // ROME

    XmlReader.setDefaultEncoding(StringPool.UTF8);

    if (_PRINT_TIME) {
        System.out.println("InitAction takes " + stopWatch.getTime() + " ms");
    }

    _initialized = true;
}

From source file:com.dosport.system.utils.ReflectionUtils.java

/**
 * ??/*  www  . j a  v  a2 s .co  m*/
 * 
 * @param cls
 * @return
 * @throws IOException
 * @throws ClassNotFoundException
 */
public static List<Class<?>> getClasses(Class<?> cls) throws IOException, ClassNotFoundException {
    String pk = cls.getPackage().getName();
    String path = pk.replace('.', '/');
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    URL url = classloader.getResource(path);
    return getClasses(new File(url.getFile()), pk);
}

From source file:com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.java

/**
 * Loads up a ZIP file that's contained in the classpath.
 * @param path path of ZIP resource/*  w ww. jav  a  2  s.c  o  m*/
 * @return contents of files within the ZIP
 * @throws IOException if any IO error occurs
 * @throws NullPointerException if any argument is {@code null} or contains {@code null} elements
 * @throws IllegalArgumentException if {@code path} cannot be found, or if zipPaths contains duplicates
 */
public static Map<String, byte[]> readZipFromResource(String path) throws IOException {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL url = cl.getResource(path);
    Validate.isTrue(url != null);

    Map<String, byte[]> ret = new LinkedHashMap<>();

    try (InputStream is = url.openStream(); ZipArchiveInputStream zais = new ZipArchiveInputStream(is)) {
        ZipArchiveEntry entry;
        while ((entry = zais.getNextZipEntry()) != null) {
            ret.put(entry.getName(), IOUtils.toByteArray(zais));
        }
    }

    return ret;
}

From source file:jp.terasoluna.fw.batch.unit.util.ClassLoaderUtils.java

/**
 * <pre>/* w w w  .  j a  v a2 s . c om*/
 * srcPaths??????????
 * ??????
 * ????destPaths????
 * </pre>
 * 
 * @param destPaths
 * @param srcPaths
 */
public static void addPathIfExists(List<String> destPaths, List<String> srcPaths) {
    Assert.notNull(destPaths);
    Assert.notNull(srcPaths);

    ClassLoader cl = getClassLoader();
    for (String path : srcPaths) {
        if (path != null) {
            URL r = cl.getResource(path);
            if (r != null) {
                try {
                    String protocol = r.getProtocol();
                    if (protocol.equals("file")) {
                        URI uri = r.toURI();
                        File f = new File(uri);
                        if (f.isFile()) {
                            // ?????
                            destPaths.add(path);
                        }
                    } else {
                        // jar
                        URLConnection con = null;
                        try {
                            con = r.openConnection();
                            if (con.getContentLength() > 0) {
                                // ?????
                                destPaths.add(path);
                            }
                        } catch (IOException e) {
                            // ?????????
                            LOG.warn(con + " is illegal.", e);
                        }
                    }
                } catch (URISyntaxException e) {
                    // r != null???????????????
                    LOG.warn(path + " is illegal.", e);
                }
            } else {
                LOG.debug(path + " is not found.");
            }
        }
    }
}

From source file:org.jodconverter.office.OnlineOfficeManagerPoolEntry.java

private static File getFile(final String resourceLocation) throws FileNotFoundException {

    Validate.notNull(resourceLocation, "Resource location must not be null");
    if (resourceLocation.startsWith("classpath:")) {
        final String path = resourceLocation.substring("classpath:".length());
        final String description = "class path resource [" + path + "]";
        final ClassLoader cl = getDefaultClassLoader();
        final URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path));
        if (url == null) {
            throw new FileNotFoundException(
                    description + " cannot be resolved to absolute file path because it does not exist");
        }/* w  ww  . j ava 2s .  c om*/
        return getFile(url.toString());
    }

    try {
        // try URL
        return getFile(new URL(resourceLocation));
    } catch (MalformedURLException ex) {
        // no URL -> treat as file path
        return new File(resourceLocation);
    }
}