Example usage for java.lang ClassLoader getResource

List of usage examples for java.lang ClassLoader getResource

Introduction

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

Prototype

public URL getResource(String name) 

Source Link

Document

Finds the resource with the given name.

Usage

From source file:hudson.plugins.testlink.result.ResultSeekerTestCase.java

protected void setUp() throws Exception {
    super.setUp();

    project = createFreeStyleProject();/*  w w w  .  j  a v a2  s  .  co  m*/
    File temp = File.createTempFile("resultseeker", Long.toString(System.nanoTime()));

    if (!(temp.delete())) {
        throw new IOException("Could not delete temp directory " + temp);
    }

    if (!(temp.mkdir())) {
        throw new IOException("Could not create temp directory " + temp);
    }

    File workspaceFile = new File(temp, getResultsDirectory());

    if (!(workspaceFile.mkdirs())) {
        throw new IOException("Could not create temp workspace " + temp);
    }

    ClassLoader cl = ResultSeekerTestCase.class.getClassLoader();
    URL url = cl.getResource(getResultsDirectory());
    File junitDir = new File(url.getFile());

    FileUtils.copyDirectory(junitDir, workspaceFile);

    project.setCustomWorkspace(workspaceFile.getAbsolutePath());

    project.getBuildersList()
            .add(new ResultSeekerBuilder(getResultSeeker(), getAutomatedTestCases(), testlink));
}

From source file:org.apache.jackrabbit.core.config.RepositoryConfig.java

/**
 * Returns the configuration of a repository with the home directory,
 * configuration file, and other options as specified in the given
 * configuration parser variables. //from   w  w  w  .ja  v a  2 s .  co m
 * <p>
 * The directory is created if it does not exist. If the repository
 * configuration file does not exist, then it is created using the
 * default Jackrabbit configuration settings.
 *
 * @param variables parser variables
 * @return repository configuration
 * @throws ConfigurationException on configuration errors
 * @throws java.io.IOException If an error occurs.
 * @since Apache Jackrabbit 2.1
 */
public static RepositoryConfig install(Properties variables) throws IOException, ConfigurationException {
    Properties copy = new Properties(variables);

    String home = copy.getProperty(REPOSITORY_HOME_VARIABLE);
    if (home == null) {
        home = copy.getProperty(RepositoryFactoryImpl.REPOSITORY_HOME, "jackrabbit");
        copy.setProperty(REPOSITORY_HOME_VARIABLE, home);
    }
    File dir = new File(home);

    String conf = copy.getProperty(REPOSITORY_CONF_VARIABLE);
    if (conf == null) {
        conf = copy.getProperty(RepositoryFactoryImpl.REPOSITORY_CONF);
    }

    URL resource = RepositoryImpl.class.getResource(REPOSITORY_XML);
    if (conf == null) {
        conf = new File(dir, REPOSITORY_XML).getPath();
    } else if (conf.startsWith("classpath:")) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if (loader == null) {
            loader = RepositoryImpl.class.getClassLoader();
        }
        resource = loader.getResource(conf.substring("classpath:".length()));
        conf = new File(dir, REPOSITORY_XML).getPath();
    }

    File xml = new File(conf);
    installRepositorySkeleton(dir, xml, resource);
    return create(new InputSource(xml.toURI().toString()), copy);
}

From source file:no.kantega.publishing.spring.PluginStaticContentController.java

private URL getResourceFromPlugins(String resourcePath) {
    for (OpenAksessPlugin plugin : pluginManager.getPlugins()) {
        ClassLoader classLoader = pluginManager.getClassLoader(plugin);

        if (classLoader != null) {
            URL resource = classLoader.getResource(resourcePath);
            if (resource != null) {
                return resource;
            }/* w w  w .  j av  a2  s. co  m*/
        }
    }
    return null;
}

From source file:org.cbioportal.annotation.TestAnnotationPipeline.java

@Test
public void pipelineTest() throws Exception {
    ClassLoader classLoader = getClass().getClassLoader();
    JobExecution jobExecution = jobLauncherTestUtils.launchJob(new JobParametersBuilder()
            .addString("filename", classLoader.getResource("data/testmaf.txt").getPath())
            .addString("outputFilename", "target/test-outputs/output.txt").addString("replace", "false")
            .addString("isoformOverride", "uniprot").toJobParameters());
    AssertFile.assertFileEquals(/*from ww w .ja  v a  2s  .  com*/
            new FileSystemResource(classLoader.getResource("data/expectedmaf.txt").getPath()),
            new FileSystemResource("target/test-outputs/output.txt"));
}

From source file:com.glaf.core.util.ReflectUtils.java

