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:de.decoit.simu.cbor.xml.dictionary.DictionaryTest.java

@Test
public void testFindAttributeByPath_NotExistentElement() throws Exception {
    Path input = Paths.get(ClassLoader.getSystemResource("namespace-with-complex-elements.dict").toURI());

    Dictionary instance = new Dictionary();
    instance.extendDictionary(input);//w ww.j  av a  2 s . c  o m

    String dictPath = "<http://www.trustedcomputinggroup.org/2010/IFMAP/2>access@name";

    DictionarySimpleAttribute result = instance.findAttributeByPath(dictPath);

    assertNull(result);
}

From source file:org.astrojournal.gui.AJMainGUI.java

/**
 * Set AstroJournal control buttons. A small keyboard.
 *//*from w w w. j  a  v a2s. co m*/
private void setControlButtons() {

    // Create the button for creating the journals
    btnCreateJournal = new JButton();
    btnCreateJournal.setText(resourceBundle.getString("AJ.cmdCreateJournal.text"));
    btnCreateJournal
            .setIcon(new ImageIcon(ClassLoader.getSystemResource("graphics/icons/create_journals_16.png")));
    btnCreateJournal.setActionCommand(AJGUIActions.CREATE_JOURNAL.name());
    btnCreateJournal.addActionListener(this);
    // Set this button as default. :)
    getRootPane().setDefaultButton(btnCreateJournal);

    // Create the button for opening the journals
    btnOpenJournal = new JButton();
    btnOpenJournal.setIcon(new ImageIcon(ClassLoader.getSystemResource("graphics/icons/open_journals_16.png")));
    btnOpenJournal.setText(resourceBundle.getString("AJ.cmdOpenJournal.text"));
    btnOpenJournal.setActionCommand(AJGUIActions.OPEN_JOURNAL.name());
    btnOpenJournal.addActionListener(this);
    btnOpenJournal.setEnabled(false);

    // Create the button for closing the application
    btnQuit = new JButton();
    btnQuit.setIcon(new ImageIcon(ClassLoader.getSystemResource("graphics/icons/quit_16.png")));
    btnQuit.setText(resourceBundle.getString("AJ.cmdQuit.text"));
    btnQuit.setActionCommand(AJGUIActions.QUIT.name());
    btnQuit.addActionListener(this);
}

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

