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.apache.catalina.loader.WebappClassLoader.java

/**
 * Find the resource with the given name.  A resource is some data
 * (images, audio, text, etc.) that can be accessed by class code in a
 * way that is independent of the location of the code.  The name of a
 * resource is a "/"-separated path name that identifies the resource.
 * If the resource cannot be found, return <code>null</code>.
 * <p>//from  w ww . j a  v a 2s  .c o  m
 * This method searches according to the following algorithm, returning
 * as soon as it finds the appropriate URL.  If the resource cannot be
 * found, returns <code>null</code>.
 * <ul>
 * <li>If the <code>delegate</code> property is set to <code>true</code>,
 *     call the <code>getResource()</code> method of the parent class
 *     loader, if any.</li>
 * <li>Call <code>findResource()</code> to find this resource in our
 *     locally defined repositories.</li>
 * <li>Call the <code>getResource()</code> method of the parent class
 *     loader, if any.</li>
 * </ul>
 *
 * @param name Name of the resource to return a URL for
 */
public URL getResource(String name) {

    if (log.isDebugEnabled())
        log.debug("getResource(" + name + ")");
    URL url = null;

    // (1) Delegate to parent if requested
    if (delegate) {
        if (log.isDebugEnabled())
            log.debug("  Delegating to parent classloader " + parent);
        ClassLoader loader = parent;
        if (loader == null)
            loader = system;
        url = loader.getResource(name);
        if (url != null) {
            if (log.isDebugEnabled())
                log.debug("  --> Returning '" + url.toString() + "'");
            return (url);
        }
    }

    // (2) Search local repositories
    url = findResource(name);
    if (url != null) {
        // Locating the repository for special handling in the case 
        // of a JAR
        ResourceEntry entry = (ResourceEntry) resourceEntries.get(name);
        try {
            String repository = entry.codeBase.toString();
            if ((repository.endsWith(".jar")) && (!(name.endsWith(".class")))) {
                // Copy binary content to the work directory if not present
                File resourceFile = new File(loaderDir, name);
                url = resourceFile.toURL();
            }
        } catch (Exception e) {
            // Ignore
        }
        if (log.isDebugEnabled())
            log.debug("  --> Returning '" + url.toString() + "'");
        return (url);
    }

    // (3) Delegate to parent unconditionally if not already attempted
    if (!delegate) {
        ClassLoader loader = parent;
        if (loader == null)
            loader = system;
        url = loader.getResource(name);
        if (url != null) {
            if (log.isDebugEnabled())
                log.debug("  --> Returning '" + url.toString() + "'");
            return (url);
        }
    }

    // (4) Resource was not found
    if (log.isDebugEnabled())
        log.debug("  --> Resource not found, returning null");
    return (null);

}

From source file:org.apache.click.util.ClickUtils.java

/**
 * Finds a resource with a given name. This method returns null if no
 * resource with this name is found./* w  w  w.  j  a va2s.c  o  m*/
 * <p>
 * This method uses the current <tt>Thread</tt> context <tt>ClassLoader</tt> to find
 * the resource. If the resource is not found the class loader of the given
 * class is then used to find the resource.
 *
 * @param name the name of the resource
 * @param aClass the class lookup the resource against, if the resource is
 *     not found using the current <tt>Thread</tt> context <tt>ClassLoader</tt>.
 * @return the URL of the resource if found or null otherwise
 */
public static URL getResource(String name, Class<?> aClass) {
    Validate.notNull(name, "Parameter name is null");
    Validate.notNull(aClass, "Parameter aClass is null");

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

    URL url = classLoader.getResource(name);
    if (url == null) {
        url = aClass.getResource(name);
    }

    return url;
}

From source file:javazoom.jlgui.player.amp.Player.java

/**
 * Constructor./*from   w  w  w.ja  v a2  s .  co m*/
 */
