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.mailbox.elasticsearch.json.MessageToElasticSearchJsonTest.java

@Test
public void convertToJsonWithoutAttachmentShouldConvertEmailBoby() throws IOException {
    // Given//  ww w .j a  v a2s . co  m
    MailboxMessage message = new SimpleMailboxMessage(MESSAGE_ID, null, SIZE, BODY_START_OCTET,
            new SharedByteArrayInputStream(IOUtils.toByteArray(
                    ClassLoader.getSystemResourceAsStream("eml/emailWithNonIndexableAttachment.eml"))),
            new FlagsBuilder().add(Flags.Flag.DELETED, Flags.Flag.SEEN).add("debian", "security").build(),
            propertyBuilder, MAILBOX_ID);
    message.setModSeq(MOD_SEQ);
    message.setUid(UID);

    // When
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"), IndexAttachments.NO);
    String convertToJsonWithoutAttachment = messageToElasticSearchJson.convertToJsonWithoutAttachment(message,
            ImmutableList.of(new MockMailboxSession("username").getUser()));

    // Then
    assertThatJson(convertToJsonWithoutAttachment).when(IGNORING_ARRAY_ORDER).when(IGNORING_VALUES)
            .isEqualTo(IOUtils.toString(ClassLoader
                    .getSystemResource("eml/emailWithNonIndexableAttachmentWithoutAttachment.json")));
}

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

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

    ComposedMessageId messageNotSeenNotFlagged = 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 messageNotSeenFlagged = mailboxProbe.appendMessage(username,
            new MailboxPath(MailboxConstants.USER_NAMESPACE, username, "mailbox"),
            ClassLoader.getSystemResourceAsStream("eml/twoAttachments.eml"), new Date(), false,
            new Flags(Flags.Flag.FLAGGED));
    ComposedMessageId messageSeenNotFlagged = mailboxProbe.appendMessage(username,
            new MailboxPath(MailboxConstants.USER_NAMESPACE, username, "mailbox"),
            ClassLoader.getSystemResourceAsStream("eml/oneInlinedImage.eml"), new Date(), false,
            new Flags(Flags.Flag.SEEN));
    ComposedMessageId messageSeenFlagged = mailboxProbe.appendMessage(username,
            new MailboxPath(MailboxConstants.USER_NAMESPACE, username, "mailbox"),
            ClassLoader.getSystemResourceAsStream("eml/oneInlinedImage.eml"), new Date(), false,
            FlagsBuilder.builder().add(Flags.Flag.SEEN, Flags.Flag.FLAGGED).build());

    await();/* w w w  . j av a2 s.com*/

    given().header("Authorization", accessToken.serialize()).body(
            "[[\"getMessageList\", {\"filter\":{\"operator\":\"AND\",\"conditions\":[{\"isFlagged\":\"true\"},{\"isUnread\":\"true\"}]}}, \"#0\"]]")
            .when().post("/jmap").then().statusCode(200).body(NAME, equalTo("messageList"))
            .body(ARGUMENTS + ".messageIds",
                    allOf(containsInAnyOrder(messageNotSeenFlagged.getMessageId().serialize()),
                            not(containsInAnyOrder(messageNotSeenNotFlagged.getMessageId().serialize(),
                                    messageSeenNotFlagged.getMessageId().serialize(),
                                    messageSeenFlagged.getMessageId().serialize()))));
}

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

/**
 * Uses a project.properties file that Maven does substitution on to to replace the value of a property with the
 * path to the Maven build directory (a.k.a. target). It then uses this path to generate a random String which it
 * uses to append a path component to so a unique directory is selected. If already present it's deleted, then the
 * directory is created.//from ww  w  . j a va 2 s . c o m
 *
 * @return a unique temporary directory
 *
 * @throws IOException if we cannot access the properties file
 */
public static File getTempDirectory() throws IOException {
    File tmpdir;
    Properties props = new Properties();
    props.load(ClassLoader.getSystemResourceAsStream(PROPERTIES_FILE));
    File basedir = new File((String) props.get(TARGET_DIRECTORY_KEY));
    String comp = RandomStringUtils.randomAlphanumeric(7);
    tmpdir = new File(basedir, comp);

    if (tmpdir.exists()) {
        LOG.info("Deleting directory: {}", tmpdir);
        FileUtils.forceDelete(tmpdir);
    } else {
        LOG.info("Creating temporary directory: {}", tmpdir);
        FileUtils.forceMkdir(tmpdir);
    }

    return tmpdir;
}

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

