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:gov.jgi.meta.MetaUtils.java

/**
 * same as {@link #loadConfiguration(Configuration, String[]) loadConfiguration()} but loads from
 * a specified file instead of the default filename.
 *
 * @param conf the job configuration to add the defaults to
 * @param configurationFileName the cluster defaults file to load
 * @param args the commandline args//www .ja  v  a2 s  .  com
 * @return modifies conf
* @throws IOException 
 */
public static String[] loadConfiguration(Configuration conf, String configurationFileName, String[] args)
        throws IOException {
    /*
     * first load the configuration from the build properties (typically packaged in the jar)
     */
    System.out.println("loading build.properties ...");
    try {
        Properties buildProperties = new Properties();
        buildProperties.load(MetaUtils.class.getResourceAsStream("/build.properties"));
        for (Enumeration e = buildProperties.propertyNames(); e.hasMoreElements();) {
            String k = (String) e.nextElement();
            System.out.println("setting " + k + " to " + buildProperties.getProperty(k));
            System.setProperty(k, buildProperties.getProperty(k));
            conf.set(k, buildProperties.getProperty(k));
        }
    } catch (Exception e) {
        System.out.println("unable to find build.properties ... skipping");
    }

    /*
     * override properties with the deployment descriptor
     */
    if (configurationFileName == null) {
        String appName = System.getProperty("application.name");
        String appVersion = System.getProperty("application.version");
        configurationFileName = appName + "-" + appVersion + "-conf.xml";
    }
    System.out.println("loading application configuration from " + configurationFileName);
    try {
        URL u = ClassLoader.getSystemResource(configurationFileName);
        if (u == null) {
            System.err.println("unable to find " + configurationFileName + " ... skipping");
        } else {
            conf.addResource(configurationFileName);
        }
    } catch (Exception e) {
        System.err.println("unable to find " + configurationFileName + " ... skipping");
    }

    /*
     * override properties from user's preferences defined in ~/.meta-prefs
     */

    try {
        java.io.FileInputStream fis = new java.io.FileInputStream(
                new java.io.File(System.getenv("HOME") + "/.meta-prefs"));
        Properties props = new Properties();
        props.load(fis);
        System.out.println("loading preferences from ~/.meta-prefs");
        for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
            String k = (String) e.nextElement();
            System.out.println("overriding property: " + k);
            conf.set(k, props.getProperty(k));
        }
    } catch (Exception e) {
        System.out.println("unable to find ~/.meta-prefs ... skipping");
    }

    /*
     * finally, allow user to override from commandline
     */
    return (new GenericOptionsParser(conf, args).getRemainingArgs());
}

From source file:org.jboss.pressgang.ccms.contentspec.client.commands.CreateCommandTest.java

@Before
public void setUp() {
    bindStdOut();/*www.  j  a v  a 2 s. c  o  m*/
    command = new CreateCommand(parser, cspConfig, clientConfig);

    when(textContentSpecProvider.newTextContentSpec()).thenReturn(textContentSpecWrapper);
    when(textContentSpecProvider.newTextProcessingOptions()).thenReturn(textCSProcessingOptionsWrapper);
    when(textContentSpecProvider.createTextContentSpec(any(TextContentSpecWrapper.class),
            any(TextCSProcessingOptionsWrapper.class), any(LogMessageWrapper.class)))
                    .thenReturn(textContentSpecWrapper);

    // Authentication is tested in the base implementation so assume all users are valid
    TestUtil.setUpAuthorisedUser(command, userProvider, users, user, username);

    // Return the test directory as the root directory
    rootTestDirectory = FileUtils.toFile(ClassLoader.getSystemResource(""));
    when(cspConfig.getRootOutputDirectory()).thenReturn(rootTestDirectory.getAbsolutePath() + File.separator);

    // Make the book title directory
    bookDir = new File(rootTestDirectory, BOOK_TITLE);
    bookDir.mkdir();
}

From source file:org.programmatori.domotica.own.sdk.config.AbstractConfig.java

/**
 * Give the home of the project. <br>
 * For return the home of the project need to have a file in the home
 *
 * @return path of home directory//from w w  w  .  j  a va2 s .c  o  m
 * @deprecated
 */
public static String getOldHomeDirectory(String fileName) throws Exception {
    String home = "";
    String separator = File.separator;
    boolean first = true;

    try {
        Log log = LogFactory.getLog(AbstractConfig.class);

        // for solve bug in the jar use a real file instead a "."
        String filePath = null;

        // check presence of "filename", if it isn't raise an Exception
        filePath = ClassLoader.getSystemResource(fileName).toString();

        log.debug("Path of " + fileName + ": " + filePath);
        StringTokenizer st = new StringTokenizer(filePath, "/"); // URI Separator
        st.nextToken(); // don't calculate "file:"
        while (st.hasMoreTokens()) {
            String folder = st.nextToken();
            log.debug("Foledr: " + folder);

            // BUG Linux starting slash
            if (separator.equals("/") && first) {
                folder = separator + folder;
                first = false;
            }

            // BUG Eclipse put in the bin
            boolean bBin = !(folder.equals("bin") && (st.countTokens() < 2));

            // BUG jar can not support . then use a real file for find a path
            boolean bRealFile = !(folder.equals(fileName) && (st.countTokens() < 1));

            // BUG the home directory it cannot end with .jar
            boolean bJar = !(folder.endsWith(".jar!") && (st.countTokens() < 2));

            if (bBin && bRealFile && bJar) { // If i build under bin i don't insert in
                // home path
                if (home.length() > 0)
                    home += "/";
                home = home + folder;
                log.debug("home: " + home);
            }
        }
    } catch (Exception e) {
        throw new Exception("File " + fileName + " must be present, please ensure it exists ");
    }

    return home;
}

