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:shuffle.fwk.ShuffleController.java

/**
 * Sets the user home to the given path.
 * // w  w w .  j ava 2s  . c o  m
 * @param userHome
 *           The absolute path to the new user home.
 */
public static void setUserHome(String userHome) {
    try {
        File absoluteFile = new File(userHome).getCanonicalFile();
        absoluteFile.mkdir();
        System.setProperty("user.dir", absoluteFile.getCanonicalPath());
        System.setProperty("user.home", absoluteFile.getCanonicalPath());
        try (InputStream is = ClassLoader.getSystemResourceAsStream(LOG_CONFIG_FILE)) {
            File logDir = new File("log").getAbsoluteFile();
            if (!logDir.exists() && !logDir.mkdirs()) {
                throw new IOException("Cannot create log directory.");
            }
            LogManager.getLogManager().readConfiguration(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}

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

@Test
public void testText() throws Exception {
    Response response = WebClient.create(endPoint + ALL_PATH).header(CONTENT_TYPE, APPLICATION_XML)
            .accept("application/zip").put(ClassLoader.getSystemResourceAsStream("test.doc"));

    String responseMsg = readArchiveText((InputStream) response.getEntity());
    assertNotNull(responseMsg);//from   w  ww .j  a v  a 2  s  . c  om
    assertTrue(responseMsg.contains("test"));
}

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

@Test
public void getTermWithInvalidTermReturnsNull()
        throws ComponentLookupException, URISyntaxException, ClientProtocolException, IOException {
    URI expectedURI = 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("NOTHING.json"));
    VocabularyTerm result = this.mocker.getComponentUnderTest().getTerm("NOTHING");
    Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
    Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
    Assert.assertNull(result);/*from  w  ww  .j ava 2s . c  o m*/
    verify(this.cache).set("NOTHING", this.emptyMarker);
}

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

@Test
public void getTermWithInvalidTermReturnsNull()
        throws ComponentLookupException, URISyntaxException, ClientProtocolException, IOException {
    URI expectedURI = 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("NOTHING.json"));
    OntologyTerm result = this.mocker.getComponentUnderTest().getTerm("NOTHING");
    Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
    Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
    Assert.assertNull(result);/*from   www .  j a  v a 2 s.  c o m*/
    verify(this.cache).set("NOTHING", this.emptyMarker);
}

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

@Test
public void recursiveEmailShouldBeWellConvertedToJson() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"));
    MailboxMessage recursiveMail = new SimpleMailboxMessage(date, 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);
    recursiveMail.setModSeq(MOD_SEQ);/*from  ww  w.  j a  va2  s  .co  m*/
    recursiveMail.setUid(UID);
    assertThatJson(messageToElasticSearchJson.convertToJson(recursiveMail,
            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.openengsb.openticket.integrationtest.util.AbstractExamTestHelper.java

@Configuration
public static Option[] configuration() throws Exception {
    Option[] baseOptions = Helper.getDefaultOptions();
    /*/* ww w.j ava  2 s.  c  om*/
     * do not change the values for loglevel or debug here, but refer the comment at the top of the class for
     * further instructions
     */
    String loglevel = "WARN";
    boolean debug = false;
    InputStream paxLocalStream = ClassLoader.getSystemResourceAsStream("itests.local.properties");
    if (paxLocalStream != null) {
        Properties properties = new Properties();
        properties.load(paxLocalStream);
        loglevel = (String) ObjectUtils.defaultIfNull(properties.getProperty("loglevel"), loglevel);
        debug = ObjectUtils.equals(Boolean.TRUE.toString(), properties.getProperty("debug"));
    }

    if (debug) {
        baseOptions = combine(baseOptions, Helper.activateDebugging(Integer.toString(DEBUG_PORT)));
    }
    String targetpath = new File("target").getAbsolutePath();
    FileUtils.deleteDirectory(new File(targetpath, "karaf.data"));
    return combine(baseOptions, Helper.loadKarafStandardFeatures("config", "management"),
            Helper.setLogLevel(loglevel),
            mavenBundle(maven().groupId("org.apache.aries").artifactId("org.apache.aries.util")
                    .versionAsInProject()),
            mavenBundle(maven().groupId("org.apache.aries.proxy").artifactId("org.apache.aries.proxy")
                    .versionAsInProject()),
            mavenBundle(maven().groupId("org.apache.aries.blueprint").artifactId("org.apache.aries.blueprint")
                    .versionAsInProject()),
            scanFeatures(
                    maven().groupId("org.openengsb.openticket").artifactId("openticket").type("xml")
                            .classifier("features").versionAsInProject(),
                    "openengsb-connector-memoryauditing", "openengsb-ui-admin", "openticket-core"),
            workingDirectory(getWorkingDirectory()),
            vmOption("-Dorg.osgi.framework.system.packages.extra=com.sun.org.apache.xerces.internal.dom,"
                    + "com.sun.org.apache.xerces.internal.jaxp,org.apache.karaf.branding,sun.reflect"),
            vmOption("-Dorg.osgi.service.http.port=" + WEBUI_PORT),
            vmOption("-DrmiRegistryPort=" + RMI_REGISTRY_PORT), vmOption("-DrmiServerPort=" + RMI_SERVER_PORT),
            waitForFrameworkStartup(), vmOption("-Dkaraf.data=" + targetpath + "/karaf.data"),
            vmOption("-Dkaraf.home=" + targetpath + "/karaf.home"),
            vmOption("-Dkaraf.base=" + targetpath + "/karaf.base"),
            mavenBundle(maven().groupId("org.openengsb.wrapped").artifactId("net.sourceforge.htmlunit-all")
                    .versionAsInProject()),
            felix());
}

From source file:org.xframium.page.keyWord.provider.XMLKeyWordProvider.java

/**
 * Parses the imports.//from   w w w . j  a v a2  s.c o m
 *
 * @param importList the import list
 */
private void parseImports(List<Import> importList, SuiteContainer sC, boolean parseDataIterators) {
    for (Import imp : importList) {
        try {
            if (log.isInfoEnabled())
                log.info("Attempting to import file [" + Paths.get(".").toAbsolutePath().normalize().toString()
                        + imp.getFileName() + "]");
            if (imp.getFileName().toLowerCase().endsWith(".xml")) {
                InputStream inputStream = ClassLoader.getSystemResourceAsStream(imp.getFileName());
                if (inputStream == null)
                    readElements(sC, new FileInputStream(findFile(new File(imp.getFileName()))),
                            imp.isIncludeTests(), imp.isIncludeFunctions(), parseDataIterators);
                else
                    readElements(sC, inputStream, imp.isIncludeTests(), imp.isIncludeFunctions(),
                            parseDataIterators);
            } else if (imp.getFileName().toLowerCase().endsWith(".bdd")) {
                Parser bddParser = new Parser(new XMLFormatter(PageDataManager.instance().getDataProvider()));

                byte[] buffer = new byte[512];
                int bytesRead = 0;

                FileInputStream is = new FileInputStream(findFile(new File(imp.getFileName())));
                StringBuilder s = new StringBuilder();

                while ((bytesRead = is.read(buffer)) > 0) {
                    s.append(new String(buffer, 0, bytesRead));
                }

                is.close();

                bddParser.parse(s.toString(), "", 0);
            }
        } catch (Exception e) {
            log.fatal("Could not read from " + imp.getFileName(), e);
            throw new IllegalStateException(e);
        }
    }
}

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

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

    ComposedMessageId messageNotFlagged = 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 messageFlagged = mailboxProbe.appendMessage(username,
            new MailboxPath(MailboxConstants.USER_NAMESPACE, username, "mailbox"),
            ClassLoader.getSystemResourceAsStream("eml/twoAttachments.eml"), new Date(), false,
            new Flags(Flags.Flag.FLAGGED));

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

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

From source file:org.kuali.kfs.sys.batch.service.BatchInputServiceParseTest.java

/**
 * Verifies error occurs when an invalid tag is given.
 *///from w ww .ja va  2  s .c  o m
public final void DISABLED_testParse_invalidTag() throws Exception {
    InputStream fileContents = ClassLoader
            .getSystemResourceAsStream(TEST_BATCH_XML_DIRECTORY + "BatchInputInvalidTagCollector.xml");
    byte[] invalidTagCollectorContents = IOUtils.toByteArray(fileContents);

    boolean failedAsExpected = false;
    try {
        batchInputFileService.parse(collectorBatchInputFileType, invalidTagCollectorContents);
    } catch (ParseException e) {
        failedAsExpected = true;
    }

    assertTrue("parse exception not thrown for invalid tag", failedAsExpected);
}

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

@Test
public void testWMFInRTF() throws Exception {
    Response response = WebClient.create(endPoint + TIKA_PATH).type("application/rtf").accept("text/plain")
            .put(ClassLoader.getSystemResourceAsStream("testRTF_npeFromWMFInTikaServer.rtf"));
    String responseMsg = getStringFromInputStream((InputStream) response.getEntity());
    assertTrue(responseMsg.contains("Example text"));
}