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.jboss.pressgang.ccms.contentspec.client.commands.StatusCommandTest.java

@Test
public void shouldShutdownWhenServerHasBeenModified() 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("CHECKSUM=" + randomNumber + "\n");
    // 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 contain the server checksum
    PowerMockito.mockStatic(FileUtils.class);
    when(FileUtils.readFileToString(any(File.class)))
            .thenReturn("CHECKSUM=" + HashUtilities.generateMD5("Title = Test Content Specification\n")
                    + "\nTitle = Test Content " + "Specification\n");

    // When processing the command
    try {//from w  w  w . j ava  2s.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(9));
    }

    // Then make sure an error message is printed and the command shutdown
    assertThat(getStdOutLogs(), containsString(
            "The local copy of the Content Specification is out of date. Please use \"csprocessor pull\" to download the latest copy"
                    + "."));
}

From source file:eu.serco.dhus.plugin.olcil1eo.OlciL1EoPlugin.java

private void loadTaskTables() throws ParserConfigurationException, SAXException, IOException {

    taskTables = new HashMap<String, TaskTable>();
    Iterator<Entry<String, String>> it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> pair = (Map.Entry<String, String>) it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
        URL taskTableName = ClassLoader
                .getSystemResource("../etc/task_tables/" + pair.getValue() + "_TaskTable.xml");
        TaskTable taskTable;/*from ww  w  .java2 s.  c om*/
        if (taskTableName != null) {

            taskTable = TaskTableParser.parseTaskTable(taskTableName.getFile());
            taskTables.put(pair.getKey() + "", taskTable);
            logger.info("Task Table parsed successfully for type " + pair.getKey());
        } else
            logger.warn(" Cannot find task table file for type " + pair.getKey());
        // it.remove(); // avoids a ConcurrentModificationException
    }

}

From source file:algo.PlotBar.java

private void comboAlgoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboAlgoActionPerformed
    // TODO add your handling code here:
    //        cb = (JComboBox) evt.getSource();
    //        String comboSelected = (String) cb.getSelectedItem();
    //        System.out.println(comboSelected);
    /// For bubbles.jpg image
    switch (comboAlgo.getSelectedIndex()) {
    /// For Heap.jpg image
    case 0:/*from  w ww  . j  a  v  a2 s  .  co  m*/
        try {
            BufferedImage wPic = ImageIO.read(ClassLoader.getSystemResource("algo/res/bubbles.jpg"));
            //JLabel wIcon = new JLabel(new ImageIcon(original));

            labelExecutionOutput.setText("");

            imageLabel.setIcon(new ImageIcon(wPic));

        } catch (IOException ex) {
            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
        }
        break;
    /// For merge.jpg
    case 1:
        try {
            BufferedImage original = ImageIO.read(ClassLoader.getSystemResource("algo/res/heap.jpg"));
            //JLabel wIcon = new JLabel(new ImageIcon(original));

            labelExecutionOutput.setText("");

            //double widthFactor = .4;
            //double heightFactor = .4;
            // imageLabel.setIcon(new ImageIcon(bufferResize(original, widthFactor, heightFactor)));
            imageLabel.setIcon(new ImageIcon(original));

        } catch (IOException ex) {
            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
        }
        break;
    /// For quick.jpg
    case 2:
        try {
            BufferedImage original = ImageIO.read(ClassLoader.getSystemResource("algo/res/merge.jpg"));

            //double widthFactor = .3;
            //double heightFactor = .38;
            labelExecutionOutput.setText("");

            // imageLabel.setIcon(new ImageIcon(bufferResize(original, widthFactor, heightFactor)));
            imageLabel.setIcon(new ImageIcon(original));

        } catch (IOException ex) {
            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
        }
        break;
    case 3:
        try {
            BufferedImage original = ImageIO.read(ClassLoader.getSystemResource("algo/res/quick.png"));
            double widthFactor = .8;
            double heightFactor = .9;
            labelExecutionOutput.setText("");
            imageLabel.setIcon(new ImageIcon(bufferResize(original, widthFactor, heightFactor)));

        } catch (IOException ex) {
            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
        }
        break;

    case 4:

        try {
            BufferedImage original = ImageIO.read(ClassLoader.getSystemResource("algo/res/chess.png"));
            //double widthFactor = .5;
            //double heightFactor = .5;
            labelExecutionOutput.setText("");
            //imageLabel.setIcon(new ImageIcon(bufferResize(original, widthFactor, heightFactor)));
            imageLabel.setIcon(new ImageIcon(original));

        } catch (IOException ex) {
            Logger.getLogger(Algorithm.class.getName()).log(Level.SEVERE, null, ex);
        }
        break;
    default:
        break;
    }

}

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