@Test
public void attachmentsShouldBeRetrievedWhenSome() 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 ww .  j av a  2s  . c  om

    String payload = "payload";
    BlobId blodId = BlobId.of("id1");
    String type = "content";
    Attachment expectedAttachment = Attachment.builder().blobId(blodId).size(payload.length()).type(type)
            .cid("cid").isInline(true).build();
    Message testee = messageFactory.fromMailboxMessage(testMail,
            ImmutableList.of(MessageAttachment.builder()
                    .attachment(org.apache.james.mailbox.store.mail.model.Attachment.builder()
                            .attachmentId(AttachmentId.from(blodId.getRawValue())).bytes(payload.getBytes())
                            .type(type).build())
                    .cid(Cid.from("cid")).isInline(true).build()),
            x -> MessageId.of("user|box|" + x));

    assertThat(testee.getAttachments()).hasSize(1);
    assertThat(testee.getAttachments().get(0)).isEqualToComparingFieldByField(expectedAttachment);
}

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

@Test
public void searchIgnoresBadOptions()
        throws ComponentLookupException, URISyntaxException, ClientProtocolException, IOException {
    when(this.client.execute(any(HttpUriRequest.class))).thenReturn(this.response);
    when(this.response.getEntity()).thenReturn(this.responseEntity);
    when(this.responseEntity.getContent()).thenReturn(ClassLoader.getSystemResourceAsStream("brca.json"));
    this.responseEntity.getContent().mark(5000);
    Map<String, Object> search = new LinkedHashMap<>();
    search.put("status", "Approved");
    Map<String, String> queryOptions = new LinkedHashMap<>();

    queryOptions.put("start", "three");
    queryOptions.put("rows", "");
    Assert.assertEquals(6, this.mocker.getComponentUnderTest().search(search, queryOptions).size());
    this.responseEntity.getContent().reset();

    queryOptions.put("start", "2");
    queryOptions.put("rows", "100");
    Assert.assertEquals(4, this.mocker.getComponentUnderTest().search(search, queryOptions).size());
    this.responseEntity.getContent().reset();

    queryOptions.put("start", "-2");
    queryOptions.put("rows", "-3");
    Assert.assertEquals(6, this.mocker.getComponentUnderTest().search(search, queryOptions).size());
}

From source file:org.kurento.test.browser.Browser.java

public InputStream getExtensionAsInputStream(String extension) {
    InputStream is = null;//w  w  w.ja  va  2s  .c o m

    try {
        log.debug("Trying to locate extension in the classpath ({}) ...", extension);
        is = ClassLoader.getSystemResourceAsStream(extension);
        if (is.available() < 0) {
            log.warn("Extension {} is not located in the classpath", extension);
            is = null;
        } else {
            log.debug("Success. Loading extension {} from classpath", extension);
        }
    } catch (Throwable t) {
        log.warn("Exception reading extension {} in the classpath ({} : {})", extension, t.getClass(),
                t.getMessage());
        is = null;
    }
    if (is == null) {
        try {
            log.debug("Trying to locate extension as URL ({}) ...", extension);
            URL url = new URL(extension);
            is = url.openStream();
            log.debug("Success. Loading extension {} from URL", extension);
        } catch (Throwable t) {
            log.warn("Exception reading extension {} as URL ({} : {})", extension, t.getClass(),
                    t.getMessage());
        }
    }
    if (is == null) {
        throw new RuntimeException(extension + " is not a valid extension (it is not located in project"
                + " classpath neither is a valid URL)");
    }
    return is;
}

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

/**
 * Loads the configuration of the described service, assuming that the file
 * is stored in the service package's folder with the file name
 * <i>properties.xml</i>. It is expected that the file corresponds to the
 * <a href="http://java.sun.com/dtd/properties.dtd">Java Property File DTD<a/>.
 * //from w ww . j  a va2s  .com
 * @return The configuration of this service as a
 *         <code>java.util.Properties</code> instance.
 * @throws MalformedServiceException,
 *             IIF the property file is missing or invalid.
 * 
 * @see java.util.Properties
 */
