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:jp.ikedam.jenkins.plugins.ldap_sasl.LdapTest.java

protected static void startLdapServer(String configFile) throws Exception {
    boolean isRunning = EmbeddedUtils.isRunning();
    if (isRunning) {
        EmbeddedUtils.stopServer(null, null);
    }/*from  w  w w  . j av a  2s  .c  o m*/
    File serverRoot = new File(ClassLoader.getSystemResource("opendj").toURI());
    DirectoryEnvironmentConfig config = new DirectoryEnvironmentConfig();
    config.disableAdminDataSynchronization();
    config.disableSynchronization();
    config.setUseLastKnownGoodConfiguration(false);
    config.setServerRoot(serverRoot);
    config.setConfigFile(new File(serverRoot, String.format("config/%s", configFile)));
    config.setSchemaDirectory(new File(serverRoot, "schema"));

    if (!isRunning) {
        File lockDir = new File(serverRoot, "locks");
        if (lockDir.exists()) {
            FileUtils.deleteDirectory(lockDir);
        }
        lockDir.mkdir();
        config.setLockDirectory(lockDir);

        File logDir = new File(serverRoot, "logs");
        if (logDir.exists()) {
            FileUtils.deleteDirectory(logDir);
        }
        logDir.mkdir();
    }
    EmbeddedUtils.startServer(config);
}

From source file:org.mule.transport.rmi.RmiMessageReceiverTestCase.java

@Override
protected void doSetUp() throws Exception {
    registerRmi();/*  w  w w . j  a  v a 2s  .  com*/

    connector = new RmiConnector(muleContext);
    connector.setName("TestConnector:" + this.getClass());
    connector.setSecurityPolicy(ClassLoader.getSystemResource("rmi.policy").getPath());
    connector.setJndiInitialFactory("com.sun.jndi.rmi.registry.RegistryContextFactory");
    connector.setJndiProviderUrl("rmi://localhost:11099");

    muleContext.getRegistry().registerConnector(connector);

    super.doSetUp();
}

From source file:org.covito.kit.utility.ClassUtil.java

public static URL getClassLocation(final String clsName) {
    if (clsName == null) {
        return null;
    }//from ww  w  . ja  v a 2s  .  c  o  m
    Class cls = null;
    try {
        cls = Class.forName(clsName);
    } catch (Exception e) {
        return null;
    }
    URL result = null;
    final String clsAsResource = cls.getName().replace('.', '/').concat(".class");
    final ProtectionDomain pd = cls.getProtectionDomain();
    // java.lang.Class contract does not specify if 'pd' can ever be null;
    // it is not the case for Sun's implementations, but guard against null
    // just in case:
    if (pd != null) {
        final CodeSource cs = pd.getCodeSource();
        // 'cs' can be null depending on the classloader behavior:
        if (cs != null)
            result = cs.getLocation();
        if (result != null) {
            // Convert a code source location into a full class file
            // location
            // for some common cases:
            if ("file".equals(result.getProtocol())) {
                try {
                    if (result.toExternalForm().endsWith(".jar") || result.toExternalForm().endsWith(".zip"))
                        result = new URL(
                                "jar:".concat(result.toExternalForm()).concat("!/").concat(clsAsResource));
                    else if (new File(result.getFile()).isDirectory()) {
                        result = new URL(result, clsAsResource);
                    }
                } catch (MalformedURLException ignore) {
                }
            }
        }
    }
    if (result == null) {
        // Try to find 'cls' definition as a resource; this is not
        // documentd to be legal, but Sun's implementations seem to //allow
        // this:
        final ClassLoader clsLoader = cls.getClassLoader();
        result = clsLoader != null ? clsLoader.getResource(clsAsResource)
                : ClassLoader.getSystemResource(clsAsResource);
    }
    return result;
}

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

