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.nutch.webapp.common.PluginResourceLoader.java

public URL getResource(String name) {
    Iterator i = classloaders.iterator();

    while (i.hasNext()) {
        ClassLoader loader = (ClassLoader) i.next();
        URL retVal = loader.getResource(name);
        if (retVal != null) {
            return retVal;
        }//w w  w . j a v a  2  s  .c  o  m
    }
    return null;
}

From source file:halfpipe.properties.UrlPropertiesSource.java

private URL getConfigFileFromClasspath() {
    URL url = null;/*from w w  w .j av  a  2  s.c o m*/
    // attempt to load from the context classpath
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader != null) {
        url = loader.getResource(DEFAULT_CONFIG_FILE_FROM_CLASSPATH);
    }
    if (url == null) {
        // attempt to load from the system classpath
        url = ClassLoader.getSystemResource(DEFAULT_CONFIG_FILE_FROM_CLASSPATH);
    }
    if (url == null) {
        // attempt to load from the system classpath
        url = UrlPropertiesSource.class.getResource(DEFAULT_CONFIG_FILE_FROM_CLASSPATH);
    }
    return url;
}

From source file:ffx.xray.CrystalReciprocalSpaceTest.java

@Test
public void test1NSFPermanent() {
    String filename = "ffx/xray/structures/1NSF.pdb";
    int index = filename.lastIndexOf(".");
    String name = filename.substring(0, index);

    // load the structure
    ClassLoader cl = this.getClass().getClassLoader();
    File structure = new File(cl.getResource(filename).getPath());

    // load any properties associated with it
    CompositeConfiguration properties = Keyword.loadProperties(structure);
    Crystal crystal = new Crystal(115.996, 115.996, 44.13, 90.0, 90.0, 120.0, "P6");
    Resolution resolution = new Resolution(1.89631);

    ReflectionList reflectionList = new ReflectionList(crystal, resolution);
    DiffractionRefinementData refinementData = new DiffractionRefinementData(properties, reflectionList);

    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();//from ww w  .ja  va2s  .com
    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 parallelTeam = new ParallelTeam();
    CrystalReciprocalSpace crs = new CrystalReciprocalSpace(reflectionList, atomArray, parallelTeam,
            parallelTeam);
    crs.computeAtomicDensity(refinementData.fc);

    // tests
    ComplexNumber b = new ComplexNumber(-496.999, 431.817);
    HKL hkl = reflectionList.getHKL(1, 9, 4);
    ComplexNumber a = refinementData.getFc(hkl.index());
    System.out.println("1 9 4: " + a.toString() + " | " + b.toString() + " | " + a.divides(b).toString());

    assertEquals("1 9 4 reflection should be correct", -493.7799429881329, a.re(), 0.0001);
    assertEquals("1 9 4 reflection should be correct", 460.7022632345927, a.im(), 0.0001);

    b.re(-129.767);
    b.im(-76.9812);
    hkl = reflectionList.getHKL(5, 26, 8);
    a = refinementData.getFc(hkl.index());
    System.out.println("5 26 8: " + a.toString() + " | " + b.toString() + " | " + a.divides(b).toString());

    assertEquals("5 26 8 reflection should be correct", -123.05535567943377, a.re(), 0.0001);
    assertEquals("5 26 8 reflection should be correct", -74.59007322382718, a.im(), 0.0001);
}

From source file:ffx.xray.CrystalReciprocalSpaceTest.java

/**
 * Test of permanent method, of class CrystalReciprocalSpace.
 *//*  w  w w . jav  a  2s  .  c  o m*/
@Test
public void test1N7SPermanent() {
    String filename = "ffx/xray/structures/1N7S.pdb";
    int index = filename.lastIndexOf(".");
    String name = filename.substring(0, index);

    // load the structure
    ClassLoader cl = this.getClass().getClassLoader();
    File structure = new File(cl.getResource(filename).getPath());

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

    Crystal crystal = new Crystal(39.767, 51.750, 132.938, 90.00, 90.00, 90.00, "P212121");
    Resolution resolution = new Resolution(1.45);

    ReflectionList reflectionList = new ReflectionList(crystal, resolution);
    DiffractionRefinementData refinementData = new DiffractionRefinementData(properties, reflectionList);

    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 parallelTeam = new ParallelTeam();
    CrystalReciprocalSpace crs = new CrystalReciprocalSpace(reflectionList, atomArray, parallelTeam,
            parallelTeam);
    crs.computeAtomicDensity(refinementData.fc);

    // tests
    ComplexNumber b = new ComplexNumber(-828.584, -922.704);
    HKL hkl = reflectionList.getHKL(1, 1, 4);
    ComplexNumber a = refinementData.getFc(hkl.index());
    System.out.println("1 1 4: " + a.toString() + " | " + b.toString() + " | " + a.divides(b).toString());

    assertEquals("1 1 4 reflection should be correct", -753.4722104328416, a.re(), 0.0001);
    assertEquals("1 1 4 reflection should be correct", -1012.1341308707799, a.im(), 0.0001);

    b.re(-70.4582);
    b.im(-486.142);
    hkl = reflectionList.getHKL(2, 1, 10);
    a = refinementData.getFc(hkl.index());
    System.out.println("2 1 10: " + a.toString() + " | " + b.toString() + " | " + a.divides(b).toString());

    assertEquals("2 1 10 reflection should be correct", -69.39660884054359, a.re(), 0.0001);
    assertEquals("2 1 10 reflection should be correct", -412.0147625765328, a.im(), 0.0001);
}

