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:de.ipk_gatersleben.ag_nw.graffiti.plugins.gui.webstart.MainM.java

public MainM(final boolean showMainFrame, String applicationName, String[] args, String[] addon,
        String addPluginFile) {/*from  w ww  .j ava 2 s  .com*/
    this(applicationName, args, addon,
            new DBEsplashScreen(applicationName, "", new RunnableWithSplashScreenReference() {
                private SplashScreenInterface ss;

                @Override
                public void run() {
                    if (showMainFrame) {
                        ClassLoader cl = this.getClass().getClassLoader();
                        String path = this.getClass().getPackage().getName().replace('.', '/');
                        ImageIcon icon = new ImageIcon(cl.getResource(path + "/vanted_logo.png"));
                        final MainFrame mainFrame = MainFrame.getInstance();
                        if (icon != null && mainFrame != null)
                            mainFrame.setIconImage(icon.getImage());
                        if (mainFrame == null)
                            System.err.println("Internal Error: MainFrame is NULL");
                        else {
                            Thread t = new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    long waitTime = 0;
                                    long start = System.currentTimeMillis();
                                    do {
                                        if (ErrorMsg.getAppLoadingStatus() == ApplicationStatus.ADDONS_LOADED)
                                            break;
                                        try {
                                            Thread.sleep(50);
                                        } catch (InterruptedException e) {
                                        }
                                        waitTime = System.currentTimeMillis() - start;
                                    } while (waitTime < 2000);
                                    SwingUtilities.invokeLater(new Runnable() {
                                        @Override
                                        public void run() {
                                            ss.setVisible(false);
                                            mainFrame.setVisible(true);
                                        }
                                    });
                                }
                            }, "wait for add-on initialization");
                            t.start();
                        }
                    }
                }

                @Override
                public void setSplashscreenInfo(SplashScreenInterface ss) {
                    this.ss = ss;
                }
            }) {
            }, addPluginFile, showMainFrame);
}

From source file:de.fischer.thotti.core.runner.NDRunner.java

/**
 * Searches the classpath for the standard test configuration
 * file./*from ww w.ja  v  a2 s .c  o m*/
 *
 * @see #THOTTI_STANDARD_TEST_CONFIGURATION
 */
protected URL findTestConfiguration() throws NoTestConfigurationException {
    ClassLoader myLoader = getClass().getClassLoader();

    URL config = myLoader.getResource(THOTTI_STANDARD_TEST_CONFIGURATION);

    if (null == config) {
        throw new NoTestConfigurationException(
                "Standard configuration file " + THOTTI_STANDARD_TEST_CONFIGURATION + " "
                        + "not found as resource with the current " + "classpath settings.");
    }

    return config;
}

From source file:org.picketbox.test.authentication.http.jetty.DelegatingSecurityFilterHTTPBasicUnitTestCase.java

@Override
protected void establishUserApps() {
    ClassLoader tcl = Thread.currentThread().getContextClassLoader();
    if (tcl == null) {
        tcl = getClass().getClassLoader();
    }/* w  ww .  jav  a  2 s.com*/

    final String WEBAPPDIR = "auth/webapp";

    final String CONTEXTPATH = "/auth";

    // for localhost:port/admin/index.html and whatever else is in the webapp directory
    final URL warUrl = tcl.getResource(WEBAPPDIR);
    final String warUrlString = warUrl.toExternalForm();

    Context context = new WebAppContext(warUrlString, CONTEXTPATH);
    server.setHandler(context);

    Thread.currentThread().setContextClassLoader(context.getClassLoader());

    System.setProperty(PicketBoxConstants.USERNAME, "Aladdin");
    System.setProperty(PicketBoxConstants.CREDENTIAL, "Open Sesame");

    FilterHolder filterHolder = new FilterHolder(DelegatingSecurityFilter.class);
    filterHolder.setInitParameter(PicketBoxConstants.AUTH_MGR,
            SimpleCredentialAuthenticationManager.class.getName());
    filterHolder.setInitParameter(PicketBoxConstants.AUTH_SCHEME_LOADER,
            HTTPBasicAuthenticationSchemeLoader.class.getName());
    context.addFilter(filterHolder, "/", 1);
}

From source file:com.adeptj.runtime.osgi.BundleInstaller.java

