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:fr.gael.dhus.server.http.webapp.search.controller.SearchController.java

/**
 * Provides the openSearch description file via /search/description API.
 *
 * @param res response//from w  w w  . j  a v  a2 s. co  m
 * @throws IOException if file description cannot be accessed
 */
@PreAuthorize("hasRole('ROLE_SEARCH')")
@RequestMapping(value = "/description")
public void search(HttpServletResponse res) throws IOException {
    String url = configurationManager.getServerConfiguration().getExternalUrl();
    if (url != null && url.endsWith("/")) {
        url = url.substring(0, url.length() - 1);
    }

    String long_name = configurationManager.getNameConfiguration().getLongName();
    String short_name = configurationManager.getNameConfiguration().getShortName();
    String contact_mail = configurationManager.getSupportConfiguration().getMail();

    InputStream is = ClassLoader.getSystemResourceAsStream(DESCRIPTION_FILE);
    if (is == null) {
        throw new IOException("Cannot find \"" + DESCRIPTION_FILE + "\" OpenSearch description file.");
    }

    LineIterator li = IOUtils.lineIterator(is, "UTF-8");

    try (ServletOutputStream os = res.getOutputStream()) {
        while (li.hasNext()) {
            String line = li.next();
            // Last line? -> the iterator eats LF
            if (li.hasNext()) {
                line = line + "\n";
            }

            line = line.replace("[dhus_server]", url);
            if (long_name != null) {
                line = line.replace("[dhus_long_name]", long_name);
            }
            if (short_name != null) {
                line = line.replace("[dhus_short_name]", short_name);
            }
            if (contact_mail != null) {
                line = line.replace("[dhus_contact_mail]", contact_mail);
            }

            os.write(line.getBytes());
        }
    } finally {
        IOUtils.closeQuietly(is);
        LineIterator.closeQuietly(li);
    }
}

From source file:org.dhatim.util.ClassUtil.java

/**
 * Get the specified resource as a stream.
 *
 * @param resourceName The name of the class to load.
 * @param classLoader The ClassLoader to use, if the resource is not located via the
  * Thread context ClassLoader.//from w  w w.j  av a 2  s. c  om
 * @return The input stream for the resource or null if not found.
 */
public static InputStream getResourceAsStream(final String resourceName, final ClassLoader classLoader) {
    final ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader();
    final String resource;

    if (resourceName.startsWith("/")) {
        resource = resourceName.substring(1);
    } else {
        resource = resourceName;
    }

    if (threadClassLoader != null) {
        final InputStream is = threadClassLoader.getResourceAsStream(resource);
        if (is != null) {
            return is;
        }
    }

    if (classLoader != null) {
        final InputStream is = classLoader.getResourceAsStream(resource);
        if (is != null) {
            return is;
        }
    }

    return ClassLoader.getSystemResourceAsStream(resource);
}

From source file:com.linkedin.thirdeye.hadoop.derivedcolumn.transformation.DerivedColumnTransformationTest.java

private void resetAvroSerialization() throws IOException {
    Configuration conf = mapDriver.getConfiguration();
    conf.set("io.serializations", "org.apache.hadoop.io.serializer.JavaSerialization,"
            + "org.apache.hadoop.io.serializer.WritableSerialization");
    Schema outputSchema = new Schema.Parser()
            .parse(ClassLoader.getSystemResourceAsStream(TRANSFORMATION_SCHEMA));

    String[] currentSerializations = conf.getStrings(HADOOP_IO_SERIALIZATION);
    String[] finalSerializations = new String[currentSerializations.length + 1];
    System.arraycopy(currentSerializations, 0, finalSerializations, 0, currentSerializations.length);
    finalSerializations[finalSerializations.length - 1] = AvroSerialization.class.getName();
    mapDriver.getConfiguration().setStrings(HADOOP_IO_SERIALIZATION, finalSerializations);

    AvroSerialization.addToConfiguration(conf);
    AvroSerialization.setKeyWriterSchema(conf, outputSchema);
    AvroSerialization.setValueWriterSchema(conf, Schema.create(Schema.Type.NULL));

}