From source file:io.lightlink.excel.ExcelImportExportTest.java

public void test() throws IOException {

    int COLUMNS_CNT = 30;
    int ROWS_CNT = 10000;

    List<String> headers = new ArrayList<String>();
    List<String> columns = new ArrayList<String>();

    for (int i = 0; i < COLUMNS_CNT; i++) {
        columns.add("col_" + i);
        headers.add("Name " + i);
    }/*from   w w  w.  j  a v  a  2 s .c  o m*/

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream templateStream = cl.getResource("io/lightlink/excel/ExcelImportExportTest.xlsx").openStream();
    InputStream templateStream2 = cl.getResource("io/lightlink/excel/ExcelImportExportTest.xlsx").openStream();

    HashMap<String, Object> data = new HashMap<String, Object>();
    HashMap<String, Object> p = new HashMap<String, Object>();
    p.put("firstName", "My firstName");
    p.put("lastName", "My lastName");
    p.put("minHireDate", new Date(0).toString());
    p.put("maxHireDate", new Date().toString());
    p.put("minSalary", "1200");
    p.put("maxSalary", "5000");
    data.put("p", p);

    data.put("date", new Date().toString());
    data.put("headers", headers);
    data.put("columns", columns);

    List<Map<String, Object>> resultSet = new ArrayList<Map<String, Object>>();
    for (int i = 0; i < ROWS_CNT; i++) {
        HashMap<String, Object> line = new HashMap<String, Object>();
        for (String column : columns) {
            line.put(column, column + "_" + i);
        }
        resultSet.add(line);
        if (i % 1000 == 0) {
            System.out.println(i + " : " + Runtime.getRuntime().totalMemory() / 1000000 + "Mb used");
        }
    }

    data.put("resultSet", resultSet);

    String fName = "ExcelImportExportTest-OUT.xlsx";
    OutputStream outFile = new FileOutputStream(fName);

    long l = System.currentTimeMillis();

    new StreamingExcelTransformer().doExport(templateStream, outFile,
            new WritingExcelStreamVisitor(data, DateFormat.getDateTimeInstance()));

    outFile.close();

    //        System.out.println(COLUMNS_CNT + "x" + ROWS_CNT + " generated in " + (System.currentTimeMillis() - l) / 1000f + "sec");

    //        resultSet = null;
    //        data = null;

    //        for debug
    InputStream fileToRead = new FileInputStream(fName);

    HashMap<String, MappingBean> outData = new HashMap<String, MappingBean>();

    // read definition
    DefinitionReadingExcelStreamVisitor definitionReadingExcelStreamVisitor = new DefinitionReadingExcelStreamVisitor();
    new StreamingExcelTransformer().doExport(templateStream2, new NullOutputStream(),
            definitionReadingExcelStreamVisitor);
    Map<String, MappingBean> targets = definitionReadingExcelStreamVisitor.getTargets();

    // read data
    DataReadingExcelStreamVisitor dataReadingExcelStreamVisitor = new DataReadingExcelStreamVisitor(targets);
    new StreamingExcelTransformer().doExport(fileToRead, new NullOutputStream(), dataReadingExcelStreamVisitor);

    Map<String, Object> loadedData = dataReadingExcelStreamVisitor.getData();

    compareAssertMap("", data, loadedData);

    fileToRead.close();
    new File(fName).delete();

}

From source file:mercury.Controller.java

@Override
public void init() {
    //--- Runs just once !
    try {/*from   w w  w  .  j a va 2s.c  om*/
        ClassLoader cl = Controller.class.getClassLoader();
        URL fileURL = cl.getResource("/targetHandlers.properties");
        Controller.targetHandlers = new Properties();
        Controller.targetHandlers.load(fileURL.openStream());
    } catch (IOException ioe) {
        System.out.println("[mercury.Controller.init()] Error: " + ioe.getMessage());
    }
}

