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:fxts.stations.util.UserPreferences.java

/**
 * Loads default properties from properties file.
 *//*  w ww  .  ja  va2s.  c o m*/
private void loadDefaultProrerties() throws Exception {
    ClassLoader loader = UserPreferences.class.getClassLoader();
    URL url = loader.getResource("fxts/stations/util/UserPreferences.properties");
    if (url == null) {
        throw new Exception("Not found UserPreferences.properties");
    }
    try {
        InputStream istream = url.openStream();
        //loads from input stream
        mDefaultProperties.load(istream);
        istream.close();
    } catch (IOException e) {
        throw new Exception("Not loaded properties from UserPreferences.properties!");
    }
}

From source file:ffx.Main.java

/**
 * Main does some window initializations.
 *
 * @param commandLineFile a {@link java.io.File} object.
 * @param argList a {@link java.util.List} object.
 *///  w  w  w  . jav a2  s  . c  o  m
public Main(File commandLineFile, List<String> argList) {
    super("Force Field X");
    // Start the clock.
    stopWatch.start();
    setVisible(false);

    // Create the MainPanel and MainMenu, then add them to the JFrame
    java.awt.Toolkit.getDefaultToolkit().setDynamicLayout(true);
    mainPanel = new MainPanel(this);
    logHandler.setMainPanel(mainPanel);
    add(mainPanel);
    mainPanel.initialize();
    setJMenuBar(mainPanel.getMainMenu());
    // Set the Title and Icon
    setTitle("Force Field X");
    URL iconURL = getClass().getClassLoader().getResource("ffx/ui/icons/icon64.png");
    ImageIcon icon = new ImageIcon(iconURL);
    setIconImage(icon.getImage());
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            if (mainPanel != null) {
                mainPanel.exit();
            }
            System.exit(0);
        }
    });
    // This is a hack to get GraphicsCanvis to initialize on some
    // platform/Java3D combinations.
    mainPanel.setPanel(MainPanel.KEYWORDS);
    setVisible(true);
    mainPanel.setPanel(MainPanel.GRAPHICS);
    // Mac OS X specific features that help Force Field X look native
    // on Macs. This needs to be done after the MainPanel is created.
    if (SystemUtils.IS_OS_MAC_OSX) {
        osxAdapter = new OSXAdapter(mainPanel);
    }

    // Finally, open the supplied file if necessary.
    if (commandLineFile != null && !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.info(String.format(" The embedded script %s could not be extracted.", embeddedScript));
            }
        }
    }

    if (commandLineFile != null) {
        if (commandLineFile.exists()) {
            mainPanel.getModelingShell().setArgList(argList);
            mainPanel.open(commandLineFile, null);
        } else {
            logger.warning(format("%s was not found.", commandLineFile.toString()));
        }
    }

    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:rbcp.XMLResourceBundleControl.java

@Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader,
        boolean reload) throws IllegalAccessException, InstantiationException, IOException {
    if (baseName == null || locale == null || format == null || loader == null) {
        throw new NullPointerException();
    }/*from w w  w  .  j  a v  a  2 s.  com*/
    ResourceBundle bundle = null;
    if (format.equals("xml")) {
        String bundleName = toBundleName(baseName, locale);
        String resourceName = toResourceName(bundleName, format);
        URL url = loader.getResource(resourceName);
        if (url != null) {
            URLConnection connection = url.openConnection();
            if (connection != null) {
                if (reload) {
                    // disable caches if reloading
                    connection.setUseCaches(false);
                }
                try (InputStream stream = connection.getInputStream()) {
                    if (stream != null) {
                        BufferedInputStream bis = new BufferedInputStream(stream);
                        bundle = new XMLResourceBundle(bis);
                    }
                }
            }
        }
    }
    return bundle;
}

From source file:com.liferay.portal.jsonwebservice.JSONWebServiceConfigurator.java