public Player(String Skin, Frame top) {
    super(top);
    topFrame = top;

    // Config feature.
    config = Config.getInstance();
    config.load(initConfig);
    OrigineX = config.getXLocation();
    OrigineY = config.getYLocation();

    // Get screen size
    try {
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension dimension = toolkit.getScreenSize();
        screenWidth = dimension.width;
        screenHeight = dimension.height;
    } catch (Exception e) {
    }

    // Minimize/Maximize/Icon features.
    topFrame.addWindowListener(this);
    topFrame.setLocation(OrigineX, OrigineY);
    topFrame.setSize(0, 0);
    // Polis : Comment out to fix a bug under XWindow
    //topFrame.setResizable(false);
    ClassLoader cl = this.getClass().getClassLoader();
    URL iconURL = cl.getResource("javazoom/jlgui/player/amp/jlguiicon.gif");
    if (iconURL != null) {
        ImageIcon jlguiIcon = new ImageIcon(iconURL);
        topFrame.setIconImage(jlguiIcon.getImage());
    }
    topFrame.show();

    // DnD feature.
    DropTarget dt = new DropTarget(this, DnDConstants.ACTION_COPY, this, true);

    // Playlist feature.
    boolean playlistfound = false;
    if ((initSong != null) && (!initSong.equals("")))
        playlistfound = loadPlaylist(initSong);
    else
        playlistfound = loadPlaylist(config.getPlaylistFilename());

    // Load skin specified in args
    if (Skin != null) {
        thePath = Skin;
        log.info("Load default skin from " + thePath);
        loadSkin(thePath);
        config.setDefaultSkin(thePath);
    }
    // Load skin specified in jlgui.ini
    else if ((config.getDefaultSkin() != null) && (!config.getDefaultSkin().trim().equals(""))) {
        log.info("Load default skin from " + config.getDefaultSkin());
        loadSkin(config.getDefaultSkin());
    }
    // Default included skin
    else {
        //ClassLoader cl = this.getClass().getClassLoader();
        InputStream sis = cl.getResourceAsStream("javazoom/jlgui/player/amp/metrix.wsz");
        log.info("Load default skin for JAR");
        loadSkin(sis);
    }

    // Go to playlist begining if needed.
    if ((playlist != null) && (playlistfound == true)) {
        if (playlist.getPlaylistSize() > 0)
            acNext.fireEvent();
    }

    // Display the whole
    hide();
    show();
    repaint();
}

From source file:de.innovationgate.utils.WGUtils.java

/**
 * Determines the location of the classfile that defines the given class.
 * This can be useful if a class is in classpath multiple times to determine
 * which version is really used.//from   w  w  w .j  a  v  a 2  s .co  m
 * 
 * @param className
 *            The class to find.
 * @param cl
 *            The classloader to use to load the class
 * @return The location of the classfile as path.
 */
public static String which(String className, ClassLoader cl) {

    /*if (!className.startsWith("/")) {
    className = "/" + className;
    }*/
    className = className.replace('.', '/');
    className = className + ".class";

    java.net.URL classUrl = cl.getResource(className);

    if (classUrl != null) {
        return classUrl.getFile();
    } else {
        return null;
    }
}

From source file:javazoom.jlgui.player.amp.PlayerApplet.java

/**
 * Init player applet.//  www . ja v  a 2s  .com
 */
public void initPlayer(String Skin) {
    // Config feature.
    config = Config.getInstance();
    config.load(initConfig);
    OrigineX = config.getXLocation();
    OrigineY = config.getYLocation();

    // Get screen size
    try {
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension dimension = toolkit.getScreenSize();
        screenWidth = dimension.width;
        screenHeight = dimension.height;
    } catch (Exception e) {
    }

    // Minimize/Maximize/Icon features.
    //topFrame.addWindowListener(this);
    topFrame.setLocation(OrigineX, OrigineY);
    topFrame.setSize(0, 0);
    // Polis : Comment out to fix a bug under XWindow
    //topFrame.setResizable(false);
    ClassLoader cl = this.getClass().getClassLoader();
    URL iconURL = cl.getResource("javazoom/jlgui/player/amp/jlguiicon.gif");
    if (iconURL != null) {
        ImageIcon jlguiIcon = new ImageIcon(iconURL);
        //topFrame.setIconImage(jlguiIcon.getImage());
    }
    topFrame.show();

    // DnD feature.
    DropTarget dt = new DropTarget(this, DnDConstants.ACTION_COPY, this, true);

    // Playlist feature.
    boolean playlistfound = false;
    if ((initSong != null) && (!initSong.equals("")))
        playlistfound = loadPlaylist(initSong);
    else
        playlistfound = loadPlaylist(config.getPlaylistFilename());

    // Load skin specified in args
    if (Skin != null) {
        thePath = Skin;
        log.info("Load default skin from " + thePath);
        loadSkin(thePath);
        config.setDefaultSkin(thePath);
    }
    // Load skin specified in jlgui.ini
    else if ((config.getDefaultSkin() != null) && (!config.getDefaultSkin().trim().equals(""))) {
        log.info("Load default skin from " + config.getDefaultSkin());
        loadSkin(config.getDefaultSkin());
    }
    // Default included skin
    else {
        //ClassLoader cl = this.getClass().getClassLoader();
        InputStream sis = cl.getResourceAsStream("javazoom/jlgui/player/amp/metrix.wsz");
        log.info("Load default skin for JAR");
        loadSkin(sis);
    }

    // Go to playlist begining if needed.
    if ((playlist != null) && (playlistfound == true)) {
        if (playlist.getPlaylistSize() > 0)
            acNext.fireEvent();
    }

    // Display the whole
    hide();
    show();
    repaint();
}

