Example usage for java.lang ClassLoader getSystemResource

List of usage examples for java.lang ClassLoader getSystemResource

Introduction

In this page you can find the example usage for java.lang ClassLoader getSystemResource.

Prototype

public static URL getSystemResource(String name) 

Source Link

Document

Find a resource of the specified name from the search path used to load classes.

Usage

From source file:com.datamoin.tajo.tpcds.TpcDsSingleTest.java

public void testAllQueries(boolean local) throws Exception {
    String resultParentPath = TpcDSTestUtil.getResultDataPath();
    File queryResultParentDir = null;
    if (local) {//from ww w .jav  a  2 s  .c  o  m
        File resourceDir = null;
        if (resultParentPath == null || resultParentPath.isEmpty()) {
            resourceDir = new File(ClassLoader.getSystemResource("tpcds").getPath());
            queryResultParentDir = new File(resourceDir, "results");
        } else {
            queryResultParentDir = new File(resultParentPath);
        }
        if (!queryResultParentDir.exists()) {
            throw new Exception("Result directory not exists: " + resultParentPath);
        }
    } else {
        if (resultParentPath != null && !resultParentPath.isEmpty()) {
            queryResultParentDir = new File(resultParentPath);
            if (!queryResultParentDir.exists()) {
                throw new Exception("Result directory not exists: " + resultParentPath);
            }
        }
    }

    File queryRoot = new File(ClassLoader.getSystemResource("tpcds").getPath(), "/queries");
    //String[] queries = FileUtil.readTextFile(new File(queryRoot, "query.list")).split("\\n");
    String query = FileUtil.readTextFile(new File(queryRoot, getProperty("QUERY_PATH", true)));
    String queryId = getQueryId(getProperty("QUERY_PATH", true));

    numTargetQueries = 0;
    startTime = System.currentTimeMillis();
    try {
        long queryStartTime = System.currentTimeMillis();
        ResultSet res = client.executeQueryAndGetResult(query);
        try {
            String resultSetData = TpcDSTestUtil.resultSetToString(res);

            if (!local && queryResultParentDir == null) {
                System.out.println("==============================================");
                System.out.println(queryId + "result data:");
                System.out.println("----------------------------------------------");
                System.out.println(resultSetData);
                System.out.println("----------------------------------------------");
            } else {
                String expectedData = FileUtil
                        .readTextFile(new File(queryResultParentDir, queryId + ".result"));

                if (!expectedData.equals(resultSetData)) {
                    System.out.println("==============================================");
                    System.out.println("expected data:");
                    System.out.println("----------------------------------------------");
                    System.out.println(expectedData);
                    System.out.println("real data:");
                    System.out.println("----------------------------------------------");
                    System.out.println(resultSetData);
                    System.out.println("----------------------------------------------");
                }
                assertEquals("TPC-DS Query: " + queryId + " failed", expectedData, resultSetData);
            }
        } finally {
            res.close();
        }

        String logMessage = queryId + " (" + (System.currentTimeMillis() - queryStartTime) / 1000 + " sec)";
        LOG.info("========> Query Finished: " + logMessage);
        successQueries.add(logMessage);
    } finally {
        endTime = System.currentTimeMillis();
    }
}

From source file:org.openmrs.module.metadatasharing.util.VersionConverterTest.java

/**
 * @see {@link VersionConverter#convertIncomingMessage(String,String)}
 *//*from   w  w w.jav  a  2  s  .c om*/
@Test
@Verifies(value = "should convert a message from one dot six", method = "convert(String,String,String)")
public void convert_shouldConvertAMessageFromOneDotSix() throws Exception {
    String filePath = ClassLoader.getSystemResource("VersionConverterTest-metadata-from-16.xml").getPath();
    String xml = FileUtils.readFileToString(new File(filePath), "UTF-8");
    Assert.assertTrue(xml.indexOf("conceptNameType") < 0);
    Assert.assertTrue(xml.indexOf("localePreferred") < 0);
    Assert.assertTrue(xml.indexOf("FULLY_SPECIFIED") < 0);
    Assert.assertTrue(xml.indexOf("SHORT") < 0);
    Assert.assertTrue(xml.indexOf("preferred name in a language") > 0);

    String output = new VersionConverter().convert(xml, "1.6.3", "");

    Assert.assertTrue(output.indexOf("conceptNameType") > 0);
    Assert.assertTrue(output.indexOf("localePreferred") > 0);
    Assert.assertTrue(output.indexOf("FULLY_SPECIFIED") > 0);
    Assert.assertTrue(output.indexOf("SHORT") > 0);
    Assert.assertTrue(output.indexOf("preferred name in a language") < 0);
}

