Example usage for java.lang ClassLoader getSystemResource

List of usage examples for java.lang ClassLoader getSystemResource

Introduction

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

Prototype

public static URL getSystemResource(String name) 

Source Link

Document

Find a resource of the specified name from the search path used to load classes.

Usage

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

@Test
public void spamEmailShouldBeWellConvertedToJsonWithApacheTika() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new TikaTextExtractor(), ZoneId.of("Europe/Paris"));
    MailboxMessage spamMail = new SimpleMailboxMessage(date, SIZE, BODY_START_OCTET,
            new SharedByteArrayInputStream(
                    IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("eml/nonTextual.eml"))),
            new Flags(), propertyBuilder, MAILBOX_ID);
    spamMail.setModSeq(MOD_SEQ);/* w  ww .  ja  v a 2  s .  c  o  m*/
    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.apache.james.adapter.mailbox.MailboxManagementTest.java

@Test
void importEmlFileToMailboxShouldNotImportEmlFileWithWrongPathToGivenMailbox() throws Exception {
    Mailbox mailbox = new SimpleMailbox(MailboxPath.forUser(USER, "name"), UID_VALIDITY);
    mapperFactory.createMailboxMapper(session).save(mailbox);
    String emlpath = ClassLoader.getSystemResource("eml/frnog.eml").getFile();
    mailboxManagerManagement.importEmlFileToMailbox(MailboxConstants.USER_NAMESPACE, USER, "name",
            "wrong_path" + emlpath);

    assertThat(mapperFactory.getMessageMapper(session).countMessagesInMailbox(mailbox)).isEqualTo(0);
    Iterator<MailboxMessage> iterator = mapperFactory.getMessageMapper(session).findInMailbox(mailbox,
            MessageRange.all(), MessageMapper.FetchType.Full, LIMIT);
    assertThat(iterator.hasNext()).isFalse();
}

From source file:org.jamwiki.utils.Utilities.java

/**
 * Given a file name for a file that is located somewhere in the application
 * classpath, return a File object representing the file.
 *
 * @param filename The name of the file (relative to the classpath) that is
 *  to be retrieved./*from www . ja va  2  s.  co  m*/
 * @return A file object representing the requested filename
 * @throws FileNotFoundException Thrown if the classloader can not be found or if
 *  the file can not be found in the classpath.
 */
public static File getClassLoaderFile(String filename) throws FileNotFoundException {
    // note that this method is used when initializing logging, so it must
    // not attempt to log anything.
    File file = null;
    ClassLoader loader = Utilities.getClassLoader();
    URL url = loader.getResource(filename);
    if (url == null) {
        url = ClassLoader.getSystemResource(filename);
    }
    if (url == null) {
        throw new FileNotFoundException("Unable to find " + filename);
    }
    file = FileUtils.toFile(url);
    if (file == null || !file.exists()) {
        try {
            // url exists but file cannot be read, so perhaps it's not a "file:" url (an example
            // would be a "jar:" url).  as a workaround, copy the file to a temp file and return
            // the temp file.
            file = File.createTempFile(filename, null);
            FileUtils.copyURLToFile(url, file);
        } catch (IOException e) {
            throw new FileNotFoundException("Unable to load file with URL " + url);
        }
    }
    return file;
}

From source file:org.ldp4j.rdf.query.QueryTest.java

private String loadResource(String resource) throws IOException {
    return IOUtils.toString(ClassLoader.getSystemResource(resource));
}

From source file:org.apache.ambari.server.stack.StackDirectory.java

/**
 * Parse role command order file/*from www  .ja  v a  2s.c  om*/
 */