From source file:com.delphix.session.test.ServiceTest.java

@BeforeClass
public void init() throws FileNotFoundException, IOException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Properties testprops = new Properties();
    testprops.load(cl.getResourceAsStream("test.properties"));

    String password = testprops.getProperty("password");

    // Initialize key store
    this.keyStore = cl.getResource(testprops.getProperty("keystore")).getPath();
    this.keyPass = password;
    this.storePass = password;

    // Initialize throughput tests
    this.testServer = testprops.getProperty("server");
    this.testData = cl.getResource(testprops.getProperty("data")).getPath();
    this.testStats = Boolean.parseBoolean(testprops.getProperty("stats"));
    this.multiSessions = Boolean.parseBoolean(testprops.getProperty("multisess"));
    this.serverMode = Boolean.parseBoolean(testprops.getProperty("mode"));
    this.testStreams = Integer.parseInt(testprops.getProperty("streams"));

    // Comma separated port list
    String portList = testprops.getProperty("ports");

    if (portList != null) {
        String[] ports = portList.split(",");

        testPorts = new int[ports.length];
        assertEquals(ports.length, testStreams);

        for (int i = 0; i < ports.length; i++) {
            testPorts[i] = Integer.parseInt(ports[i]);
        }//from  w  ww .j av a2  s .  co  m
    }

    // Initialize trust store
    this.trustStore = cl.getResource(testprops.getProperty("truststore")).getPath();
    this.trustPass = password;

    // Initialize service types
    helloService = new ServiceType(HELLO_UUID, HELLO_NAME, HELLO_DESC);
    delayService = new ServiceType(DELAY_UUID, DELAY_NAME, DELAY_DESC);

    try {
        localhost = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        fail("failed to get local host", e);
    }

    clientManager.start();
    serverManager.start();

    executor = Executors.newCachedThreadPool();
}

From source file:ffx.ui.MainPanel.java

/**
 * {@inheritDoc}//w  ww .  j a v  a  2s . c o m
 *
 * Handle most File, Selection, Trajectory, Simulation, Window and Help Menu
 * Commands This should probably be partitioned between a few different
 * handlers
 */
