Example usage for java.lang ClassLoader getSystemResourceAsStream

List of usage examples for java.lang ClassLoader getSystemResourceAsStream

Introduction

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

Prototype

public static InputStream getSystemResourceAsStream(String name) 

Source Link

Document

Open for reading, a resource of the specified name from the search path used to load classes.

Usage

From source file:org.apache.james.jmap.model.MessageFactoryTest.java

@Test
public void attachmentsShouldBeEmptyWhenNone() throws Exception {
    MetaDataWithContent testMail = MetaDataWithContent.builder().uid(2).flags(new Flags(Flag.SEEN)).size(0)
            .internalDate(INTERNAL_DATE)
            .content(new ByteArrayInputStream(
                    IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("spamMail.eml"))))
            .attachments(ImmutableList.of()).mailboxId(MAILBOX_ID).messageId(MessageId.of("user|box|2"))
            .build();/*from ww  w . j  a v a  2 s. c o  m*/
    Message testee = messageFactory.fromMetaDataWithContent(testMail);
    assertThat(testee.getAttachments()).isEmpty();
}

From source file:org.apache.james.jmap.methods.integration.GetMessageListMethodTest.java

@Test
public void getMessageListReadFilterShouldWork() throws Exception {
    mailboxProbe.createMailbox(MailboxConstants.USER_NAMESPACE, username, "mailbox");

    ComposedMessageId messageNotRead = mailboxProbe.appendMessage(username,
            new MailboxPath(MailboxConstants.USER_NAMESPACE, username, "mailbox"),
            new ByteArrayInputStream("Subject: test\r\n\r\ntestmail".getBytes()), new Date(), false,
            new Flags());
    ComposedMessageId messageRead = mailboxProbe.appendMessage(username,
            new MailboxPath(MailboxConstants.USER_NAMESPACE, username, "mailbox"),
            ClassLoader.getSystemResourceAsStream("eml/twoAttachments.eml"), new Date(), false,
            new Flags(Flags.Flag.SEEN));

    await();/*from  w w w.j  a  v  a 2  s .c  o  m*/

    given().header("Authorization", accessToken.serialize())
            .body("[[\"getMessageList\", {\"filter\":{\"isUnread\":\"false\"}}, \"#0\"]]").when().post("/jmap")
            .then().statusCode(200).body(NAME, equalTo("messageList"))
            .body(ARGUMENTS + ".messageIds", allOf(containsInAnyOrder(messageRead.getMessageId().serialize()),
                    not(containsInAnyOrder(messageNotRead.getMessageId().serialize()))));
}

From source file:org.apache.usergrid.cassandra.CassandraResource.java

/**
 * Starts up Cassandra before TestSuite or test Class execution.
 *
 * @throws Throwable if we cannot start up Cassandra
 *///w w w.  j a  v a  2s .  co m
