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.google.gwt.dev.shell.tomcat.EmbeddedTomcatServer.java

/**
 * Hacky, but fast./*  w w w.  ja v a  2  s  . co  m*/
 */
private Map<String, Resource> getResourcesFor(TreeLogger logger, String tomcatEtcDir)
        throws URISyntaxException, IOException {
    ClassLoader contextClassLoader = this.getClass().getClassLoader();
    URL url = contextClassLoader.getResource(tomcatEtcDir);
    if (url == null) {
        return null;
    }
    String prefix = "";
    String urlString = url.toString();
    if (urlString.startsWith("jar:")) {
        assert urlString.toLowerCase(Locale.ENGLISH).contains(".jar!/" + tomcatEtcDir);
        urlString = urlString.substring(4, urlString.indexOf('!'));
        url = new URL(urlString);
        prefix = tomcatEtcDir;
    } else if (urlString.startsWith("zip:")) {
        assert urlString.toLowerCase(Locale.ENGLISH).contains(".zip!/" + tomcatEtcDir);
        urlString = urlString.substring(4, urlString.indexOf('!'));
        url = new URL(urlString);
        prefix = tomcatEtcDir;
    }
    ClassPathEntry entry = ResourceOracleImpl.createEntryForUrl(logger, url);
    assert (entry != null);
    ResourceOracleImpl resourceOracle = new ResourceOracleImpl(Collections.singletonList(entry));
    PathPrefixSet pathPrefixSet = new PathPrefixSet();
    PathPrefix pathPrefix = new PathPrefix(prefix, null, true);
    pathPrefixSet.add(pathPrefix);
    resourceOracle.setPathPrefixes(pathPrefixSet);
    ResourceOracleImpl.refresh(logger, resourceOracle);
    Map<String, Resource> resourceMap = resourceOracle.getResourceMap();
    return resourceMap;
}

From source file:ar.com.allium.rules.core.service.LoadAlliumRules.java

private File getPackageDirectory(String basePackage) {

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

    if (classLoader == null) {
        throw new AlliumRuleConfigurationException("Can't get class loader.");
    }/*from   w  ww .ja  v  a  2 s .c  om*/

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

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

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

/**
 * Load player front-end./*from w  w w .  j a v a  2  s  . co m*/
 */
public void loadUI() {
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
        log.debug(ex);
    }
    config = Config.getInstance();
    config.load(initConfig);
    config.setTopParent(this);
    if (showPlaylist != null) {
        if (showPlaylist.equalsIgnoreCase("true")) {
            config.setPlaylistEnabled(true);
        } else {
            config.setPlaylistEnabled(false);
        }
    }
    if (showEqualizer != null) {
        if (showEqualizer.equalsIgnoreCase("true")) {
            config.setEqualizerEnabled(true);
        } else {
            config.setEqualizerEnabled(false);
        }
    }
    if (config.isPlaylistEnabled())
        eqFactor = 2;
    else
        eqFactor = 1;
    setTitle(Skin.TITLETEXT);
    ClassLoader cl = this.getClass().getClassLoader();
    URL iconURL = cl.getResource("javazoom/jlgui/player/amp/jlguiicon.gif");
    if (iconURL != null) {
        ImageIcon jlguiIcon = new ImageIcon(iconURL);
        setIconImage(jlguiIcon.getImage());
        config.setIconParent(jlguiIcon);
    }
    setUndecorated(true);
    mp = new PlayerUI();
    if ((showDsp != null) && (showDsp.equalsIgnoreCase("false"))) {
        mp.getSkin().setDspEnabled(false);
    }
    if (skinPath != null) {
        mp.getSkin().setPath(skinPath);
    }
    mp.getSkin().setSkinVersion(skinVersion);
    mp.loadUI(this);
    setContentPane(mp);
    setSize(new Dimension(mp.getSkin().getMainWidth(), mp.getSkin().getMainHeight()));
    eqWin = new JWindow(this);
    eqWin.setContentPane(mp.getEqualizerUI());
    eqWin.setSize(new Dimension(mp.getSkin().getMainWidth(), mp.getSkin().getMainHeight()));
    eqWin.setVisible(false);
    plWin = new JWindow(this);
    plWin.setContentPane(mp.getPlaylistUI());
    plWin.setSize(new Dimension(mp.getSkin().getMainWidth(), mp.getSkin().getMainHeight()));
    plWin.setVisible(false);
    // Window listener
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            // Closing window (Alt+F4 under Win32)
            close();
        }
    });
    // Keyboard shortcut
    setKeyBoardShortcut();
    // Display front-end
    setLocation(config.getXLocation(), config.getYLocation());
    setVisible(true);
    if (config.isPlaylistEnabled())
        plWin.setVisible(true);
    if (config.isEqualizerEnabled())
        eqWin.setVisible(true);
}