@Override
public void actionPerformed(ActionEvent evt) {
    String arg = evt.getActionCommand();
    if (logger.isLoggable(Level.FINEST)) {
        logger.finest(" Action: " + arg);
    }
    // File Commands
    if (arg.equals("Open")) {
        open();
    } else if (arg.equals("DownloadFromPDB")) {
        openFromPDB();
    } else if (arg.equals("SaveAs")) {
        saveAsXYZ(null);
    } else if (arg.equals("Close")) {
        close();
    } else if (arg.equals("CloseAll")) {
        closeAll();
    } else if (arg.equals("ChooseKeyFile")) {
        chooseKey();
    } else if (arg.equals("ChooseLogFile")) {
        chooseLog();
    } else if (arg.equals("LoadInducedData")) {
        openInduced();
        // Selection Commands
    } else if (arg.equals("SelectAll")) {
        selectAll();
    } else if (arg.equals("MergeSelections")) {
        merge();
    } else if (arg.equals("HighlightSelections")) {
        highlightSelections(evt);
        // Trajectory
    } else if (arg.equals("Play")) {
        play();
    } else if (arg.equals("Stop")) {
        stop();
    } else if (arg.equals("StepForward")) {
        stepForward();
    } else if (arg.equals("StepBack")) {
        stepBack();
    } else if (arg.equals("Reset")) {
        reset();
    } else if (arg.equals("Oscillate")) {
        oscillate(evt);
    } else if (arg.equals("Frame")) {
        frame();
    } else if (arg.equals("Speed")) {
        speed();
    } else if (arg.equals("Skip")) {
        skip();
        // Simulation
    } else if (arg.equals("ConnectToLocalJob")) {
        connectToTINKER(null, null);
    } else if (arg.equals("ConnectToRemoteJob")) {
        connect();
    } else if (arg.equals("ReleaseJob")) {
        release();
    } else if (arg.equals("SetPort")) {
        setPort();
    } else if (arg.equals("SetRemoteJobAddress")) {
        setRemoteJobAddress();
        // Window
    } else if (arg.equals("ShowToolBar")) {
        showToolBar(evt);
    } else if (arg.equals("ShowTree")) {
        showTree(evt);
    } else if (arg.equals("ShowGlobalAxes")) {
        showGlobalAxes(evt);
    } else if (arg.equals("ResetPanes")) {
        resetPanes();
    } else if (arg.equals("ResetConsole")) {
        resetShell();
    } else if (arg.equals("OceanLookAndFeel")) {
        oceanLookAndFeel();
    } else if (arg.equals("WindowsLookAndFeel") || arg.equals("MacOSXLookAndFeel")
            || arg.equals("MotifLookAndFeel")) {
        platformLookAndFeel();
    } else if (arg.equals("ShrinkGraphicsWindow")) {
        resizePanes(20);
    } else if (arg.equals("ExpandGraphicsWindow")) {
        resizePanes(-20);
        // Help
    } else if (arg.equals("HelpContents")) {
        help();
    } else if (arg.equals("About")) {
        about();
        // Others
    } else if (arg.equals("GarbageCollect")) {
        Runtime.getRuntime().runFinalization();
        Runtime.getRuntime().gc();
    } else if (arg.equals("Exit")) {
        exit();
    } else {
        try {
            ClassLoader cl = MainPanel.class.getClassLoader();
            URL url = cl.getResource(arg);
            logger.info(url.toString());
            File structureFile = new File(url.getFile());
            logger.info(structureFile.toString());
            String tempFile = StringUtils.copyInputStreamToTmpFile(url.openStream(), structureFile.getName(),
                    "pdb");
            open(tempFile);
        } catch (Exception e) {
            System.err.println("MainPanel - Menu command not found: " + arg);
        }

    }
}

From source file:org.apache.axis2.jaxws.description.impl.ServiceDescriptionImpl.java

/**
 * create a catalog manager only if a catalog file is found for this classloader.
 * Also parses the catalog to get it ready for resolution.
 * @param cl - Classloader of the composite passes to this ServiceDescription
 * @return a catalogManager with parsed catalog, or null if no catalog found
 *//*from   w w  w .ja  va2s.  co  m*/
private JAXWSCatalogManager createCatalogManager(ClassLoader cl) {
    JAXWSCatalogManager returnCatalogManager = null;

    try {
        URL catalogURL = cl.getResource(OASISCatalogManager.DEFAULT_CATALOG_WEB);
        if (catalogURL == null) {
            catalogURL = cl.getResource(OASISCatalogManager.DEFAULT_CATALOG_EJB);
            if (catalogURL != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Found JAX-WS catalog in EJB file");
                }
                returnCatalogManager = new OASISCatalogManager(cl);
                returnCatalogManager.getCatalog().parseCatalog(catalogURL);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Found JAX-WS catalog in WAR file");
            }
            returnCatalogManager = new OASISCatalogManager(cl);
            returnCatalogManager.getCatalog().parseCatalog(catalogURL);
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("ServiceDescriptionImpl caught exception from parseCatalog ", e);
        }
        returnCatalogManager = null;
    }
    return (returnCatalogManager);
}

From source file:org.apache.axis2.jaxws.description.impl.ServiceDescriptionImpl.java

private URL getResource(final String wsdlLocation, final ClassLoader loader) {
    return (URL) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return loader.getResource(wsdlLocation);
        }//  ww  w  . ja  va  2  s.c  o  m
    });
}

From source file:ffx.ui.MainPanel.java

/**
 * <p>/*from ww w.j  a v a2  s  .  c  o  m*/
 * initialize</p>
 */