@Override
protected void before() throws Throwable {
    /*
     * Note that the lock is static so it is JVM wide which prevents other
     * instances of this class from making changes to the Cassandra system
     * properties while we are initializing Cassandra with unique settings.
     */

    synchronized (lock) {
        super.before();

        if (isReady()) {
            return;
        }

        LOG.info("Initializing Cassandra at {} ...", tempDir.toString());

        // Create temp directory, setup to create new File configuration there
        File newYamlFile = new File(tempDir, "cassandra.yaml");
        URL newYamlUrl = FileUtils.toURLs(new File[] { newYamlFile })[0];

        // Read the original yaml file, make changes, and dump to new position in tmpdir
        Yaml yaml = new Yaml();
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (Map<String, Object>) yaml
                .load(ClassLoader.getSystemResourceAsStream("cassandra.yaml"));
        map.put(RPC_PORT_KEY, getRpcPort());
        map.put(STORAGE_PORT_KEY, getStoragePort());
        map.put(SSL_STORAGE_PORT_KEY, getSslStoragePort());
        map.put(NATIVE_TRANSPORT_PORT_KEY, getNativeTransportPort());
        map.put(COMMIT_FILE_DIR_KEY, new File(tempDir, "commitlog").toString());
        map.put(DATA_FILE_DIR_KEY, new String[] { new File(tempDir, "data").toString() });
        map.put(SAVED_CACHES_DIR_KEY, new File(tempDir, "saved_caches").toString());
        FileWriter writer = new FileWriter(newYamlFile);
        yaml.dump(map, writer);
        writer.flush();
        writer.close();

        // Fire up Cassandra by setting configuration to point to new yaml file
        System.setProperty("cassandra.url", "localhost:" + Integer.toString(rpcPort));
        System.setProperty("cassandra-foreground", "true");
        System.setProperty("log4j.defaultInitOverride", "true");
        System.setProperty("log4j.configuration", "log4j.properties");
        System.setProperty("cassandra.ring_delay_ms", "100");
        System.setProperty("cassandra.config", newYamlUrl.toString());

        //while ( !AvailablePortFinder.available( rpcPort ) || rpcPort == 9042 ) {
        // why previously has a or condition of rpc == 9042?
        while (!AvailablePortFinder.available(rpcPort)) {
            rpcPort++;
        }

        while (!AvailablePortFinder.available(storagePort)) {
            storagePort++;
        }

        while (!AvailablePortFinder.available(sslStoragePort)) {
            sslStoragePort++;
        }

        while (!AvailablePortFinder.available(nativeTransportPort)) {
            nativeTransportPort++;
        }

        System.setProperty("cassandra." + RPC_PORT_KEY, Integer.toString(rpcPort));
        System.setProperty("cassandra." + STORAGE_PORT_KEY, Integer.toString(storagePort));
        System.setProperty("cassandra." + SSL_STORAGE_PORT_KEY, Integer.toString(sslStoragePort));
        System.setProperty("cassandra." + NATIVE_TRANSPORT_PORT_KEY, Integer.toString(nativeTransportPort));

        LOG.info(
                "before() test, setting system properties for ports : [rpc, storage, sslStoage, native] = [{}, {}, {}, {}]",
                new Object[] { rpcPort, storagePort, sslStoragePort, nativeTransportPort });
        if (!newYamlFile.exists()) {
            throw new RuntimeException("Cannot find new Yaml file: " + newYamlFile);
        }

        cassandraDaemon = new CassandraDaemon();
        cassandraDaemon.activate();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                after();
            }
        });

        String[] locations = { "usergrid-test-context.xml" };
        applicationContext = new ClassPathXmlApplicationContext(locations);

        loadSchemaManager(schemaManagerName);
        initialized = true;
        LOG.info("External Cassandra resource at {} is ready!", tempDir.toString());
        lock.notifyAll();
    }
}

From source file:org.phenotips.vocabulary.internal.GeneNomenclatureTest.java

@Test
public void getTermsFetchesFromRemoteServer()
        throws ComponentLookupException, URISyntaxException, ClientProtocolException, IOException {
    URI expectedURI1 = new URI("http://rest.genenames.org/fetch/symbol/BRCA1");
    URI expectedURI2 = new URI("http://rest.genenames.org/fetch/symbol/NOTHING");
    CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
    when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
    when(this.response.getEntity()).thenReturn(this.responseEntity);
    when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("BRCA1.json"),
            ClassLoader.getSystemResourceAsStream("NOTHING.json"));
    Set<VocabularyTerm> result = this.mocker.getComponentUnderTest()
            .getTerms(Arrays.asList("BRCA1", "NOTHING"));
    List<HttpUriRequest> calledURIs = reqCapture.getAllValues();
    Assert.assertEquals(expectedURI1, calledURIs.get(0).getURI());
    Assert.assertEquals(expectedURI2, calledURIs.get(1).getURI());
    Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
    Assert.assertEquals(1, result.size());
    Assert.assertEquals("BRCA1", result.iterator().next().getId());
}

From source file:org.phenotips.ontology.internal.GeneNomenclatureTest.java

@Test
public void getTermsFetchesFromRemoteServer()
        throws ComponentLookupException, URISyntaxException, ClientProtocolException, IOException {
    URI expectedURI1 = new URI("http://rest.genenames.org/fetch/symbol/BRCA1");
    URI expectedURI2 = new URI("http://rest.genenames.org/fetch/symbol/NOTHING");
    CapturingMatcher<HttpUriRequest> reqCapture = new CapturingMatcher<>();
    when(this.client.execute(Matchers.argThat(reqCapture))).thenReturn(this.response);
    when(this.response.getEntity()).thenReturn(this.responseEntity);
    when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("BRCA1.json"),
            ClassLoader.getSystemResourceAsStream("NOTHING.json"));
    Set<OntologyTerm> result = this.mocker.getComponentUnderTest().getTerms(Arrays.asList("BRCA1", "NOTHING"));
    List<HttpUriRequest> calledURIs = reqCapture.getAllValues();
    Assert.assertEquals(expectedURI1, calledURIs.get(0).getURI());
    Assert.assertEquals(expectedURI2, calledURIs.get(1).getURI());
    Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
    Assert.assertEquals(1, result.size());
    Assert.assertEquals("BRCA1", result.iterator().next().getId());
}

