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.hubiquitus.hubotsdk.Hubot.java

/**
 * Connect the Hubot to the hAPI with params set in the file "config.txt"
 *///from  www  .j av  a  2 s . c  om
protected final void start() {
    try {
        // Create a default context for Camel
        camelContext = new DefaultCamelContext();
        ProducerTemplateSingleton.setContext(camelContext);
        URL configFilePath = ClassLoader.getSystemResource("config.txt");
        String jsonString = fileToString(configFilePath.getFile());
        topology = new HTopology(jsonString);
        setStatus(HubotStatus.CREATED);
        //Connecting to HNode
        HOptions options = new HOptions();
        options.setTransport("socketio");
        JSONArray endpoints = new JSONArray();
        endpoints.put(topology.getHserver());
        options.setEndpoints(endpoints);
        hClient.onStatus(statusDelegate);
        hClient.connect(topology.getActor(), topology.getPwd(), options);
        // see onStatus to know how this actor go the started status
    } catch (Exception e) {
        logger.error("Oooops a big error on starting this bot : ", e);
    }
}

From source file:com.blackducksoftware.tools.notifiers.email.EmailNotifierUtility.java

static int process(String[] args) {
    System.out.println("Email Notifier for Black Duck Suite");
    CommandLineParser parser = new DefaultParser();

    options.addOption("h", "help", false, "show help.");

    Option protexProjectNameOption = new Option(NotifierConstants.CL_PROTEX_PROJECT_NAME, true,
            "Name of Project (required)");
    protexProjectNameOption.setRequired(true);
    options.addOption(protexProjectNameOption);

    Option configFileOption = new Option("config", true, "Location of configuration file (required)");
    configFileOption.setRequired(true);/*from   ww  w.j  ava 2s.  co  m*/
    options.addOption(configFileOption);

    Option templateFileOption = new Option("template", true, "Location of email template file (optional)");
    templateFileOption.setRequired(false);
    options.addOption(templateFileOption);

    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            help();
            return 0;
        }

        String projectName = null;
        File configFile = null;
        String templateFileLocation = null;
        if (cmd.hasOption(NotifierConstants.CL_PROTEX_PROJECT_NAME)) {
            projectName = cmd.getOptionValue(NotifierConstants.CL_PROTEX_PROJECT_NAME);
            log.info("Project name: " + projectName);
        } else {
            log.error("Must specify project name!");
            help();
            return -1;
        }

        // Config File
        if (cmd.hasOption(NotifierConstants.CL_CONFIG)) {
            String configFilePath = cmd.getOptionValue(NotifierConstants.CL_CONFIG);
            log.info("Config file location: " + configFilePath);
            configFile = new File(configFilePath);
            if (!configFile.exists()) {
                log.error("Configuration file does not exist at location: " + configFile);
                return -1;
            }
        } else {
            log.error("Must specify configuration file!");
            help();
            return -1;
        }

        if (cmd.hasOption(NotifierConstants.CL_TEMPLATE_FILE)) {
            templateFileLocation = cmd.getOptionValue(NotifierConstants.CL_TEMPLATE_FILE);
            log.info("Template file location: " + templateFileLocation);
        }

        // Configuration manager
        EmailNotifierUtilityConfig emailConfig = new EmailNotifierUtilityConfig(configFile);

        // Call the processor
        try {
            CFEmailNotifier emailer = new CFEmailNotifier(emailConfig);
            if (!emailer.isConfigured()) {
                throw new NotifierException("Email Configuration not properly configured.");
            }
            // Make sure the template is parsed now
            // If user did not specify template file, use default resource
            // package.
            if (templateFileLocation == null) {
                templateFileLocation = ClassLoader
                        .getSystemResource(NotifierConstants.PROTEX_EMAIL_SUCCESS_TEMPLATE).getFile();
            }
            emailer.configureContentMap(templateFileLocation);

            IHandler notificationHandler = new EmailHandler(emailConfig, emailer);
            ProtexServerWrapper<ProtexProjectPojo> psw = new ProtexServerWrapper<>(emailConfig.getServerBean(),
                    emailConfig, true);
            NotifierProcessor enp = new NotifierProcessor(emailConfig, psw, notificationHandler,
                    emailer.getEmailContentMap(), projectName, projectName);
            enp.process();
        } catch (Exception e) {
            log.error("Fatal error: " + e.getMessage());
        }

        log.info("Exiting.");
        return 0;

    } catch (ParseException e) {
        log.error("Unable to parse command line arguments: " + e.getMessage());
        help();
        return -1;
    }
}