private Properties loadProperties() throws MalformedServiceException {
    // constant for the property file name
    final String PROPERTIES_FILENAME = "properties.xml";

    Properties p = new Properties();
    try {
        p.loadFromXML(
                ClassLoader.getSystemResourceAsStream(this.pkg.replace('.', '/') + "/" + PROPERTIES_FILENAME));

        /*
         * due to the stoopid implementation of
         * Properties#loadFromXML(InputStream), leading and trailing
         * whitespace of values is preserved; we have to fix this to prevent
         * ClassLoader#getSystemResource(String) and
         * ClassLoader#getSystemResourceAsStream(String) from wreckage.
         */
        Enumeration e = p.propertyNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            Object o = p.getProperty(key);
            if (o instanceof String) {
                String value = (String) o;
                p.setProperty(key, value.trim());
            }
        }

        /* return the demoronized result */
        return p;
    } catch (InvalidPropertiesFormatException e) {
        String msg = "invalid configuration file: " + this.pkg.replace('.', '/') + "/" + PROPERTIES_FILENAME;
        if (log.isErrorEnabled()) {
            log.error(msg, e);
        }
        throw new MalformedServiceException(msg, e);
    } catch (IOException e) {
        String msg = "could not open configuration file: " + this.pkg.replace('.', '/') + "/"
                + PROPERTIES_FILENAME;
        if (log.isErrorEnabled()) {
            log.error(msg, e);
        }
        throw new MalformedServiceException(msg, e);
    }
}

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

private static Map<Resource.InternalType, Set<String>> readPropertyIds(String filename) {
    ObjectMapper mapper = new ObjectMapper();

    try {/*from w  w w.  j  a va  2 s .c om*/
        return mapper.readValue(ClassLoader.getSystemResourceAsStream(filename),
                new TypeReference<Map<Resource.InternalType, Set<String>>>() {
                });
    } catch (IOException e) {
        throw new IllegalStateException("Can't read properties file " + filename, e);
    }
}

From source file:eu.tradegrid.tinkerpop.persistor.integration.java.TinkerpopModuleIntegrationTests.java

private JsonObject getResourceAsJson(String filename) {
    InputStream is = ClassLoader.getSystemResourceAsStream(filename);
    String jsonData = null;//from  w  ww.  j  a v a  2 s .  c  o  m
    try {
        jsonData = IOUtils.toString(is, "UTF-8");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return new JsonObject(jsonData);
}

From source file:phex.host.CaughtHostsContainer.java

/**
 * Loads the hosts file phex.hosts./*  w ww .j  av  a2 s.c  om*/
 */
private void loadHostsFromFile() {
    logger.debug("Loading hosts file.");
    try {
        File file = peer.getGnutellaNetwork().getHostsFile();
        BufferedReader br;
        if (file.exists()) {
            br = new BufferedReader(new FileReader(file));
        } else {
            logger.debug("Load default hosts file.");
            InputStream inStream = ClassLoader.getSystemResourceAsStream("phex/resources/phex.hosts");
            if (inStream != null) {
                br = new BufferedReader(new InputStreamReader(inStream));
            } else {
                logger.debug("Default Phex Hosts file not found.");
                return;
            }
        }

        long now = System.currentTimeMillis();
        PhexSecurityManager securityMgr = peer.getSecurityService();
        String line;
        short usedPriority = LOW_PRIORITY;
        while ((line = br.readLine()) != null) {
            if (line.startsWith("#")) {
                continue;
            }

            CaughtHost caughtHost = parseCaughtHostFromLine(line, now);
            if (caughtHost == null) {
                continue;
            }

            AccessType access = securityMgr.controlHostAddressAccess(caughtHost.getHostAddress());
            switch (access) {
            case ACCESS_DENIED:
            case ACCESS_STRONGLY_DENIED:
                // skip host address...
                continue;
            }
            if (IPUtils.isPortInUserInvalidList(caughtHost.getHostAddress())) {
                continue;
            }
            addPersistentCaughtHost(caughtHost);
            if (usedPriority != HIGH_PRIORITY && caughtHosts.isFull(usedPriority)) {
                // goes from lowest priority (0) to highest (2)
                usedPriority++;
            }
            addToCaughtHostFetcher(caughtHost, usedPriority);
        }
        br.close();
    } catch (IOException exp) {
        logger.warn(exp.toString(), exp);
    }
}