From source file:org.apache.james.mailbox.elasticsearch.json.MessageToElasticSearchJsonTest.java

@Test
public void emailWithNoInternalDateShouldUseNowDate() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"), IndexAttachments.YES);
    MailboxMessage mailWithNoInternalDate = new SimpleMailboxMessage(MESSAGE_ID, null, SIZE, BODY_START_OCTET,
            new SharedByteArrayInputStream(
                    IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("eml/recursiveMail.eml"))),
            new FlagsBuilder().add(Flags.Flag.DELETED, Flags.Flag.SEEN).add("debian", "security").build(),
            propertyBuilder, MAILBOX_ID);
    mailWithNoInternalDate.setModSeq(MOD_SEQ);
    mailWithNoInternalDate.setUid(UID);
    assertThatJson(messageToElasticSearchJson.convertToJson(mailWithNoInternalDate,
            ImmutableList.of(new MockMailboxSession("username").getUser()))).when(IGNORING_ARRAY_ORDER)
                    .when(IGNORING_VALUES)
                    .isEqualTo(IOUtils.toString(ClassLoader.getSystemResource("eml/recursiveMail.json")));
}

From source file:org.apache.jena.util.FileUtils.java

/**
 * Open an resource file for reading./*from   www  .  ja va 2 s .  c om*/
 */
public static InputStream openResourceFileAsStream(String filename) throws FileNotFoundException {
    InputStream is = ClassLoader.getSystemResourceAsStream(filename);
    if (is == null) {
        // Try local loader with absolute path
        is = FileUtils.class.getResourceAsStream("/" + filename);
        if (is == null) {
            // Try local loader, relative, just in case
            is = FileUtils.class.getResourceAsStream(filename);
            if (is == null) {
                // Can't find it on classpath, so try relative to current directory
                // Will throw security exception under and applet but there's not other choice left
                is = new FileInputStream(filename);
            }
        }
    }
    return is;
}

From source file:org.apache.tika.server.TikaResourceTest.java

@Test
public void testPDFOCRConfig() throws Exception {
    if (!new TesseractOCRParser().hasTesseract(new TesseractOCRConfig())) {
        return;/*  ww  w  . j  a va  2  s . c o  m*/
    }

    Response response = WebClient.create(endPoint + TIKA_PATH).type("application/pdf").accept("text/plain")
            .header(TikaResource.X_TIKA_PDF_HEADER_PREFIX + "OcrStrategy", "no_ocr")
            .put(ClassLoader.getSystemResourceAsStream("testOCR.pdf"));
    String responseMsg = getStringFromInputStream((InputStream) response.getEntity());
    assertTrue(responseMsg.trim().equals(""));

    response = WebClient.create(endPoint + TIKA_PATH).type("application/pdf").accept("text/plain")
            .header(TikaResource.X_TIKA_PDF_HEADER_PREFIX + "OcrStrategy", "ocr_only")
            .put(ClassLoader.getSystemResourceAsStream("testOCR.pdf"));
    responseMsg = getStringFromInputStream((InputStream) response.getEntity());
    assertContains("Happy New Year 2003!", responseMsg);

    //now try a bad value
    response = WebClient.create(endPoint + TIKA_PATH).type("application/pdf").accept("text/plain")
            .header(TikaResource.X_TIKA_PDF_HEADER_PREFIX + "OcrStrategy", "non-sense-value")
            .put(ClassLoader.getSystemResourceAsStream("testOCR.pdf"));
    assertEquals(500, response.getStatus());
}

From source file:com.bbva.kltt.apirest.core.util.FilesUtility.java

/**
 * Load file content from the classpath// w  ww . j a  v  a 2 s  .  co  m
 * @param location with the location
 * @return the input stream
 */