public void configure(ClassLoader classLoader) throws PortalException, SystemException {

    File[] classPathFiles = null;

    if (classLoader != null) {
        URL servicePropertiesURL = classLoader.getResource("service.properties");

        String servicePropertiesPath = null;

        try {/*from  ww w  . jav a  2  s  .c o m*/
            servicePropertiesPath = URLDecoder.decode(servicePropertiesURL.getPath(), StringPool.UTF8);
        } catch (UnsupportedEncodingException uee) {
            throw new SystemException(uee);
        }

        File classPathFile = null;

        File libDir = null;

        int pos = servicePropertiesPath.indexOf("_wl_cls_gen.jar!");

        if (pos != -1) {
            String wlClsGenJarPath = servicePropertiesPath.substring(0, pos + 15);

            classPathFile = new File(wlClsGenJarPath);

            libDir = new File(classPathFile.getParent());
        } else {
            File servicePropertiesFile = new File(servicePropertiesPath);

            classPathFile = servicePropertiesFile.getParentFile();

            libDir = new File(classPathFile.getParent(), "lib");
        }

        classPathFiles = new File[2];

        classPathFiles[0] = classPathFile;

        FindFile findFile = new WildcardFindFile("*-portlet-service*.jar");

        findFile.searchPath(libDir);

        classPathFiles[1] = findFile.nextFile();

        if (classPathFiles[1] == null) {
            File classesDir = new File(libDir.getParent(), "classes");

            classPathFiles[1] = classesDir;
        }
    } else {
        Thread currentThread = Thread.currentThread();

        classLoader = currentThread.getContextClassLoader();

        File portalImplJarFile = new File(PortalUtil.getPortalLibDir(), "portal-impl.jar");
        File portalServiceJarFile = new File(PortalUtil.getGlobalLibDir(), "portal-service.jar");

        if (portalImplJarFile.exists() && portalServiceJarFile.exists()) {
            classPathFiles = new File[2];

            classPathFiles[0] = portalImplJarFile;
            classPathFiles[1] = portalServiceJarFile;
        } else {
            classPathFiles = ClassLoaderUtil.getDefaultClasspath(classLoader);
        }
    }

    _classLoader = classLoader;

    _configure(classPathFiles);
}

From source file:io.siddhi.extension.io.file.FileSourceTextFullModeTestCase.java

@BeforeClass
public void init() {
    ClassLoader classLoader = FileSourceTextFullModeTestCase.class.getClassLoader();
    String rootPath = classLoader.getResource("files").getFile();
    sourceRoot = new File(rootPath + "/repo");
    dirUri = rootPath + "/new";
    newRoot = new File(dirUri);
    moveAfterProcessDir = rootPath + "/moved_files";
}

From source file:com.revinate.ws.spring.SpringService.java

/**
 * Converts {@link String} into {@link SDDocumentSource}.
 * <p/>// www  .jav a2  s .c  om
 * If <code>resourceLocation</code> is a <code>String</code>,
 * {@link ServletContext} (if available) and {@link ClassLoader}
 * are searched for this path, then failing that, it's treated as an
 * absolute {@link URL}.
 *
 * @throws ServerRtException if <code>resourceLocation</code> cannot be
 * resolved through {@link ServletContext} (if available), {@link ClassLoader},
 * or as an absolute {@link java.net.URL}.
 */
private SDDocumentSource convertStringToSource(String resourceLocation) {
    URL url = null;

    if (servletContext != null) {
        // in the servlet environment, consult ServletContext so that we can load
        // WEB-INF/wsdl/... and so on.
        try {
            url = servletContext.getResource(resourceLocation);
        } catch (MalformedURLException e) {
            // ignore it and try the next method
        }
    }

    if (url == null) {
        // also check a resource in classloader.
        ClassLoader cl = implType.getClassLoader();
        url = cl.getResource(resourceLocation);
    }

    if (url == null) {
        try {
            url = new URL(resourceLocation);
        } catch (MalformedURLException e) {
            // ignore it throw exception later
        }
    }

    if (url == null) {
        throw new ServerRtException("cannot.load.wsdl", resourceLocation);
    }

    return SDDocumentSource.create(url);
}