private void parseRoleCommandOrder() {
    HashMap<String, Object> result = null;
    ObjectMapper mapper = new ObjectMapper();
    try {
        TypeReference<Map<String, Object>> rcoElementTypeReference = new TypeReference<Map<String, Object>>() {
        };
        if (rcoFilePath != null) {
            File file = new File(rcoFilePath);
            result = mapper.readValue(file, rcoElementTypeReference);
            LOG.info("Role command order info was loaded from file: {}", file.getAbsolutePath());
        } else {
            InputStream rcoInputStream = ClassLoader.getSystemResourceAsStream(ROLE_COMMAND_ORDER_FILE);
            result = mapper.readValue(rcoInputStream, rcoElementTypeReference);
            LOG.info("Role command order info was loaded from classpath: "
                    + ClassLoader.getSystemResource(ROLE_COMMAND_ORDER_FILE));
        }
        roleCommandOrder = new StackRoleCommandOrder(result);
    } catch (IOException e) {
        LOG.error(String.format("Can not read role command order info %s", rcoFilePath), e);
    }
}

From source file:edu.stanford.muse.launcher.Splash.java

private static void basicSetup(String[] args) throws ParseException {
    // set javawebstart.version to a dummy value if not already set (might happen when running with java -jar from cmd line)
    // exit.jsp doesn't allow us to showdown unless this prop is set
    if (System.getProperty("javawebstart.version") == null)
        System.setProperty("javawebstart.version", "UNKNOWN");

    if (args.length > 0) {
        out.print(args.length + " argument(s): ");
        for (int i = 0; i < args.length; i++)
            out.print(args[i] + " ");
        out.println();/*ww w  .  j av a2 s  .c  o  m*/
    }

    Options options = getOpt();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("ePADD batch mode", options);
        return;
    }

    debug = false;
    if (cmd.hasOption("debug")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = true;
    } else if (cmd.hasOption("debug-address-book")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.ab");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    } else if (cmd.hasOption("debug-groups")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.groups");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    }

    if (cmd.hasOption("no-browser-open") || System.getProperty("nobrowseropen") != null)
        browserOpen = false;

    if (cmd.hasOption("port")) {
        String portStr = cmd.getOptionValue('p');
        try {
            PORT = Integer.parseInt(portStr);
            String mesg = " Running on port: " + PORT;
            out.println(mesg);
        } catch (NumberFormatException nfe) {
            out.println("invalid port number " + portStr);
        }
    }

    if (cmd.hasOption("start-page"))
        startPage = cmd.getOptionValue("start-page");
    if (cmd.hasOption("base-dir"))
        baseDir = cmd.getOptionValue("base-dir");

    if (!cmd.hasOption("no-shutdown")) {
        // arrange to kill Muse after a period of time, we don't want the server to run forever

        // i clearly have too much time on my hands right now...
        long secs = KILL_AFTER_MILLIS / 1000;
        long hh = secs / 3600;
        long mm = (secs % 3600) / 60;
        long ss = secs % (60);
        out.print("ePADD will shut down automatically after ");
        if (hh != 0)
            out.print(hh + " hours ");
        if (mm != 0 || (hh != 0 && ss != 0))
            out.print(mm + " minutes");
        if (ss != 0)
            out.print(ss + " seconds");
        out.println();

        Timer timer = new Timer();
        TimerTask tt = new ShutdownTimerTask();
        timer.schedule(tt, KILL_AFTER_MILLIS);
    }
    System.setSecurityManager(null); // this is important   
}

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

/**
 * Loads the WSDL of the described service, assuming that the file is stored
 * in the service package's folder with the file name <i>service.wsdl</i>.
 * /*w  ww . j av a 2  s  .  com*/
 * @return The WSDL of this service as a <code>javax.wsdl.Definition</code>
 *         instance.
 * @throws MalformedServiceException,
 *             IIF the WSDL file is missing or invalid.
 * 
 * @see javax.wsdl.Definition
 */