From source file:halfpipe.properties.UrlPropertiesSource.java

private URL getConfigFileFromClasspath() {
    URL url = null;//from  w  w w .  j a v  a  2s  . c  o  m
    // attempt to load from the context classpath
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader != null) {
        url = loader.getResource(DEFAULT_CONFIG_FILE_FROM_CLASSPATH);
    }
    if (url == null) {
        // attempt to load from the system classpath
        url = ClassLoader.getSystemResource(DEFAULT_CONFIG_FILE_FROM_CLASSPATH);
    }
    if (url == null) {
        // attempt to load from the system classpath
        url = UrlPropertiesSource.class.getResource(DEFAULT_CONFIG_FILE_FROM_CLASSPATH);
    }
    return url;
}

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

@Before
public void setUp() {
    bindStdOut();//from  w w w  .  j a v  a2  s .c  o m
    command = spy(new SnapshotCommand(parser, cspConfig, clientConfig));

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

    when(providerFactory.getRESTManager()).thenReturn(restManager);
    when(restManager.getRESTClient()).thenReturn(restClient);
    when(restClient.freezeJSONTextContentSpec(anyInt(), anyString(), anyBoolean(), anyInt(), anyBoolean(),
            anyString(), anyInt(), anyString())).thenReturn(textContentSpec);

    rootTestDirectory = FileUtils.toFile(ClassLoader.getSystemResource(""));
    when(cspConfig.getRootOutputDirectory()).thenReturn(rootTestDirectory.getAbsolutePath() + File.separator);
}

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

@Before
public void setUp() throws IOException {
    bindStdOut();/*from  w  ww .  j  a v  a 2 s  . c  o m*/

    command = new AssembleCommand(parser, cspConfig, clientConfig);

    // Only test the assemble command and not the build command content.
    command.setNoBuild(true);

    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();

    // Make a empty file in that directory
    emptyFile = new File(bookDir, DUMMY_BUILD_FILE_NAME);
    emptyFile.createNewFile();

    // Make the project book directory
    projectBookDir = new File(rootTestDirectory, BOOK_TITLE + File.separator + "assembly");
    projectBookDir.mkdirs();

    // Make a empty file in that directory
    projectEmptyFile = new File(projectBookDir, DUMMY_PROJECT_BUILD_FILE_NAME);
    projectEmptyFile.createNewFile();
    PowerMockito.mockStatic(FileUtilities.class);
    when(FileUtilities.deleteDirContents(any(File.class))).thenCallRealMethod();
}

From source file:com.blackducksoftware.tools.commonframework.core.config.ConfigurationManagerTest.java

/**
 * Tests to make sure that the list is parsed and the server bean is correct
 * The list specified is the /server/test_server_config.xml
 *//* w w  w.  j a  va 2  s  .c o  m*/
@Test
public void testConfigFileWithServerListAndOldConfig() {
    final String fullLocationFileWithList = ClassLoader.getSystemResource(testFileWithServerList).getFile();

    final ConfigurationManager cm = new TestConfigurationManagerBean(fullLocationFileWithList);

    final ServerBean protexServerBean = cm.getServerBean(protex);
    final ServerBean ccServerBean = cm.getServerBean(cc);

    Assert.assertEquals("bla_protex", protexServerBean.getServerName());
    Assert.assertEquals("bla_codecenter", ccServerBean.getServerName());

}

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

private void initlize() {
    setTitle("??");
    setBounds(120, 80, 1024, 550);/*from w  w  w . java  2  s.  c o  m*/
    setDefaultCloseOperation(3);
    setLayout(new BorderLayout(5, 5));
    // ?MenuBar
    initMenuBar();
    JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, getWestPanel(), getCenterPanel());
    split.setContinuousLayout(false);
    split.setOneTouchExpandable(true);
    split.setDividerLocation(150);
    add(split, BorderLayout.CENTER);
    //?pdm
    openLastPdmFile();
    addCloseListener();
    this.setIconImage(new ImageIcon(ClassLoader.getSystemResource("resources/images/logo.jpg")).getImage());
}

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