private static void basicSetup(String[] args) throws org.apache.commons.cli.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");

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

    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"))
        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");
    noShutdown = !cmd.hasOption("no-shutdown");
    System.setSecurityManager(null); // this is important   
}

From source file:ch.fork.AdHocRailway.ui.AdHocRailway.java

private void setUpLogging() {
    PropertyConfigurator.configure(ClassLoader.getSystemResource("log4j.properties"));

    final FileAppender appender = new FileAppender();
    appender.setName("MyFileAppender");
    appender.setLayout(new PatternLayout("%d [%t] %-5p %c{1} - %m%n"));
    String localhostname = "";
    try {/*  ww  w .ja  va 2  s. co  m*/
        localhostname = java.net.InetAddress.getLocalHost().getHostName();
    } catch (final UnknownHostException e) {
        e.printStackTrace();
    }
    final String userName = System.getProperty("user.name");

    appender.setFile("./logs/" + localhostname + "_" + userName + ".log");
    appender.setAppend(true);
    appender.setThreshold(Level.DEBUG);
    appender.activateOptions();
    Logger.getRootLogger().addAppender(appender);

}

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

public URL getResourceUrl(String resource) {
    URL url = ClassLoader.getSystemResource(getResourceName(resource));
    assertThat("Failed to find test resource " + resource, url, Matchers.notNullValue());
    return url;/*from   ww  w . j  a  v  a  2  s  .co m*/
}

From source file:org.pentaho.pac.server.common.AppConfigProperties.java

IConsoleConfig getConsoleConfig() {
    if (consoleConfig == null) {
        try {// ww  w.  j a  v a  2s. c  om
            consoleConfig = new ConsoleConfigXml(
                    new File(ClassLoader.getSystemResource(CONFIG_FILE_NAME).toURI()));
        } catch (Exception ex) {
            logger.warn(Messages.getErrorString("AppConfigProperties.ERROR_0004_UNABLE_TO_READ_FILE", //$NON-NLS-1$
                    CONFIG_FILE_NAME));
            consoleConfig = new ConsoleConfigXml();
        }
    }
    return consoleConfig;
}

From source file:org.ambraproject.service.crossref.CrossRefLookupServiceImplTest.java

@Test(dataProvider = "expectedCrossRefSeaches")
public void testCrossRefQueryBuilder(String[] searches) throws Exception {
    Document article = DocumentBuilderFactoryCreator.createFactory().newDocumentBuilder()
            .parse(new File(ClassLoader.getSystemResource("articles/pone.0047851.xml").toURI()));

    CrossRefLookupServiceImpl service = new CrossRefLookupServiceImpl();
    CrossRefSearch crossRefSearches[] = service.getCrossRefSearchTerms(article);

    assertEquals(crossRefSearches.length, searches.length);

    String[] results = new String[crossRefSearches.length];

    for (int a = 0; a < crossRefSearches.length; a++) {
        results[a] = crossRefSearches[a].buildQuery();
    }/*from  ww  w.  j  av  a  2 s  .c  om*/

    assertEqualsNoOrder(results, searches);
}

From source file:org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScriptTest.java

private List<File> getAllJarFiles() throws URISyntaxException {
    String testClassPath = String.format(StringUtils.join(getClass().getName().split("\\."), "/"));
    File testClassDir = new File(ClassLoader.getSystemResource(testClassPath).toURI()).getAbsoluteFile();

    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(testClassDir);/*w  w w .j av  a 2 s. c  o  m*/
    ds.setIncludes(new String[] { "*.jar" });
    ds.scan();

    List<File> ret = new ArrayList<File>();

    for (String relpath : ds.getIncludedFiles()) {
        ret.add(new File(testClassDir, relpath));
    }

    return ret;
}

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

@Test
public void emailWithAttachmentsShouldConvertAttachmentsWhenIndexAttachmentsIsTrue() throws IOException {
    // Given// w  ww. ja v a2 s . c  om
    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);

    // When
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"), IndexAttachments.YES);
    String convertToJson = messageToElasticSearchJson.convertToJson(mailWithNoInternalDate,
            ImmutableList.of(new MockMailboxSession("username").getUser()));

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