Stream<Bundle> install(ClassLoader cl, String bundlesDir) throws IOException {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    Pattern pattern = Pattern.compile("^bundles.*\\.jar$");
    return ((JarURLConnection) this.getClass().getResource(bundlesDir).openConnection()).getJarFile().stream()
            .filter(jarEntry -> pattern.matcher(jarEntry.getName()).matches())
            .map(jarEntry -> cl.getResource(jarEntry.getName())).filter(Objects::nonNull).map(url -> {
                logger.debug("Installing Bundle from location: [{}]", url);
                Bundle bundle = null;//from w  ww. j  a va  2 s  .c  om
                try (JarInputStream jis = new JarInputStream(url.openStream(), false)) {
                    if (StringUtils
                            .isEmpty(jis.getManifest().getMainAttributes().getValue(BUNDLE_SYMBOLIC_NAME))) {
                        logger.warn("Artifact [{}] is not a Bundle, skipping install!!", url);
                    } else {
                        bundle = BundleContextHolder.getInstance().getBundleContext()
                                .installBundle(url.toExternalForm());
                        this.installationCount.incrementAndGet();
                    }
                } catch (BundleException | IllegalStateException | SecurityException | IOException ex) {
                    logger.error("Exception while installing Bundle: [{}]. Cause:", url, ex);
                }
                return bundle;
            }).filter(Objects::nonNull).sorted(Comparator.comparingLong(Bundle::getBundleId));
}

From source file:com.github.dozermapper.core.builder.xml.SchemaLSResourceResolver.java

/**
 * Attempt to resolve systemId resource from classpath by checking:
 *
 * 1. Try {@link SchemaLSResourceResolver#getClass()#getClassLoader()}
 * 2. Try {@link BeanContainer#getClassLoader()}
 * 3. Try {@link Activator#getBundle()}/*from  w  w  w  .  j a  v a 2  s  .c o m*/
 *
 * @param systemId systemId used by XSD
 * @return stream to XSD
 * @throws IOException if fails to find XSD
 */
private InputStream resolveFromClassPath(String systemId) throws IOException, URISyntaxException {
    InputStream source;

    String xsdPath;
    URI uri = new URI(systemId);
    if (uri.getScheme().equalsIgnoreCase("file")) {
        xsdPath = uri.toString();
    } else {
        xsdPath = uri.getPath();
        if (xsdPath.charAt(0) == '/') {
            xsdPath = xsdPath.substring(1);
        }
    }

    ClassLoader localClassLoader = getClass().getClassLoader();

    LOG.debug("Trying to locate [{}] via ClassLoader [{}]", xsdPath,
            localClassLoader.getClass().getSimpleName());

    //Attempt to find within this JAR
    URL url = localClassLoader.getResource(xsdPath);
    if (url == null) {
        //Attempt to find via user defined class loader
        DozerClassLoader dozerClassLoader = beanContainer.getClassLoader();

        LOG.debug("Trying to locate [{}] via DozerClassLoader [{}]", xsdPath,
                dozerClassLoader.getClass().getSimpleName());

        url = dozerClassLoader.loadResource(xsdPath);
    }

    if (url == null) {
        //Attempt to find via OSGi
        Bundle bundle = Activator.getBundle();
        if (bundle != null) {
            LOG.debug("Trying to locate [{}] via Bundle [{}]", xsdPath, bundle.getClass().getSimpleName());

            url = bundle.getResource(xsdPath);
        }
    }

    if (url == null) {
        throw new IOException("Could not resolve bean-mapping XML Schema [" + systemId
                + "]: not found in classpath; " + xsdPath);
    }

    try {
        source = url.openStream();
    } catch (IOException ex) {
        throw new IOException("Could not resolve bean-mapping XML Schema [" + systemId
                + "]: not found in classpath; " + xsdPath, ex);
    }

    LOG.debug("Found bean-mapping XML Schema [{}] in classpath @ [{}]", systemId, url.toString());

    return source;
}

From source file:com.github.helenusdriver.commons.lang3.reflect.ReflectionUtils.java

/**
 * Find all resources from a given jar file and add them to the provided
 * list.//from  w ww .j av  a2s.  co  m
 *
 * @author paouelle
 *
 * @param urls the non-<code>null</code> collection of resources where to add new
 *        found resources
 * @param url the non-<code>null</code> url for the jar where to find resources
 * @param resource the non-<code>null</code> resource being scanned that
 *        corresponds to given package
 * @param cl the classloader to find the resources with
 */