From source file:org.apache.brooklyn.util.core.ClassLoaderUtilsTest.java

private void assertLoadSucceeds(ClassLoaderUtils clu, String bundledClassName, Class<?> expectedClass)
        throws ClassNotFoundException {
    BundledName className = new BundledName(bundledClassName);

    Class<?> cls = clu.loadClass(bundledClassName);
    assertEquals(cls.getName(), className.name);
    if (expectedClass != null) {
        assertEquals(cls, expectedClass);
    }/*from w  w w. j a  v  a 2  s .c o  m*/

    ClassLoader cl = cls.getClassLoader();
    BundledName resource = className.toResource();
    String bundledResource = resource.toString();
    URL resourceUrl = cl.getResource(resource.name);
    assertEquals(clu.getResource(bundledResource), resourceUrl);
    assertEquals(clu.getResources(bundledResource), ImmutableList.of(resourceUrl), "Loading with " + clu);

    BundledName rootResource = new BundledName(resource.bundle, resource.version, "/" + resource.name);
    String rootBundledResource = rootResource.toString();
    assertEquals(clu.getResource(rootBundledResource), resourceUrl);
    assertEquals(clu.getResources(rootBundledResource), ImmutableList.of(resourceUrl));
}

From source file:XMLResourceBundleControl.java

public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader,
            boolean reload) throws IllegalAccessException, InstantiationException, IOException {

        if ((baseName == null) || (locale == null) || (format == null) || (loader == null)) {
            throw new NullPointerException();
        }/*from   w  ww . j a va 2 s. c om*/
        ResourceBundle bundle = null;
        if (!format.equals(XML)) {
            return null;
        }

        String bundleName = toBundleName(baseName, locale);
        String resourceName = toResourceName(bundleName, format);
        URL url = loader.getResource(resourceName);
        if (url == null) {
            return null;
        }
        URLConnection connection = url.openConnection();
        if (connection == null) {
            return null;
        }
        if (reload) {
            connection.setUseCaches(false);
        }
        InputStream stream = connection.getInputStream();
        if (stream == null) {
            return null;
        }
        BufferedInputStream bis = new BufferedInputStream(stream);
        bundle = new XMLResourceBundle(bis);
        bis.close();

        return bundle;
    }

From source file:eu.betaas.taas.contextmanager.onto.classesExt.wordnet.WordNetUtils.java