public static String loadFileContentFromClasspath(final String location) {
    InputStream inputStream = FilesUtility.class.getResourceAsStream(location);

    if (inputStream == null) {
        inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(location);
    }

    if (inputStream == null) {
        inputStream = ClassLoader.getSystemResourceAsStream(location);
    }

    if (inputStream != null) {
        try {
            return IOUtils.toString(inputStream);
        } catch (IOException ioException) {
            final String errorString = "Could not read " + location + " from the classpath to get the content";

            FilesUtility.LOGGER.error(errorString, ioException);
            throw new RuntimeException(errorString, ioException);
        }
    }

    final String errorString = "Could not find " + location + " on the classpath to get the content";

    FilesUtility.LOGGER.error(errorString);
    throw new RuntimeException(errorString);
}

From source file:com.evolveum.midpoint.test.ldap.OpenDJController.java

/**
 * Extract template from class/*w ww  .j  a va 2  s  . co  m*/
 */
private void extractTemplate(File dst, String templateName) throws IOException, URISyntaxException {

    LOGGER.info("Extracting OpenDJ template....");
    if (!dst.exists()) {
        LOGGER.debug("Creating target dir {}", dst.getPath());
        dst.mkdirs();
    }

    templateRoot = new File(DATA_TEMPLATE_DIR, templateName);
    String templateRootPath = DATA_TEMPLATE_DIR + "/" + templateName; // templateRoot.getPath does not work on Windows, as it puts "\" into the path name (leading to problems with getSystemResource)

    // Determing if we need to extract from JAR or directory
    if (templateRoot.isDirectory()) {
        LOGGER.trace("Need to do directory copy.");
        MiscUtil.copyDirectory(templateRoot, dst);
        return;
    }

    LOGGER.debug("Try to localize OpenDJ Template in JARs as " + templateRootPath);

    URL srcUrl = ClassLoader.getSystemResource(templateRootPath);
    LOGGER.debug("srcUrl " + srcUrl);
    // sample:
    // file:/C:/.m2/repository/test-util/1.9-SNAPSHOT/test-util-1.9-SNAPSHOT.jar!/test-data/opendj.template
    // output:
    // /C:/.m2/repository/test-util/1.9-SNAPSHOT/test-util-1.9-SNAPSHOT.jar
    //
    // beware that in the URL there can be spaces encoded as %20, e.g.
    // file:/C:/Documents%20and%20Settings/user/.m2/repository/com/evolveum/midpoint/infra/test-util/2.1-SNAPSHOT/test-util-2.1-SNAPSHOT.jar!/test-data/opendj.template
    //
    if (srcUrl.getPath().contains("!/")) {
        URI srcFileUri = new URI(srcUrl.getPath().split("!/")[0]); // e.g. file:/C:/Documents%20and%20Settings/user/.m2/repository/com/evolveum/midpoint/infra/test-util/2.1-SNAPSHOT/test-util-2.1-SNAPSHOT.jar
        File srcFile = new File(srcFileUri);
        JarFile jar = new JarFile(srcFile);
        LOGGER.debug("Extracting OpenDJ from JAR file {} to {}", srcFile.getPath(), dst.getPath());

        Enumeration<JarEntry> entries = jar.entries();

        JarEntry e;
        byte buf[] = new byte[655360];
        while (entries.hasMoreElements()) {
            e = entries.nextElement();

            // skip other files
            if (!e.getName().contains(templateRootPath)) {
                continue;
            }

            // prepare destination file
            String filepath = e.getName().substring(templateRootPath.length());
            File dstFile = new File(dst, filepath);

            // test if directory
            if (e.isDirectory()) {
                LOGGER.debug("Create directory: {}", dstFile.getAbsolutePath());
                dstFile.mkdirs();
                continue;
            }

            LOGGER.debug("Extract {} to {}", filepath, dstFile.getAbsolutePath());
            // Find file on classpath
            InputStream is = ClassLoader.getSystemResourceAsStream(e.getName());
            // InputStream is = jar.getInputStream(e); //old way

            // Copy content
            OutputStream out = new FileOutputStream(dstFile);
            int len;
            while ((len = is.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.close();
            is.close();
        }
        jar.close();
    } else {
        try {
            File file = new File(srcUrl.toURI());
            File[] files = file.listFiles();
            for (File subFile : files) {
                if (subFile.isDirectory()) {
                    MiscUtil.copyDirectory(subFile, new File(dst, subFile.getName()));
                } else {
                    MiscUtil.copyFile(subFile, new File(dst, subFile.getName()));
                }
            }
        } catch (Exception ex) {
            throw new IOException(ex);
        }
    }
    LOGGER.debug("OpenDJ Extracted");
}