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.methods.integration.GetMessageListMethodTest.java

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

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

    await();//from ww  w. ja v a  2s .c  om

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

From source file:org.eclipse.wst.wsi.internal.core.util.Utils.java

/**
* Get contents of a resource and return as a input stream.
*
* @param resourceName the name of the resource to get and return as
*                      an input stream./*from www  . j a  v  a 2 s  .  co m*/
* @return contents of a resource as an input stream.
* @throws IOException if the resource could not be located.
*/
public static InputStream getInputStream(String resourceName) throws IOException {
    InputStream is = null;

    // If resource reference is a URL, then input stream from URL
    try {
        // Try to create URL
        URL urlResource = new URL(resourceName);

        // If successful, then get URL input stream
        is = getInputStream(urlResource);
    }

    // Else try to read resource directly
    catch (MalformedURLException mue) {
        boolean bTryClassLoader = false;

        try {
            // Open file input stream
            is = new BufferedInputStream(new FileInputStream(resourceName));
        } catch (FileNotFoundException fnfe) {
            // Set try class loader flag
            bTryClassLoader = true;
        } catch (SecurityException se) {
            // Set try class loader flag
            bTryClassLoader = true;
        } catch (Exception e) {
            // DEBUG:
            System.out.println("Exception in getInputStream :" + e.toString());
        }

        // If try class loader, then use it to get input stream
        if (bTryClassLoader) {
            // Use class loader to load resource
            is = ClassLoader.getSystemResourceAsStream(resourceName);
        }
    }

    // If the input stream is null, then throw FileNotFoundException
    if (is == null) {
        //try this
        is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName);
    }

    // If the input stream is null, then throw FileNotFoundException
    if (is == null) {
        //try this
        URL aURL = Thread.currentThread().getContextClassLoader().getResource(resourceName);
        if (aURL != null)
            is = getInputStream(aURL);
    }

    if (is == null)
        // Throw execption
        throw new FileNotFoundException("Could not locate resource file: " + resourceName);

    // Return input stream
    return is;
}

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

@Test
public void testUnicodePasswordProtectedSpaces() throws Exception {
    //TIKA-2858/*from w  w w  .  j  a v  a 2  s.  c  om*/
    final String password = "    ";
    final String encoded = new Base64().encodeAsString(password.getBytes(StandardCharsets.UTF_8));
    Response response = WebClient.create(endPoint + TIKA_PATH).accept("text/plain")
            .header(TikaResource.PASSWORD_BASE64_UTF8, encoded)
            .put(ClassLoader.getSystemResourceAsStream("testPassword4Spaces.pdf"));
    String responseMsg = getStringFromInputStream((InputStream) response.getEntity());
    assertContains("Just some text.", responseMsg);
}

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

@Test
public void spamEmailShouldBeWellConvertedToJsonWithApacheTika() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new TikaTextExtractor(), ZoneId.of("Europe/Paris"), IndexAttachments.YES);
    MailboxMessage spamMail = new SimpleMailboxMessage(MESSAGE_ID, date, SIZE, BODY_START_OCTET,
            new SharedByteArrayInputStream(
                    IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("eml/nonTextual.eml"))),
            new Flags(), propertyBuilder, MAILBOX_ID);
    spamMail.setUid(UID);/*from ww  w .  j  a va  2 s . com*/
    spamMail.setModSeq(MOD_SEQ);
    assertThatJson(messageToElasticSearchJson.convertToJson(spamMail,
            ImmutableList.of(new MockMailboxSession("username").getUser()))).when(IGNORING_ARRAY_ORDER)
                    .isEqualTo(IOUtils.toString(ClassLoader.getSystemResource("eml/nonTextual.json"), CHARSET));
}

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