public JPanel getGenPanel() {
    if (genPanel == null) {
        genPanel = new JPanel();
        genPanel.setLayout(new BorderLayout());
        genPanel.add(getCenterPanel(), BorderLayout.CENTER);
        JPanel northPanel = new JPanel();
        addLineBtn = new JButton("?");
        addLineBtn.setIcon(new ImageIcon(ClassLoader.getSystemResource("resources/images/add.gif")));
        addLineBtn.addActionListener(this);
        northPanel.add(addLineBtn);/* w  w  w.jav a  2s . c om*/
        previewBtn = new JButton("?");
        previewBtn.setIcon(new ImageIcon(ClassLoader.getSystemResource("resources/images/preview1.gif")));
        previewBtn.addActionListener(this);
        northPanel.add(previewBtn);
        genBtn = new JButton("?");
        genBtn.setIcon(new ImageIcon(ClassLoader.getSystemResource("resources/images/file.gif")));
        genBtn.addActionListener(this);
        northPanel.add(genBtn);
        genPanel.add(northPanel, BorderLayout.SOUTH);
    }
    return genPanel;
}

From source file:org.ebayopensource.turmeric.runtime.tests.common.jetty.AbstractWithProxyServerTest.java

/**
 * Create a proxied service that uses the embedded jetty proxy server + embedded jetty SPF server.
 * <p>/*  w w w  .j  a v a 2  s  .c o  m*/
 * The process here is:
 * <p>
 * <ol>
 * <li>Read the raw ClientConfig.xml as specified by the clientName parameter</li>
 * <li>Updates the <code>PROXY_HOST</code> and <code>PROXY_PORT</code> values present in the raw ClientConfig.xml</li>
 * <li>Write the modified ClientConfig.xml back out to a test specific directory (
 * <code>target/tests/{testClassName}/{testMethodName}/res/</code>) using the path
 * <code>META-INF/soa/client/config/{clientName}_modified/ClientConfig.xml</code></li>
 * <li>Using a test local classloader, and the {@link ServiceFactory#create(String, String, URL)} method to load the
 * modified ClientConfig.xml to create a {@link Service} suitable for talking to the embedded jetty proxy server.</li>
 * </ol>
 * 
 * @param serviceAdminName
 *            the service admin name.
 * @param clientName
 *            the client name.
 * @return
 */
protected Service createProxiedService(String serviceAdminName, String clientName) throws Exception {
    // Read/Parse baseline ClientConfig.xml

    String rawConfigPath = String.format("META-INF/soa/client/config/%s/ClientConfig.xml", clientName);
    URL rawConfigUrl = ClassLoader.getSystemResource(rawConfigPath);
    Assert.assertThat("Unable to find config resource: " + rawConfigPath, rawConfigUrl, notNullValue());

    Document doc = parseXml(rawConfigUrl);

    // Modify the PROXY_HOST and PROXY_PORT to point to embedded jetty server

    XPath expression = new JDOMXPath("//e:default-options/e:other-options/e:option");
    expression.addNamespace("e", "http://www.ebayopensource.org/turmeric/common/config");
    // Navigator navigator = expression.getNavigator();

    @SuppressWarnings("unchecked")
    List<Element> nodes = expression.selectNodes(doc);
    for (Element elem : nodes) {
        String optName = elem.getAttributeValue("name").trim();
        if ("PROXY_HOST".equals(optName)) {
            elem.setText(proxyUri.getHost());
        } else if ("PROXY_PORT".equals(optName)) {
            elem.setText(String.valueOf(proxyUri.getPort()));
        }
    }

    // Write modified document out to target directory

    File testingResourceDir = new File(testingdir.getDir(), "res");
    MavenTestingUtils.ensureEmpty(testingResourceDir);
    String modifiedConfigPath = String.format("META-INF/soa/client/config/%s_modified/ClientConfig.xml",
            clientName);
    File outputFile = new File(testingResourceDir, modifiedConfigPath);
    MavenTestingUtils.ensureDirExists(outputFile.getParentFile());

    System.out.println("Writing modified ClientConfig to " + outputFile.getAbsolutePath());
    writeXml(outputFile, doc);

    // Let ServiceFactory create service from modified ClientConfig.xml
    URL urls[] = new URL[] { testingResourceDir.toURI().toURL() };
    URLClassLoader testingSpecificCL = new URLClassLoader(urls, this.getClass().getClassLoader());

    ClassLoader original = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(testingSpecificCL);
        return ServiceFactory.create(serviceAdminName, clientName + "_modified", null);
    } finally {
        Thread.currentThread().setContextClassLoader(original);
    }
}