private Definition loadWSDL() throws MalformedServiceException {
    // constant for the WSDL file name
    final String WSDL_FILENAME = "service.wsdl";

    Definition d = null;
    try {
        WSDLReader r = WSDLFactory.newInstance().newWSDLReader();

        URL u = ClassLoader.getSystemResource(this.pkg.replace('.', '/') + "/" + WSDL_FILENAME);
        d = r.readWSDL(u.toString());
    } catch (WSDLException e) {
        String msg = "failed to load the WSDL file";
        if (log.isErrorEnabled()) {
            log.error(msg, e);
        }
        throw new MalformedServiceException(msg, e);
    }
    return d;
}

From source file:edu.stanford.epadd.launcher.Splash.java

private static void basicSetup(String[] args) throws ParseException {
    // set javawebstart.version to a dummy value if not already set (might happen when running with java -jar from cmd line)
    // exit.jsp doesn't allow us to showdown unless this prop is set
    if (System.getProperty("javawebstart.version") == null)
        System.setProperty("javawebstart.version", "UNKNOWN");

    if (args.length > 0) {
        out.print(args.length + " argument(s): ");
        for (int i = 0; i < args.length; i++)
            out.print(args[i] + " ");
        out.println();/*from ww w  .  j a v a 2s  .  c  om*/
    }

    Options options = getOpt();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("ePADD batch mode", options);
        return;
    }

    debug = false;
    if (cmd.hasOption("debug")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = true;
    } else if (cmd.hasOption("debug-address-book")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.ab");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    } else if (cmd.hasOption("debug-groups")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.groups");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    }

    if (cmd.hasOption("no-browser-open") || System.getProperty("nobrowseropen") != null)
        browserOpen = false;

    if (cmd.hasOption("port")) {
        String portStr = cmd.getOptionValue('p');
        try {
            PORT = Integer.parseInt(portStr);
            String mesg = " Running on port: " + PORT;
            out.println(mesg);
        } catch (NumberFormatException nfe) {
            out.println("invalid port number " + portStr);
        }
    }

    if (cmd.hasOption("start-page"))
        startPage = cmd.getOptionValue("start-page");
    if (cmd.hasOption("base-dir"))
        baseDir = cmd.getOptionValue("base-dir");

    /*
      if (!cmd.hasOption("no-shutdown")) {
      // arrange to kill Muse after a period of time, we don't want the server to run forever
            
      // i clearly have too much time on my hands right now...
      long secs = KILL_AFTER_MILLIS/1000;
      long hh = secs/3600;
      long mm = (secs%3600)/60;
      long ss = secs % (60);
      out.print ("ePADD will shut down automatically after ");
      if (hh != 0)
      out.print (hh  + " hours ");
      if (mm != 0 || (hh != 0 && ss != 0))
      out.print (mm + " minutes");
      if (ss != 0)
      out.print (ss + " seconds");
      out.println();
            
      Timer timer = new Timer(); 
      TimerTask tt = new ShutdownTimerTask();
      timer.schedule (tt, KILL_AFTER_MILLIS);
      }
        */
    System.setSecurityManager(null); // this is important   
}

From source file:uk.ac.babraham.BamQC.Preferences.BamQCPreferences.java

/**
 * Gets the genome base.//from   w  w w.  j  a  v a 2 s . c  o  m
 * 
 * @return The folder under which genomes are stored
 * @throws FileNotFoundException 
 */
public File getGenomeBase() throws FileNotFoundException {

    /*
     * This method returns a file which represents the directory
     * under which the genomes are stored.  If a custom location
     * has not been specified then the default Genomes folder in
     * the install dir is returned.  If that can't be found then
     * a FileNotFound exception is thrown
     * 
     * If a custom location has been set then this is returned
     * regardless of it it exists or can be used.
     */

    File f;

    if (genomeBase == null) {
        // Check for the default genomes folder.  This should always be present, but
        // you can't be too careful!
        try {
            f = new File(ClassLoader.getSystemResource("Genomes").getFile().replaceAll("%20", " "));
        } catch (NullPointerException npe) {
            throw new FileNotFoundException("Couldn't find default Genomes folder");
        }
    } else {
        f = genomeBase;
    }

    return f;
}