From source file:org.richie.codeGen.ui.GenAndPreviewUI.java

public JSplitPane getCenterPanel() {
    JToolBar logToolBar = new JToolBar();
    logToolBar.setFloatable(false);//  w ww.  j  av a2s . c  om
    clearLogBtn = new JButton("");
    clearLogBtn.setIcon(new ImageIcon(ClassLoader.getSystemResource("resources/images/clear.gif")));
    clearLogBtn.addActionListener(this);
    clearLogBtn.addActionListener(this);
    logToolBar.add(clearLogBtn);
    logToolBar.addSeparator();
    JPanel logPanel = new JPanel();
    logPanel.setLayout(new BorderLayout());
    JScrollPane textPanel = new JScrollPane();
    logTextArea = new JTextArea();
    logTextArea.setMinimumSize(new Dimension(1, 1));
    textPanel.setViewportView(logTextArea);
    logPanel.add(logToolBar, BorderLayout.NORTH);
    logPanel.add(textPanel, BorderLayout.CENTER);
    split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, getTemplatePanel(), logPanel);
    split.setContinuousLayout(false);
    split.setOneTouchExpandable(true);
    split.setDividerLocation(400);
    return split;
}

From source file:de.brendamour.jpasskit.signing.PKFileBasedSigningUtilTest.java

private String getPathFromClasspath(String path) throws URISyntaxException {
    return Paths.get(ClassLoader.getSystemResource(path).toURI()).toString();
}

From source file:com.siphyc.utils.Utilities.java

public static URL getResource(String resource) {
    URL url;//w  ww .j a  va  2s .  c o m

    //Try with the Thread Context Loader. 
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader != null) {
        url = classLoader.getResource(resource);
        if (url != null) {
            return url;
        }
    }
    //Last ditch attempt. Get the resource from the classpath.
    return ClassLoader.getSystemResource(resource);
}

From source file:org.jboss.pressgang.ccms.contentspec.client.commands.StatusCommandTest.java

@Test
public void shouldShutdownWhenEmptyFileFound() throws URISyntaxException, IOException {
    URL specFileUrl = ClassLoader.getSystemResource("StatusCommand-post.contentspec");
    File specFile = new File(specFileUrl.toURI());
    String specFilePath = specFile.getParentFile().getAbsolutePath() + File.separator;
    // Given a valid csprocessor.cfg
    given(cspConfig.getContentSpecId()).willReturn(id);
    // and a valid id
    given(contentSpecProvider.getContentSpec(anyInt(), anyInt())).willReturn(contentSpecWrapper);
    given(contentSpecProvider.getContentSpecAsString(anyInt(), anyInt())).willReturn("");
    // and the file it should find is inn the resources folder
    given(contentSpecWrapper.getTitle()).willReturn("");
    // Note: this is a bypass since the command works on the current directory, however the actual file might be in a different
    // location for tests.
    PowerMockito.mockStatic(DocBookUtilities.class);
    when(DocBookUtilities.escapeTitle(anyString())).thenReturn(specFilePath + "StatusCommand");
    // and that file should read as empty
    PowerMockito.mockStatic(FileUtils.class);
    when(FileUtils.readFileToString(any(File.class))).thenReturn("");

    // When processing the command
    try {/*from   ww w .j a  va 2 s . c o  m*/
        command.process();
        // Then an error is printed and the program is shut down
        fail(SYSTEM_EXIT_ERROR);
    } catch (CheckExitCalled e) {
        assertThat(e.getStatus(), is(-1));
    }

    // Then make sure an error message is printed and the command shutdown
    assertThat(getStdOutLogs(), containsString("The specified file was empty!"));
}

From source file:org.keyboardplaying.xtt.ui.i18n.I18nHelper.java

/**
 * Returns a list of all locales a bundle has been written for.
 *
 * @return a list of all locales availables within the application
 *///from  w ww.j a  v  a2  s .c  o  m
public List<Locale> getAvailableLocales() {

    /* Convert base name to a path. */
    String bundlePath = BUNDLE_BASE_NAME.replaceAll("\\.", "/") + "_%s.properties";

    List<Locale> available = new ArrayList<>();

    /* Loop over all locales to find those we do support. */
    // Get a list of all locales the JVM supports
    Locale[] locales = Locale.getAvailableLocales();
    // Loop over those to find available locales
    for (Locale locale : locales) {
        URL bundleUrl = ClassLoader.getSystemResource(String.format(bundlePath, locale.toString()));
        if (bundleUrl != null) {
            available.add(locale);
        }
    }

    /* Return the list. */
    return available;
}

From source file:de.unisb.cs.st.javalanche.mutation.analyze.html.HtmlReport.java

private void copyFile(String name) {
    URL systemResource = ClassLoader.getSystemResource("report/" + name);
    logger.debug("Copying from resource: " + systemResource);
    copyFile(systemResource, new File(REPORT_DIR, name));
}

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

public static URL getResourceUrl(String resource) {
    URL url = ClassLoader.getSystemResource(getResourceName(resource));
    assertThat("Failed to find test resource " + resource, url, Matchers.notNullValue());
    return url;//from   w  ww. j  a va2s . c om
}