public void initialize() {
    if (init) {
        return;
    }
    init = true;
    String dir = System.getProperty("user.dir",
            FileSystemView.getFileSystemView().getDefaultDirectory().getAbsolutePath());
    setCWD(new File(dir));
    locale = new FFXLocale("en", "US");
    JDialog splashScreen = null;
    ClassLoader loader = getClass().getClassLoader();
    if (!GraphicsEnvironment.isHeadless()) {
        // Splash Screen
        JFrame.setDefaultLookAndFeelDecorated(true);
        splashScreen = new JDialog(frame, false);
        ImageIcon logo = new ImageIcon(loader.getResource("ffx/ui/icons/splash.png"));
        JLabel ffxLabel = new JLabel(logo);
        ffxLabel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
        Container contentpane = splashScreen.getContentPane();
        contentpane.setLayout(new BorderLayout());
        contentpane.add(ffxLabel, BorderLayout.CENTER);
        splashScreen.setUndecorated(true);
        splashScreen.pack();
        Dimension screenDimension = getToolkit().getScreenSize();
        Dimension splashDimension = splashScreen.getSize();
        splashScreen.setLocation((screenDimension.width - splashDimension.width) / 2,
                (screenDimension.height - splashDimension.height) / 2);
        splashScreen.setResizable(false);
        splashScreen.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        splashScreen.setVisible(true);
        // Make all pop-up Menus Heavyweight so they play nicely with Java3D
        JPopupMenu.setDefaultLightWeightPopupEnabled(false);
    }
    // Create the Root Node
    dataRoot = new MSRoot();
    Border bb = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
    statusLabel = new JLabel("  ");
    JLabel stepLabel = new JLabel("  ");
    stepLabel.setHorizontalAlignment(JLabel.RIGHT);
    JLabel energyLabel = new JLabel("  ");
    energyLabel.setHorizontalAlignment(JLabel.RIGHT);
    JPanel statusPanel = new JPanel(new GridLayout(1, 3));
    statusPanel.setBorder(bb);
    statusPanel.add(statusLabel);
    statusPanel.add(stepLabel);
    statusPanel.add(energyLabel);
    if (!GraphicsEnvironment.isHeadless()) {
        GraphicsConfigTemplate3D template3D = new GraphicsConfigTemplate3D();
        template3D.setDoubleBuffer(GraphicsConfigTemplate.PREFERRED);
        GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getBestConfiguration(template3D);
        graphicsCanvas = new GraphicsCanvas(gc, this);
        graphicsPanel = new GraphicsPanel(graphicsCanvas, statusPanel);
    }
    // Initialize various Panels
    hierarchy = new Hierarchy(this);
    hierarchy.setStatus(statusLabel, stepLabel, energyLabel);
    keywordPanel = new KeywordPanel(this);
    modelingPanel = new ModelingPanel(this);
    JPanel treePane = new JPanel(new BorderLayout());
    JScrollPane scrollPane = new JScrollPane(hierarchy, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    treePane.add(scrollPane, BorderLayout.CENTER);
    tabbedPane = new JTabbedPane();

    ImageIcon graphicsIcon = new ImageIcon(loader.getResource("ffx/ui/icons/monitor.png"));
    ImageIcon keywordIcon = new ImageIcon(loader.getResource("ffx/ui/icons/key.png"));
    ImageIcon modelingIcon = new ImageIcon(loader.getResource("ffx/ui/icons/cog.png"));
    tabbedPane.addTab(locale.getValue("Graphics"), graphicsIcon, graphicsPanel);
    tabbedPane.addTab(locale.getValue("KeywordEditor"), keywordIcon, keywordPanel);
    tabbedPane.addTab(locale.getValue("ModelingCommands"), modelingIcon, modelingPanel);
    tabbedPane.addChangeListener(this);
    splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false, treePane, tabbedPane);

    /* splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false,
     treePane, graphicsPanel); */
    splitPane.setResizeWeight(0.25);
    splitPane.setOneTouchExpandable(true);
    setLayout(new BorderLayout());
    add(splitPane, BorderLayout.CENTER);
    if (!GraphicsEnvironment.isHeadless()) {
        mainMenu = new MainMenu(this);
        add(mainMenu.getToolBar(), BorderLayout.NORTH);
        getModelingShell();
        loadPrefs();
        SwingUtilities.updateComponentTreeUI(SwingUtilities.getRoot(this));
        splashScreen.dispose();
    }
}