@Test
public void emailWithNoInternalDateShouldUseNowDate() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"));
    MailboxMessage mailWithNoInternalDate = new SimpleMailboxMessage(null, 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);
    mailWithNoInternalDate.setModSeq(MOD_SEQ);
    mailWithNoInternalDate.setUid(UID);
    assertThatJson(messageToElasticSearchJson.convertToJson(mailWithNoInternalDate,
            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.skb.tribe.Tribe.java

/**
 * Start parsing with Tribe. Input parameters are the supported languages (string array) and the actual
 * arguments. /*from  ww  w .j av  a  2s  .com*/
 * @param supportedLanguages LanguageParser array containing all information on supported source and target languages.
 * @param args Command line arguments.
 */
public void start(LanguageParser[] supportedLanguages, String[] args) {
    logger.trace("start -- in");

    cli.setApplicationName(prop.getValue(TribeProperties.tpmKeyNameLC));

    /**
     * Create an object for the supported language and set the property for languages
     */
    logger.trace("set languages");
    //Languages languages=new Languages(supportedLanguages);
    LanguageList languages = new LanguageList();
    languages.addLanguages(supportedLanguages);
    prop.setValueDefault(TribeProperties.tpmKeyLanguages, languages);

    /**
     * Get an instance of the report manager, to be able to write output, and give it the standard stg.
     */
    logger.trace("set report manager");
    repMgr.setApplicationName(prop.getValue(TribeProperties.tpmKeyNameLC));
    repMgr.setSTGUrlName(prop.get(TribeProperties.tpmKeyReportManagerStg, TSPropertyMap.pmValValueDefault));
    repMgr.loadSTG("Report Manager String Template Group", "");

    /**
     * Do the first pass of options. This is needed to detect:
     * - a new TRIBE stg file if requested
     * - input language if specified
     * - target language if specified
     */
    logger.trace("cli propOptions and setOptions pass 1");
    this.cli.setPropOptions(this.prop);
    this.setOptions(args, languages);
    //System.err.println(prop);
    /**
     * If there is a new stg given, instruct the report manager to load it. Checks on the content of the
     * new stg file will be handled by the report manager.
     */
    if (!(prop.getValueCli(TribeProperties.tpmKeyReportManagerStg)).tsIsType(TEnum.TS_NULL)) {
        logger.trace("changed tribe stg");
        repMgr.setSTGFileName(prop.getValueCli(TribeProperties.tpmKeyReportManagerStg));
        repMgr.loadSTG("Tribe report stg", "");
    }
    //System.err.println(prop);
    /**
     * Check if the selected source and/or target language are valid. If they are not valid, check
     * if other CLI options still need to be addressed (such as -help or -version). If there are options
     * that result in exit (help, version), doExitOptions will not return! Otherwise we still need to go
     * through the CLI options again, cause that might include other exit options.
     */
    logger.trace("testing source and target languages pass1");
    Boolean gc = false;
    TSBase srcLang = new TSNull();
    TSBase tgtLang = new TSNull();
    srcLang = prop.getValue(TribeProperties.tpmKeySrcLanguage);
    tgtLang = prop.getValue(TribeProperties.tpmKeyTgtLanguage);
    gc = ((TSBoolean) prop.getValue(TribeProperties.tpmKeyGC)).tsvalue;

    //      if(!(prop.getValue(TribeProperties.tpmKeySrcLanguage)).tsIsType(TEnum.TS_NULL)) //TODO fill
    //         ;
    Boolean ssl = languages.setSelectedLanguage(srcLang, tgtLang, gc);
    this.cli.setPropOptions(this.prop);
    cli.setApplicationName(prop.getValue(TribeProperties.tpmKeyNameLC));
    //System.err.println(prop);
    if (ssl == false)
        this.doExitOptions(1);

    /**
     * Second pass of the CLI options, this time including the specific options of the selected source
     * and/or target languages.
     */
    logger.trace("cli pass 2");
    this.setOptions(args, languages);
    //System.err.println(prop);
    /**
     * Now, if we have problems with the selected source and/or target language, exit with an error. 
     */
    // if we got a language problem earlier, exit now
    logger.trace("testing source and target languages pass2");
    ssl = languages.checkSelectedLanguage();
    if (ssl == false)
        System.exit(3);
    //System.err.println(prop);
    /**
     * Now do the language specific exit options (such as print an stg).
     */
    logger.trace("exitOptions pass2");
    //System.err.println(prop);
    this.doExitOptions(2);

    /**
     * If we do not have any input file, exit now. All other CLI options that do not need an input file need to be processed
     * before this line!
     */
    logger.trace("testing input file");
    if (prop.getValue(TribeProperties.tpmKeySrcFile) == null
            || prop.getValue(TribeProperties.tpmKeySrcFile).toString().equals("")) {
        repMgr.reportError("no input file specified");
        System.exit(1);
    }

    /**
     * From here on we MUST have all options set via either default, files or CLI! 
     */
    logger.trace("end of option look up, starting processing");

    repMgr.doErrors(((TSBoolean) this.prop.getValue(TribeProperties.tpmKeyNoErrors)).tsvalue);
    repMgr.doWarnings(((TSBoolean) this.prop.getValue(TribeProperties.tpmKeyNoWarnings)).tsvalue);
    repMgr.setProgrammeName(((TSString) this.prop.getValue(TribeProperties.tpmKeyNameLC)).tsvalue);

    /**
       * Everything is set, so start loading the stg for the target file. If the stg should only be printed, print and exit.
       */
    logger.trace("load language stg");
    gc = false;
    Boolean prStgFileTgt = false;
    gc = ((TSBoolean) prop.getValue(TribeProperties.tpmKeyGC)).tsvalue;
    prStgFileTgt = ((TSBoolean) prop.getValue(TribeProperties.tpmKeyPrStgFileTarget)).tsvalue;
    //System.err.println(prop);
    if (gc == true) {
        languages.loadStg();
        if (prStgFileTgt == true) {
            languages.printStg();
            System.exit(0);
        }
    }

    /**
     * Test the source and target files (including directories) by mean of:
     * - source file exists (check simple access and then classpath)
     * - target directory and target file can be written into
     */
    logger.trace("testing source and target files and target directory");
    try {
        File fnTest;
        fnTest = new File(prop.getValue(TribeProperties.tpmKeySrcFile).toString());
        if (fnTest.canRead() == false) {
            URL url = ClassLoader.getSystemResource(prop.getValue(TribeProperties.tpmKeySrcFile).toString());
            fnTest = new File(url.getFile());
            if (fnTest.canRead() == false) {
                repMgr.reportError("can't open source file <" + prop.getValue(TribeProperties.tpmKeySrcFile)
                        + "> for reading");
                System.exit(1);
            } else
                prop.put(TribeProperties.tpmKeySrcFile, TSPropertyMap.pmValValueCli, fnTest.getAbsolutePath());
        }

        TSBase ata = prop.getValue(TribeProperties.tpmKeyGC);
        if (ata != null && ata.tsIsType(TSRepository.TEnum.TS_ATOMIC_JAVA_BOOLEAN)
                && ((TSBoolean) ata).tsvalue == true) {
            fnTest = new File(prop.getValue(TribeProperties.tpmKeyTgtDir).toString());
            if (fnTest.canWrite() == false) {
                repMgr.reportError("can't write in target directory <"
                        + prop.getValue(TribeProperties.tpmKeyTgtDir) + ">");
                System.exit(1);
            }
            fnTest = new File(prop.getValue(TribeProperties.tpmKeyTgtDir) + "/"
                    + prop.getValue(TribeProperties.tpmKeyTgtFile)
                    + prop.getValue(TribeProperties.tpmKeyTgtFileExt));
            fnTest.createNewFile();
            if (fnTest.canWrite() == false) {
                repMgr.reportError("can't open target file <" + prop.getValue(TribeProperties.tpmKeyTgtDir)
                        + "/" + prop.getValue(TribeProperties.tpmKeyTgtFile)
                        + prop.getValue(TribeProperties.tpmKeyTgtFileExt) + "> for writing");
                System.exit(1);
            } else
                fnTest.delete();
        }
    } catch (Exception e) {
        repMgr.reportError(e.toString());
    }

    /**
     * Save the current configuration.
     */
    logger.trace("save current configuration, if requested");
    if (!(prop.getValueCli(TribeProperties.tpmKeyCfgSave)).tsIsType(TEnum.TS_NULL)) {
        TSString cl = (TSString) prop.getValueCli(TribeProperties.tpmKeyCfgSave);
        //         String _cret="";
        try {
            prop.writeToFile(cl.tsvalue);
        } catch (Exception e) {
        }

        //         if(_cret!=null)
        //            repMgr.reportError(_cret+", trying to continue");

        //           if(sTest!=null)
        //              repMgr.reportError(sTest+", trying to continue");
    }

    /**
     * Rock'n roll. Create an input stream and (if requested) the preprocessor, finally hand over the stream to
     * the language parser.
     */
    logger.trace("rock'n roll, creating input stream");
    try {
        InputStream tribeIS;
        TSBase ata = prop.getValue(TribeProperties.tpmKeyNoCPP);
        if (ata != null && ata.tsIsType(TSRepository.TEnum.TS_ATOMIC_JAVA_BOOLEAN)
                && ((TSBoolean) ata).tsvalue == false) {
            logger.trace("use build-in cpp");
            File temp = File.createTempFile("_tribe", "cpp");
            temp.deleteOnExit();
            PrintWriter pw = new PrintWriter(new FileWriter(temp));
            CPP prep = new CPP();
            prep.parse_initial(prop.getValue(TribeProperties.tpmKeySrcFile).toString(), pw);
            logger.trace("finished cpp, create input stream");
            tribeIS = new FileInputStream(temp);
        } else {
            logger.trace("no cpp requested, create input stream");
            tribeIS = new FileInputStream(prop.getValue(TribeProperties.tpmKeySrcFile).toString());
        }
        logger.trace("calling language.parse");
        languages.parse(tribeIS);
    } catch (IOException io) {
        repMgr.reportError("catched exception while parsing", "IOException: " + io.toString());
    } catch (Exception e) {
        repMgr.reportError("catched exception while parsing", "Exception: " + e.toString());
    }

    /**
     * Cleanup, especially remove the temporary files created by the preprocessor.
     */
    logger.trace("finally, garbage collector");
    System.gc();

    logger.trace("start -- out");
}

From source file:org.apache.hadoop.gateway.SecureClusterTest.java

private static void setupLogging() {
    PropertyConfigurator.configure(ClassLoader.getSystemResource("log4j.properties"));
}

From source file:de.decoit.simu.cbor.xml.dictionary.DictionaryTest.java

@Test
public void testFindAttributeByPath_NotExistentAttribute() throws Exception {
    Path input = Paths.get(ClassLoader.getSystemResource("namespace-with-complex-elements.dict").toURI());

    Dictionary instance = new Dictionary();
    instance.extendDictionary(input);//  ww w.jav a  2s. co m

    String dictPath = "<http://www.trustedcomputinggroup.org/2010/IFMAP/2>access@myattr";

    DictionarySimpleAttribute result = instance.findAttributeByPath(dictPath);

    assertNull(result);
}

From source file:org.openadaptor.util.FileUtils.java

/**
 * Returns an URL to the supplied file. Will search the classpath if required.
 * //from   www  . j  av  a2 s.  c o m
 * @param path
 *          the path to convert
 * 
 * @return a URL pointing to the file represented by the supplied path string or null if it does not exist
 */
public static URL toURL(String path) {
    URL url;
    try {
        /*
         * Let java do the work instead of us... if ( path.indexOf(":") == -1 ) url = new URL("file:" + path); else url =
         * new URL(path);
         */
        // todo: the File() constructor will not fail so we will not use the Classloasder
        url = new File(path).toURL();
    } catch (MalformedURLException e) {
        url = ClassLoader.getSystemResource(path);
    }

    return url;
}

From source file:com.cloud.utils.script.Script.java

public static String findScript(String path, String script) {
    s_logger.debug("Looking for " + script + " in the classpath");

    URL url = ClassLoader.getSystemResource(script);
    s_logger.debug("System resource: " + url);
    File file = null;/*w w w  .  j ava2s. c  o  m*/
    if (url != null) {
        file = new File(url.getFile());
        s_logger.debug("Absolute path =  " + file.getAbsolutePath());
        return file.getAbsolutePath();
    }

    if (path == null) {
        s_logger.warn("No search path specified, unable to look for " + script);
        return null;
    }
    path = path.replace("/", File.separator);

    /**
     * Look in WEB-INF/classes of the webapp
     * URI workaround the URL encoding of url.getFile
     */
    if (path.endsWith(File.separator)) {
        url = Script.class.getClassLoader().getResource(path + script);
    } else {
        url = Script.class.getClassLoader().getResource(path + File.separator + script);
    }
    s_logger.debug("Classpath resource: " + url);
    if (url != null) {
        try {
            file = new File(new URI(url.toString()).getPath());
            s_logger.debug("Absolute path =  " + file.getAbsolutePath());
            return file.getAbsolutePath();
        } catch (URISyntaxException e) {
            s_logger.warn("Unable to convert " + url.toString() + " to a URI");
        }
    }

    if (path.endsWith(File.separator)) {
        path = path.substring(0, path.lastIndexOf(File.separator));
    }

    if (path.startsWith(File.separator)) {
        // Path given was absolute so we assume the caller knows what they want.
        file = new File(path + File.separator + script);
        return file.exists() ? file.getAbsolutePath() : null;
    }

    s_logger.debug("Looking for " + script);
    String search = null;
    for (int i = 0; i < 3; i++) {
        if (i == 0) {
            String cp = Script.class.getResource(Script.class.getSimpleName() + ".class").toExternalForm();
            int begin = cp.indexOf(File.separator);

            // work around with the inconsistency of java classpath and file separator on Windows 7
            if (begin < 0)
                begin = cp.indexOf('/');

            int endBang = cp.lastIndexOf("!");
            int end = cp.lastIndexOf(File.separator, endBang);
            if (end < 0)
                end = cp.lastIndexOf('/', endBang);
            if (end < 0)
                cp = cp.substring(begin);
            else
                cp = cp.substring(begin, end);

            s_logger.debug("Current binaries reside at " + cp);
            search = cp;
        } else if (i == 1) {
            s_logger.debug("Searching in environment.properties");
            try {
                final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
                if (propsFile == null) {
                    s_logger.debug("environment.properties could not be opened");
                } else {
                    final Properties props = PropertiesUtil.loadFromFile(propsFile);
                    search = props.getProperty("paths.script");
                }
            } catch (IOException e) {
                s_logger.debug("environment.properties could not be opened");
                continue;
            }
            s_logger.debug("environment.properties says scripts should be in " + search);
        } else {
            s_logger.debug("Searching in the current directory");
            search = ".";
        }

        search += File.separatorChar + path + File.separator;
        do {
            search = search.substring(0, search.lastIndexOf(File.separator));
            file = new File(search + File.separator + script);
            s_logger.debug("Looking for " + script + " in " + file.getAbsolutePath());
        } while (!file.exists() && search.lastIndexOf(File.separator) != -1);

        if (file.exists()) {
            return file.getAbsolutePath();
        }

    }

    search = System.getProperty("paths.script");

    search += File.separatorChar + path + File.separator;
    do {
        search = search.substring(0, search.lastIndexOf(File.separator));
        file = new File(search + File.separator + script);
        s_logger.debug("Looking for " + script + " in " + file.getAbsolutePath());
    } while (!file.exists() && search.lastIndexOf(File.separator) != -1);

    if (file.exists()) {
        return file.getAbsolutePath();
    }

    s_logger.warn("Unable to find script " + script);
    return null;
}

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

@Test
public void emailWithNoInternalDateShouldUseNowDate() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"), IndexAttachments.YES);
    MailboxMessage mailWithNoInternalDate = new SimpleMailboxMessage(MESSAGE_ID, null, 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);
    mailWithNoInternalDate.setModSeq(MOD_SEQ);
    mailWithNoInternalDate.setUid(UID);
    assertThatJson(messageToElasticSearchJson.convertToJson(mailWithNoInternalDate,
            ImmutableList.of(new MockMailboxSession("username").getUser()))).when(IGNORING_ARRAY_ORDER)
                    .when(IGNORING_VALUES)
                    .isEqualTo(IOUtils.toString(ClassLoader.getSystemResource("eml/recursiveMail.json")));
}