@Test
public void searchFetchesFromRemoteServer()
        throws ComponentLookupException, URISyntaxException, ClientProtocolException, IOException {
    URI expectedURI = new URI("http://rest.genenames.org/search/"
            + "+status%3A%28Approved%29+AND+%28+symbol%3A%28brcA*%29+alias_symbol%3A%28brcA*%29%29");
    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("brca.json"));
    Map<String, Object> search = new LinkedHashMap<>();
    search.put("status", "Approved");
    Map<String, String> subquery = new LinkedHashMap<>();
    subquery.put("symbol", "brcA*");
    subquery.put("alias_symbol", "brcA*");
    search.put("AND", subquery);
    Map<String, String> queryOptions = new LinkedHashMap<>();
    queryOptions.put("start", "3");
    queryOptions.put("rows", "2");
    List<VocabularyTerm> result = this.mocker.getComponentUnderTest().search(search, queryOptions);
    Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
    Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
    Assert.assertEquals(2, result.size());
    Iterator<VocabularyTerm> terms = result.iterator();
    Assert.assertEquals("BRCA1", terms.next().getId());
    Assert.assertEquals("BRCA1P1", terms.next().getId());
}

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

@Test
public void searchFetchesFromRemoteServer()
        throws ComponentLookupException, URISyntaxException, ClientProtocolException, IOException {
    URI expectedURI = new URI("http://rest.genenames.org/search/"
            + "+status%3A%28Approved%29+AND+%28+symbol%3A%28brcA*%29+alias_symbol%3A%28brcA*%29%29");
    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("brca.json"));
    Map<String, Object> search = new LinkedHashMap<>();
    search.put("status", "Approved");
    Map<String, String> subquery = new LinkedHashMap<>();
    subquery.put("symbol", "brcA*");
    subquery.put("alias_symbol", "brcA*");
    search.put("AND", subquery);
    Map<String, String> queryOptions = new LinkedHashMap<>();
    queryOptions.put("start", "3");
    queryOptions.put("rows", "2");
    Set<OntologyTerm> result = this.mocker.getComponentUnderTest().search(search, queryOptions);
    Assert.assertEquals(expectedURI, reqCapture.getLastValue().getURI());
    Assert.assertEquals("application/json", reqCapture.getLastValue().getLastHeader("Accept").getValue());
    Assert.assertEquals(2, result.size());
    Iterator<OntologyTerm> terms = result.iterator();
    Assert.assertEquals("BRCA1", terms.next().getId());
    Assert.assertEquals("BRCA1P1", terms.next().getId());
}

From source file:com.wallabystreet.kinjo.common.transport.ws.ServiceDescriptor.java

/**
 * Loads the WSDD of the described service, assuming that the file is stored
 * in the service package's folder with the file name
 * <ul>//from   ww  w  .ja va  2  s  . c o  m
 * <li><i>deploy.wsdd</i> for the deployment WSDD and</li>
 * <li><i>undeploy.wsdd</i> for the undeployment WSDD,</li>
 * </ul>
 * depending on the passed argument.
 * 
 * @param deploy
 *            Set this parameter to
 *            <ul>
 *            <li><code>true</code> for the <b>deployment</b> WSDD</li>
 *            <li><code>false</code> for the <b>undeployment</b> WSDD</li>
 *            </ul>
 * @return The (un)deployment WSDD of this service as an
 *         <code>org.w3c.dom.Element</code>
 * @throws MalformedServiceException,
 *             IIF the requested WSDD file is missing or invalid.
 * 
 * @see org.w3c.dom.Element
 */
private Element loadWSDD(boolean deploy) throws MalformedServiceException {
    // constants for the (un)deployment WSDD file names
    final String DEPLOY_WSDD_FILENAME = "deploy.wsdd";
    final String UNDEPLOY_WSDD_FILENAME = "undeploy.wsdd";

    String wsddFileName = null;
    if (deploy) {
        wsddFileName = DEPLOY_WSDD_FILENAME;
    } else {
        wsddFileName = UNDEPLOY_WSDD_FILENAME;
    }

    InputStream is = null;
    try {
        is = ClassLoader.getSystemResourceAsStream(pkg.replace('.', '/') + "/" + wsddFileName);
        return XMLUtils.newDocument(is).getDocumentElement();
    } catch (ParserConfigurationException e) {
        String msg = "parser instantiation failed";
        if (log.isErrorEnabled()) {
            log.error(msg, e);
        }
        throw new MalformedServiceException(msg, e);
    } catch (SAXException e) {
        String msg = "deployment descriptor has errors: " + this.pkg;
        if (log.isErrorEnabled()) {
            log.error(msg, e);
        }
        throw new MalformedServiceException(msg, e);
    } catch (IOException e) {
        String msg = "failed to find " + wsddFileName + " for service \"" + this.pkg + "\"";
        if (log.isErrorEnabled()) {
            log.error(msg, e);
        }
        throw new MalformedServiceException(msg, e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            if (log.isWarnEnabled()) {
                log.warn("InputStream.close() failed", e);
            }
        }
    }
}