private static void findResourcesFromJar(Collection<URL> urls, URL url, String resource, ClassLoader cl) {
    try {
        final JarURLConnection conn = (JarURLConnection) url.openConnection();
        final URL jurl = conn.getJarFileURL();

        try (final JarInputStream jar = new JarInputStream(jurl.openStream());) {
            while (true) {
                final JarEntry entry = jar.getNextJarEntry();

                if (entry == null) {
                    break;
                }
                final String name = entry.getName();

                if (name.startsWith(resource)) {
                    final URL u = cl.getResource(name);

                    if (u != null) {
                        urls.add(u);
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("unable to find resources in package", e);
    }
}

From source file:musiccrawler.App.java

private JPanel loadingPanel() {
    JPanel panel = new JPanel();
    BoxLayout layoutMgr = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
    panel.setLayout(layoutMgr);/*from   w ww  . j  av  a2 s.  c  o  m*/
    ClassLoader cldr = this.getClass().getClassLoader();
    java.net.URL imageURL = cldr.getResource("image/ajax-loader.gif");
    ImageIcon imageIcon = new ImageIcon(imageURL);
    JLabel iconLabel = new JLabel();
    iconLabel.setIcon(imageIcon);
    imageIcon.setImageObserver(iconLabel);
    JLabel label = new JLabel("Loading...");
    panel.add(iconLabel);
    panel.add(label);
    return panel;
}

From source file:ar.com.jrules.core.service.LoadJRules.java

private File getPackageDirectory(String basePackage) {

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

    if (classLoader == null) {
        throw new JRuleConfigurationException("Can't get class loader.");
    }//ww  w  .  j a  va2 s  .  c o m

    URL resource = classLoader.getResource(basePackage.replace('.', '/'));
    if (resource == null) {
        throw new JRuleConfigurationException("Package " + basePackage + " not found on classpath.");
    }

    return new File(resource.getFile());
}

From source file:org.picketbox.http.test.authentication.jetty.DelegatingSecurityFilterHTTPBasicUnitTestCase.java

@Override
protected void establishUserApps() {
    ClassLoader tcl = Thread.currentThread().getContextClassLoader();
    if (tcl == null) {
        tcl = getClass().getClassLoader();
    }/*from  w ww .ja  v a 2s .co  m*/

    final String WEBAPPDIR = "auth/webapp";

    final String CONTEXTPATH = "/auth";

    // for localhost:port/admin/index.html and whatever else is in the webapp directory
    final URL warUrl = tcl.getResource(WEBAPPDIR);
    final String warUrlString = warUrl.toExternalForm();

    /*
     * Context context = new WebAppContext(warUrlString, CONTEXTPATH); server.setHandler(context);
     *
     * Thread.currentThread().setContextClassLoader(context.getClassLoader());
     */
    this.webapp = createWebApp(CONTEXTPATH, warUrlString);
    this.server.setHandler(webapp);

    System.setProperty(PicketBoxConstants.USERNAME, "Aladdin");
    System.setProperty(PicketBoxConstants.CREDENTIAL, "Open Sesame");

    FilterHolder filterHolder = new FilterHolder(DelegatingSecurityFilter.class);

    webapp.setInitParameter(PicketBoxConstants.AUTHENTICATION_KEY, PicketBoxConstants.BASIC);
    webapp.setInitParameter(PicketBoxConstants.HTTP_CONFIGURATION_PROVIDER,
            HTTPDigestConfigurationProvider.class.getName());

    ServletHandler servletHandler = new ServletHandler();

    servletHandler.addFilter(filterHolder, createFilterMapping("/", filterHolder));

    webapp.setServletHandler(servletHandler);
}

From source file:massbank.DatabaseManager.java

public static void init_db() throws SQLException, IOException {
    Connection connection = DriverManager
            .getConnection("jdbc:mariadb://" + dbHostName + "/" + "?user=" + user + "&password=" + password);
    Statement stmt = connection.createStatement();

    stmt.executeUpdate("DROP DATABASE IF EXISTS MassBank;");
    stmt.executeUpdate("CREATE DATABASE MassBank CHARACTER SET = 'latin1' COLLATE = 'latin1_general_cs';");
    stmt.executeUpdate("USE MassBank;");

    ClassLoader classLoader = DatabaseManager.class.getClassLoader();
    File file = new File(classLoader.getResource("create_massbank_scheme.sql").getFile());
    ScriptRunner runner = new ScriptRunner(connection, false, false);
    runner.runScript(new BufferedReader(new FileReader(file)));

    stmt.close();/*from www.j  a va 2 s.co m*/
    connection.close();
}