From source file:XMLResourceBundleControl.java

  public ResourceBundle newBundle(String baseName, Locale locale, String format,
    ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException,
    IOException {// www.j a  v a 2s.  com

  if ((baseName == null) || (locale == null) || (format == null) || (loader == null)) {
    throw new NullPointerException();
  }
  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:org.suren.autotest.web.framework.code.DefaultXmlDataSourceGenerator.java

/**
 * xml//from w w  w.j a  v a 2  s .c  om
 * @param doc 
 * @param format ?
 * @param resPath 
 */
private void write(final Document doc, final OutputFormat format, final String resPath) {
    ClassLoader clsLoader = this.getClass().getClassLoader();
    URL url = clsLoader.getResource(resPath);

    String outputFileName = null;
    if (url != null) {
        outputFileName = new File(url.getFile()).getName();
    } else {
        outputFileName = new File(resPath).getName();
    }

    File outputDirFile = new File(outputDir);
    if (!outputDirFile.isDirectory()) {
        outputDirFile.mkdirs();
    }

    File outputFile = new File(outputDirFile, outputFileName);
    try (OutputStream dsOutput = new FileOutputStream(outputFile)) {
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        outputFormat.setIndentSize(4);
        XMLWriter xmlWriter = new XMLWriter(dsOutput, outputFormat);

        xmlWriter.write(doc);

        if (callback != null) {
            callback.callback(outputFile);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

@Override
protected void establishUserApps() {
    ClassLoader tcl = Thread.currentThread().getContextClassLoader();
    if (tcl == null) {
        tcl = getClass().getClassLoader();
    }// ww w .  ja v  a  2  s .c o 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());

    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,
            HTTPDigestAuthenticationSchemeLoader.class.getName());
    context.addFilter(filterHolder, "/", 1);
}

From source file:com.google.gwt.dev.shell.CompilingClassLoader.java

/**
 * Magic: {@link JavaScriptHost} was never compiled because it's a part of the
 * hosted mode infrastructure. However, unlike {@link #BRIDGE_CLASSES},
 * {@code JavaScriptHost} needs a separate copy per inside the ClassLoader for
 * each module./*from   w w w .  j a  v  a 2  s . c om*/
 */
private static void ensureJavaScriptHostBytes(TreeLogger logger) throws UnableToCompleteException {

    if (javaScriptHostBytes != null) {
        return;
    }

    String className = JavaScriptHost.class.getName();
    try {
        String path = className.replace('.', '/') + ".class";
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        URL url = cl.getResource(path);
        if (url != null) {
            javaScriptHostBytes = getClassBytesFromStream(url.openStream());
        } else {
            logger.log(TreeLogger.ERROR,
                    "Could not find required bootstrap class '" + className + "' in the classpath", null);
            throw new UnableToCompleteException();
        }
    } catch (IOException e) {
        logger.log(TreeLogger.ERROR, "Error reading class bytes for " + className, e);
        throw new UnableToCompleteException();
    }
}

From source file:ffx.xray.XRayMinimizeTest.java

public XRayMinimizeTest(boolean ciOnly, String info, String pdbname, String mtzname, String cifname, double r,
        double rFree, double sigmaA, double sigmaW) {
    this.ciOnly = ciOnly;
    this.info = info;
    this.r = r;/*  ww  w. j  av  a2s .c om*/
    this.rFree = rFree;
    this.sigmaA = sigmaA;
    this.sigmaW = sigmaW;

    ci = System.getProperty("ffx.ci", "false").equalsIgnoreCase("true");
    if (!ci && ciOnly) {
        crystalStats = null;
        return;
    }

    int index = pdbname.lastIndexOf(".");
    String name = pdbname.substring(0, index);

    // load the structure
    ClassLoader cl = this.getClass().getClassLoader();
    File structure = new File(cl.getResource(pdbname).getPath());
    File mtzFile = null, cifFile = null;
    if (mtzname != null) {
        mtzFile = new File(cl.getResource(mtzname).getPath());
    } else {
        cifFile = new File(cl.getResource(cifname).getPath());
    }

    // load any properties associated with it
    CompositeConfiguration properties = Keyword.loadProperties(structure);

    // read in Fo/sigFo/FreeR
    MTZFilter mtzFilter = new MTZFilter();
    CIFFilter cifFilter = new CIFFilter();
    Crystal crystal = Crystal.checkProperties(properties);
    Resolution resolution = Resolution.checkProperties(properties);
    if (crystal == null || resolution == null) {
        if (mtzname != null) {
            reflectionList = mtzFilter.getReflectionList(mtzFile);
        } else {
            reflectionList = cifFilter.getReflectionList(cifFile);
        }
    } else {
        reflectionList = new ReflectionList(crystal, resolution);
    }

    refinementData = new DiffractionRefinementData(properties, reflectionList);
    if (mtzname != null) {
        assertTrue(info + " mtz file should be read in without errors",
                mtzFilter.readFile(mtzFile, reflectionList, refinementData, properties));
    } else {
        assertTrue(info + " cif file should be read in without errors",
                cifFilter.readFile(cifFile, reflectionList, refinementData, properties));
    }

    ForceFieldFilter forceFieldFilter = new ForceFieldFilter(properties);
    ForceField forceField = forceFieldFilter.parse();

    // associate molecular assembly with the structure, set up forcefield
    MolecularAssembly molecularAssembly = new MolecularAssembly(name);
    molecularAssembly.setFile(structure);
    molecularAssembly.setForceField(forceField);
    PDBFilter pdbFile = new PDBFilter(structure, molecularAssembly, forceField, properties);
    pdbFile.readFile();
    pdbFile.applyAtomProperties();
    molecularAssembly.finalize(true, forceField);
    ForceFieldEnergy energy = new ForceFieldEnergy(molecularAssembly, pdbFile.getCoordRestraints());

    List<Atom> atomList = molecularAssembly.getAtomList();
    Atom atomArray[] = atomList.toArray(new Atom[atomList.size()]);

    // set up FFT and run it
    parallelTeam = new ParallelTeam();
    CrystalReciprocalSpace crs = new CrystalReciprocalSpace(reflectionList, atomArray, parallelTeam,
            parallelTeam, false);
    crs.computeDensity(refinementData.fc);
    refinementData.setCrystalReciprocalSpace_fc(crs);
    crs = new CrystalReciprocalSpace(reflectionList, atomArray, parallelTeam, parallelTeam, true);
    crs.computeDensity(refinementData.fs);
    refinementData.setCrystalReciprocalSpace_fs(crs);

    ScaleBulkMinimize scaleBulkMinimize = new ScaleBulkMinimize(reflectionList, refinementData, crs,
            parallelTeam);
    scaleBulkMinimize.minimize(6, 1.0e-4);

    SigmaAMinimize sigmaAMinimize = new SigmaAMinimize(reflectionList, refinementData, parallelTeam);
    sigmaAMinimize.minimize(7, 2.0e-2);

    SplineMinimize splineMinimize = new SplineMinimize(reflectionList, refinementData, refinementData.spline,
            SplineEnergy.Type.FOFC);
    splineMinimize.minimize(7, 1e-5);

    crystalStats = new CrystalStats(reflectionList, refinementData);
}

From source file:org.apache.xmlgraphics.util.ClasspathResource.java

private void addToMapping(final String contentType, final String name, final ClassLoader classLoader) {
        List existingFiles = (List) contentMappings.get(contentType);
        if (existingFiles == null) {
            existingFiles = new Vector();
            contentMappings.put(contentType, existingFiles);
        }//w  w  w  . j ava  2 s  . co m
        final URL url = classLoader.getResource(name);
        if (url != null) {
            existingFiles.add(url);
        }
    }

From source file:org.apache.axis2.classloader.MultiParentClassLoader.java

public URL getResource(String name) {
    if (isDestroyed()) {
        return null;
    }// w  w  w.j  a  v a2  s . com

    //
    // if we are using inverse class loading, check local urls first
    //
    if (inverseClassLoading && !isDestroyed() && !isNonOverridableResource(name)) {
        URL url = findResource(name);
        if (url != null) {
            return url;
        }
    }

    //
    // Check parent class loaders
    //
    if (!isHiddenResource(name)) {
        for (int i = 0; i < parents.length; i++) {
            ClassLoader parent = parents[i];
            URL url = parent.getResource(name);
            if (url != null) {
                return url;
            }
        }
    }

    //
    // if we are not using inverse class loading, check local urls now
    //
    // don't worry about excluding non-overridable resources here... we
    // have alredy checked he parent and the parent didn't have the
    // resource, so we can override now
    if (!isDestroyed()) {
        // parents didn't have the resource; attempt to load it from my urls
        return findResource(name);
    }

    return null;
}