public static URL getResource(String name) {
    URL url = null;/*from w  w w .j  a  v a  2s. com*/
    ClassLoader classLoader = getCustomClassLoader();
    if (classLoader != null) {
        url = classLoader.getResource(name);
    }
    if (url == null) {
        // Try the current Thread context classloader
        classLoader = Thread.currentThread().getContextClassLoader();
        url = classLoader.getResource(name);
        if (url == null) {
            // Finally, try the classloader for this class
            classLoader = ReflectUtils.class.getClassLoader();
            url = classLoader.getResource(name);
        }
    }

    return url;
}

From source file:com.mgmtp.perfload.core.client.web.io.XmlRequestFlowReader.java

private Document loadDocument() throws ParserConfigurationException, SAXException, DocumentException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    String schemaUrl = loader.getResource(SCHEMA_RESOURCE).toString();
    String resource = resourcePath + resourceName;
    String xmlResourceUrl = loader.getResource(resource).toString();
    return Dom4jReader.loadDocument(new InputSource(xmlResourceUrl), new StreamSource(schemaUrl), "UTF-8");
}

From source file:org.apache.archiva.webdav.util.MimeTypes.java

public void load(String resourceName) {
    ClassLoader cloader = this.getClass().getClassLoader();

    /* Load up the mime types table */
    URL mimeURL = cloader.getResource(resourceName);

    if (mimeURL == null) {
        throw new IllegalStateException("Unable to find resource " + resourceName);
    }/*from  ww  w .ja  v  a  2  s  .c  o m*/

    try (InputStream mimeStream = mimeURL.openStream()) {
        load(mimeStream);
    } catch (IOException e) {
        log.error("Unable to load mime map " + resourceName + " : " + e.getMessage(), e);
    }
}

From source file:com.cws.esolutions.security.listeners.SecurityServiceInitializer.java

/**
 * Initializes the security service in a standalone mode - used for applications outside of a container or when
 * run as a standalone jar.//from   w  w w.  j  a  va2  s  .c  o  m
 *
 * @param configFile - The security configuration file to utilize
 * @param logConfig - The logging configuration file to utilize
 * @param startConnections - Configure, load and start repository connections
 * @throws SecurityServiceException @{link com.cws.esolutions.security.exception.SecurityServiceException}
 * if an exception occurs during initialization
 */
public static void initializeService(final String configFile, final String logConfig,
        final boolean startConnections) throws SecurityServiceException {
    URL xmlURL = null;
    JAXBContext context = null;
    Unmarshaller marshaller = null;
    SecurityConfigurationData configData = null;

    final ClassLoader classLoader = SecurityServiceInitializer.class.getClassLoader();
    final String serviceConfig = (StringUtils.isBlank(configFile)) ? System.getProperty("configFileFile")
            : configFile;
    final String loggingConfig = (StringUtils.isBlank(logConfig)) ? System.getProperty("secLogConfig")
            : logConfig;

    try {
        try {
            DOMConfigurator.configure(Loader.getResource(loggingConfig));
        } catch (NullPointerException npx) {
            try {
                DOMConfigurator.configure(FileUtils.getFile(loggingConfig).toURI().toURL());
            } catch (NullPointerException npx1) {
                System.err.println("Unable to load logging configuration. No logging enabled!");
                System.err.println("");
                npx1.printStackTrace();
            }
        }

        xmlURL = classLoader.getResource(serviceConfig);

        if (xmlURL == null) {
            // try loading from the filesystem
            xmlURL = FileUtils.getFile(serviceConfig).toURI().toURL();
        }

        context = JAXBContext.newInstance(SecurityConfigurationData.class);
        marshaller = context.createUnmarshaller();
        configData = (SecurityConfigurationData) marshaller.unmarshal(xmlURL);

        SecurityServiceInitializer.svcBean.setConfigData(configData);

        if (startConnections) {
            DAOInitializer.configureAndCreateAuthConnection(
                    new FileInputStream(FileUtils.getFile(configData.getSecurityConfig().getAuthConfig())),
                    false, SecurityServiceInitializer.svcBean);

            Map<String, DataSource> dsMap = SecurityServiceInitializer.svcBean.getDataSources();

            if (DEBUG) {
                DEBUGGER.debug("dsMap: {}", dsMap);
            }

            if (configData.getResourceConfig() != null) {
                if (dsMap == null) {
                    dsMap = new HashMap<String, DataSource>();
                }

                for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) {
                    if (!(dsMap.containsKey(mgr.getDsName()))) {
                        StringBuilder sBuilder = new StringBuilder()
                                .append("connectTimeout=" + mgr.getConnectTimeout() + ";")
                                .append("socketTimeout=" + mgr.getConnectTimeout() + ";")
                                .append("autoReconnect=" + mgr.getAutoReconnect() + ";")
                                .append("zeroDateTimeBehavior=convertToNull");

                        if (DEBUG) {
                            DEBUGGER.debug("StringBuilder: {}", sBuilder);
                        }

                        BasicDataSource dataSource = new BasicDataSource();
                        dataSource.setDriverClassName(mgr.getDriver());
                        dataSource.setUrl(mgr.getDataSource());
                        dataSource.setUsername(mgr.getDsUser());
                        dataSource.setConnectionProperties(sBuilder.toString());
                        dataSource.setPassword(PasswordUtils.decryptText(mgr.getDsPass(), mgr.getDsSalt(),
                                configData.getSecurityConfig().getSecretAlgorithm(),
                                configData.getSecurityConfig().getIterations(),
                                configData.getSecurityConfig().getKeyBits(),
                                configData.getSecurityConfig().getEncryptionAlgorithm(),
                                configData.getSecurityConfig().getEncryptionInstance(),
                                configData.getSystemConfig().getEncoding()));

                        if (DEBUG) {
                            DEBUGGER.debug("BasicDataSource: {}", dataSource);
                        }

                        dsMap.put(mgr.getDsName(), dataSource);
                    }
                }

                if (DEBUG) {
                    DEBUGGER.debug("dsMap: {}", dsMap);
                }

                SecurityServiceInitializer.svcBean.setDataSources(dsMap);
            }
        }
    } catch (JAXBException jx) {
        jx.printStackTrace();
        throw new SecurityServiceException(jx.getMessage(), jx);
    } catch (FileNotFoundException fnfx) {
        fnfx.printStackTrace();
        throw new SecurityServiceException(fnfx.getMessage(), fnfx);
    } catch (MalformedURLException mux) {
        mux.printStackTrace();
        throw new SecurityServiceException(mux.getMessage(), mux);
    } catch (SecurityException sx) {
        sx.printStackTrace();
        throw new SecurityServiceException(sx.getMessage(), sx);
    }
}