public boolean init() {
    String[] includedWordnetFiles = null;
    boolean bCorrect = true;
    try {/*from  ww w  . j  a va2  s  .c o  m*/
        mLogger.debug(
                "Component CM perform operation WordNetUtils.checkWordnet. This is a wrapper for the MIT WordNet inteface that simplifies basic operations such as retrieving synonyms for a word.");
        File fileDestiny = null;
        String pathWordnetFileName = null;

        if (isLinux()) {
            WORDNET = WORDNET_LINUX;
        } else if (isWindows()) {
            WORDNET = WORDNET_WIN;
        } else
            mLogger.error("ERROR, unknown SO");

        PREFIX_WORDNET = "/META-INF/" + WORDNET + "/";
        File pathWordnetDirectory = new File(tmpdir1, WORDNET);

        if (!pathWordnetDirectory.exists() && !pathWordnetDirectory.mkdir())
            throw new IOException("Failed to create temporary directory " + pathWordnetDirectory);

        if (isLinux()) {
            includedWordnetFiles = new String[] { PREFIX_WORDNET + "adj.exc", PREFIX_WORDNET + "adv.exc",
                    PREFIX_WORDNET + "cntlist", PREFIX_WORDNET + "cntlist.rev", PREFIX_WORDNET + "data.adj",
                    PREFIX_WORDNET + "data.adv", PREFIX_WORDNET + "data.noun", PREFIX_WORDNET + "data.verb",
                    PREFIX_WORDNET + "frames.vrb", PREFIX_WORDNET + "index.verb", PREFIX_WORDNET + "index.adj",
                    PREFIX_WORDNET + "index.adv", PREFIX_WORDNET + "index.noun", PREFIX_WORDNET + "index.sense",
                    PREFIX_WORDNET + "lexnames", PREFIX_WORDNET + "log.grind.3.0", PREFIX_WORDNET + "Makefile",
                    PREFIX_WORDNET + "Makefile.am", PREFIX_WORDNET + "Makefile.in", PREFIX_WORDNET + "noun.exc",
                    PREFIX_WORDNET + "sentidx.vrb", PREFIX_WORDNET + "sents.vrb", PREFIX_WORDNET + "verb.exc",
                    PREFIX_WORDNET + "verb.Framestext" };
        } else if (isWindows()) {
            includedWordnetFiles = new String[] { PREFIX_WORDNET + "adj.exc", PREFIX_WORDNET + "adv.exc",
                    PREFIX_WORDNET + "cntlist", PREFIX_WORDNET + "cntlist.rev", PREFIX_WORDNET + "data.adj",
                    PREFIX_WORDNET + "data.adv", PREFIX_WORDNET + "data.noun", PREFIX_WORDNET + "data.verb",
                    PREFIX_WORDNET + "frames.vrb", PREFIX_WORDNET + "index.verb", PREFIX_WORDNET + "index.adj",
                    PREFIX_WORDNET + "index.adv", PREFIX_WORDNET + "index.noun", PREFIX_WORDNET + "index.sense",
                    PREFIX_WORDNET + "log.grind.2.1", PREFIX_WORDNET + "noun.exc",
                    PREFIX_WORDNET + "sentidx.vrb", PREFIX_WORDNET + "sents.vrb", PREFIX_WORDNET + "verb.exc",
                    PREFIX_WORDNET + "verb.Framestext" };
        } else
            mLogger.error("Your OS is not support!!");

        ClassLoader wordnetClassLoader = WordNetUtils.class.getClassLoader();
        for (String includedWordnetFile : includedWordnetFiles) {
            URL urlSource = wordnetClassLoader.getResource(includedWordnetFile);
            InputStream isSource = this.getClass().getResourceAsStream(includedWordnetFile);

            if (urlSource != null) {
                try {
                    String pathWordnetFile = urlSource.toString();
                    pathWordnetFileName = pathWordnetFile.substring(pathWordnetFile.lastIndexOf("/") + 1);
                    fileDestiny = new File(tmpdir1, "/" + WORDNET + "/" + pathWordnetFileName);
                    fileDestiny.deleteOnExit();
                    FileUtils.copyInputStreamToFile(isSource, fileDestiny);
                    isSource.close();
                } catch (Exception e) {
                    bCorrect = false;
                    mLogger.error(
                            "Component CM perform operation WordNetUtils.checkWordnet. It has not been executed correctly. Problems with copy InputStream to File. Exception: "
                                    + e.getMessage() + ".");
                } finally {
                    isSource.close();
                    IOUtils.closeQuietly(isSource);
                    isSource = null;
                    System.gc();
                }
            }
        }

    } catch (Exception e) {
        mLogger.error(
                "Component CM perform operation WordNetUtils.checkWordnet. It has not been executed correctly. Exception: "
                        + e.getMessage() + ".");
    }

    return bCorrect;
}

From source file:de.netsat.orekit.util.ZipJarCrawler.java

/** Build a zip crawler for an archive file in classpath.
 * @param classLoader class loader to use to retrieve the resources
 * @param resource name of the zip file to browse
 * @exception OrekitException if resource name is malformed
 *///w  w w .  j ava2s. c om
public ZipJarCrawler(final ClassLoader classLoader, final String resource) throws OrekitException {
    try {
        this.file = null;
        this.resource = resource;
        this.classLoader = classLoader;
        this.url = null;
        this.name = classLoader.getResource(resource).toURI().toString();
    } catch (URISyntaxException use) {
        throw new OrekitException(use, LocalizedFormats.SIMPLE_MESSAGE, use.getMessage());
    }
}