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:com.marc.lastweek.business.services.images.impl.ImageServiceImpl.java

private Properties getPropertiesFromFile(String fileName) {
    /* Read properties file */
    ClassLoader loader = LastweekApplication.class.getClassLoader();
    URL url = loader.getResource(fileName);
    InputStream in;/*w w  w .  j  a  va2 s  . c  o  m*/
    Properties properties = new Properties();
    try {
        in = url.openStream();
        properties.load(in);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return properties;
}

From source file:com.galeoconsulting.leonardinius.api.impl.ChainingClassLoader.java

@Override
public URL getResource(String name) {
    for (ClassLoader classloader : classLoaders) {
        final URL url = classloader.getResource(name);
        if (url != null) {
            return url;
        }/*from   w w w .  j av  a2s.  c om*/
    }
    return null;
}

From source file:io.apiman.manager.api.jpa.JpaStorageInitializer.java

/**
 * Called to initialize the database./*from  w  w  w.  j a v  a  2  s  . c  o  m*/
 */
@SuppressWarnings("nls")
public void initialize() {
    QueryRunner run = new QueryRunner(ds);
    Boolean isInitialized;

    try {
        isInitialized = run.query("SELECT * FROM apis", new ResultSetHandler<Boolean>() {
            @Override
            public Boolean handle(ResultSet rs) throws SQLException {
                return true;
            }
        });
    } catch (SQLException e) {
        isInitialized = false;
    }

    if (isInitialized) {
        System.out.println("============================================");
        System.out.println("Apiman Manager database already initialized.");
        System.out.println("============================================");
        return;
    }

    ClassLoader cl = JpaStorageInitializer.class.getClassLoader();
    URL resource = cl.getResource("ddls/apiman_" + dbType + ".ddl");
    try (InputStream is = resource.openStream()) {
        System.out.println("=======================================");
        System.out.println("Initializing apiman Manager database.");
        DdlParser ddlParser = new DdlParser();
        List<String> statements = ddlParser.parse(is);
        for (String sql : statements) {
            System.out.println(sql);
            run.update(sql);
        }
        System.out.println("=======================================");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:de.kaiserpfalzEdv.office.core.license.impl.LicenseServiceImpl.java

private void loadKeyringOrTestkeyring() throws IOException {
    ClassLoader loader = getClass().getClassLoader();

    LOG.debug("Loading key: {}", loader.getResource(KEY_RING));

    try {/*from w ww .jav a  2  s .  c om*/
        rawLicense.loadKeyRingFromResource(KEY_RING, DIGEST);
    } catch (IllegalArgumentException e) {
        LOG.warn("Loading test keyring instead of production ring!");
        rawLicense.loadKeyRingFromResource(KEY_RING, TEST_DIGEST);
    }
}

From source file:ResourceBundleSupport.java

/**
 * Returns the resource specified by the <strong>absolute</strong> name.
 *
 * @param name the name of the resource/*from   w  w  w .j  a  va2  s.com*/
 * @param c    the source class
 * @return the url of the resource or null, if not found.
 */
public static URL getResource(final String name, final Class c) {
    final ClassLoader cl = getClassLoader(c);
    if (cl == null) {
        return null;
    }
    return cl.getResource(name);
}

From source file:ffx.HeadlessMain.java

/**
 * Complete initializations./*from  w w  w.  j av a2  s.  c o  m*/
 *
 * @param commandLineFile a {@link java.io.File} object.
 * @param argList a {@link java.util.List} object.
 * @param logHandler a {@link ffx.ui.LogHandler} object.
 */
public HeadlessMain(File commandLineFile, List<String> argList, LogHandler logHandler) {
    // Start a timer.
    stopWatch.start();

    // Construct the MainPanel, set it's LogHandler, and initialize then it.
    mainPanel = new MainPanel();
    logHandler.setMainPanel(mainPanel);
    mainPanel.initialize();

    // Open the supplied script file.
    if (commandLineFile != null) {
        if (!commandLineFile.exists()) {
            /**
             * See if the commandLineFile is an embedded script.
             */
            String name = commandLineFile.getName();
            name = name.replace('.', '/');
            String pathName = "ffx/scripts/" + name;
            ClassLoader loader = getClass().getClassLoader();
            URL embeddedScript = loader.getResource(pathName + ".ffx");
            if (embeddedScript == null) {
                embeddedScript = loader.getResource(pathName + ".groovy");
            }
            if (embeddedScript != null) {
                try {
                    commandLineFile = new File(FFXClassLoader.copyInputStreamToTmpFile(
                            embeddedScript.openStream(), commandLineFile.getName(), ".ffx"));
                } catch (Exception e) {
                    logger.warning("Exception extracting embedded script " + embeddedScript.toString() + "\n"
                            + e.toString());
                }
            }
        }
        if (commandLineFile.exists()) {
            mainPanel.getModelingShell().setArgList(argList);
            mainPanel.open(commandLineFile, null);
        } else {
            logger.warning(format("%s was not found.", commandLineFile.toString()));
        }
    }

    /**
     * Print start-up information.
     */
    if (logger.isLoggable(Level.FINE)) {
        StringBuilder sb = new StringBuilder();
        sb.append(format("\n Start-up Time (msec): %s.", stopWatch.getTime()));
        Runtime runtime = Runtime.getRuntime();
        runtime.runFinalization();
        runtime.gc();
        long occupiedMemory = runtime.totalMemory() - runtime.freeMemory();
        long KB = 1024;
        sb.append(format("\n In-Use Memory   (Kb): %d", occupiedMemory / KB));
        sb.append(format("\n Free Memory     (Kb): %d", runtime.freeMemory() / KB));
        sb.append(format("\n Total Memory    (Kb): %d", runtime.totalMemory() / KB));
        logger.fine(sb.toString());
    }
}

From source file:io.github.thefishlive.updater.HttpServer.java

public void run() {
    try {/*from w  w w  . j  a va 2  s .com*/
        int port = GitUpdater.port;

        // Set up the HTTP protocol processor
        HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
                .add(new ResponseServer("GitUpdater/1.0-SNAPSHOT")).add(new ResponseContent())
                .add(new ResponseConnControl()).build();

        // Set up request handlers
        UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
        reqistry.register("*", new ResponceHandler());

        // Set up the HTTP service
        HttpService httpService = new HttpService(httpproc, reqistry);

        SSLServerSocketFactory sf = null;
        if (port == 8443) {
            // Initialize SSL context
            ClassLoader cl = getClass().getClassLoader();
            URL url = cl.getResource("my.keystore");
            if (url == null) {
                System.out.println("Keystore not found");
                System.exit(1);
            }
            KeyStore keystore = KeyStore.getInstance("jks");
            keystore.load(url.openStream(), "secret".toCharArray());
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keystore, "secret".toCharArray());
            KeyManager[] keymanagers = kmfactory.getKeyManagers();
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(keymanagers, null, null);
            sf = sslcontext.getServerSocketFactory();
        }

        try {
            Thread t = new RequestListenerThread(port, httpService, sf);
            t.setDaemon(false);
            t.start();
        } catch (BindException ex) {
            System.out.println("Error binding to port " + port);
            System.out.println("Perhaps another server is running on that port");
            return;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.adaptris.core.AbstractMarshaller.java

/**
 * <p>//from   ww  w  .jav a2 s .c  o m
 * Create an InputStream from a local file.
 * </p>
 *
 * @param localFile the local file.
 * @return an InputStream from the local file.
 * @throws IOException on error.
 */
private InputStream connectToFile(String localFile) throws IOException {
    InputStream in = null;
    File f = new File(localFile);
    if (f.exists()) {
        in = new FileInputStream(f);
    } else {
        ClassLoader c = this.getClass().getClassLoader();
        URL u = c.getResource(localFile);

        if (u != null) {
            in = u.openStream();
        }
    }
    return in;
}

From source file:org.ajax4jsf.cache.CacheManager.java

String findFactory(String factoryId, Map env) {

    String envFactoryClass = (String) env.get(CACHE_MANAGER_FACTORY_CLASS);
    if (!isEmptyString(envFactoryClass))
        return envFactoryClass;

    // Use the system property first
    try {//from  w ww .ja  v a2 s  . c  om
        String factoryClass = System.getProperty(factoryId);
        if (!isEmptyString(factoryClass))
            return factoryClass;
    } catch (SecurityException ignore) {
    }

    // try to read from $java.home/lib/jcache.properties
    try {
        String configFile = System.getProperty("java.home") + File.separator + "lib" + File.separator
                + "jcache.properties";
        File f = new File(configFile);
        if (f.exists()) {
            InputStream in = new FileInputStream(f);
            try {
                Properties props = new Properties();
                props.load(in);
                String factoryClass = props.getProperty(factoryId);
                if (!isEmptyString(factoryClass))
                    return factoryClass;
            } finally {
                in.close();
            }
        }
    } catch (SecurityException ignore) {
    } catch (IOException ignore) {
    }

    // try to find services in CLASSPATH
    try {
        ClassLoader cl = findClassLoader();
        InputStream is = URLToStreamHelper.urlToStreamSafe(cl.getResource("META-INF/services/" + factoryId));
        if (is != null) {
            BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            try {
                String factoryName = r.readLine();
                if (!isEmptyString(factoryName))
                    return factoryName;
            } finally {
                r.close();
            }
        }
    } catch (IOException ignore) {
    }

    return DEFAULT_FACTORY_NAME;
}

From source file:org.gallery.persist.ImageDaoTest.java

@Before
public void setUp() throws DatabaseUnitException, SQLException, IOException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL url = loader.getResource(jsonfilename);
    file = new File(url.getFile());

    ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:applicationContext-test.xml");
    Connection connection = DataSourceUtils.getConnection((DataSource) ctx.getBean("dataSource"));
    DatabaseConnection dbunitConnection = new DatabaseConnection(connection, null);
    IDataSet expectedDataSet = getDataSet("data-test/full-database.xml");
    DatabaseOperation.CLEAN_INSERT.execute(dbunitConnection, expectedDataSet);
    imageDao = ctx.getBean(ImageDao.class);
}