From source file:com.linkedin.thirdeye.hadoop.derivedcolumn.transformation.DerivedColumnNoTransformationTest.java

private void resetAvroSerialization() throws IOException {
    Configuration conf = mapDriver.getConfiguration();
    conf.set("io.serializations", "org.apache.hadoop.io.serializer.JavaSerialization,"
            + "org.apache.hadoop.io.serializer.WritableSerialization");
    Schema outputSchema = new Schema.Parser()
            .parse(ClassLoader.getSystemResourceAsStream(NO_TRANSFORMATION_SCHEMA));

    String[] currentSerializations = conf.getStrings(HADOOP_IO_SERIALIZATION);
    String[] finalSerializations = new String[currentSerializations.length + 1];
    System.arraycopy(currentSerializations, 0, finalSerializations, 0, currentSerializations.length);
    finalSerializations[finalSerializations.length - 1] = AvroSerialization.class.getName();
    mapDriver.getConfiguration().setStrings(HADOOP_IO_SERIALIZATION, finalSerializations);

    AvroSerialization.addToConfiguration(conf);
    AvroSerialization.setKeyWriterSchema(conf, outputSchema);
    AvroSerialization.setValueWriterSchema(conf, Schema.create(Schema.Type.NULL));

}

From source file:org.evosuite.junit.DetermineSUT.java