From source file:org.apache.ambari.server.controller.utilities.PropertyHelper.java

private static Map<Resource.InternalType, Map<String, Map<String, PropertyInfo>>> readPropertyProviderIds(
        String filename) {/*from w w  w .  j  a v  a 2s  .  c om*/
    ObjectMapper mapper = new ObjectMapper();

    try {
        Map<Resource.InternalType, Map<String, Map<String, Metric>>> resourceMetricMap = mapper.readValue(
                ClassLoader.getSystemResourceAsStream(filename),
                new TypeReference<Map<Resource.InternalType, Map<String, Map<String, Metric>>>>() {
                });

        Map<Resource.InternalType, Map<String, Map<String, PropertyInfo>>> resourceMetrics = new HashMap<Resource.InternalType, Map<String, Map<String, PropertyInfo>>>();

        for (Map.Entry<Resource.InternalType, Map<String, Map<String, Metric>>> resourceEntry : resourceMetricMap
                .entrySet()) {
            Map<String, Map<String, PropertyInfo>> componentMetrics = new HashMap<String, Map<String, PropertyInfo>>();

            for (Map.Entry<String, Map<String, Metric>> componentEntry : resourceEntry.getValue().entrySet()) {
                Map<String, PropertyInfo> metrics = new HashMap<String, PropertyInfo>();

                for (Map.Entry<String, Metric> metricEntry : componentEntry.getValue().entrySet()) {
                    String property = metricEntry.getKey();
                    Metric metric = metricEntry.getValue();
                    PropertyInfo propertyInfo = new PropertyInfo(metric.getMetric(), metric.isTemporal(),
                            metric.isPointInTime());
                    propertyInfo.setAmsId(metric.getAmsId());
                    propertyInfo.setAmsHostMetric(metric.isAmsHostMetric());
                    propertyInfo.setUnit(metric.getUnit());
                    metrics.put(property, propertyInfo);
                }
                componentMetrics.put(componentEntry.getKey(), metrics);
            }
            if (REPORT_METRIC_RESOURCES.contains(resourceEntry.getKey())) {
                updateMetricsWithAggregateFunctionSupport(componentMetrics);
            }
            resourceMetrics.put(resourceEntry.getKey(), componentMetrics);
        }
        return resourceMetrics;
    } catch (IOException e) {
        throw new IllegalStateException("Can't read properties file " + filename, e);
    }
}

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

@Test
public void attachmentsShouldBeEmptyWhenNone() throws Exception {
    MailboxMessage testMail = new SimpleMailboxMessage(INTERNAL_DATE, 0, 0,
            new SharedByteArrayInputStream(
                    IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("spamMail.eml"))),
            new Flags(Flag.SEEN), new PropertyBuilder(), MAILBOX_ID);
    testMail.setModSeq(MOD_SEQ);//  w w w . j ava  2  s  . c  om
    Message testee = messageFactory.fromMailboxMessage(testMail, ImmutableList.of(),
            x -> MessageId.of("user|box|" + x));
    assertThat(testee.getAttachments()).isEmpty();
}

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

@Test
public void testUnicodePasswordProtectedUnicode() throws Exception {
    //TIKA-2858/* w w  w.ja v a2 s. c  o  m*/
    final String password = "  ! < > \" \\ \u20AC \u0153 \u00A4 \u0031\u2044\u0034 \u0031\u2044\u0032 \uD841\uDF0E \uD867\uDD98 \uD83D\uDE00  ";
    final String encoded = new Base64().encodeAsString(password.getBytes(StandardCharsets.UTF_8));
    Response response = WebClient.create(endPoint + TIKA_PATH).accept("text/plain")
            .header(TikaResource.PASSWORD_BASE64_UTF8, encoded)
            .put(ClassLoader.getSystemResourceAsStream("testUnicodePassword.pdf"));
    String responseMsg = getStringFromInputStream((InputStream) response.getEntity());
    assertContains("Just some text.", responseMsg);
}