public void testAllQueries(boolean local) throws Exception {
    String resultParentPath = TpcDSTestUtil.getResultDataPath();
    File queryResultParentDir = null;
    if (local) {/* w  w w .  ja v  a  2 s .c  om*/
        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");

    numTargetQueries = 0;
    startTime = System.currentTimeMillis();
    try {
        for (String eachQuery : queries) {
            if (eachQuery.trim().isEmpty() || eachQuery.trim().startsWith("#")) {
                continue;
            }
            numTargetQueries++;
        }

        for (String eachQuery : queries) {
            eachQuery = eachQuery.trim();
            if (eachQuery.isEmpty() || eachQuery.startsWith("#")) {
                continue;
            }
            String queryId = getQueryId(eachQuery);
            LOG.info("========> Run TPC-DS Query: " + queryId);
            String query = FileUtil.readTextFile(new File(queryRoot, eachQuery));
            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.apache.james.backends.cassandra.init.CassandraConfigurationReadingTest.java

@Test
public void provideCassandraConfigurationShouldReturnRightConfigurationFile() throws ConfigurationException {
    CassandraConfiguration configuration = CassandraConfiguration
            .from(new PropertiesConfiguration(ClassLoader.getSystemResource("cassandra.properties")));

    assertThat(configuration).isEqualTo(CassandraConfiguration.builder().aclMaxRetry(1).modSeqMaxRetry(2)
            .uidMaxRetry(3).flagsUpdateMessageMaxRetry(4).flagsUpdateMessageIdMaxRetry(5)
            .fetchNextPageInAdvanceRow(6).flagsUpdateChunkSize(7).messageReadChunkSize(8).expungeChunkSize(9)
            .blobPartSize(10).attachmentV2MigrationReadTimeout(11).messageAttachmentIdsReadTimeout(12).build());
}

From source file:org.n52.sir.data.DummySensorGenerator.java

@Test
public void parseJsonSensorsAndInsert() throws IOException, OwsExceptionReport, XmlException, HttpException {

    File sensor_file = new File(ClassLoader.getSystemResource("data/randomSensors.json").getFile());
    File sensor_temp = new File(ClassLoader.getSystemResource("AirBase-test.xml").getFile());
    SensorMLDocument DOC = SensorMLDocument.Factory.parse(sensor_temp);
    Gson gson = new Gson();
    StringBuilder builder = new StringBuilder();
    String s;/*from  w w  w. j a v a 2 s  .  c o  m*/
    try (BufferedReader reader = new BufferedReader((new FileReader(sensor_file)));) {
        while ((s = reader.readLine()) != null)
            builder.append(s);
    }

    JSONSensorsCollection collection = gson.fromJson(builder.toString(), JSONSensorsCollection.class);
    Iterator<JSONSensor> sensors = collection.sensors.iterator();
    while (sensors.hasNext()) {
        SirSensor sensor = new SirSensor();
        JSONSensor jsensor = sensors.next();
        sensor.setKeywords(jsensor.keywords);
        TimePeriod period = new TimePeriod();
        DateTime begin = DateTime.parse(jsensor.beginPosition);
        DateTime end = DateTime.parse(jsensor.endPosition);
        // fix because we need start < end , and the data is randomly
        // generated
        if (begin.getMillis() > end.getMillis()) {
            DateTime temp = begin;
            end = begin;
            begin = temp;
        }
        period.setStartTime(new IndeterminateTime(begin.toDate()));
        period.setEndTime(new IndeterminateTime(end.toDate()));
        sensor.setTimePeriod(period);
        sensor.setIdentificationsList(jsensor.Identifiers);
        List<String> contacts = new ArrayList<>();
        contacts.add(jsensor.contacts);
        sensor.setContacts(contacts);

        /*
         * Add to SIRPQSQL
         */
        KeywordList klist = KeywordList.Factory.newInstance();
        klist.setKeywordArray(jsensor.keywords.toArray(new String[] {}));
        DOC.getSensorML().getMemberArray(0).getProcess().getKeywordsArray(0).setKeywordList(klist);
        InsertSensorInfoRequestDocument req = InsertSensorInfoRequestDocument.Factory.newInstance();
        req.addNewInsertSensorInfoRequest().addNewInfoToBeInserted()
                .setSensorDescription(DOC.getSensorML().getMemberArray(0).getProcess());

        XmlObject res = this.client.xSendPostRequest(req);

        InsertSensorInfoResponseDocument resp = InsertSensorInfoResponseDocument.Factory
                .parse(res.getDomNode());
        if (resp.getInsertSensorInfoResponse().getNumberOfInsertedSensors() < 1)
            System.out.println("Failed to insert sensor");

        /*
         * Insert into apache solr
         */
        // SOLRInsertSensorInfoDAO dao = new SOLRInsertSensorInfoDAO();
        // dao.insertSensor(sensor);
    }

}

From source file:org.n52.oss.testdata.json.DummySensorGenerator.java

@Test
public void parseJsonSensorsAndInsert() throws IOException, OwsExceptionReport, XmlException, HttpException {

    File sensor_file = new File(ClassLoader.getSystemResource("data/randomSensors.json").getFile());
    File sensor_temp = new File(ClassLoader.getSystemResource("AirBase-test.xml").getFile());
    SensorMLDocument DOC = SensorMLDocument.Factory.parse(sensor_temp);
    Gson gson = new Gson();
    StringBuilder builder = new StringBuilder();
    String s;//from w  w w  .j  av  a2 s  .c  o  m
    try (BufferedReader reader = new BufferedReader((new FileReader(sensor_file)));) {
        while ((s = reader.readLine()) != null)
            builder.append(s);
    }

    JSONSensorsCollection collection = gson.fromJson(builder.toString(), JSONSensorsCollection.class);
    Iterator<JSONSensor> sensors = collection.sensors.iterator();
    while (sensors.hasNext()) {
        SirSensor sensor = new SirSensor();
        JSONSensor jsensor = sensors.next();
        sensor.setKeywords(jsensor.keywords);
        SirTimePeriod period = new SirTimePeriod();
        DateTime begin = DateTime.parse(jsensor.beginPosition);
        DateTime end = DateTime.parse(jsensor.endPosition);
        // fix because we need start < end , and the data is randomly
        // generated
        if (begin.getMillis() > end.getMillis()) {
            DateTime temp = begin;
            end = begin;
            begin = temp;
        }
        period.setStartTime(begin.toDate());
        period.setEndTime(end.toDate());
        sensor.setTimePeriod(period);
        sensor.setIdentificationsList(jsensor.Identifiers);
        List<String> contacts = new ArrayList<>();
        contacts.add(jsensor.contacts);
        sensor.setContacts(contacts);

        /*
         * Add to SIRPQSQL
         */
        KeywordList klist = KeywordList.Factory.newInstance();
        klist.setKeywordArray(jsensor.keywords.toArray(new String[] {}));
        DOC.getSensorML().getMemberArray(0).getProcess().getKeywordsArray(0).setKeywordList(klist);
        InsertSensorInfoRequestDocument req = InsertSensorInfoRequestDocument.Factory.newInstance();
        req.addNewInsertSensorInfoRequest().addNewInfoToBeInserted()
                .setSensorDescription(DOC.getSensorML().getMemberArray(0).getProcess());

        XmlObject res = this.client.xSendPostRequest(req);

        InsertSensorInfoResponseDocument resp = InsertSensorInfoResponseDocument.Factory
                .parse(res.getDomNode());
        assertNotEquals("Failed to insert sensor",
                resp.getInsertSensorInfoResponse().getNumberOfInsertedSensors(), 0);
        /*
         * Insert into apache solr
         */
        // SOLRInsertSensorInfoDAO dao = new SOLRInsertSensorInfoDAO();
        // dao.insertSensor(sensor);
    }

}

From source file:org.n52.sir.IT.HarvestScheduleIT.java

@Before
public void uploadAFileAndRetrieveScriptId() throws ClientProtocolException, IOException {
    File harvestScript = new File(ClassLoader.getSystemResource("Requests/randomSensor.js").getFile());
    PostMethod method = new PostMethod("http://localhost:8080/OpenSensorSearch/script/submit");
    Part[] parts = new Part[] { new StringPart("user", "User"), new FilePart("file", harvestScript) };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
    MultipartEntity multipartEntity = new MultipartEntity();
    // upload the file
    multipartEntity.addPart("file", new FileBody(harvestScript));
    multipartEntity.addPart("user", new StringBody("User"));
    HttpPost post = new HttpPost("http://localhost:8080/OpenSensorSearch/script/submit");
    post.setEntity(multipartEntity);/*  ww  w.  ja v a2  s  .  co m*/
    org.apache.http.client.HttpClient client = new DefaultHttpClient();
    HttpResponse resp = client.execute(post);
    int responseCode = resp.getStatusLine().getStatusCode();

    assertEquals(responseCode, 200);
    StringBuilder response = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
    String s = null;
    while ((s = reader.readLine()) != null)
        response.append(s);

    int scriptId = Integer.parseInt(response.toString());

    System.setProperty(SCRIPT_ID, scriptId + "");
}

From source file:org.n52.sir.harvest.ScheduleBinding.java

public void testBinding() throws HttpException, IOException, InterruptedException, SolrServerException {
    File harvestScript = new File(ClassLoader.getSystemResource("Requests/randomSensor.js").getFile());
    PostMethod method = new PostMethod("http://localhost:8080/SIR/harvest/script/submit");
    Part[] parts = new Part[] { new StringPart("user", "testUser"), new FilePart("file", harvestScript) };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
    MultipartEntity multipartEntity = new MultipartEntity();
    //upload the file
    multipartEntity.addPart("file", new FileBody(harvestScript));
    multipartEntity.addPart("user", new StringBody("testUserTest"));
    HttpPost post = new HttpPost("http://localhost:8080/SIR/harvest/script/submit");
    post.setEntity(multipartEntity);//  w  w  w  . j av a  2 s.  com
    org.apache.http.client.HttpClient client = new DefaultHttpClient();
    HttpResponse resp = client.execute(post);
    int responseCode = resp.getStatusLine().getStatusCode();

    assertEquals(responseCode, 200);

    StringBuilder response = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
    String s = null;
    while ((s = reader.readLine()) != null)
        response.append(s);

    int scriptId = Integer.parseInt(response.toString());

    //now do a scheduling

    StringBuilder scheduleRequest = new StringBuilder();
    scheduleRequest.append("http://localhost:8080/SIR/harvest/script/schedule");
    scheduleRequest.append("?id=");
    scheduleRequest.append(scriptId);
    Date d = new Date();
    scheduleRequest.append("&date=" + (d.getTime() + (10 * 1000)));

    HttpGet get = new HttpGet(scheduleRequest.toString());
    resp = new DefaultHttpClient().execute(get);

    assertEquals(resp.getStatusLine().getStatusCode(), 200);

    Thread.sleep(10 * 1000);

    SOLRSearchSensorDAO DAO = new SOLRSearchSensorDAO();
    Collection<SirSearchResultElement> results = DAO.searchByContact(randomString);

    assertTrue(results.size() > 0);

    new SolrConnection().deleteByQuery("contacts:" + randomString);
}

From source file:org.n52.oss.IT.harvest.ScheduleBinding.java

public void testBinding() throws HttpException, IOException, InterruptedException, SolrServerException {
    File harvestScript = new File(ClassLoader.getSystemResource("Requests/randomSensor.js").getFile());
    PostMethod method = new PostMethod("http://localhost:8080/SIR/harvest/script/submit");
    Part[] parts = new Part[] { new StringPart("user", "testUser"), new FilePart("file", harvestScript) };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
    MultipartEntity multipartEntity = new MultipartEntity();
    //upload the file
    multipartEntity.addPart("file", new FileBody(harvestScript));
    multipartEntity.addPart("user", new StringBody("testUserTest"));
    HttpPost post = new HttpPost("http://localhost:8080/SIR/harvest/script/submit");
    post.setEntity(multipartEntity);//ww  w  . ja va  2s .  c o m
    org.apache.http.client.HttpClient client = new DefaultHttpClient();
    HttpResponse resp = client.execute(post);
    int responseCode = resp.getStatusLine().getStatusCode();

    assertEquals(responseCode, 200);

    StringBuilder response = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
    String s = null;
    while ((s = reader.readLine()) != null)
        response.append(s);

    int scriptId = Integer.parseInt(response.toString());

    //now do a scheduling

    StringBuilder scheduleRequest = new StringBuilder();
    scheduleRequest.append("http://localhost:8080/SIR/harvest/script/schedule");
    scheduleRequest.append("?id=");
    scheduleRequest.append(scriptId);
    Date d = new Date();
    scheduleRequest.append("&date=" + (d.getTime() + (10 * 1000)));

    HttpGet get = new HttpGet(scheduleRequest.toString());
    resp = new DefaultHttpClient().execute(get);

    assertEquals(resp.getStatusLine().getStatusCode(), 200);

    Thread.sleep(10 * 1000);

    SolrConnection c = new SolrConnection("http://localhost:8983/solr", 2000);
    SOLRSearchSensorDAO dao = new SOLRSearchSensorDAO(c);
    Collection<SirSearchResultElement> results = dao.searchByContact(randomString);

    assertTrue(results.size() > 0);

    // FIXME use transactional delete operation, or just use a mocked up database
    c.deleteSensor("contacts:" + randomString);
}