public Set<String> determineCalledClasses(String fullyQualifiedTargetClass, Set<String> targetClasses)
        throws ClassNotFoundException, NoJUnitClassException {
    Set<String> calledClasses = new HashSet<String>();

    String className = fullyQualifiedTargetClass.replace('.', '/');
    try {/*from   w w w  .  j av  a 2 s .co  m*/

        InputStream is = ClassLoader.getSystemResourceAsStream(className + ".class");
        if (is == null) {
            throw new ClassNotFoundException("Class '" + className + ".class"
                    + "' should be in target project, but could not be found!");
        }
        ClassReader reader = new ClassReader(is);
        ClassNode classNode = new ClassNode();
        reader.accept(classNode, ClassReader.SKIP_FRAMES);
        superClasses = getSuperClasses(classNode);

        if (isJUnitTest(classNode)) {
            handleClassNode(calledClasses, classNode, targetClasses);
        } else {
            throw new NoJUnitClassException();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    calledClasses.remove("java.lang.Object");
    calledClasses.remove(fullyQualifiedTargetClass);

    return calledClasses;
}

From source file:abs.backend.erlang.ErlApp.java

private void copyRuntime() throws IOException {
    InputStream is = null;/*from www  .  j  ava2s . c o m*/
    // TODO: this only works when the erlang compiler is invoked
    // from a jar file.  See http://stackoverflow.com/a/2993908 on
    // how to handle the other case.
    URLConnection resource = getClass().getResource("").openConnection();
    try {
        for (String f : RUNTIME_FILES) {
            if (f.endsWith("/*")) {
                String dirname = f.substring(0, f.length() - 2);
                String inname = RUNTIME_PATH + dirname;
                String outname = destDir + "/" + dirname;
                new File(outname).mkdirs();
                if (resource instanceof JarURLConnection) {
                    copyJarDirectory(((JarURLConnection) resource).getJarFile(), inname, outname);
                } else if (resource instanceof FileURLConnection) {
                    /* stolz: This at least works for the unit tests from within Eclipse */
                    File file = new File("src");
                    assert file.exists();
                    FileUtils.copyDirectory(new File("src/" + RUNTIME_PATH), destDir);
                } else {
                    throw new UnsupportedOperationException("File type: " + resource);
                }

            } else {
                is = ClassLoader.getSystemResourceAsStream(RUNTIME_PATH + f);
                if (is == null)
                    throw new RuntimeException("Could not locate Runtime file:" + f);
                String outputFile = f.replace('/', File.separatorChar);
                File file = new File(destDir, outputFile);
                file.getParentFile().mkdirs();
                ByteStreams.copy(is, Files.newOutputStreamSupplier(file));
            }
        }
    } finally {
        if (is != null)
            is.close();
    }
    for (String f : EXEC_FILES) {
        new File(destDir, f).setExecutable(true, false);
    }
}

From source file:org.apache.james.mailbox.tika.TikaTextExtractorTest.java

@Test
public void slidePowerPointTest() throws Exception {
    InputStream inputStream = ClassLoader.getSystemResourceAsStream("documents/slides.pptx");
    assertThat(inputStream).isNotNull();
    assertThat(textExtractor/*from w  ww .  j ava  2 s. c o  m*/
            .extractContent(inputStream,
                    "application/vnd.openxmlformats-officedocument.presentationml.presentation")
            .getTextualContent()).contains("James is awesome\nIt manages attachments so well!\n\n\n");
}

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

@Given("^\"([^\"]*)\" mailbox \"([^\"]*)\" contains a message \"([^\"]*)\" with an attachment \"([^\"]*)\"$")
public void appendMessageWithAttachmentToMailbox(String user, String mailbox, String messageId,
        String attachmentId) throws Throwable {
    MailboxPath mailboxPath = new MailboxPath(MailboxConstants.USER_NAMESPACE, user, mailbox);

    mainStepdefs.jmapServer.serverProbe().appendMessage(user, mailboxPath,
            ClassLoader.getSystemResourceAsStream("eml/oneAttachment.eml"), new Date(), false, new Flags());

    attachmentsByMessageId.put(messageId, attachmentId);
    blobIdByAttachmentId.put(attachmentId, "4000c5145f633410b80be368c44e1c394bff9437");
}

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

@Test
public void testDocWAVText() throws Exception {
    Response response = WebClient.create(endPoint + ALL_PATH).type(APPLICATION_MSWORD).accept("application/zip")
            .put(ClassLoader.getSystemResourceAsStream(TEST_DOC_WAV));

    Map<String, String> data = readZipArchive((InputStream) response.getEntity());
    assertEquals(WAV1_MD5, data.get(WAV1_NAME));
    assertEquals(WAV2_MD5, data.get(WAV2_NAME));
    assertTrue(data.containsKey(UnpackerResource.TEXT_FILENAME));
}

From source file:fr.gael.dhus.server.http.webapp.solr.SolrWebapp.java

@Override
public void afterPropertiesSet() throws Exception {
    try {//from ww w .jav a 2s .  co m
        SolrConfiguration solr = configurationManager.getSolrConfiguration();

        File solrroot = new File(solr.getPath());
        System.setProperty("solr.solr.home", solrroot.getAbsolutePath());

        if (Boolean.getBoolean("dhus.solr.reindex")) {
            // reindexing
            try {
                LOGGER.info("Reindex: deleting " + solrroot);
                FileUtils.deleteDirectory(solrroot);
            } catch (IllegalArgumentException | IOException ex) {
                LOGGER.error("Cannot delete solr root directory " + ex.getMessage());
            }
        }

        File libdir = new File(solrroot, "lib");
        libdir.mkdirs();
        File coredir = new File(solrroot, "dhus");
        coredir.mkdirs();
        File confdir = new File(coredir, "conf");

        // Move old data/conf dirs if any
        File olddata = new File(solrroot, "data/dhus");
        if (olddata.exists()) {
            File newdata = new File(coredir, "data");
            olddata.renameTo(newdata);
        }
        File oldconf = new File(solrroot, "conf");
        if (oldconf.exists()) {
            oldconf.renameTo(confdir);
        }
        confdir.mkdirs();

        // Rename old `schema.xml` file to `managed-schema`
        File schemafile = new File(confdir, "managed-schema");
        File oldschema = new File(confdir, "schema.xml");
        if (oldschema.exists()) {
            oldschema.renameTo(schemafile);
        }

        // solr.xml
        InputStream input = ClassLoader
                .getSystemResourceAsStream("fr/gael/dhus/server/http/webapp/solr/cfg/solr.xml");
        OutputStream output = new FileOutputStream(new File(solrroot, "solr.xml"));
        IOUtils.copy(input, output);
        output.close();
        input.close();

        // dhus/core.properties
        input = ClassLoader
                .getSystemResourceAsStream("fr/gael/dhus/server/http/webapp/solr/cfg/core.properties");
        File core_props = new File(coredir, "core.properties");
        output = new FileOutputStream(core_props);
        IOUtils.copy(input, output);
        output.close();
        input.close();

        // dhus/solrconfig.xml
        input = ClassLoader
                .getSystemResourceAsStream("fr/gael/dhus/server/http/webapp/solr/cfg/solrconfig.xml");
        File solrconfigfile = new File(confdir, "solrconfig.xml");
        output = new FileOutputStream(solrconfigfile);
        IOUtils.copy(input, output);
        output.close();
        input.close();

        // dhus/schema.xml
        if (!schemafile.exists()) {
            String schemapath = solr.getSchemaPath();
            if ((schemapath == null) || ("".equals(schemapath)) || (!(new File(schemapath)).exists())) {
                input = ClassLoader
                        .getSystemResourceAsStream("fr/gael/dhus/server/http/webapp/solr/cfg/schema.xml");
            } else {
                input = new FileInputStream(new File(schemapath));
            }
            output = new FileOutputStream(schemafile);
            IOUtils.copy(input, output);
            output.close();
            input.close();
        }

        // dhus/stopwords.txt
        input = ClassLoader.getSystemResourceAsStream("fr/gael/dhus/server/http/webapp/solr/cfg/stopwords.txt");
        output = new FileOutputStream(new File(confdir, "stopwords.txt"));
        IOUtils.copy(input, output);
        output.close();
        input.close();

        // dhus/synonyms.txt
        String synonympath = solr.getSynonymPath();
        if ((synonympath == null) || ("".equals(synonympath)) || (!(new File(synonympath)).exists())) {
            input = ClassLoader
                    .getSystemResourceAsStream("fr/gael/dhus/server/http/webapp/solr/cfg/synonyms.txt");
        } else {
            input = new FileInputStream(new File(synonympath));
        }
        output = new FileOutputStream(new File(confdir, "synonyms.txt"));
        IOUtils.copy(input, output);
        output.close();
        input.close();

        // dhus/xslt/opensearch_atom.xsl
        input = ClassLoader
                .getSystemResourceAsStream("fr/gael/dhus/server/http/webapp/solr/cfg/xslt/opensearch_atom.xsl");
        if (input != null) {
            File xslt_dir = new File(confdir, "xslt");
            if (!xslt_dir.exists()) {
                xslt_dir.mkdirs();
            }
            output = new FileOutputStream(new File(xslt_dir, "opensearch_atom.xsl"));
            IOUtils.copy(input, output);
            output.close();
            input.close();
        } else {
            LOGGER.warn("Cannot file opensearch xslt file. " + "Opensearch interface is not available.");
        }

        // dhus/conf/suggest.dic
        try (InputStream in = ClassLoader.getSystemResourceAsStream("suggest.dic")) {
            File suggest_dict = new File(confdir, "suggest.dic");
            if (in != null) {
                LOGGER.info("Solr config file `suggest.dic` found");
                try (OutputStream out = new FileOutputStream(suggest_dict)) {
                    IOUtils.copy(in, out);
                }
            } else {
                LOGGER.warn("Solr config file `suggest.dic` not found");
                suggest_dict.createNewFile();
            }
        }

        solrInitializer.createSchema(coredir.toPath(), schemafile.getAbsolutePath());

    } catch (IOException e) {
        throw new UnsupportedOperationException("Cannot initialize Solr service.", e);
    }
}