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:com.solidmaps.webapp.report.utils.ExcelMapCivilGenerator.java

private void createNewFile() throws IOException {

    ClassLoader classLoader = ExcelMapCivilGenerator.class.getClassLoader();
    File templateFile = new File(classLoader.getResource(TEMPLATE_FILE).getFile());

    FileUtils.copyFile(templateFile, FileUtils.getFile(usedFile));
}

From source file:com.liferay.portal.osgi.web.wab.generator.internal.processor.WabProcessorTest.java

protected File getFile(String fileName) throws URISyntaxException {
    ClassLoader classLoader = getClassLoader();

    URL url = classLoader.getResource(fileName);

    if (!"file".equals(url.getProtocol())) {
        return null;
    }/*from  w  w w  .j a  v  a  2 s  .com*/

    Path path = Paths.get(url.toURI());

    return path.toFile();
}

From source file:info.magnolia.module.templatingcomponents.jspx.AbstractJspTest.java

@Before
public void setUp() throws Exception {
    // this was mainly copied from displaytag's org.displaytag.test.DisplaytagCase

    // need to pass a web.xml file to setup servletunit working directory
    final ClassLoader classLoader = getClass().getClassLoader();
    final URL webXmlUrl = classLoader.getResource("WEB-INF/web.xml");
    if (webXmlUrl == null) {
        fail("Could not find WEB-INF/web.xml");
    }//w w w. j a  va2  s.c  om
    final String path = URLDecoder.decode(webXmlUrl.getFile(), "UTF-8");

    HttpUnitOptions.setDefaultCharacterSet("utf-8");
    System.setProperty("file.encoding", "utf-8");

    // check we can write in jasper's scratch directory
    final File jspScratchDir = new File("target/jsp-test-scratch-dir");
    final String jspScratchDirAbs = jspScratchDir.getAbsolutePath();
    if (!jspScratchDir.exists()) {
        assertTrue("Can't create path " + jspScratchDirAbs + ", aborting test", jspScratchDir.mkdirs());
    }
    final File checkFile = new File(jspScratchDir, "empty");
    assertTrue("Can't write check file: " + checkFile + ", aborting test", checkFile.createNewFile());
    assertTrue("Can't remove check file:" + checkFile + ", aborting test", checkFile.delete());

    // start servletRunner
    final Hashtable<String, String> params = new Hashtable<String, String>();
    params.put("javaEncoding", "utf-8");
    params.put("development", "true");
    params.put("keepgenerated", "false");
    params.put("modificationTestInterval", "1000");
    params.put("scratchdir", jspScratchDirAbs);
    params.put("engineOptionsClass", TestServletOptions.class.getName());
    runner = new ServletRunner(new File(path), CONTEXT);
    runner.registerServlet("*.jsp", "org.apache.jasper.servlet.JspServlet", params);

    // setup context
    websiteHM = MockUtil.createHierarchyManager(StringUtils.join(Arrays.asList("/foo/bar@type=mgnl:content",
            "/foo/bar/MetaData@type=mgnl:metadata", "/foo/bar/MetaData/mgnl\\:template=testPageTemplate",
            "/foo/bar/paragraphs@type=mgnl:contentNode", "/foo/bar/paragraphs/0@type=mgnl:contentNode",
            "/foo/bar/paragraphs/0/text=hello 0", "/foo/bar/paragraphs/0/MetaData@type=mgnl:metadata",
            "/foo/bar/paragraphs/0/MetaData/mgnl\\:template=testParagraph0",
            "/foo/bar/paragraphs/1@type=mgnl:contentNode", "/foo/bar/paragraphs/1/text=hello 1",
            "/foo/bar/paragraphs/1/MetaData@type=mgnl:metadata",
            "/foo/bar/paragraphs/1/MetaData/mgnl\\:template=testParagraph1",
            "/foo/bar/paragraphs/2@type=mgnl:contentNode", "/foo/bar/paragraphs/2/text=hello 2",
            "/foo/bar/paragraphs/2/MetaData@type=mgnl:metadata",
            "/foo/bar/paragraphs/2/MetaData/mgnl\\:template=testParagraph2", ""), "\n"));

    final AggregationState aggState = new AggregationState();
    setupAggregationState(aggState);

    // let's make sure we render stuff on an author instance
    aggState.setPreviewMode(false);

    final ServerConfiguration serverCfg = new ServerConfiguration();
    serverCfg.setAdmin(true);
    ComponentsTestUtil.setInstance(ServerConfiguration.class, serverCfg);

    // register some default components used internally
    ComponentsTestUtil.setInstance(MessagesManager.class, new DefaultMessagesManager());
    final DefaultI18nContentSupport i18nContentSupport = new DefaultI18nContentSupport();
    i18nContentSupport.setEnabled(true);
    i18nContentSupport.addLocale(LocaleDefinition.make("fr", "CH", true));
    i18nContentSupport.addLocale(LocaleDefinition.make("de", "CH", true));
    i18nContentSupport.addLocale(LocaleDefinition.make("de", null, true));
    ComponentsTestUtil.setInstance(I18nContentSupport.class, i18nContentSupport);
    final DefaultI18nAuthoringSupport i18nAuthoringSupport = new DefaultI18nAuthoringSupport();
    i18nAuthoringSupport.setEnabled(true);
    // TODO - tests with i18AuthoringSupport disabled/enabled
    ComponentsTestUtil.setInstance(I18nAuthoringSupport.class, i18nAuthoringSupport);

    final Template t1 = new Template();
    t1.setName("testPageTemplate");
    t1.setI18nBasename("info.magnolia.module.templatingcomponents.test_messages");
    final AbstractAuthoringUiComponentTest.TestableTemplateManager tman = new AbstractAuthoringUiComponentTest.TestableTemplateManager();
    tman.register(t1);
    ComponentsTestUtil.setInstance(TemplateManager.class, tman);
    ComponentsTestUtil.setInstance(RenderingEngine.class, new DefaultRenderingEngine());

    req = createMock(HttpServletRequest.class);
    // cheating - this mock request is NOT the same that's used by htmlunit to do the ACTUAL request
    expect(req.getAttribute(Sources.REQUEST_LINKS_DRAWN)).andReturn(Boolean.FALSE).anyTimes();//times(0, 1);
    req.setAttribute(Sources.REQUEST_LINKS_DRAWN, Boolean.TRUE);
    expectLastCall().anyTimes();//times(0, 1);

    ctx = createMock(WebContext.class);
    expect(ctx.getAggregationState()).andReturn(aggState).anyTimes();
    expect(ctx.getLocale()).andReturn(Locale.US).anyTimes();
    expect(ctx.getContextPath()).andReturn("/lol").anyTimes();
    expect(ctx.getServletContext()).andStubReturn(createMock(ServletContext.class));
    expect(ctx.getRequest()).andStubReturn(req);
    MgnlContext.setInstance(ctx);

    setupExpectations(ctx, websiteHM, req);

    replay(ctx, req);
}

