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.wso2.carbon.identity.common.testng.CarbonBasedTestListener.java

@Override
public void onBeforeClass(ITestClass iTestClass, IMethodInstance iMethodInstance) {

    Class realClass = iTestClass.getRealClass();
    if (annotationPresent(realClass, WithCarbonHome.class)) {
        System.setProperty(CarbonBaseConstants.CARBON_HOME, realClass.getResource("/").getFile());
        System.setProperty(TestConstants.CARBON_PROTOCOL, TestConstants.CARBON_PROTOCOL_HTTPS);
        System.setProperty(TestConstants.CARBON_HOST, TestConstants.CARBON_HOST_LOCALHOST);
        System.setProperty(TestConstants.CARBON_MANAGEMENT_PORT, TestConstants.CARBON_DEFAULT_HTTPS_PORT);
        copyDefaultConfigsIfNotExists(realClass);
    }//w  ww  . ja v  a2 s .co m
    if (annotationPresent(realClass, WithAxisConfiguration.class)) {
        AxisConfiguration axisConfiguration = new AxisConfiguration();
        ConfigurationContext configurationContext = new ConfigurationContext(axisConfiguration);
        setInternalState(IdentityCoreServiceComponent.class, "configurationContextService",
                new ConfigurationContextService(configurationContext, configurationContext));
    }
    if (annotationPresent(realClass, WithH2Database.class)) {
        System.setProperty("java.naming.factory.initial",
                "org.wso2.carbon.identity.common.testng.MockInitialContextFactory");
        Annotation annotation = realClass.getAnnotation(WithH2Database.class);
        WithH2Database withH2Database = (WithH2Database) annotation;
        MockInitialContextFactory.initializeDatasource(withH2Database.jndiName(), this.getClass(),
                withH2Database.files());
        setInternalState(JDBCPersistenceManager.class, "instance", null);
    }
    if (annotationPresent(realClass, WithRealmService.class)) {
        Annotation annotation = realClass.getAnnotation(WithRealmService.class);
        WithRealmService withRealmService = (WithRealmService) annotation;
        try {
            createRealmService(withRealmService, false);
        } catch (UserStoreException e) {
            log.error("Could not initialize the realm service for test. Test class:  " + realClass.getName(),
                    e);
        }
    }
    if (annotationPresent(realClass, WithRegistry.class)) {
        Annotation annotation = realClass.getAnnotation(WithRegistry.class);
        WithRegistry withRegistry = (WithRegistry) annotation;
        createRegistryService(realClass, withRegistry);
    }
    if (annotationPresent(realClass, WithKeyStore.class)) {
        Annotation annotation = realClass.getAnnotation(WithKeyStore.class);
        WithKeyStore withKeyStore = (WithKeyStore) annotation;
        createKeyStore(realClass, withKeyStore);
    }
    if (annotationPresent(realClass, WithMicroService.class)
            && !microserviceServerInitialized(iMethodInstance.getInstance())) {
        MicroserviceServer microserviceServer = initMicroserviceServer(iMethodInstance.getInstance());
        scanAndLoadClasses(microserviceServer, realClass, iMethodInstance.getInstance());
    }
    Field[] fields = realClass.getDeclaredFields();
    processFields(fields, iMethodInstance.getInstance());
}

From source file:org.wso2.carbon.identity.test.common.testng.utils.ReadCertStoreSampleUtil.java

public static KeyStore createKeyStore(Class clazz) throws Exception {
    clazz.getResource("");
    File file = new File(clazz.getResource("/repository/resources/security/wso2carbon.jks").getFile());
    KeyStore keyStore = KeyStore.getInstance("JKS");
    if (file.exists()) {
        // if exists, load
        keyStore.load(new FileInputStream(file), "wso2carbon".toCharArray());
    } else {/*  w ww .ja  v  a 2  s  .c om*/
        // if not exists, create
        keyStore.load(null, null);
        keyStore.store(new FileOutputStream(file), "wso2carbon".toCharArray());
    }
    return keyStore;
}

From source file:org.xmlactions.common.io.ResourceIO.java

/**
 * Open InputStream from a file location or a resource location (path or classpath)
 * <p>//  w  ww .j av  a2 s  .c om
 *    <b>You must close the inputstream</b> maybe use <code>IOUtils.closeQuietly(inputStream);</code>
 * </p>
 * @param name - can be fileName or resourceFileName
 * @return the loaded String
 */
public static InputStream openInputStreamForFileOrResource(Class<?> clas, String name) {

    String errorMessage = "Unable to load resource from [" + name + "]";
    InputStream inputStream = null;
    try {
        if (new File(name).exists() == true) {
            inputStream = new FileInputStream(name);
        } else {
            URL url = clas.getResource(name);
            if (url == null) {
                throw new IllegalArgumentException(errorMessage);
            }
            inputStream = url.openStream();
        }
        return inputStream;
    } catch (IllegalArgumentException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new IllegalArgumentException(errorMessage, ex);
    }
}

From source file:org.zilverline.util.TestClassFinder.java

public void testLocateClass() {
    Class pClass = FileSystemCollection.class;
    // get the name of the class (e.g. my.package.MyClass)
    String className = pClass.getName();

    // create the resource path for this class
    String resourcePath = "/" + className.replace('.', '/') + ".class";

    // get the resource as a url (e.g.
    // file:/C:/temp/my/package/MyClass.class
    URL classURL = pClass.getResource(resourcePath);
    log.debug(classURL);//from   ww w. ja va2  s.  co m
    log.debug(classURL.getPath());
}