From source file:org.apache.hadoop.hive.ql.session.DependencyResolver.java

public DependencyResolver() {

    // Check if HIVE_CONF_DIR is defined
    if (System.getenv().containsKey(HIVE_CONF_DIR)) {
        ivysettingsPath = System.getenv().get(HIVE_CONF_DIR) + "/ivysettings.xml";
    }/*www  .j  av a2  s  .co  m*/

    // If HIVE_CONF_DIR is not defined or file is not found in HIVE_CONF_DIR then check HIVE_HOME/conf
    if (ivysettingsPath == null || !(new File(ivysettingsPath).exists())) {
        if (System.getenv().containsKey(HIVE_HOME)) {
            ivysettingsPath = System.getenv().get(HIVE_HOME) + "/conf/ivysettings.xml";
        }
    }

    // If HIVE_HOME is not defined or file is not found in HIVE_HOME/conf then load default ivysettings.xml from class loader
    if (ivysettingsPath == null || !(new File(ivysettingsPath).exists())) {
        URL ivysetttingsResource = ClassLoader.getSystemResource("ivysettings.xml");
        if (ivysetttingsResource != null) {
            ivysettingsPath = ivysetttingsResource.getFile();
            _console.printInfo("ivysettings.xml file not found in HIVE_HOME or HIVE_CONF_DIR," + ivysettingsPath
                    + " will be used");
        }
    }

}

From source file:com.dsf.dbxtract.cdc.AppJournalWindowTest.java

@Test
public void setUp() throws Exception {

    configFile = ClassLoader.getSystemResource(PROPERTY_RESOURCE).getFile();

    logger.info("Testing Journal-based CDC with window strategy");

    // Add configuration to zk
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    client = CuratorFrameworkFactory.newClient("localhost:2181", retryPolicy);
    client.start();/* ww w.j av  a2  s . com*/

    // Clean previous statistics and states
    if (client.checkExists().forPath(ZK_STATISTICS_PATH) != null) {
        List<String> children = client.getChildren().forPath(ZK_STATISTICS_PATH);
        for (String k : children)
            client.delete().forPath(ZK_STATISTICS_PATH + "/" + k);
        client.delete().forPath(ZK_STATISTICS_PATH);
    }
}

From source file:org.wte4j.TemplateEngineTest.java

@Test

public void createDocumentWithBasicDynamicContent() throws Exception {
    final String documentName = "basic_values";
    final String language = "de";
    final File templateDocument = FileUtils
            .toFile(ClassLoader.getSystemResource("org/wte4j/basic-values-template.docx"));

    Template<Integer> template = createTemplate(documentName, language, templateDocument);

    TemplateRepository repository = wte.getTemplateRepository();
    template = repository.persist(template);

    File document = wte.createDocument(documentName, language, 1);

    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(document);
    StringWriter writer = new StringWriter();
    TextUtils.extractText(wordMLPackage.getMainDocumentPart().getContents(), writer);
    String contentAsText = writer.toString();
    assertTrue(!contentAsText.contains("toReplace"));
}

From source file:org.jamocha.classloading.Loader.java

/**
 * Recursively loads all class files in the specified package.
 *
 * @param packageString//from  w w  w.  j  a  v a 2 s. c  om
 *         the path within the package hierarchy (separator '/')
 */
public static void loadClasses(final String packageString) {
    final String string = ClassLoader.getSystemResource(Loader.class.getName().replace('.', '/') + ".class")
            .toString();
    if (string.startsWith("jar:")) {
        final String jarFile = string.substring("jar:file:".length(), string.indexOf('!'));
        Loader.loadClassesInJar(jarFile, packageString);
    } else {
        Loader.loadClassesInDirectory("target/classes", packageString);
    }
}

From source file:org.jpac.configuration.Configuration.java