From source file:io.fabric8.mq.coordination.KubernetesControl.java

private String getOrCreaBteBrokerReplicationControllerId() {
    if (replicationControllerId == null) {
        try {//from www.j  ava  2s . c  o m
            ReplicationController running = kubernetes.getReplicationController(
                    getOrCreaBteBrokerReplicationControllerId(), kubernetes.getNamespace());
            if (running == null) {
                ObjectMapper mapper = KubernetesFactory.createObjectMapper();

                //ToDo chould change this to look for ReplicationController for AMQ_Broker from Maven
                File file = new File(getBrokerTemplateLocation());
                URL url;
                if (file.exists()) {
                    url = Paths.get(file.getAbsolutePath()).toUri().toURL();
                } else {
                    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                    url = classLoader.getResource(getBrokerTemplateLocation());
                }

                if (url != null) {
                    ReplicationController replicationController = mapper.reader(ReplicationController.class)
                            .readValue(url);
                    replicationControllerId = getName(replicationController);
                    running = kubernetes.getReplicationController(replicationControllerId);
                    if (running == null) {
                        kubernetes.createReplicationController(replicationController);
                        LOG.info("Created ReplicationController " + replicationControllerId);
                    } else {
                        replicationControllerId = getName(running);
                        LOG.info("Found ReplicationController " + replicationControllerId);
                    }

                } else {
                    LOG.error("Could not find location of Broker Template from " + getBrokerTemplateLocation());
                }
            }

        } catch (Throwable e) {
            LOG.error("Failed to create a Broker", e);
        }
    }
    return replicationControllerId;
}

From source file:de.uni_rostock.goodod.tools.Configuration.java

private Configuration(String args[]) {
    setupCommandLineOptions();/*from   ww  w.ja  va  2 s  . c o  m*/
    config = new CombinedConfiguration();
    // Comandline arguments have highest precedence, add them first.
    config.addConfiguration(getConfigMap(args), "environment");
    String configFile = config.getString("configFile");
    PropertyListConfiguration mainConfig = null;
    try {
        if ((null == configFile) || configFile.isEmpty()) {
            ClassLoader loader = EvaluatorApp.class.getClassLoader();
            mainConfig = new PropertyListConfiguration(loader.getResource("config.plist"));

        } else {
            mainConfig = new PropertyListConfiguration(configFile);
        }
    } catch (ConfigurationException configExc) {
        logger.fatal("Could not load configuration", configExc);
        System.exit(1);
    }
    config.addConfiguration(mainConfig, "configurationFile");
    logger.debug("Configuration loaded");
}