From source file:org.apache.axis2.scripting.ScriptReceiver.java

/**
 * Reads the complete script source code into a String
 *//*from   ww w  .  j  av  a  2 s . c o  m*/
protected String readScript(ClassLoader cl, String scriptName) throws AxisFault {
    URL url = cl.getResource(scriptName);
    if (url == null) {
        throw new AxisFault("Script not found: " + scriptName);
    }
    InputStream is;
    try {
        is = url.openStream();
    } catch (IOException e) {
        throw new AxisFault("IOException opening script: " + scriptName, e);
    }
    try {
        Reader reader = new InputStreamReader(is, "UTF-8");
        char[] buffer = new char[1024];
        StringBuffer source = new StringBuffer();
        int count;
        while ((count = reader.read(buffer)) > 0) {
            source.append(buffer, 0, count);
        }
        return source.toString();
    } catch (IOException e) {
        throw new AxisFault("IOException reading script: " + scriptName, e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            throw new AxisFault("IOException closing script: " + scriptName, e);
        }
    }
}

From source file:com.krawler.portal.util.SystemProperties.java

private SystemProperties() {
    Properties p = new Properties();

    ClassLoader classLoader = getClass().getClassLoader();

    // system.properties

    try {//from  w  w  w  . j av  a2  s . c om
        URL url = classLoader.getResource("system.properties");

        if (url != null) {
            InputStream is = url.openStream();

            p.load(is);

            is.close();

            logger.debug("Loading " + url);
        }
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
    }

    // system-ext.properties

    try {
        URL url = classLoader.getResource("system-ext.properties");

        if (url != null) {
            InputStream is = url.openStream();

            p.load(is);

            is.close();

            logger.debug("Loading " + url);
        }
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
    }

    // Set environment properties

    SystemEnv.setProperties(p);

    // Set system properties

    boolean systemPropertiesLoad = GetterUtil.getBoolean(System.getProperty(SYSTEM_PROPERTIES_LOAD), true);

    boolean systemPropertiesFinal = GetterUtil.getBoolean(System.getProperty(SYSTEM_PROPERTIES_FINAL), true);

    if (systemPropertiesLoad) {
        Enumeration<String> enu = (Enumeration<String>) p.propertyNames();

        while (enu.hasMoreElements()) {
            String key = enu.nextElement();

            if (systemPropertiesFinal || Validator.isNull(System.getProperty(key))) {

                System.setProperty(key, p.getProperty(key));
            }
        }
    }

    _props = new ConcurrentHashMap<String, String>();

    // Use a fast concurrent hash map implementation instead of the slower
    // java.util.Properties

    PropertiesUtil.fromProperties(p, _props);
}

From source file:io.inkstand.jcr.provider.InMemoryRepositoryProvider.java

/**
 * Resolves the given String URL by searching the classpath using the context class loader and this class'
 * classloader. If not such resources can be found, the URL is accessed directly.
 *
 * @param strUrl/*from  w w  w .  j  a  v  a2 s.  c o m*/
 *            the URL as a string
 * @return the resolved URL
 * @throws MalformedURLException
 *             if the resource was not found in classpath and is not valid URL either.
 */
private URL resolveUrl(final String strUrl) throws MalformedURLException {
    final ClassLoader ccl = Thread.currentThread().getContextClassLoader();
    URL url = null;
    if (ccl != null) {
        url = ccl.getResource(strUrl);
    }
    if (url == null) {
        url = getClass().getResource(strUrl);
    }
    if (url == null) {
        url = new URL(strUrl);
    }
    return url;
}

From source file:com.hazelcast.config.XmlConfigSchemaLocationTest.java

@Test
public void testSchemaLocationsExist() throws Exception {
    assumeTls12Available();//from  w  w w  .  ja  va2s .com

    ResourcesScanner scanner = new ResourcesScanner();
    Reflections reflections = new Reflections(scanner);
    Set<String> resources = reflections.getResources(Pattern.compile(".*\\.xml"));
    ClassLoader classLoader = getClass().getClassLoader();
    for (String resource : resources) {
        URL resourceUrl = classLoader.getResource(resource);
        String protocol = resourceUrl.getProtocol();

        // do not validate schemas from JARs (libraries). we are interested in local project files only.
        if (protocol.startsWith("jar")) {
            continue;
        }

        InputStream stream = null;
        try {
            stream = classLoader.getResourceAsStream(resource);
            validateSchemaLocationUrl(stream, resource);
        } finally {
            IOUtil.closeResource(stream);
        }
    }
}