From source file:com.itemanalysis.jmetrik.data.JmetrikFileReaderTest.java

@Test
public void dataTest() {
    System.out.println("JmetrikFileReader: Reading data/example-import-file.jmetrik");
    ClassLoader classLoader = getClass().getClassLoader();
    File f = new File(classLoader.getResource("data/example-import-file.jmetrik").getFile());

    String[] data = { "1001,F,1,A,B,C,0,10.1", "1002,F,1,B,C,A,1,11.2", "1003,M,1,A,B,A,0,12.12",
            "1004,M,1,A,B,C,0,14.3", "1005,M,0,B,B,C,1,15", "1006,F,0,A,B,C,1,10.0", "1007,M,0,B,A,C,0,21",
            "1008,F,0,A,B,C,1,10", "1009,M,0,A,B,D,0,19.5", "1010,M,0,C,B,A,1,21" };

    VariableName sid = new VariableName("sid");
    VariableName gender = new VariableName("gender");
    VariableName item1 = new VariableName("item1");
    VariableName item2 = new VariableName("item2");
    VariableName item3 = new VariableName("item3");
    VariableName item4 = new VariableName("item4");
    VariableName score = new VariableName("score");

    try (JmetrikFileReader reader = new JmetrikFileReader(f)) {
        reader.openConnection();//  w w w.  j  a  v a  2s  .com
        int index = 0;
        String[] s = null;
        JmetrikCSVRecord jmetrikCSVRecord = null;

        while (reader.hasNext()) {
            jmetrikCSVRecord = reader.next();
            s = data[index].split(",");
            //                System.out.println(jmetrikCSVRecord.toString());
            assertTrue(s[0].equals(jmetrikCSVRecord.valueOfAsString(sid)));
            assertTrue(s[1].equals(jmetrikCSVRecord.valueOfAsString(gender)));
            assertTrue(s[3].equals(jmetrikCSVRecord.valueOfAsString(item1)));
            assertTrue(s[4].equals(jmetrikCSVRecord.valueOfAsString(item2)));
            assertTrue(s[5].equals(jmetrikCSVRecord.valueOfAsString(item3)));
            assertEquals("Item int test", Integer.parseInt(s[6]), jmetrikCSVRecord.valueOfAsInt(item4), 1e-15);
            assertEquals("Score test", Double.parseDouble(s[7]), jmetrikCSVRecord.valueOfAsDouble(score),
                    1e-15);
            index++;
        }

        assertEquals("Number of records test", data.length, index);
        assertEquals("Number of records test2", reader.getNumberOfRows(), index);

    } catch (IOException ex) {
        ex.printStackTrace();
    }

}

From source file:mercury.JsonController.java

/**
 *
 *//* w w  w  .  ja  va2 s .  c o  m*/
@Override
public void init() {
    //--- Runs just once !
    try {
        //--- Loads the mapping "jsp page X Handler"
        ClassLoader cl = Controller.class.getClassLoader();
        URL fileURL = cl.getResource("/targetJsonHandlers.properties");
        JsonController.targetJsonHandlers = new Properties();
        JsonController.targetJsonHandlers.load(fileURL.openStream());
    } catch (IOException ioe) {
        System.out.println("[mercury.JsonController.init()] Error: " + ioe.getMessage());
    }
}