From source file:com.joyent.manta.client.MantaClientPutIT.java

@Test
public final void testPutWithStreamAndKnownContentLength() throws IOException {
    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Assert.assertNotNull(classLoader.getResource(TEST_FILENAME));

    final int length = 20 * 1024;
    try (InputStream testDataInputStream = new RandomInputStream(length)) {
        mantaClient.put(path, testDataInputStream, length, null, null);
    }//from   w  w  w .  j  a va  2  s . c  o  m
}

From source file:com.joyent.manta.client.MantaClientPutIT.java

@Test
public final void testPutWithStreamAndKnownContentLengthBeyondBuffer() throws IOException {
    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Assert.assertNotNull(classLoader.getResource(TEST_FILENAME));

    final int length = mantaClient.getContext().getUploadBufferSize() + 1024;
    try (InputStream testDataInputStream = new RandomInputStream(length)) {
        mantaClient.put(path, testDataInputStream, length, null, null);
    }/*from ww w  . j a va  2s  . com*/
}

From source file:com.joyent.manta.client.MantaClientPutIT.java

@Test
public final void testPutWithStreamThatDoesntFitInBuffer() throws IOException {
    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Assert.assertNotNull(classLoader.getResource(TEST_FILENAME));

    final int length = mantaClient.getContext().getUploadBufferSize() + 1024;

    try (InputStream testDataInputStream = new RandomInputStream(length)) {
        Assert.assertFalse(testDataInputStream.markSupported());
        mantaClient.put(path, testDataInputStream);
    }//from  ww  w.jav a 2  s  .c om
}

From source file:com.joyent.manta.client.MantaClientPutIT.java

@Test
public final void testPutWithStreamAndErrorProneName() throws IOException {
    final String name = UUID.randomUUID().toString() + "- -!@#$%^&*().txt";
    final String path = testPathPrefix + name;
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Assert.assertNotNull(classLoader.getResource(TEST_FILENAME));

    final int length = mantaClient.getContext().getUploadBufferSize() + 1024;

    try (InputStream testDataInputStream = new RandomInputStream(length)) {
        Assert.assertFalse(testDataInputStream.markSupported());
        mantaClient.put(path, testDataInputStream);
    }/*w ww  .j a  v a2s.c  o m*/
    try (MantaObjectInputStream object = mantaClient.getAsInputStream(path)) {
        Assert.assertEquals(object.getPath(), path, "path not returned as written");
        byte[] actualBytes = IOUtils.readFully(object, length);
    }
}

From source file:de.ipk_gatersleben.ag_nw.graffiti.plugins.gui.webstart.MainM.java

/**
 * Constructs a new instance of the editor.
 * @param addPluginFile/* w ww . ja  v a2 s . c  o  m*/
 */
public MainM(String applicationName, String[] args, String[] addon, SplashScreenInterface splashScreen,
        String addPluginFile, final boolean showMainFrame) {

    setupLogger();

    ClassLoader cl = this.getClass().getClassLoader();
    String path = this.getClass().getPackage().getName().replace('.', '/');
    ImageIcon icon = new ImageIcon(cl.getResource(path + "/vanted_logo.png"));

    if (splashScreen != null && (splashScreen instanceof DBEsplashScreen)) {
        ((DBEsplashScreen) splashScreen).setIconImage(icon.getImage());
    }

    splashScreen.setVisible(showMainFrame);

    GravistoMainHelper.createApplicationSettingsFolder(splashScreen);

    if (!showMainFrame && !(new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_accepted")).exists()
            && !(new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_rejected")).exists()) { // command line version automatically rejects
        // kegg
        try {
            new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_rejected").createNewFile();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    if (!(new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_accepted")).exists()
            && !(new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_rejected")).exists()) {

        ReleaseInfo.setIsFirstRun(true);

        splashScreen.setVisible(false);
        splashScreen.setText("Request KEGG License Status");
        int result = askForEnablingKEGG();
        if (result == JOptionPane.YES_OPTION) {
            try {
                new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_accepted").createNewFile();
            } catch (IOException e) {
                ErrorMsg.addErrorMessage(e);
            }
        }
        if (result == JOptionPane.NO_OPTION) {
            try {
                new File(ReleaseInfo.getAppFolderWithFinalSep() + "license_kegg_rejected").createNewFile();
            } catch (IOException e) {
                ErrorMsg.addErrorMessage(e);
            }
        }
        if (result == JOptionPane.CANCEL_OPTION) {
            JOptionPane.showMessageDialog(null, "Startup of VANTED is aborted.",
                    "VANTED Program Features Initialization", JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
        }
        splashScreen.setVisible(true);
    }

    GravistoMainHelper.initApplicationExt(args, splashScreen, cl, addPluginFile, addon);
}