From source file:ro.agrade.jira.qanda.utils.ResourceUtils.java

/**
 * Gets a resource as URL. A resource means a simple resource in the
 * classpath or a plain URL/*from   w w w  .  ja v a 2  s.c om*/
 *
 * @param resFileName the resource name
 * @param loaderClazz the loader class
 * @return the URL, or null if URL verification failed
 */
public static URL getResourceAsURL(String resFileName, Class<?> loaderClazz) {
    URL url = null;

    if (resFileName.startsWith("/")) {
        url = loaderClazz.getResource(resFileName);
        if (LOG.isDebugEnabled()) {
            if (url == null) {
                LOG.debug(String.format("Resource %s is not a resource.", resFileName));
            }
        }
    } else {
        try {
            url = new URL(resFileName);
        } catch (MalformedURLException ex) {
            LOG.debug(String.format("Resource %s is not a URL resource.", resFileName));
        }
    }
    return url;
}

From source file:ro.agrade.jira.qanda.utils.ResourceUtils.java

/**
 * Gets the resource//from  w  ww. j  a  va2 s . co  m
 *
 * @param resFileName file path, URL, or internal resource denominator.
 * @param loaderClazz the loader class
 * @throws IOException if something goes wrong.
 * @return the configuration as an input stream
 */
public static InputStream getAsInputStream(String resFileName, Class<?> loaderClazz) throws IOException {
    //first, try to see if this is a file
    File f = new File(resFileName);
    if (f.exists()) {
        return new BufferedInputStream(new FileInputStream(f));
    }

    //fallback to URL config
    URL configurationUrl = null;
    if (resFileName.startsWith("/")) {
        configurationUrl = loaderClazz.getResource(resFileName);
        if (configurationUrl == null) {
            String msg = String.format("The resource >>%s<< is not a valid resource.", resFileName);
            LOG.error(msg);
            throw new java.io.IOException(msg);
        }
    } else {
        try {
            configurationUrl = new URL(resFileName);
        } catch (MalformedURLException ex) {
            String msg = String.format("The resource >>%s<< is not a valid URL.", resFileName);
            LOG.error(msg, ex);
            throw new IOException(msg);
        }
    }

    //we have the URL, connect on it ...
    URLConnection conn = configurationUrl.openConnection();
    conn.connect();
    return conn.getInputStream();
}

From source file:ru.runa.notifier.util.ClassLoaderUtil.java

public static URL getAsURL(String resourceName, Class<?> callingClass) {
    Preconditions.checkNotNull(resourceName, "resourceName");
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL url = null;//  ww w  .  jav a 2  s . com
    while ((loader != null) && (url == null)) {
        url = loader.getResource(resourceName);
        loader = loader.getParent();
    }
    if (url == null) {
        loader = extensionClassLoader;
        url = loader.getResource(resourceName);
    }
    if (url == null) {
        loader = callingClass.getClassLoader();
        if (loader != null) {
            url = loader.getResource(resourceName);
        }
    }
    if (url == null) {
        url = callingClass.getResource(resourceName);
    }
    if (url == null && resourceName.length() > 0 && resourceName.charAt(0) != '/') {
        return getAsURL('/' + resourceName, callingClass);
    }
    return url;
}

From source file:ru.runa.wfe.commons.ClassLoaderUtil.java

public static URL getAsURL(String resourceName, Class<?> callingClass) {
    Preconditions.checkNotNull(resourceName, "resourceName");
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL url = null;//from  www.jav  a 2s. c  om
    while (loader != null && url == null) {
        url = loader.getResource(resourceName);
        loader = loader.getParent();
    }
    if (url == null) {
        loader = extensionClassLoader;
        url = loader.getResource(resourceName);
    }
    if (url == null) {
        loader = callingClass.getClassLoader();
        if (loader != null) {
            url = loader.getResource(resourceName);
        }
    }
    if (url == null) {
        url = callingClass.getResource(resourceName);
    }
    if (url == null && resourceName.length() > 0 && resourceName.charAt(0) != '/') {
        return getAsURL('/' + resourceName, callingClass);
    }
    return url;
}

From source file:se.vgregion.portal.innovatinosslussen.domain.TypesBeanTest.java

private List<Class> getTypes(Class sampelTypeFromPack) throws ClassNotFoundException {
    Package aPackage = sampelTypeFromPack.getPackage();
    URL url = sampelTypeFromPack.getResource("/");
    File file = new File(url.getFile());
    file = new File(file.getParent());
    String sc = File.separator;
    String path = file.getParent() + sc + "target" + sc + "classes" + sc
            + aPackage.getName().replace('.', sc.charAt(0)) + sc;
    file = new File(path);
    List<Class> result = new ArrayList<Class>();

    if (file != null && file.list() != null) {
        for (String clazzFileName : file.list()) {
            if (clazzFileName.endsWith(".class")) {
                clazzFileName = clazzFileName.substring(0, clazzFileName.indexOf(".class"));
                result.add(Class.forName(aPackage.getName() + "." + clazzFileName));
            }//from ww  w. ja va  2s .  c  o m
        }
    } else {
        System.out.println("File or its children did not exist " + file);
    }

    return result;
}