private Configuration() throws ConfigurationException, UnsupportedEncodingException {
    super();// w  w  w .  ja va 2  s.com
    URL configFileUrl = ClassLoader.getSystemResource("org.jpac.Configuration.xml");
    if (configFileUrl != null) {
        File configFile = new File(URLDecoder.decode(configFileUrl.getFile(), "UTF-8"));
        backupConfigFile = new File(configFile.getAbsolutePath() + ".bak");
        setFile(configFile);
        try {
            load();
            loadedSuccessFully = true;
            //configuration loaded successfully
            //store a backup version, if it has been modified since last session
            if (configFile.lastModified() > backupConfigFile.lastModified()) {
                save(backupConfigFile);
                backupedSuccessFully = true;
            }
        } catch (ConfigurationException exc) {
            if (!loadedSuccessFully) {
                Log.error("error occured while loading the configuration: ", exc);
                //configuration file cannot be read
                //try the backup file
                if (backupConfigFile.exists()) {
                    load(backupConfigFile);//throw exception up, if this operation fails
                    //and store it as the actual configuration
                    save();//throw exception up, if this operation fails
                    Log.error("backup configuration loaded instead and saved as actual configuration.");
                }
            } else if (!backupedSuccessFully) {
                Log.error("error occured while backing up the configuration: ", exc);
                try {
                    backupConfigFile.delete();//try to remove backup configuration
                    save(backupConfigFile);//and retry backing up the current configuration
                } catch (Exception ex) {
                    Log.error("error occured while backing up the configuration (2nd trial): ", exc);
                }
            }
        }
    } else {
        //no configuration file found in class path. Set default
        setFile(new File("./cfg/org.jpac.Configuration.xml"));
    }
}

From source file:org.openmrs.contrib.liquibaserunner.LiquibaseRunner.java

public LiquibaseRunner(final String changeLogFile, final boolean useOpenmrsChangeLog)
        throws LiquibaseRunnerException {
    try {/*from   w ww. j av  a  2s  .  co m*/
        final Properties properties = loadProperties();
        connection = openConnection(properties);

        final Database database = DatabaseFactory.getInstance()
                .findCorrectDatabaseImplementation(new JdbcConnection(connection));

        if (useOpenmrsChangeLog) {
            changeLogTable = "liquibasechangelog";
            changeLogLockTable = "liquibasechangeloglock";
        } else {
            changeLogTable = "databasechangelog_v2";
            changeLogLockTable = "databasechangeloglock_v2";
        }

        database.setDatabaseChangeLogTableName(changeLogTable);
        database.setDatabaseChangeLogLockTableName(changeLogLockTable);

        if (ClassLoader.getSystemResource(changeLogFile) != null) {
            liquibase = new Liquibase(changeLogFile, new ClassLoaderResourceAccessor(), database);
        } else {
            final String changeLogTempFile = createTempChangeLogFile(changeLogFile);
            liquibase = new Liquibase(changeLogTempFile, new FileSystemResourceAccessor(), database);
        }
        liquibase.forceReleaseLocks();
    } catch (Exception e) {
        throw new LiquibaseRunnerException(e);
    }
}

From source file:com.autentia.wuija.etl.readers.CsvFileReaderTest.java

public void readCsv(String csvFile) throws FileNotFoundException, IOException {

    URL path = ClassLoader.getSystemResource(csvFile);
    List<List<String>> importRecords = csvFileReader.readCsv(path.getFile());

    Assert.assertEquals("Incorrect record count", records.size(), importRecords.size());

    for (int i = 0; i < records.size(); i++) {
        List<String> record = records.get(i);
        List<String> importRecord = importRecords.get(i);

        Assert.assertEquals("Incorrect field count for record" + i, record.size(), importRecord.size());

        for (int j = 0; j < record.size(); j++) {
            String field = record.get(j);
            String importField = importRecord.get(j);

            Assert.assertEquals("Incorrect value for field " + j + " in record " + i, field, importField);
        }/*w  w w  .j a  v a2s. com*/
    }
}

From source file:TextureMapping.java

/**
 * Wurfeldarstellung/* w  w w  .ja v  a 2 s .  c  o m*/
 * 
 * @return Appearance
 */
private Appearance makeAppearance() {
    Appearance a = new Appearance();
    TextureLoader loader = null;
    if (getCodeBase() != null)
        try {
            // Laden der Obj Datei als Applet mit jar
            loader = new TextureLoader(new URL("jar:" + getCodeBase() + "TextureMapping.jar!/burnstone.jpg"),
                    null);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    else
        // Laden der Obj Datei mittels jar
        loader = new TextureLoader(ClassLoader.getSystemResource("burnstone.jpg"), null);

    Texture2D texture = (Texture2D) loader.getTexture();
    a.setTexture(texture);
    return a;
}