java.net.URL

Here are the examples of the java api class java.net.URL taken from open source projects.

1. Implies#main()

Project: openjdk
Source File: Implies.java
View license
public static void main(String[] args) throws Exception {
    URL thisURL = new URL("http", "localhost", "file");
    URL thatURL = new URL("http", null, "file");
    // should not throw NullPointerException
    testImplies(thisURL, thatURL, false);
    thisURL = new URL("http", "localhost", "dir/-");
    thatURL = new URL("HTTP", "localhost", "dir/file");
    // protocol check should ignore case
    testImplies(thisURL, thatURL, true);
    thisURL = new URL("http", "localhost", 80, "dir/-");
    thatURL = new URL("HTTP", "localhost", "dir/file");
    // port check should match default port of thatURL
    testImplies(thisURL, thatURL, true);
    System.out.println("test passed");
}

2. FileAssemblerTest#setUp()

View license
protected void setUp() throws Exception {
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setControlEntityResolver(new ResourceEntityResolver());
    XMLUnit.setTestEntityResolver(new ResourceEntityResolver());
    final URL webXmlUrl = this.getClass().getResource("/org/apache/pluto/util/assemble/file/web.xml");
    this.webXmlFile = new File(webXmlUrl.getFile());
    final URL web23XmlUrl = this.getClass().getResource("/org/apache/pluto/util/assemble/file/webServlet23.xml");
    this.web23XmlFile = new File(web23XmlUrl.getFile());
    final URL portletXmlUrl = this.getClass().getResource("/org/apache/pluto/util/assemble/file/portlet.xml");
    this.portletXmlFile = new File(portletXmlUrl.getFile());
    final URL portlet23XmlUrl = this.getClass().getResource("/org/apache/pluto/util/assemble/file/portletWebServlet23.xml");
    this.portlet23XmlFile = new File(portlet23XmlUrl.getFile());
    final URL assembledWebXmlUrl = this.getClass().getResource("/org/apache/pluto/util/assemble/file/assembled.web.xml");
    this.assembledWebXmlFile = new File(assembledWebXmlUrl.getFile());
    final URL assembledWeb23XmlUrl = this.getClass().getResource("/org/apache/pluto/util/assemble/file/assembled.webServlet23.xml");
    this.assembledWeb23XmlFile = new File(assembledWeb23XmlUrl.getFile());
}

3. TestFileLocatorUtils#testGetBasePath()

View license
@Test
public void testGetBasePath() throws Exception {
    URL url = new URL("http://xyz.net/foo/bar.xml");
    assertEquals("base path of " + url, "http://xyz.net/foo/", FileLocatorUtils.getBasePath(url));
    url = new URL("http://xyz.net/foo/");
    assertEquals("base path of " + url, "http://xyz.net/foo/", FileLocatorUtils.getBasePath(url));
    url = new URL("http://xyz.net/foo");
    assertEquals("base path of " + url, "http://xyz.net/", FileLocatorUtils.getBasePath(url));
    url = new URL("http://xyz.net/");
    assertEquals("base path of " + url, "http://xyz.net/", FileLocatorUtils.getBasePath(url));
    url = new URL("http://xyz.net");
    assertEquals("base path of " + url, "http://xyz.net", FileLocatorUtils.getBasePath(url));
}

4. AgentManagerServiceTest#testCompressAgentFolder()

View license
@Test
public void testCompressAgentFolder() throws IOException, URISyntaxException {
    URLClassLoader loader = (URLClassLoader) this.getClass().getClassLoader();
    URL core = this.getClass().getClassLoader().getResource("lib/ngrinder-core-test.jar");
    URL sh = this.getClass().getClassLoader().getResource("lib/ngrinder-sh-test.jar");
    URL[] ls = { core, sh };
    URL[] urls = loader.getURLs();
    URL[] allLib = cast(ArrayUtils.addAll(urls, ls));
    URLClassLoader child = new URLClassLoader(allLib, this.getClass().getClassLoader());
    File agentUpgrade = agentPackageService.createAgentPackage(child, null, null, 10000, null);
    FileUtils.deleteQuietly(agentUpgrade);
}

5. UrlResourceFinderTest#testUrlCopy()

View license
public void testUrlCopy() throws Exception {
    URL jar = jarFile.toURL();
    UrlResourceFinder resourceFinder = new UrlResourceFinder(new URL[] { jar });
    // get the resource
    URL resource = resourceFinder.findResource("resource");
    assertNotNull(resource);
    assertEquals("resource3", toString(resource.openStream()));
    // copy resource with string
    URL stringCopy = new URL(resource.toExternalForm());
    assertEquals("resource3", toString(stringCopy.openStream()));
    // copy resource perserving the url handler
    URL handlerCopy = new URL(resource, resource.toExternalForm());
    assertEquals("resource3", toString(handlerCopy.openStream()));
    // access the other resource using the original url as a starting point
    URL other = new URL(resource, "jar3");
    assertEquals("jar3", toString(other.openStream()));
}

6. TestURLUtil#testResolveURL()

Project: anthelion
Source File: TestURLUtil.java
View license
public void testResolveURL() throws Exception {
    // test NUTCH-436
    URL u436 = new URL("http://a/b/c/d;p?q#f");
    assertEquals("http://a/b/c/d;p?q#f", u436.toString());
    URL abs = URLUtil.resolveURL(u436, "?y");
    assertEquals("http://a/b/c/d;p?y", abs.toString());
    // test NUTCH-566
    URL u566 = new URL("http://www.fleurie.org/entreprise.asp");
    abs = URLUtil.resolveURL(u566, "?id_entrep=111");
    assertEquals("http://www.fleurie.org/entreprise.asp?id_entrep=111", abs.toString());
    URL base = new URL(baseString);
    assertEquals("base url parsing", baseString, base.toString());
    for (int i = 0; i < targets.length; i++) {
        URL u = URLUtil.resolveURL(base, targets[i][0]);
        assertEquals(targets[i][1], targets[i][1], u.toString());
    }
}

7. UrlResourceFinderTest#testResourceEnumeration()

View license
/**
     * There are 2 "jars" with a "resource" inside.  Make sure the enumeration has exactly 2 elements and
     * that hasMoreElements() doesn't advance the iterator.
     *
     * @throws Exception
     */
public void testResourceEnumeration() throws Exception {
    URL jar1 = new File(basedir, "src/test-data/resourceFinderTest/jar1/").toURL();
    URL jar2 = new File(basedir, "src/test-data/resourceFinderTest/jar2/").toURL();
    UrlResourceFinder resourceFinder = new UrlResourceFinder(new URL[] { jar1, jar2 });
    Enumeration enumeration = resourceFinder.findResources("resource");
    // resource1
    assertTrue(enumeration.hasMoreElements());
    assertTrue(enumeration.hasMoreElements());
    URL resource1 = (URL) enumeration.nextElement();
    assertNotNull(resource1);
    assertEquals("resource1", toString(resource1.openStream()));
    // resource2
    assertTrue(enumeration.hasMoreElements());
    assertTrue(enumeration.hasMoreElements());
    URL resource2 = (URL) enumeration.nextElement();
    assertNotNull(resource2);
    assertEquals("resource2", toString(resource2.openStream()));
    assertFalse(enumeration.hasMoreElements());
}

8. MultipleParentClassLoaderTest#setUp()

View license
@Before
public void setUp() throws Exception {
    Method loadClass = ClassLoader.class.getDeclaredMethod("loadClass", String.class, boolean.class);
    loadClass.setAccessible(true);
    when(loadClass.invoke(first, FOO, false)).thenReturn(Foo.class);
    when(loadClass.invoke(first, BAR, false)).thenReturn(BarFirst.class);
    when(loadClass.invoke(first, QUX, false)).thenThrow(new ClassNotFoundException());
    when(loadClass.invoke(first, BAZ, false)).thenThrow(new ClassNotFoundException());
    when(loadClass.invoke(second, BAR, false)).thenReturn(BarSecond.class);
    when(loadClass.invoke(second, QUX, false)).thenReturn(Qux.class);
    when(loadClass.invoke(second, BAZ, false)).thenThrow(new ClassNotFoundException());
    fooUrl = new URL(SCHEME + FOO);
    barFirstUrl = new URL(SCHEME + BAR);
    barSecondUrl = new URL(SCHEME + BAZ);
    quxUrl = new URL(SCHEME + QUX);
    when(first.getResource(FOO)).thenReturn(fooUrl);
    when(first.getResource(BAR)).thenReturn(barFirstUrl);
    when(second.getResource(BAR)).thenReturn(barSecondUrl);
    when(second.getResource(QUX)).thenReturn(quxUrl);
    when(first.getResources(FOO)).thenReturn(new SingleElementEnumeration(fooUrl));
    when(first.getResources(BAR)).thenReturn(new SingleElementEnumeration(barFirstUrl));
    when(second.getResources(BAR)).thenReturn(new SingleElementEnumeration(barSecondUrl));
    when(second.getResources(QUX)).thenReturn(new SingleElementEnumeration(quxUrl));
}

9. DownloadServiceTest#testReduceFunctionWithMavenJsons()

Project: Jenkins2
Source File: DownloadServiceTest.java
View license
public void testReduceFunctionWithMavenJsons() throws Exception {
    URL resource1 = DownloadServiceTest.class.getResource("hudson.tasks.Maven.MavenInstaller1.json");
    URL resource2 = DownloadServiceTest.class.getResource("hudson.tasks.Maven.MavenInstaller2.json");
    URL resource3 = DownloadServiceTest.class.getResource("hudson.tasks.Maven.MavenInstaller3.json");
    JSONObject json1 = JSONObject.fromObject(DownloadService.loadJSON(resource1));
    JSONObject json2 = JSONObject.fromObject(DownloadService.loadJSON(resource2));
    JSONObject json3 = JSONObject.fromObject(DownloadService.loadJSON(resource3));
    List<JSONObject> jsonObjectList = new ArrayList<>();
    jsonObjectList.add(json1);
    jsonObjectList.add(json2);
    jsonObjectList.add(json3);
    Downloadable downloadable = new Maven.MavenInstaller.DescriptorImpl().createDownloadable();
    JSONObject reducedJson = downloadable.reduce(jsonObjectList);
    URL expectedResult = DownloadServiceTest.class.getResource("hudson.tasks.Maven.MavenInstallerResult.json");
    JSONObject expectedResultJson = JSONObject.fromObject(DownloadService.loadJSON(expectedResult));
    assertEquals(reducedJson, expectedResultJson);
}

10. DownloadServiceTest#testReduceFunctionWithAntJsons()

Project: Jenkins2
Source File: DownloadServiceTest.java
View license
public void testReduceFunctionWithAntJsons() throws Exception {
    URL resource1 = DownloadServiceTest.class.getResource("hudson.tasks.Ant.AntInstaller1.json");
    URL resource2 = DownloadServiceTest.class.getResource("hudson.tasks.Ant.AntInstaller2.json");
    URL resource3 = DownloadServiceTest.class.getResource("hudson.tasks.Ant.AntInstaller3.json");
    JSONObject json1 = JSONObject.fromObject(DownloadService.loadJSON(resource1));
    JSONObject json2 = JSONObject.fromObject(DownloadService.loadJSON(resource2));
    JSONObject json3 = JSONObject.fromObject(DownloadService.loadJSON(resource3));
    List<JSONObject> jsonObjectList = new ArrayList<>();
    jsonObjectList.add(json1);
    jsonObjectList.add(json2);
    jsonObjectList.add(json3);
    Downloadable downloadable = new hudson.tasks.Ant.AntInstaller.DescriptorImpl().createDownloadable();
    JSONObject reducedJson = downloadable.reduce(jsonObjectList);
    URL expectedResult = DownloadServiceTest.class.getResource("hudson.tasks.Ant.AntInstallerResult.json");
    JSONObject expectedResultJson = JSONObject.fromObject(DownloadService.loadJSON(expectedResult));
    assertEquals(reducedJson, expectedResultJson);
}

11. DownloadServiceTest#testReduceFunctionWithJDKJsons()

Project: Jenkins2
Source File: DownloadServiceTest.java
View license
public void testReduceFunctionWithJDKJsons() throws Exception {
    URL resource1 = DownloadServiceTest.class.getResource("hudson.tools.JDKInstaller1.json");
    URL resource2 = DownloadServiceTest.class.getResource("hudson.tools.JDKInstaller2.json");
    URL resource3 = DownloadServiceTest.class.getResource("hudson.tools.JDKInstaller3.json");
    JSONObject json1 = JSONObject.fromObject(DownloadService.loadJSON(resource1));
    JSONObject json2 = JSONObject.fromObject(DownloadService.loadJSON(resource2));
    JSONObject json3 = JSONObject.fromObject(DownloadService.loadJSON(resource3));
    List<JSONObject> jsonObjectList = new ArrayList<>();
    jsonObjectList.add(json1);
    jsonObjectList.add(json2);
    jsonObjectList.add(json3);
    JDKInstaller.JDKList downloadable = new JDKInstaller.JDKList();
    JSONObject reducedJson = downloadable.reduce(jsonObjectList);
    URL expectedResult = DownloadServiceTest.class.getResource("hudson.tools.JDKInstallerResult.json");
    JSONObject expectedResultJson = JSONObject.fromObject(DownloadService.loadJSON(expectedResult));
    assertEquals(reducedJson, expectedResultJson);
}

12. PortletApplicationContextTest#testGetResource()

View license
/**
     * Test method for {@link org.apache.tiles.request.portlet.PortletApplicationContext#getResource(java.lang.String)}.
     * @throws IOException If something goes wrong.
     */
@Test
public void testGetResource() throws IOException {
    URL url = new URL("file:///portletContext/my/path.html");
    // normalize it
    url = new URL(url.toExternalForm());
    URL urlFr = new URL("file:///portletContext/my/path_fr.html");
    // normalize it
    urlFr = new URL(urlFr.toExternalForm());
    expect(portletContext.getResource("/my/path.html")).andReturn(url);
    expect(portletContext.getResource("/my/path_fr.html")).andReturn(urlFr);
    expect(portletContext.getResource("/null/path.html")).andReturn(null);
    replay(portletContext);
    ApplicationResource resource = context.getResource("/my/path.html");
    assertNotNull(resource);
    assertEquals(resource.getLocalePath(), "/my/path.html");
    assertEquals(resource.getPath(), "/my/path.html");
    assertEquals(Locale.ROOT, resource.getLocale());
    ApplicationResource resourceFr = context.getResource(resource, Locale.FRENCH);
    assertNotNull(resourceFr);
    assertEquals("/my/path_fr.html", resourceFr.getLocalePath());
    assertEquals("/my/path.html", resourceFr.getPath());
    assertEquals(Locale.FRENCH, resourceFr.getLocale());
    ApplicationResource nullResource = context.getResource("/null/path.html");
    assertNull(nullResource);
    verify(portletContext);
}

13. RestartServerTests#updateAndRestart()

Project: spring-boot
Source File: RestartServerTests.java
View license
@Test
public void updateAndRestart() throws Exception {
    URL url1 = new URL("file:/proj/module-a.jar!/");
    URL url2 = new URL("file:/proj/module-b.jar!/");
    URL url3 = new URL("file:/proj/module-c.jar!/");
    URL url4 = new URL("file:/proj/module-d.jar!/");
    URLClassLoader classLoaderA = new URLClassLoader(new URL[] { url1, url2 });
    URLClassLoader classLoaderB = new URLClassLoader(new URL[] { url3, url4 }, classLoaderA);
    SourceFolderUrlFilter filter = new DefaultSourceFolderUrlFilter();
    MockRestartServer server = new MockRestartServer(filter, classLoaderB);
    ClassLoaderFiles files = new ClassLoaderFiles();
    ClassLoaderFile fileA = new ClassLoaderFile(Kind.ADDED, new byte[0]);
    ClassLoaderFile fileB = new ClassLoaderFile(Kind.ADDED, new byte[0]);
    files.addFile("my/module-a", "ClassA.class", fileA);
    files.addFile("my/module-c", "ClassB.class", fileB);
    server.updateAndRestart(files);
    Set<URL> expectedUrls = new LinkedHashSet<URL>(Arrays.asList(url1, url3));
    assertThat(server.restartUrls).isEqualTo(expectedUrls);
    assertThat(server.restartFiles).isEqualTo(files);
}

14. DefaultSourceFolderUrlFilterTests#skippedProjects()

View license
@Test
public void skippedProjects() throws Exception {
    String sourceFolder = "/Users/me/code/spring-boot-samples/" + "spring-boot-sample-devtools";
    URL jarUrl = new URL("jar:file:/Users/me/tmp/" + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar!/");
    assertThat(this.filter.isMatch(sourceFolder, jarUrl)).isTrue();
    URL nestedJarUrl = new URL("jar:file:/Users/me/tmp/" + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar!/" + "lib/spring-boot-1.3.0.BUILD-SNAPSHOT.jar!/");
    assertThat(this.filter.isMatch(sourceFolder, nestedJarUrl)).isFalse();
    URL fileUrl = new URL("file:/Users/me/tmp/" + "spring-boot-sample-devtools-1.3.0.BUILD-SNAPSHOT.jar");
    assertThat(this.filter.isMatch(sourceFolder, fileUrl)).isTrue();
}

15. ExternalFactory#loadJARs()

View license
public static void loadJARs(URL[] jarURLs, boolean download) {
    // find lib jars first
    ArrayList<URL> libs = new ArrayList<>();
    for (URL jarURL : jarURLs) {
        if (isLib(jarURL)) {
            libs.add(jarURL);
        }
    }
    URL[] jarURLs1 = new URL[libs.size() + 1];
    libs.toArray(jarURLs1);
    int pos = libs.size();
    for (URL jarURL : jarURLs) {
        jarURLs1[pos] = jarURL;
        loadJAR(jarURLs1, download, jarURL);
    }
}

16. DownloadServiceTest#testReduceFunctionWithNotDefaultSchemaJsons()

Project: Jenkins2
Source File: DownloadServiceTest.java
View license
public void testReduceFunctionWithNotDefaultSchemaJsons() throws Exception {
    URL resource1 = DownloadServiceTest.class.getResource("hudson.plugins.cmake.CmakeInstaller1.json");
    URL resource2 = DownloadServiceTest.class.getResource("hudson.plugins.cmake.CmakeInstaller2.json");
    JSONObject json1 = JSONObject.fromObject(DownloadService.loadJSON(resource1));
    JSONObject json2 = JSONObject.fromObject(DownloadService.loadJSON(resource2));
    List<JSONObject> jsonObjectList = new ArrayList<>();
    jsonObjectList.add(json1);
    jsonObjectList.add(json2);
    Downloadable downloadable = new GenericDownloadFromUrlInstaller.DescriptorImpl().createDownloadable();
    JSONObject reducedJson = downloadable.reduce(jsonObjectList);
    URL expectedResult = DownloadServiceTest.class.getResource("hudson.plugins.cmake.CmakeInstallerResult.json");
    JSONObject expectedResultJson = JSONObject.fromObject(DownloadService.loadJSON(expectedResult));
    assertEquals(reducedJson, expectedResultJson);
}

17. ResourceBundleWrapper#removeCodeBase()

View license
/**
     * Instantiate a {@link URLClassLoader} for resource lookups where the
     * codeBase URL is removed.  This method is typically called from an
     * applet's init() method.  If this method is never called, the
     * <code>getBundle()</code> methods map to the standard
     * {@link ResourceBundle} lookup methods.
     *
     * @param codeBase  the codeBase URL.
     * @param urlClassLoader  the class loader.
     */
public static void removeCodeBase(URL codeBase, URLClassLoader urlClassLoader) {
    List<URL> urlsNoBase = new ArrayList<URL>();
    URL[] urls = urlClassLoader.getURLs();
    for (URL url : urls) {
        if (!url.sameFile(codeBase)) {
            urlsNoBase.add(url);
        }
    }
    // substitute the filtered URL list
    URL[] urlsNoBaseArray = urlsNoBase.toArray(new URL[urlsNoBase.size()]);
    noCodeBaseClassLoader = URLClassLoader.newInstance(urlsNoBaseArray);
}

18. TestXmlRpcFileManagerClient#testMetadataPersistence()

View license
/**
     * @since OODT-404
     *
     */
public void testMetadataPersistence() throws Exception {
    URL ingestUrl = this.getClass().getResource("/ingest");
    URL refUrl = this.getClass().getResource("/ingest/test-file-3.txt");
    URL metUrl = this.getClass().getResource("/ingest/test-file-3.txt.met");
    Metadata prodMet;
    StdIngester ingester = new StdIngester(transferServiceFacClass);
    prodMet = new SerializableMetadata(new FileInputStream(metUrl.getFile()));
    // now add the right file location
    prodMet.addMetadata(CoreMetKeys.FILE_LOCATION, new File(ingestUrl.getFile()).getCanonicalPath());
    String productId = ingester.ingest(new URL("http://localhost:" + FM_PORT), new File(refUrl.getFile()), prodMet);
    XmlRpcFileManagerClient fmc = new XmlRpcFileManagerClient(new URL("http://localhost:" + FM_PORT));
    Metadata m = fmc.getMetadata(fmc.getProductById(productId));
    assertEquals(m.getAllMetadata("TestElement").size(), 4);
    assertEquals(m.getMetadata("TestElement"), "fe");
}

19. AbstractServletsAdapterTest#servletDeployment()

View license
protected static WebArchive servletDeployment(String name, String adapterConfig, Class... servletClasses) {
    String webInfPath = "/adapter-test/" + name + "/WEB-INF/";
    URL keycloakJSON = AbstractServletsAdapterTest.class.getResource(webInfPath + adapterConfig);
    URL webXML = AbstractServletsAdapterTest.class.getResource(webInfPath + "web.xml");
    WebArchive deployment = ShrinkWrap.create(WebArchive.class, name + ".war").addClasses(servletClasses).addAsWebInfResource(webXML, "web.xml").addAsWebInfResource(jbossDeploymentStructure, JBOSS_DEPLOYMENT_STRUCTURE_XML);
    URL keystore = AbstractServletsAdapterTest.class.getResource(webInfPath + "keystore.jks");
    if (keystore != null) {
        deployment.addAsWebInfResource(keystore, "classes/keystore.jks");
    }
    if (keycloakJSON != null) {
        deployment.addAsWebInfResource(keycloakJSON, "keycloak.json");
    }
    addContextXml(deployment, name);
    return deployment;
}

20. UrlTests#testURL()

Project: commons-vfs
Source File: UrlTests.java
View license
/**
     * Tests url.
     */
public void testURL() throws Exception {
    final FileObject file = getReadFolder().resolveFile("some-dir/");
    final URL url = file.getURL();
    assertEquals(file.getName().getURI(), url.toExternalForm());
    final URL parentURL;
    try {
        parentURL = new URL(url, "..");
    } catch (final MalformedURLException e) {
        throw e;
    }
    assertEquals(file.getParent().getURL(), parentURL);
    final URL rootURL = new URL(url, "/");
    assertEquals(file.getFileSystem().getRoot().getURL(), rootURL);
}

21. SysinfoLocaleTest#runSysinfo()

Project: derby
Source File: SysinfoLocaleTest.java
View license
/**
     * Run a sysinfo class that is loaded in a separate class loader. A
     * separate class loader is required in order to force sysinfo to re-read
     * <code>derby.ui.locale</code> (happens when the class is loaded).
     */
private static void runSysinfo() throws Exception {
    final String className = "org.apache.derby.tools.sysinfo";
    URL sysinfoURL = SecurityManagerSetup.getURL(className);
    URL emmaURL = getEmmaJar();
    URL[] urls = null;
    if (emmaURL != null) {
        urls = new URL[] { sysinfoURL, emmaURL };
    } else {
        urls = new URL[] { sysinfoURL };
    }
    // Create a new class loader that loads the Derby classes afresh.
    // Its parent (platformLoader) is a class loader that is able to
    // load the JDBC classes and other core classes needed by the Derby
    // classes.
    ClassLoader platformLoader = java.sql.Connection.class.getClassLoader();
    URLClassLoader loader = new URLClassLoader(urls, platformLoader);
    Class<?> copy = Class.forName(className, true, loader);
    Method main = copy.getMethod("main", new Class[] { String[].class });
    main.invoke(null, new Object[] { new String[0] });
}

22. TestResourceLoader#testClasspathOrURL()

Project: esper
Source File: TestResourceLoader.java
View license
public void testClasspathOrURL() {
    URL url = this.getClass().getClassLoader().getResource(TEST_RESOURCE);
    URL urlAfterResolve = ResourceLoader.resolveClassPathOrURLResource("a", url.toString());
    assertEquals(url, urlAfterResolve);
    URL url3 = ResourceLoader.resolveClassPathOrURLResource("a", "file:///xxx/a.b");
    assertEquals("file:/xxx/a.b", url3.toString());
    try {
        ResourceLoader.resolveClassPathOrURLResource("a", "b");
        fail();
    } catch (EPException ex) {
    }
}

23. EndpointTest#testChangeDefaultParamValues()

Project: hbc
Source File: EndpointTest.java
View license
@Test
public void testChangeDefaultParamValues() throws MalformedURLException {
    DefaultStreamingEndpoint endpoint = new DefaultStreamingEndpoint("/path", HttpConstants.HTTP_GET, false);
    endpoint.delimited(false);
    URL url = new URL(Constants.STREAM_HOST + endpoint.getURI());
    assertFalse(url.getQuery().contains(Constants.DELIMITED_PARAM));
    assertTrue(url.getQuery().contains(Constants.STALL_WARNING_PARAM + "=" + Constants.STALL_WARNING_VALUE));
    endpoint.stallWarnings(false);
    url = new URL(Constants.STREAM_HOST + endpoint.getURI());
    assertNull(url.getQuery());
}

24. App#getClassesForPackage()

Project: juddi
Source File: App.java
View license
public static List<Class> getClassesForPackage(Package pkg) {
    List<Class> classes = new ArrayList<Class>();
    String pkgname = pkg.getName();
    log(pkgname);
    log(pkg.getName());
    String relPath = pkgname.replace('.', '/');
    URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
    if (resource == null) {
        processDirectory(new File(pkgname), pkgname, classes);
        throw new RuntimeException("Unexpected problem: No resource for " + relPath);
    }
    log("Package: '" + pkgname + "' becomes Resource: '" + resource.toString() + "'");
    resource.getPath();
    if (resource.toString().startsWith("jar:")) {
        processJarfile(resource, pkgname, classes);
    } else {
        processDirectory(new File(resource.getPath()), pkgname, classes);
    }
    return classes;
}

25. ComponentFamilyTest#setup()

View license
@Before
public void setup() throws Exception {
    URL componentProfileUrl = getClass().getClassLoader().getResource("ValidationComponent.xml");
    assertNotNull(componentProfileUrl);
    componentProfile = util.getProfile(componentProfileUrl);
    componentRegistry.addComponentProfile(componentProfile, null, null);
    URL dataflowUrl = getClass().getClassLoader().getResource("beanshell_test.t2flow");
    assertNotNull(dataflowUrl);
    bundle = new WorkflowBundleIO().readBundle(dataflowUrl, null);
    componentFamily = componentRegistry.createComponentFamily("Test Component Family", componentProfile, "Some description", null, null);
}

26. ComponentTest#setUp()

View license
@Before
public void setUp() throws Exception {
    URL dataflowUrl = getClass().getClassLoader().getResource("beanshell_test.t2flow");
    assertNotNull(dataflowUrl);
    bundle = new WorkflowBundleIO().readBundle(dataflowUrl, null);
    URL componentProfileUrl = getClass().getClassLoader().getResource("ValidationComponent.xml");
    assertNotNull(componentProfileUrl);
    Profile componentProfile = util.getProfile(componentProfileUrl);
    componentFamily = componentRegistry.createComponentFamily("Test Component Family", componentProfile, "Some description", null, null);
    component = componentFamily.createComponentBasedOn("Test Component", "Some description", bundle).getComponent();
}

27. ComponentVersionTest#setUp()

View license
@Before
public void setUp() throws Exception {
    URL dataflowUrl = getClass().getClassLoader().getResource("beanshell_test.t2flow");
    assertNotNull(dataflowUrl);
    bundle = new WorkflowBundleIO().readBundle(dataflowUrl, null);
    URL componentProfileUrl = getClass().getClassLoader().getResource("ValidationComponent.xml");
    assertNotNull(componentProfileUrl);
    Profile componentProfile = util.getProfile(componentProfileUrl);
    componentFamily = componentRegistry.createComponentFamily("Test Component Family", componentProfile, "Some description", null, null);
    componentVersion = componentFamily.createComponentBasedOn("Test Component", "Some description", bundle);
}

28. TestTezClientUtils#validateSetTezJarLocalResourcesDefinedExistingDirectoryIgnored()

View license
/**
   * 
   * @throws Exception
   */
@Test(timeout = 5000)
public void validateSetTezJarLocalResourcesDefinedExistingDirectoryIgnored() throws Exception {
    URL[] cp = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
    StringBuffer buffer = new StringBuffer();
    for (URL url : cp) {
        buffer.append(url.toExternalForm());
        buffer.append(",");
    }
    TezConfiguration conf = new TezConfiguration();
    conf.set(TezConfiguration.TEZ_LIB_URIS, buffer.toString());
    conf.setBoolean(TezConfiguration.TEZ_IGNORE_LIB_URIS, true);
    Credentials credentials = new Credentials();
    Map<String, LocalResource> localizedMap = TezClientUtils.setupTezJarsLocalResources(conf, credentials);
    assertTrue(localizedMap.isEmpty());
}

29. TestTezClientUtils#validateSetTezJarLocalResourcesDefinedExistingDirectoryIgnoredSetToFalse()

View license
/**
   * 
   * @throws Exception
   */
@Test(timeout = 5000)
public void validateSetTezJarLocalResourcesDefinedExistingDirectoryIgnoredSetToFalse() throws Exception {
    URL[] cp = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
    StringBuffer buffer = new StringBuffer();
    for (URL url : cp) {
        buffer.append(url.toExternalForm());
        buffer.append(",");
    }
    TezConfiguration conf = new TezConfiguration();
    conf.set(TezConfiguration.TEZ_LIB_URIS, buffer.toString());
    conf.setBoolean(TezConfiguration.TEZ_IGNORE_LIB_URIS, false);
    Credentials credentials = new Credentials();
    Map<String, LocalResource> localizedMap = TezClientUtils.setupTezJarsLocalResources(conf, credentials);
    assertFalse(localizedMap.isEmpty());
}

30. IncludeProjectDependenciesComponentConfigurator#addProjectDependenciesToClassRealm()

View license
@SuppressWarnings({ "unchecked" })
private void addProjectDependenciesToClassRealm(ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm) throws ComponentConfigurationException {
    List<String> classpathElements;
    try {
        classpathElements = (List<String>) expressionEvaluator.evaluate("${project.testClasspathElements}");
    } catch (ExpressionEvaluationException e) {
        throw new ComponentConfigurationException("There was a problem evaluating: ${project.testClasspathElements}", e);
    }
    // Add the project dependencies to the ClassRealm
    final URL[] urls = buildURLs(classpathElements);
    for (URL url : urls) {
        containerRealm.addConstituent(url);
    }
}

31. ClassScaner#scanByURLClassLoader()

Project: Gaea
Source File: ClassScaner.java
View license
private Set<Class> scanByURLClassLoader() throws URISyntaxException, IOException, ClassNotFoundException {
    Set<Class> classes = new LinkedHashSet<Class>();
    URL[] urlAry = ((URLClassLoader) Thread.currentThread().getContextClassLoader()).getURLs();
    for (URL url : urlAry) {
        if (!url.getPath().equalsIgnoreCase("/")) {
            System.out.println("scanByURLClassLoader:" + URLDecoder.decode(url.getPath(), "utf-8"));
            if (url.getPath().endsWith(".jar")) {
                classes.addAll(ClassHelper.GetClassFromJar(URLDecoder.decode(url.getPath(), "utf-8"), KEY_WORD));
            } else {
                getClassFromURL(url, "", classes);
            }
        }
    }
    return classes;
}

32. AppsForYourDomainClient#suspendUser()

View license
/**
   * Suspends a user. Note that executing this method for a user who is already
   * suspended has no effect.
   * 
   * @param username The user you wish to suspend.
   * @throws AppsForYourDomainException If a Provisioning API specific occurs.
   * @throws ServiceException If a generic GData framework error occurs.
   * @throws IOException If an error occurs communicating with the GData
   *         service.
   */
public UserEntry suspendUser(String username) throws AppsForYourDomainException, ServiceException, IOException {
    LOGGER.log(Level.INFO, "Suspending user '" + username + "'.");
    URL retrieveUrl = new URL(domainUrlBase + "user/" + SERVICE_VERSION + "/" + username);
    UserEntry userEntry = userService.getEntry(retrieveUrl, UserEntry.class);
    userEntry.getLogin().setSuspended(true);
    URL updateUrl = new URL(domainUrlBase + "user/" + SERVICE_VERSION + "/" + username);
    return userService.update(updateUrl, userEntry);
}

33. AppsForYourDomainClient#restoreUser()

View license
/**
   * Restores a user. Note that executing this method for a user who is not
   * suspended has no effect.
   * 
   * @param username The user you wish to restore.
   * @throws AppsForYourDomainException If a Provisioning API specific occurs.
   * @throws ServiceException If a generic GData framework error occurs.
   * @throws IOException If an error occurs communicating with the GData
   *         service.
   */
public UserEntry restoreUser(String username) throws AppsForYourDomainException, ServiceException, IOException {
    LOGGER.log(Level.INFO, "Restoring user '" + username + "'.");
    URL retrieveUrl = new URL(domainUrlBase + "user/" + SERVICE_VERSION + "/" + username);
    UserEntry userEntry = userService.getEntry(retrieveUrl, UserEntry.class);
    userEntry.getLogin().setSuspended(false);
    URL updateUrl = new URL(domainUrlBase + "user/" + SERVICE_VERSION + "/" + username);
    return userService.update(updateUrl, userEntry);
}

34. AppsForYourDomainClient#addAdminPrivilege()

View license
/**
   * Set admin privilege for user. Note that executing this method for a user
   * who is already an admin has no effect.
   * 
   * @param username The user you wish to make an admin.
   * @throws AppsForYourDomainException If a Provisioning API specific error
   *         occurs.
   * @throws ServiceException If a generic GData framework error occurs.
   * @throws IOException If an error occurs communicating with the GData
   *         service.
   */
public UserEntry addAdminPrivilege(String username) throws AppsForYourDomainException, ServiceException, IOException {
    LOGGER.log(Level.INFO, "Setting admin privileges for user '" + username + "'.");
    URL retrieveUrl = new URL(domainUrlBase + "user/" + SERVICE_VERSION + "/" + username);
    UserEntry userEntry = userService.getEntry(retrieveUrl, UserEntry.class);
    userEntry.getLogin().setAdmin(true);
    URL updateUrl = new URL(domainUrlBase + "user/" + SERVICE_VERSION + "/" + username);
    return userService.update(updateUrl, userEntry);
}

35. AppsForYourDomainClient#removeAdminPrivilege()

View license
/**
   * Remove admin privilege for user. Note that executing this method for a user
   * who is not an admin has no effect.
   * 
   * @param username The user you wish to remove admin privileges.
   * @throws AppsForYourDomainException If a Provisioning API specific error
   *         occurs.
   * @throws ServiceException If a generic GData framework error occurs.
   * @throws IOException If an error occurs communicating with the GData
   *         service.
   */
public UserEntry removeAdminPrivilege(String username) throws AppsForYourDomainException, ServiceException, IOException {
    LOGGER.log(Level.INFO, "Removing admin privileges for user '" + username + "'.");
    URL retrieveUrl = new URL(domainUrlBase + "user/" + SERVICE_VERSION + "/" + username);
    UserEntry userEntry = userService.getEntry(retrieveUrl, UserEntry.class);
    userEntry.getLogin().setAdmin(false);
    URL updateUrl = new URL(domainUrlBase + "user/" + SERVICE_VERSION + "/" + username);
    return userService.update(updateUrl, userEntry);
}

36. AppsForYourDomainClient#forceUserToChangePassword()

View license
/**
   * Require a user to change password at next login. Note that executing this
   * method for a user who is already required to change password at next login
   * as no effect.
   * 
   * @param username The user who must change his or her password.
   * @throws AppsForYourDomainException If a Provisioning API specific occurs.
   * @throws ServiceException If a generic GData framework error occurs.
   * @throws IOException If an error occurs communicating with the GData
   *         service.
   */
public UserEntry forceUserToChangePassword(String username) throws AppsForYourDomainException, ServiceException, IOException {
    LOGGER.log(Level.INFO, "Requiring " + username + " to change password at " + "next login.");
    URL retrieveUrl = new URL(domainUrlBase + "user/" + SERVICE_VERSION + "/" + username);
    UserEntry userEntry = userService.getEntry(retrieveUrl, UserEntry.class);
    userEntry.getLogin().setChangePasswordAtNextLogin(true);
    URL updateUrl = new URL(domainUrlBase + "user/" + SERVICE_VERSION + "/" + username);
    return userService.update(updateUrl, userEntry);
}

37. CreateMap#createMap()

Project: gdata-java-client
Source File: CreateMap.java
View license
public static MapEntry createMap(MapsService myService) throws ServiceException, IOException {
    // Replace the following URL with your metafeed's POST (Edit) URL
    // Replace userID with appropriate values for your map
    final URL editUrl = new URL("http://maps.google.com/maps/feeds/maps/userID/full");
    MapFeed resultFeed = myService.getFeed(editUrl, MapFeed.class);
    URL mapUrl = new URL(resultFeed.getEntryPostLink().getHref());
    // Create a MapEntry object
    MapEntry myEntry = new MapEntry();
    myEntry.setTitle(new PlainTextConstruct("Demo Map"));
    myEntry.setSummary(new PlainTextConstruct("Summary"));
    myEntry.getAuthors().add(new Person("My Name", null, "username"));
    return myService.insert(mapUrl, myEntry);
}

38. ConfigurationPropertyReaderTest#shouldRetrieveUrlPropertyGivenAsStringUrl()

View license
@Test
public void shouldRetrieveUrlPropertyGivenAsStringUrl() throws Exception {
    URL root = ConfigurationPropertyReaderTest.class.getClassLoader().getResource(".");
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("configuration_resource", root.toExternalForm() + "/configuration-test.properties");
    ConfigurationPropertyReader reader = new ConfigurationPropertyReader(properties);
    URL value = reader.property("configuration_resource", URL.class).getValue();
    assertThat(value).isNotNull();
    Properties loadedProperties = loadPropertiesFromUrl(value);
    assertThat(loadedProperties.get("hibernate.ogm.configuration.testproperty")).isEqualTo("foobar");
}

39. DDLGeneratorTest#generatorTest()

Project: ignite
Source File: DDLGeneratorTest.java
View license
@Test
@SuppressWarnings("unchecked")
public /** */
void generatorTest() {
    ClassLoader clsLdr = DDLGeneratorTest.class.getClassLoader();
    URL url1 = clsLdr.getResource("org/apache/ignite/tests/persistence/primitive/persistence-settings-1.xml");
    // TODO IGNITE-1371 Possible NPE
    String file1 = url1.getFile();
    URL url2 = clsLdr.getResource("org/apache/ignite/tests/persistence/pojo/persistence-settings-3.xml");
    // TODO IGNITE-1371 Possible NPE
    String file2 = url2.getFile();
    DDLGenerator.main(new String[] { file1, file2 });
}

40. JettyRestProcessorSignedSelfTest#testUnauthorized()

View license
/**
     * @throws Exception If failed.
     */
public void testUnauthorized() throws Exception {
    String addr = "http://" + LOC_HOST + ":" + restPort() + "/ignite?cmd=top";
    URL url = new URL(addr);
    URLConnection conn = url.openConnection();
    // Request has not been signed.
    conn.connect();
    assert ((HttpURLConnection) conn).getResponseCode() == 401;
    // Request with authentication info.
    addr = "http://" + LOC_HOST + ":" + restPort() + "/ignite?cmd=top";
    url = new URL(addr);
    conn = url.openConnection();
    conn.setRequestProperty("X-Signature", signature());
    conn.connect();
    assertEquals(200, ((HttpURLConnection) conn).getResponseCode());
}

41. PopulateObrFileJob#getAntBuildFile()

Project: karaf-eik
Source File: PopulateObrFileJob.java
View license
/**
     * Getter for the {@code build.xml} file used to execute the
     * {@link AntRunner}
     *
     * @return the {@link File} that the {@code AntRunner} will execute
     * @throws IOException
     *             thrown if the {@code File} cannot be created
     */
private File getAntBuildFile() throws IOException {
    final Bundle thisBundle = KarafUIPluginActivator.getDefault().getBundle();
    final URL[] urls = FileLocator.findEntries(thisBundle, new Path(ANT_BUILD_OBR_FILE));
    if (urls.length > 1 || urls.length == 0) {
        throw new AssertionError("Error locating Bundle URL for " + ANT_BUILD_OBR_FILE);
    }
    final URL fileUrl = FileLocator.toFileURL(urls[0]);
    try {
        return new File(fileUrl.toURI());
    } catch (final URISyntaxException e) {
        throw new IOException("Unable to convert URI to File", e);
    }
}

42. ClasspathReader#read()

Project: Kundera
Source File: ClasspathReader.java
View license
@Override
public final void read() {
    URL[] resources = findResources();
    for (URL resource : resources) {
        try {
            ResourceIterator itr = getResourceIterator(resource, getFilter());
            InputStream is = null;
            while ((is = itr.next()) != null) {
                scanClass(is);
            }
        } catch (IOException e) {
            logger.error("Error during reading via classpath, Caused by:" + e.getMessage());
            throw new ResourceReadingException(e);
        }
    }
}

43. FilePathTest#installIfNecessaryFollowsRedirects()

Project: Jenkins2
Source File: FilePathTest.java
View license
@Issue("JENKINS-23507")
@Test
public void installIfNecessaryFollowsRedirects() throws Exception {
    File tmp = temp.getRoot();
    final FilePath d = new FilePath(tmp);
    FilePath.UrlFactory urlFactory = mock(FilePath.UrlFactory.class);
    d.setUrlFactory(urlFactory);
    final HttpURLConnection con = mock(HttpURLConnection.class);
    final HttpURLConnection con2 = mock(HttpURLConnection.class);
    final URL url = someUrlToZipFile(con);
    when(con.getResponseCode()).thenReturn(HttpURLConnection.HTTP_MOVED_TEMP);
    URL url2 = someUrlToZipFile(con2);
    String someUrl = url2.toExternalForm();
    when(con.getHeaderField("Location")).thenReturn(someUrl);
    when(urlFactory.newURL(someUrl)).thenReturn(url2);
    when(con2.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK);
    when(con2.getInputStream()).thenReturn(someZippedContent());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String message = "going ahead";
    assertTrue(d.installIfNecessaryFrom(url, new StreamTaskListener(baos), message));
}

44. IncludeProjectDependenciesComponentConfigurator#addProjectDependenciesToClassRealm()

View license
private void addProjectDependenciesToClassRealm(ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm) throws ComponentConfigurationException {
    List<String> runtimeClasspathElements;
    try {
        //noinspection unchecked
        runtimeClasspathElements = (List<String>) expressionEvaluator.evaluate("${project.runtimeClasspathElements}");
    } catch (ExpressionEvaluationException e) {
        throw new ComponentConfigurationException("There was a problem evaluating: ${project.runtimeClasspathElements}", e);
    }
    // Add the project dependencies to the ClassRealm
    final URL[] urls = buildURLs(runtimeClasspathElements);
    for (URL url : urls) {
        containerRealm.addConstituent(url);
    }
}

45. DocumentLoaderTest#jarCacheHitThreadCtx()

Project: jsonld-java
Source File: DocumentLoaderTest.java
View license
@Test
public void jarCacheHitThreadCtx() throws Exception {
    final URL url = new URL("http://nonexisting.example.com/nested/hello");
    final URL nestedJar = getClass().getResource("/nested.jar");
    try {
        final Object hello = documentLoader.fromURL(url);
        fail("Should not be able to find nested/hello yet");
    } catch (final IOException ex) {
    }
    final ClassLoader cl = new URLClassLoader(new URL[] { nestedJar });
    Thread.currentThread().setContextClassLoader(cl);
    final Object hello = documentLoader.fromURL(url);
    assertTrue(hello instanceof Map);
    assertEquals("World!", ((Map) hello).get("Hello"));
}

46. FileExtensionsIT#extensionsCanBeRemovedFromNames()

View license
@Test
public void extensionsCanBeRemovedFromNames() throws ClassNotFoundException {
    URL schema1 = getClass().getResource("/schema/fileExtensions/nameWithExtension.schema.json");
    URL schema2 = getClass().getResource("/schema/fileExtensions/nameWithNoExtension");
    schemaRule.generate(schema1, "com.example", config("fileExtensions", new String[] { ".schema.json" }));
    schemaRule.generate(schema2, "com.example", config("fileExtensions", new String[] { ".schema.json" }));
    ClassLoader loader = schemaRule.compile();
    loader.loadClass("com.example.NameWithExtension");
    loader.loadClass("com.example.NameWithNoExtension");
}

47. FileExtensionsIT#byDefaultOnlyfirstExtensionRemoved()

View license
@Test
public void byDefaultOnlyfirstExtensionRemoved() throws ClassNotFoundException {
    URL schema1 = getClass().getResource("/schema/fileExtensions/nameWithExtension.schema.json");
    URL schema2 = getClass().getResource("/schema/fileExtensions/nameWithNoExtension");
    schemaRule.generate(schema1, "com.example", config());
    schemaRule.generate(schema2, "com.example", config());
    ClassLoader loader = schemaRule.compile();
    loader.loadClass("com.example.NameWithExtensionSchema");
    loader.loadClass("com.example.NameWithNoExtension");
}

48. RemoveOldOutputIT#removeOldOutputCausesOldTypesToBeDeleted()

View license
@Test(expected = ClassNotFoundException.class)
public void removeOldOutputCausesOldTypesToBeDeleted() throws ClassNotFoundException {
    URL schema1 = getClass().getResource("/schema/properties/primitiveProperties.json");
    URL schema2 = getClass().getResource("/schema/properties/orderedProperties.json");
    schemaRule.generate(schema1, "com.example", config("removeOldOutput", true));
    schemaRule.generate(schema2, "com.example", config("removeOldOutput", true));
    schemaRule.compile().loadClass("com.example.PrimitiveProperties");
}

49. RemoveOldOutputIT#byDefaultPluginDoesNotRemoveOldOutput()

View license
@Test
public void byDefaultPluginDoesNotRemoveOldOutput() throws ClassNotFoundException {
    URL schema1 = getClass().getResource("/schema/properties/primitiveProperties.json");
    URL schema2 = getClass().getResource("/schema/properties/orderedProperties.json");
    schemaRule.generate(schema1, "com.example", config());
    schemaRule.generate(schema2, "com.example", config());
    schemaRule.compile().loadClass("com.example.PrimitiveProperties");
}

50. WSDLLocatorTest#testResolveInParentDir2()

Project: juddi
Source File: WSDLLocatorTest.java
View license
@Test
public void testResolveInParentDir2() throws URISyntaxException {
    WSDLLocatorImpl wsdlLocatorImpl = new WSDLLocatorImpl(null);
    URL wsdlFile = ClassUtil.getResource("wsdl/HelloWorld.wsdl", this.getClass());
    if (wsdlFile == null)
        Assert.fail("Can not find HelloWorld.wsdl file");
    String wsdlFileStr = wsdlFile.toExternalForm();
    String wsdlDir = wsdlFileStr.substring(0, wsdlFileStr.lastIndexOf("/"));
    wsdlDir = wsdlDir.substring(0, wsdlDir.lastIndexOf("/"));
    wsdlDir = wsdlDir.substring(0, wsdlDir.lastIndexOf("/"));
    URL url = wsdlLocatorImpl.constructImportUrl(wsdlFileStr, "../../child.wsdl");
    Assert.assertEquals(wsdlDir + "/child.wsdl", url.toExternalForm());
}

51. Support_Resources#getURL()

Project: j2objc
Source File: Support_Resources.java
View license
public static String getURL(String name) {
    String folder = null;
    String fileName = name;
    File resources = createTempFolder();
    int index = name.lastIndexOf("/");
    if (index != -1) {
        folder = name.substring(0, index);
        name = name.substring(index + 1);
    }
    copyFile(resources, folder, name);
    URL url = null;
    String resPath = resources.toString();
    if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\') {
        resPath = resPath.substring(1);
    }
    try {
        url = new URL("file:/" + resPath + "/" + fileName);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    return url.toString();
}

52. RelativePath#main()

Project: jdk7u-jdk
Source File: RelativePath.java
View license
public static void main(String[] args) throws Exception {
    String uri1 = "http://h/../d1/";
    String uri2 = "../d/i.htm";
    String expected = "http://h/../d/i.htm";
    URI uri = new URI(uri1);
    String s1 = uri.resolve(uri2).toString();
    URL url = new URL(uri1);
    URL url2 = new URL(url, uri2);
    String s2 = url2.toString();
    if (!(expected.equalsIgnoreCase(s1)))
        throw new RuntimeException("URI.resolve didn't return expected result [" + s1 + " versus " + expected + "]");
    if (!(expected.equalsIgnoreCase(s2)))
        throw new RuntimeException("URL(url, String) didn't return expected result [" + s2 + " versus " + expected + "]");
}

53. PassByJNDI#test1()

Project: log4j
Source File: PassByJNDI.java
View license
public void test1() throws Exception {
    HttpURLConnection connection;
    String contents;
    URL urlToto = new URL("http://localhost:8080/tata/XServlet");
    URL urlTiti = new URL("http://localhost:8080/titi/XServlet");
    connection = (HttpURLConnection) urlToto.openConnection();
    contents = getContents(connection).toString();
    assertEquals("tata", contents.trim());
    connection = (HttpURLConnection) urlTiti.openConnection();
    contents = getContents(connection).toString();
    assertEquals("titi", contents.trim());
}

54. MarginallyCleverTranslationXmlFileHelper#getLanguagesFolderUrl()

View license
/**
   * @return url object representing the languages folder
   * @see #getLanguagesFolderUrlRelativeToClasspath()
   * @see #getLanguagesFolderUrlFromUserDirectory()
   */
private static URL getLanguagesFolderUrl() {
    URL languagesFolderUrl = getLanguagesFolderUrlRelativeToClasspath();
    if (languagesFolderUrl != null) {
        Log.message("languages relative to classpath: " + languagesFolderUrl.toString());
    }
    URL languageFolderUsingUserDirectory = getLanguagesFolderUrlFromUserDirectory();
    if (languageFolderUsingUserDirectory != null) {
        Log.message("languages via user directory: " + languageFolderUsingUserDirectory.toString());
    }
    if (languagesFolderUrl == null) {
        languagesFolderUrl = languageFolderUsingUserDirectory;
    }
    return languagesFolderUrl;
}

55. MavenCatalogResolverTest#checkReenterability()

View license
@Test
public void checkReenterability() throws IOException {
    CatalogManager cma = new CatalogManager();
    cma.setIgnoreMissingProperties(true);
    cma.setUseStaticCatalog(false);
    final CatalogResolver cra = new CatalogResolver(cma);
    URL a = getClass().getResource("a/catalog.cat");
    cra.getCatalog().parseCatalog(a);
    InputSource ea = cra.resolveEntity(null, "http://www.w3.org/1999/xlink.xsd");
    Assert.assertNotNull(ea);
    CatalogManager cmb = new CatalogManager();
    cmb.setIgnoreMissingProperties(true);
    cmb.setUseStaticCatalog(false);
    final CatalogResolver crb = new CatalogResolver(cmb);
    URL b = getClass().getResource("b/catalog.cat");
    crb.getCatalog().parseCatalog(b);
    InputSource eb = crb.resolveEntity(null, "http://www.w3.org/2005/atom-author-link.xsd");
    Assert.assertNotNull(eb);
}

56. AbstractGrinderClassPathProcessor#buildClasspathBasedOnCurrentClassLoader()

View license
/**
	 * Construct classPath from current classLoader.
	 *
	 * @param logger logger
	 * @return classpath optimized for grinder.
	 */
public String buildClasspathBasedOnCurrentClassLoader(Logger logger) {
    URL[] urls = ((URLClassLoader) AbstractGrinderClassPathProcessor.class.getClassLoader()).getURLs();
    StringBuilder builder = new StringBuilder();
    for (URL each : urls) {
        builder.append(each.getFile()).append(File.pathSeparator);
    }
    if (builder.length() < 300) {
        // In case of the URLClassLoader is not activated, Try with system class path
        final String property = System.getProperty("java.class.path", "");
        for (String each : property.split(File.pathSeparator)) {
            builder.append(each).append(File.pathSeparator);
        }
    }
    return filterClassPath(builder.toString(), logger);
}

57. BytecodeLoadingPluginTest#testHelloworldWithDeps()

View license
/**
     * Test an archive with module dependencies.
     * @throws Exception
     */
@Test
public void testHelloworldWithDeps() throws Exception {
    URL jarPath = getClass().getClassLoader().getResource("testmodules/helloworld.jar");
    JarScriptArchive jarArchive = new JarScriptArchive.Builder(Paths.get(jarPath.getFile())).build();
    URL depJarPath = getClass().getClassLoader().getResource("testmodules/hellohelper.jar");
    JarScriptArchive depArchive = new JarScriptArchive.Builder(Paths.get(depJarPath.getFile())).build();
    Set<ScriptArchive> archives = new HashSet<ScriptArchive>();
    Collections.<ScriptArchive>addAll(archives, depArchive, jarArchive);
    moduleLoader.updateScriptArchives(archives);
    ScriptModule module = moduleLoader.getScriptModule(ModuleId.create("helloworld"));
    assertNotNull(module);
    Class<?> targetClass = ScriptModuleUtils.findClass(module, "com.netflix.nicobar.test.Helloworld");
    assertNotNull(targetClass);
    Object instance = targetClass.newInstance();
    Method method = targetClass.getMethod("execute");
    String message = (String) method.invoke(instance);
    assertEquals(message, "Hello Nicobar World!");
}

58. TestFileManagerCli#setUp()

Project: oodt
Source File: TestFileManagerCli.java
View license
@Override
public void setUp() throws Exception {
    super.setUp();
    Properties properties = new Properties(System.getProperties());
    properties.setProperty("org.apache.oodt.cas.cli.debug", "true");
    URL actionsUrl = this.getClass().getResource("/cmd-line-actions.xml");
    properties.setProperty("org.apache.oodt.cas.cli.action.spring.config", "file:" + new File(actionsUrl.getFile()).getAbsolutePath());
    URL optionsUrl = this.getClass().getResource("/cmd-line-options.xml");
    properties.setProperty("org.apache.oodt.cas.cli.option.spring.config", "file:" + new File(optionsUrl.getFile()).getAbsolutePath());
    System.setProperties(properties);
    cmdLineUtility = new CmdLineUtility();
    UseMockClientCmdLineActionStore actionStore = new UseMockClientCmdLineActionStore();
    client = actionStore.getClient();
    cmdLineUtility.setActionStore(actionStore);
}

59. TestXmlRpcFileManagerClient#testIngest()

View license
public void testIngest() throws Exception {
    URL ingestUrl = this.getClass().getResource("/ingest");
    URL refUrl = this.getClass().getResource("/ingest/test.txt");
    Metadata prodMet = new Metadata();
    prodMet.addMetadata(CoreMetKeys.FILE_LOCATION, new File(ingestUrl.getFile()).getCanonicalPath());
    prodMet.addMetadata(CoreMetKeys.FILENAME, "test.txt");
    prodMet.addMetadata(CoreMetKeys.PRODUCT_NAME, "TestFile");
    prodMet.addMetadata(CoreMetKeys.PRODUCT_TYPE, "GenericFile");
    StdIngester ingester = new StdIngester(transferServiceFacClass);
    String productId = ingester.ingest(new URL("http://localhost:" + FM_PORT), new File(refUrl.getFile()), prodMet);
    XmlRpcFileManagerClient fmc = new XmlRpcFileManagerClient(new URL("http://localhost:" + FM_PORT));
    Metadata m = fmc.getMetadata(fmc.getProductById(productId));
    assertEquals(m.getMetadata("Filename"), "test.txt");
    deleteAllFiles("/tmp/test-type");
}

60. TestXmlRpcFileManagerClient#testRemoveFile()

View license
public void testRemoveFile() throws Exception {
    URL ingestUrl = this.getClass().getResource("/ingest");
    URL refUrl = this.getClass().getResource("/ingest/test-delete.txt");
    Metadata prodMet = new Metadata();
    prodMet.addMetadata(CoreMetKeys.FILE_LOCATION, new File(ingestUrl.getFile()).getCanonicalPath());
    prodMet.addMetadata(CoreMetKeys.FILENAME, "test-delete.txt");
    prodMet.addMetadata(CoreMetKeys.PRODUCT_NAME, "TestFile");
    prodMet.addMetadata(CoreMetKeys.PRODUCT_TYPE, "GenericFile");
    StdIngester ingester = new StdIngester(transferServiceFacClass);
    String productId = ingester.ingest(new URL("http://localhost:" + FM_PORT), new File(refUrl.getFile()), prodMet);
    XmlRpcFileManagerClient fmc = new XmlRpcFileManagerClient(new URL("http://localhost:" + FM_PORT));
    Metadata m = fmc.getMetadata(fmc.getProductById(productId));
    assertEquals(m.getMetadata("Filename"), "test-delete.txt");
    String loc = m.getMetadata("FileLocation");
    fmc.removeFile(loc + "/" + m.getMetadata("Filename"));
    fmc.getProductById(productId);
    deleteAllFiles("/tmp/test-type");
}

61. JrtFileSystemProvider#newJrtFsLoader()

Project: openjdk
Source File: JrtFileSystemProvider.java
View license
private static URLClassLoader newJrtFsLoader(Path jrtfs) {
    final URL url;
    try {
        url = jrtfs.toUri().toURL();
    } catch (MalformedURLException mue) {
        throw new IllegalArgumentException(mue);
    }
    final URL[] urls = new URL[] { url };
    return AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {

        @Override
        public URLClassLoader run() {
            return new JrtFsLoader(urls);
        }
    });
}

62. RelativePath#main()

Project: openjdk
Source File: RelativePath.java
View license
public static void main(String[] args) throws Exception {
    String uri1 = "http://h/../d1/";
    String uri2 = "../d/i.htm";
    String expected = "http://h/../d/i.htm";
    URI uri = new URI(uri1);
    String s1 = uri.resolve(uri2).toString();
    URL url = new URL(uri1);
    URL url2 = new URL(url, uri2);
    String s2 = url2.toString();
    if (!(expected.equalsIgnoreCase(s1)))
        throw new RuntimeException("URI.resolve didn't return expected result [" + s1 + " versus " + expected + "]");
    if (!(expected.equalsIgnoreCase(s2)))
        throw new RuntimeException("URL(url, String) didn't return expected result [" + s2 + " versus " + expected + "]");
}

63. BaseOAuth20ClientTests#testSetState()

Project: pac4j
Source File: BaseOAuth20ClientTests.java
View license
@Test
public void testSetState() throws MalformedURLException, HttpAction, UnsupportedEncodingException {
    BaseOAuth20StateClient client = new FacebookClient(KEY, SECRET);
    client.setCallbackUrl(CALLBACK_URL);
    client.setStateData("oldstate");
    final MockWebContext mockWebContext = MockWebContext.create();
    URL url = new URL(client.getRedirectAction(mockWebContext).getLocation());
    final Map<String, String> stringMap = splitQuery(url);
    assertEquals(stringMap.get("state"), "oldstate");
    URL url2 = new URL(client.getRedirectAction(mockWebContext).getLocation());
    final Map<String, String> stringMap2 = splitQuery(url2);
    assertEquals(stringMap2.get("state"), "oldstate");
}

64. BaseOAuth20ClientTests#testStateRandom()

Project: pac4j
Source File: BaseOAuth20ClientTests.java
View license
@Test
public void testStateRandom() throws MalformedURLException, HttpAction, UnsupportedEncodingException {
    BaseOAuth20StateClient client = new FacebookClient(KEY, SECRET);
    client.setCallbackUrl(CALLBACK_URL);
    URL url = new URL(client.getRedirectAction(MockWebContext.create()).getLocation());
    final Map<String, String> stringMap = splitQuery(url);
    assertNotNull(stringMap.get("state"));
    URL url2 = new URL(client.getRedirectAction(MockWebContext.create()).getLocation());
    final Map<String, String> stringMap2 = splitQuery(url2);
    assertNotNull(stringMap2.get("state"));
    assertNotEquals(stringMap.get("state"), stringMap2.get("state"));
}

65. CMapParser#getExternalCMap()

Project: PdfBox-Android
Source File: CMapParser.java
View license
/**
     * Returns an input stream containing the given "use" CMap.
     */
protected InputStream getExternalCMap(String name) throws IOException {
    if (PDFBoxResourceLoader.isReady()) {
        return PDFBoxResourceLoader.getStream("org/apache/fontbox/resources/cmap/" + name);
    }
    // Fallback
    URL url = getClass().getResource("/org/apache/fontbox/resources/cmap/" + name);
    if (url == null) {
        throw new IOException("Error: Could not find referenced cmap stream " + name);
    }
    return url.openStream();
}

66. URLTemplatingUtilTest#testQueryParameterSeperator()

View license
public void testQueryParameterSeperator() throws MalformedURLException, AxisFault {
    URL testURL = new URL("http://locahost:8080/paramOne");
    messageContext.setProperty(WSDL2Constants.ATTR_WHTTP_LOCATION, null);
    messageContext.setProperty(WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, ";");
    URL modifiedURL = URLTemplatingUtil.appendQueryParameters(messageContext, testURL);
    System.out.println("original = " + testURL);
    System.out.println("modifiedURL = " + modifiedURL);
    String expectedURL = "http://locahost:8080/paramOne?FirstName=Foo;LastName=Bar";
    assertEquals(modifiedURL.toString(), expectedURL);
}

67. BpmPlatformXmlLocationTest#checkValidBpmPlatformXmlResourceLocationForUrl()

View license
@Test
public void checkValidBpmPlatformXmlResourceLocationForUrl() throws NamingException, MalformedURLException {
    TomcatParseBpmPlatformXmlStep tomcatParseBpmPlatformXmlStep = new TomcatParseBpmPlatformXmlStep();
    assertNull(tomcatParseBpmPlatformXmlStep.checkValidUrlLocation(BPM_PLATFORM_XML_FILE_ABSOLUTE_LOCATION));
    assertNull(tomcatParseBpmPlatformXmlStep.checkValidUrlLocation(BPM_PLATFORM_XML_LOCATION_FILE_INVALID_PATH_WINDOWS));
    assertNull(tomcatParseBpmPlatformXmlStep.checkValidUrlLocation(BPM_PLATFORM_XML_LOCATION_FILE_INVALID_PATH_UNIX));
    assertNull(tomcatParseBpmPlatformXmlStep.checkValidUrlLocation(BPM_PLATFORM_XML_LOCATION_VALID_PATH_WINDOWS));
    assertNull(tomcatParseBpmPlatformXmlStep.checkValidUrlLocation(BPM_PLATFORM_XML_LOCATION_VALID_PATH_UNIX));
    URL httpUrl = tomcatParseBpmPlatformXmlStep.checkValidUrlLocation(BPM_PLATFORM_XML_LOCATION_URL_HTTP_PROTOCOL);
    assertEquals(BPM_PLATFORM_XML_LOCATION_URL_HTTP_PROTOCOL, httpUrl.toString());
    URL httpsUrl = tomcatParseBpmPlatformXmlStep.checkValidUrlLocation(BPM_PLATFORM_XML_LOCATION_URL_HTTPS_PROTOCOL);
    assertEquals(BPM_PLATFORM_XML_LOCATION_URL_HTTPS_PROTOCOL, httpsUrl.toString());
}

68. DockerClientProfile#toUrl()

Project: camel
Source File: DockerClientProfile.java
View license
public String toUrl() throws DockerException {
    ObjectHelper.notNull(this.host, "host");
    ObjectHelper.notNull(this.port, "port");
    URL uri;
    String secure = this.secure != null && this.secure ? "https" : "http";
    try {
        uri = new URL(secure, this.host, this.port, "");
    } catch (MalformedURLException e) {
        throw new DockerException(e);
    }
    return uri.toString();
}

69. SwingSet2Applet#getURL()

Project: beautyeye
Source File: SwingSet2Applet.java
View license
/**
     * Gets the uRL.
     *
     * @param filename the filename
     * @return the uRL
     */
public URL getURL(String filename) {
    URL codeBase = this.getCodeBase();
    URL url = null;
    try {
        url = new URL(codeBase, filename);
        System.out.println(url);
    } catch (java.net.MalformedURLException e) {
        System.out.println("Error: badly specified URL");
        return null;
    }
    return url;
}

70. LinkBean#setLinks()

Project: bboss
Source File: LinkBean.java
View license
//
// Properties
//
/**
     * Refetch the URL contents.
     */
private void setLinks() {
    String url;
    URL[] urls;
    URL[] oldValue;
    url = getURL();
    if (null != url)
        try {
            urls = extractLinks();
            if (!equivalent(mLinks, urls)) {
                oldValue = mLinks;
                mLinks = urls;
                mPropertySupport.firePropertyChange(PROP_LINKS_PROPERTY, oldValue, mLinks);
            }
        } catch (ParserException hpe) {
            mLinks = null;
        }
}

71. PreferenceManager#getURL()

Project: batik
Source File: PreferenceManager.java
View license
/**
     * Returns an URL preference.
     */
public URL getURL(String key) {
    URL defaultValue = (URL) getDefault(key);
    String sp = internal.getProperty(key);
    if (sp == null) {
        return defaultValue;
    }
    URL url = null;
    try {
        url = new URL(sp);
    } catch (MalformedURLException ex) {
        internal.remove(key);
        return defaultValue;
    }
    return url;
}

72. WAStartUp#copyResourceFile()

Project: azure-tools-for-java
Source File: WAStartUp.java
View license
/**
     * Method copy specified file in eclipse plugins folder.
     * @param resourceFile
     * @param destFile
     */
private void copyResourceFile(String resourceFile, String destFile) {
    URL url = Activator.getDefault().getBundle().getEntry(resourceFile);
    URL fileURL;
    try {
        fileURL = FileLocator.toFileURL(url);
        URL resolve = FileLocator.resolve(fileURL);
        File file = new File(resolve.getFile());
        FileInputStream fis = new FileInputStream(file);
        File outputFile = new File(destFile);
        FileOutputStream fos = new FileOutputStream(outputFile);
        writeFile(fis, fos);
    } catch (IOException e) {
        Activator.getDefault().log(e.getMessage(), e);
    }
}

73. FileUtil#copyResourceFile()

Project: azure-tools-for-java
Source File: FileUtil.java
View license
/**
     * copy specified file to eclipse plugins folder
     * @param name : Name of file
     * @param entry : Location of file
     */
public static void copyResourceFile(String resourceFile, String destFile) {
    URL url = Activator.getDefault().getBundle().getEntry(resourceFile);
    URL fileURL;
    try {
        fileURL = FileLocator.toFileURL(url);
        URL resolve = FileLocator.resolve(fileURL);
        File file = new File(resolve.getFile());
        FileInputStream fis = new FileInputStream(file);
        File outputFile = new File(destFile);
        FileOutputStream fos = new FileOutputStream(outputFile);
        com.microsoftopentechnologies.azurecommons.wacommonutil.FileUtil.writeFile(fis, fos);
    } catch (IOException e) {
        Activator.getDefault().log(e.getMessage(), e);
    }
}

74. AILibraryUtil#copyResourceFile()

View license
/**
	 * copy specified file to eclipse plugins folder
	 * 
	 * @param name
	 *            : Name of file
	 * @param entry
	 *            : Location of file
	 */
public static void copyResourceFile(String resourceFile, String destFile) {
    URL url = Activator.getDefault().getBundle().getEntry(resourceFile);
    URL fileURL;
    try {
        fileURL = FileLocator.toFileURL(url);
        URL resolve = FileLocator.resolve(fileURL);
        File file = new File(resolve.getFile());
        FileInputStream fis = new FileInputStream(file);
        File outputFile = new File(destFile);
        FileOutputStream fos = new FileOutputStream(outputFile);
        writeFile(fis, fos);
    } catch (IOException e) {
        Activator.getDefault().log(e.getMessage(), e);
    }
}

75. ACSFilterUtil#copyResourceFile()

View license
/**
     * copy specified file to eclipse plugins folder
     * @param name : Name of file
     * @param entry : Location of file
     */
public static void copyResourceFile(String resourceFile, String destFile) {
    URL url = Activator.getDefault().getBundle().getEntry(resourceFile);
    URL fileURL;
    try {
        fileURL = FileLocator.toFileURL(url);
        URL resolve = FileLocator.resolve(fileURL);
        File file = new File(resolve.getFile());
        FileInputStream fis = new FileInputStream(file);
        File outputFile = new File(destFile);
        FileOutputStream fos = new FileOutputStream(outputFile);
        writeFile(fis, fos);
    } catch (IOException e) {
        Activator.getDefault().log(e.getMessage(), e);
    }
}

76. AzureClient#poll()

Project: azure-sdk-for-java
Source File: AzureClient.java
View license
/**
     * Polls from the URL provided.
     *
     * @param url the URL to poll from.
     * @return the raw response.
     * @throws CloudException REST exception
     * @throws IOException thrown by deserialization
     */
private Response<ResponseBody> poll(String url) throws CloudException, IOException {
    URL endpoint;
    endpoint = new URL(url);
    int port = endpoint.getPort();
    if (port == -1) {
        port = endpoint.getDefaultPort();
    }
    AsyncService service = restClient().retrofit().create(AsyncService.class);
    Response<ResponseBody> response = service.get(endpoint.getFile(), serviceClientUserAgent).execute();
    int statusCode = response.code();
    if (statusCode != 200 && statusCode != 201 && statusCode != 202 && statusCode != 204) {
        CloudException exception = new CloudException(statusCode + " is not a valid polling status code");
        exception.setResponse(response);
        if (response.body() != null) {
            exception.setBody((CloudError) restClient().mapperAdapter().deserialize(response.body().string(), CloudError.class));
            response.body().close();
        } else if (response.errorBody() != null) {
            exception.setBody((CloudError) restClient().mapperAdapter().deserialize(response.errorBody().string(), CloudError.class));
            response.errorBody().close();
        }
        throw exception;
    }
    return response;
}

77. XmlValidatorManagerTest#testLoadValidators()

View license
/**
   * Test that if the xml config file is properly set, XmlValidatorManager loads both the default
   * validator and the one specified in the xml file. The TestValidator class specified in the xml
   * configuration file is located with the jar file inside test resource directory project/testValidators.
   */
@Test
public void testLoadValidators() {
    Props props = new Props(baseProps);
    URL validatorUrl = Resources.getResource("project/testValidators");
    URL configUrl = Resources.getResource("test-conf/azkaban-validators-test2.xml");
    props.put(ValidatorConfigs.VALIDATOR_PLUGIN_DIR, validatorUrl.getPath());
    props.put(ValidatorConfigs.XML_FILE_PARAM, configUrl.getPath());
    XmlValidatorManager manager = new XmlValidatorManager(props);
    assertEquals("XmlValidatorManager should contain 2 validators.", manager.getValidatorsInfo().size(), 2);
    assertEquals("XmlValidatorManager should contain the validator specified in the xml configuration file.", manager.getValidatorsInfo().get(1), "Test");
}

78. TransformerDebug#loadQuickTestFile()

View license
/**
     * Load one of the "The quick brown fox" files from the classpath.
     * @param extension required, eg <b>txt</b> for the file quick.txt
     * @return Returns a test resource loaded from the classpath or <tt>null</tt> if
     *      no resource could be found.
     */
private URL loadQuickTestFile(String extension) {
    final URL result;
    URL url = this.getClass().getClassLoader().getResource("quick/quick." + extension);
    if (url == null) {
        result = null;
    } else {
        // Note that this URL may point to a file on the filesystem or to an entry in a jar file.
        // The handling should be the same either way.
        result = url;
    }
    return result;
}

79. FromXmlRuleSetTest#testCreateDigester()

View license
/**
     * Tests the DigesterLoader.createDigester(), with multiple
     * included rule sources: testrules.xml includes another rules xml
     * file, and also includes programmatically created rules.
     */
@Test
public void testCreateDigester() throws Exception {
    URL rules = getClass().getResource("testrules.xml");
    URL input = getClass().getResource("test.xml");
    Digester digester = newLoader(createRules(rules)).newDigester();
    digester.push(new ArrayList<Object>());
    Object root = digester.parse(input.openStream());
    assertEquals("[foo1 baz1 foo2, foo3 foo4]", root.toString());
}

80. URLTestCase#testResource()

Project: commons-digester
Source File: URLTestCase.java
View license
// Test parsing a resource, using a registered DTD, both passed with URLs
@Test
public void testResource() throws Exception {
    // Register the Digester Rules DTD
    URL dtd = URLTestCase.class.getResource(DIGESTER_RULES_SYSTEM_ID);
    assertNotNull(dtd);
    digester.register(DIGESTER_RULES_PUBLIC_ID, dtd);
    // Parse one of the existing test resources twice with
    // the same Digester instance
    URL xml = URLTestCase.class.getResource(TEST_INPUT_SYSTEM_ID);
    assertNotNull(xml);
    digester.parse(xml);
    digester.parse(xml);
}

81. TestDataConfiguration#testGetURL()

View license
@Test
public void testGetURL() throws Exception {
    // missing URL
    URL defaultValue = new URL("http://www.google.com");
    assertEquals(defaultValue, conf.getURL("url", defaultValue));
    URL expected = new URL("http://jakarta.apache.org");
    // URL string
    assertEquals(expected, conf.getURL("url.string"));
    // URL object
    assertEquals(expected, conf.getURL("url.object"));
    // interpolated value
    assertEquals(expected, conf.getURL("url.string.interpolated"));
}

82. ConfigurationLogger#logImportantConfig()

Project: cdap
Source File: ConfigurationLogger.java
View license
public static void logImportantConfig(CConfiguration cConf) {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL[] urls = ((URLClassLoader) cl).getURLs();
    StringBuilder classPath = new StringBuilder();
    LOG.info("Master classpath:");
    for (URL url : urls) {
        classPath.append(url.getFile()).append(":");
    }
    classPath.deleteCharAt(classPath.length() - 1);
    LOG.info(classPath.toString());
    LOG.info("Important config settings:");
    for (String featureToggleProp : Constants.FEATURE_TOGGLE_PROPS) {
        LOG.info("  {}: {}", featureToggleProp, cConf.get(featureToggleProp));
    }
    for (String portProp : Constants.PORT_PROPS) {
        LOG.info("  {}: {}", portProp, cConf.get(portProp));
    }
}

83. AbstractDistributedProgramRunner#getLogBackURI()

View license
/**
   * Returns a {@link URI} for the logback.xml file to be localized to container and available in the container
   * classpath.
   */
@Nullable
private URI getLogBackURI(Program program, File tempDir) throws IOException, URISyntaxException {
    URL logbackURL = program.getClassLoader().getResource("logback.xml");
    if (logbackURL != null) {
        return logbackURL.toURI();
    }
    URL resource = getClass().getClassLoader().getResource("logback-container.xml");
    if (resource == null) {
        return null;
    }
    // Copy the template
    File logbackFile = new File(tempDir, "logback.xml");
    Files.copy(Resources.newInputStreamSupplier(resource), logbackFile);
    return logbackFile.toURI();
}

84. JsonFileOverlayPostProcessor#lookUpResource()

View license
protected List<URL> lookUpResource(String id) throws IOException {
    List<URL> result = new ArrayList<URL>();
    String base = String.format("%s/%s.json", path, id);
    String override = String.format("%s/%s.json.d/**/*.json", path, id);
    URL url = getClass().getClassLoader().getResource(base);
    if (url != null) {
        log.info("Loading JSON schema overlay for type [{}] from [{}]", id, url);
        result.add(url);
    }
    for (URL overrideUrl : resourceLoader.getResources(override)) {
        log.info("Loading JSON schema overlay for type [{}] from [{}]", id, overrideUrl);
        result.add(overrideUrl);
    }
    resources.put(id, result);
    return result;
}

85. Main#getClassLoader()

Project: cattle
Source File: Main.java
View license
protected ClassLoader getClassLoader() throws Exception {
    URL thisLocation = getThisLocation();
    List<URL> urls = Collections.emptyList();
    if (isJar(thisLocation)) {
        urls = collectJarUrls(thisLocation);
    } else {
        urls = collectDirectoryUrls(thisLocation);
    }
    if (urls.size() == 0)
        return this.getClass().getClassLoader();
    urls.addAll(getPlugins());
    urls.add(0, thisLocation);
    URL[] urlArray = urls.toArray(new URL[urls.size()]);
    ClassLoader cl = Boolean.getBoolean("cattle.main.inherit.cl") ? Main.class.getClassLoader() : null;
    return new URLClassLoader(urlArray, cl, factory);
}

86. Activator#start()

Project: carrot2
Source File: Activator.java
View license
/*
     * 
     */
@Override
public void start(BundleContext context) throws Exception {
    super.start(context);
    final URL bundleURL = FileLocator.find(getBundle(), new Path("web"), null);
    URL resourceURL = FileLocator.toFileURL(bundleURL);
    LoggerFactory.getLogger(Activator.class).debug("Bundled resources at: " + resourceURL.toExternalForm());
    if (!"file".equals(resourceURL.getProtocol())) {
        throw new Exception("Expected file protocol on bundled Web resources: " + resourceURL.toExternalForm());
    }
    this.staticResourceURL = resourceURL.toExternalForm();
    while (this.staticResourceURL.endsWith("/")) {
        this.staticResourceURL = staticResourceURL.substring(0, staticResourceURL.length() - 1);
    }
    instance = this;
}

87. URLTemplatingUtilTest#testIgnoreUncitedFalse()

View license
public void testIgnoreUncitedFalse() throws MalformedURLException, AxisFault {
    URL testURL = new URL("http://locahost:8080/paramOne/Foo?test=1");
    messageContext.setProperty(WSDL2Constants.ATTR_WHTTP_IGNORE_UNCITED, "false");
    messageContext.setProperty(WSDL2Constants.ATTR_WHTTP_LOCATION, null);
    URL modifiedURL = URLTemplatingUtil.appendQueryParameters(messageContext, testURL);
    System.out.println("original = " + testURL);
    System.out.println("modifiedURL = " + modifiedURL);
    String expectedURL = "http://locahost:8080/paramOne/Foo?test=1&FirstName=Foo&LastName=Bar";
    assertEquals(modifiedURL.toString(), expectedURL);
}

88. InternalConfig#load()

Project: aws-sdk-java
Source File: InternalConfig.java
View license
/**
     * Loads and returns the AWS Java SDK internal configuration from the classpath.
     */
static InternalConfig load() throws JsonParseException, JsonMappingException, IOException {
    // First try loading via the class by using a relative path
    // classesFirst=true
    URL url = ClassLoaderHelper.getResource(DEFAULT_CONFIG_RESOURCE_RELATIVE_PATH, true, InternalConfig.class);
    if (url == null) {
        // Then try with the absolute path
        url = ClassLoaderHelper.getResource(DEFAULT_CONFIG_RESOURCE_ABSOLUTE_PATH, InternalConfig.class);
    }
    InternalConfigJsonHelper config = loadfrom(url);
    InternalConfigJsonHelper configOverride;
    URL overrideUrl = ClassLoaderHelper.getResource("/" + CONFIG_OVERRIDE_RESOURCE, InternalConfig.class);
    if (overrideUrl == null) {
        // Try without a leading "/"
        overrideUrl = ClassLoaderHelper.getResource(CONFIG_OVERRIDE_RESOURCE, InternalConfig.class);
    }
    if (overrideUrl == null) {
        log.debug("Configuration override " + CONFIG_OVERRIDE_RESOURCE + " not found.");
        configOverride = new InternalConfigJsonHelper();
    } else {
        configOverride = loadfrom(overrideUrl);
    }
    InternalConfig merged = new InternalConfig(config, configOverride);
    merged.setDefaultConfigFileLocation(url);
    merged.setOverrideConfigFileLocation(overrideUrl);
    return merged;
}

89. ObjectInputStreamWithClassLoaderTest#newClassLoader()

View license
// Constants -----------------------------------------------------
// Attributes ----------------------------------------------------
// Static --------------------------------------------------------
public static ClassLoader newClassLoader(final Class anyUserClass) throws Exception {
    ProtectionDomain protectionDomain = anyUserClass.getProtectionDomain();
    CodeSource codeSource = protectionDomain.getCodeSource();
    URL classLocation = codeSource.getLocation();
    StringTokenizer tokenString = new StringTokenizer(System.getProperty("java.class.path"), File.pathSeparator);
    String pathIgnore = System.getProperty("java.home");
    if (pathIgnore == null) {
        pathIgnore = classLocation.toString();
    }
    List<URL> urls = new ArrayList<>();
    while (tokenString.hasMoreElements()) {
        String value = tokenString.nextToken();
        URL itemLocation = new File(value).toURI().toURL();
        if (!itemLocation.equals(classLocation) && itemLocation.toString().indexOf(pathIgnore) >= 0) {
            urls.add(itemLocation);
        }
    }
    URL[] urlArray = urls.toArray(new URL[urls.size()]);
    ClassLoader masterClassLoader = URLClassLoader.newInstance(urlArray, null);
    ClassLoader appClassLoader = URLClassLoader.newInstance(new URL[] { classLocation }, masterClassLoader);
    return appClassLoader;
}

90. BlueprintContainerTest#testPlaceholders()

View license
@Test
public void testPlaceholders() throws Exception {
    URL url1 = getClass().getClassLoader().getResource("test.xml");
    URL url2 = getClass().getClassLoader().getResource("test2.xml");
    BlueprintContainerImpl container = new BlueprintContainerImpl(getClass().getClassLoader(), Arrays.asList(url1, url2));
    Foo foo = (Foo) container.getComponentInstance("foo");
    System.out.println(foo);
    assertNotNull(foo);
    assertEquals(5, foo.getA());
    assertEquals(1, foo.getB());
    container.destroy();
}

91. ProviderBundleTrackerCustomizerGenericCapabilityTest#mockSPIBundle()

View license
private Bundle mockSPIBundle(BundleContext implBC, Dictionary<String, String> headers, BundleRevision rev) throws ClassNotFoundException {
    if (headers == null)
        headers = new Hashtable<String, String>();
    Bundle implBundle = EasyMock.createNiceMock(Bundle.class);
    EasyMock.expect(implBundle.getBundleContext()).andReturn(implBC).anyTimes();
    EasyMock.expect(implBundle.getHeaders()).andReturn(headers).anyTimes();
    // List the resources found at META-INF/services in the test bundle
    URL dir = getClass().getResource("impl1/META-INF/services");
    assertNotNull("precondition", dir);
    EasyMock.expect(implBundle.getResource("/META-INF/services")).andReturn(dir).anyTimes();
    URL res = getClass().getResource("impl1/META-INF/services/org.apache.aries.mytest.MySPI");
    assertNotNull("precondition", res);
    EasyMock.expect(implBundle.findEntries("META-INF/services", "*", false)).andReturn(Collections.enumeration(Collections.singleton(res))).anyTimes();
    Class<?> cls = getClass().getClassLoader().loadClass("org.apache.aries.spifly.impl1.MySPIImpl1");
    EasyMock.<Object>expect(implBundle.loadClass("org.apache.aries.spifly.impl1.MySPIImpl1")).andReturn(cls).anyTimes();
    if (rev != null)
        EasyMock.expect(implBundle.adapt(BundleRevision.class)).andReturn(rev).anyTimes();
    EasyMock.replay(implBundle);
    return implBundle;
}

92. ProviderBundleTrackerCustomizerTest#mockSPIBundle()

View license
private Bundle mockSPIBundle(BundleContext implBC, String spiProviderHeader) throws ClassNotFoundException {
    Bundle implBundle = EasyMock.createNiceMock(Bundle.class);
    EasyMock.expect(implBundle.getBundleContext()).andReturn(implBC).anyTimes();
    Dictionary<String, String> headers = new Hashtable<String, String>();
    if (spiProviderHeader != null)
        headers.put(SpiFlyConstants.SPI_PROVIDER_HEADER, spiProviderHeader);
    EasyMock.expect(implBundle.getHeaders()).andReturn(headers).anyTimes();
    // List the resources found at META-INF/services in the test bundle
    URL dir = getClass().getResource("impl1/META-INF/services");
    assertNotNull("precondition", dir);
    EasyMock.expect(implBundle.getResource("/META-INF/services")).andReturn(dir).anyTimes();
    URL res = getClass().getResource("impl1/META-INF/services/org.apache.aries.mytest.MySPI");
    assertNotNull("precondition", res);
    EasyMock.expect(implBundle.findEntries("META-INF/services", "*", false)).andReturn(Collections.enumeration(Collections.singleton(res))).anyTimes();
    Class<?> cls = getClass().getClassLoader().loadClass("org.apache.aries.spifly.impl1.MySPIImpl1");
    EasyMock.<Object>expect(implBundle.loadClass("org.apache.aries.spifly.impl1.MySPIImpl1")).andReturn(cls).anyTimes();
    EasyMock.replay(implBundle);
    return implBundle;
}

93. ClientWeavingHookTest#testConsumerBundleWeaving()

View license
private void testConsumerBundleWeaving(Bundle consumerBundle, WeavingHook wh, Set<String> testClientResult, String jaxpClientResult) throws Exception {
    // Weave the TestClient class.
    URL clsUrl = getClass().getResource("TestClient.class");
    WovenClass wc = new MyWovenClass(clsUrl, TestClient.class.getName(), consumerBundle);
    wh.weave(wc);
    // Invoke the woven class and check that it propertly sets the TCCL so that the
    // META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
    Class<?> cls = wc.getDefinedClass();
    Method method = cls.getMethod("test", new Class[] { String.class });
    Object result = method.invoke(cls.newInstance(), "hello");
    Assert.assertEquals(testClientResult, result);
    URL clsUrl2 = getClass().getResource("JaxpClient.class");
    WovenClass wc2 = new MyWovenClass(clsUrl2, JaxpClient.class.getName(), consumerBundle);
    wh.weave(wc2);
    Class<?> cls2 = wc2.getDefinedClass();
    Method method2 = cls2.getMethod("test", new Class[] {});
    Class<?> result2 = (Class<?>) method2.invoke(cls2.newInstance());
    Assert.assertEquals(jaxpClientResult, result2.getName());
}

94. ConfigurationFileLocatorTest#getMockApplicationFileFromClassPath()

View license
private File getMockApplicationFileFromClassPath(ClassLoader classLoader) throws URISyntaxException {
    URL[] urls = ((URLClassLoader) classLoader).getURLs();
    for (URL url : urls) {
        URI uri = url.toURI();
        File file = new File(uri.getSchemeSpecificPart());
        if (file.isDirectory()) {
            continue;
        }
        if (MOCK_CONF_FILE.equals(file.getName())) {
            return file;
        }
    }
    return null;
}

95. BlueprintContainerTest#testPlaceholders()

Project: aries
Source File: BlueprintContainerTest.java
View license
@Test
public void testPlaceholders() throws Exception {
    URL url1 = getClass().getClassLoader().getResource("test.xml");
    URL url2 = getClass().getClassLoader().getResource("test2.xml");
    BlueprintContainerImpl container = new BlueprintContainerImpl(getClass().getClassLoader(), Arrays.asList(url1, url2));
    Foo foo = (Foo) container.getComponentInstance("foo");
    System.out.println(foo);
    assertNotNull(foo);
    assertEquals(5, foo.getA());
    assertEquals(1, foo.getB());
    container.destroy();
}

96. ProviderBundleTrackerCustomizerGenericCapabilityTest#mockSPIBundle()

View license
private Bundle mockSPIBundle(BundleContext implBC, Dictionary<String, String> headers, BundleRevision rev) throws ClassNotFoundException {
    if (headers == null)
        headers = new Hashtable<String, String>();
    Bundle implBundle = EasyMock.createNiceMock(Bundle.class);
    EasyMock.expect(implBundle.getBundleContext()).andReturn(implBC).anyTimes();
    EasyMock.expect(implBundle.getHeaders()).andReturn(headers).anyTimes();
    // List the resources found at META-INF/services in the test bundle
    URL dir = getClass().getResource("impl1/META-INF/services");
    assertNotNull("precondition", dir);
    EasyMock.expect(implBundle.getResource("/META-INF/services")).andReturn(dir).anyTimes();
    URL res = getClass().getResource("impl1/META-INF/services/org.apache.aries.mytest.MySPI");
    assertNotNull("precondition", res);
    EasyMock.expect(implBundle.findEntries("META-INF/services", "*", false)).andReturn(Collections.enumeration(Collections.singleton(res))).anyTimes();
    Class<?> cls = getClass().getClassLoader().loadClass("org.apache.aries.spifly.impl1.MySPIImpl1");
    EasyMock.<Object>expect(implBundle.loadClass("org.apache.aries.spifly.impl1.MySPIImpl1")).andReturn(cls).anyTimes();
    if (rev != null)
        EasyMock.expect(implBundle.adapt(BundleRevision.class)).andReturn(rev).anyTimes();
    EasyMock.replay(implBundle);
    return implBundle;
}

97. ProviderBundleTrackerCustomizerTest#mockSPIBundle()

View license
private Bundle mockSPIBundle(BundleContext implBC, String spiProviderHeader) throws ClassNotFoundException {
    Bundle implBundle = EasyMock.createNiceMock(Bundle.class);
    EasyMock.expect(implBundle.getBundleContext()).andReturn(implBC).anyTimes();
    Dictionary<String, String> headers = new Hashtable<String, String>();
    if (spiProviderHeader != null)
        headers.put(SpiFlyConstants.SPI_PROVIDER_HEADER, spiProviderHeader);
    EasyMock.expect(implBundle.getHeaders()).andReturn(headers).anyTimes();
    // List the resources found at META-INF/services in the test bundle
    URL dir = getClass().getResource("impl1/META-INF/services");
    assertNotNull("precondition", dir);
    EasyMock.expect(implBundle.getResource("/META-INF/services")).andReturn(dir).anyTimes();
    URL res = getClass().getResource("impl1/META-INF/services/org.apache.aries.mytest.MySPI");
    assertNotNull("precondition", res);
    EasyMock.expect(implBundle.findEntries("META-INF/services", "*", false)).andReturn(Collections.enumeration(Collections.singleton(res))).anyTimes();
    Class<?> cls = getClass().getClassLoader().loadClass("org.apache.aries.spifly.impl1.MySPIImpl1");
    EasyMock.<Object>expect(implBundle.loadClass("org.apache.aries.spifly.impl1.MySPIImpl1")).andReturn(cls).anyTimes();
    EasyMock.replay(implBundle);
    return implBundle;
}

98. ClientWeavingHookTest#testConsumerBundleWeaving()

Project: aries
Source File: ClientWeavingHookTest.java
View license
private void testConsumerBundleWeaving(Bundle consumerBundle, WeavingHook wh, Set<String> testClientResult, String jaxpClientResult) throws Exception {
    // Weave the TestClient class.
    URL clsUrl = getClass().getResource("TestClient.class");
    WovenClass wc = new MyWovenClass(clsUrl, TestClient.class.getName(), consumerBundle);
    wh.weave(wc);
    // Invoke the woven class and check that it propertly sets the TCCL so that the
    // META-INF/services/org.apache.aries.mytest.MySPI file from impl2 is visible.
    Class<?> cls = wc.getDefinedClass();
    Method method = cls.getMethod("test", new Class[] { String.class });
    Object result = method.invoke(cls.newInstance(), "hello");
    Assert.assertEquals(testClientResult, result);
    URL clsUrl2 = getClass().getResource("JaxpClient.class");
    WovenClass wc2 = new MyWovenClass(clsUrl2, JaxpClient.class.getName(), consumerBundle);
    wh.weave(wc2);
    Class<?> cls2 = wc2.getDefinedClass();
    Method method2 = cls2.getMethod("test", new Class[] {});
    Class<?> result2 = (Class<?>) method2.invoke(cls2.newInstance());
    Assert.assertEquals(jaxpClientResult, result2.getName());
}

99. LanguageWidget#activate()

Project: clerezza
Source File: LanguageWidget.java
View license
protected void activate(ComponentContext context) throws IOException, URISyntaxException {
    Bundle bundle = context.getBundleContext().getBundle();
    URL resourceDir = getClass().getResource("staticweb");
    PathNode pathNode = new BundlePathNode(bundle, resourceDir.getPath());
    fileServer = new FileServer(pathNode);
    URL template = getClass().getResource("language-list.ssp");
    renderletManager.registerRenderlet(ScalaServerPagesRenderlet.class.getName(), new UriRef(template.toURI().toString()), LANGUAGE.LanguageList, "naked", MediaType.APPLICATION_XHTML_XML_TYPE, true);
}

100. StackLoaderTest#predefinedStackWithValidJsonShouldBeCreated2()

Project: che
Source File: StackLoaderTest.java
View license
@Test
public void predefinedStackWithValidJsonShouldBeCreated2() throws ServerException, NotFoundException, ConflictException {
    URL url = Resources.getResource("stacks.json");
    URL urlFolder = Thread.currentThread().getContextClassLoader().getResource("stack_img");
    doThrow(new ServerException("Internal server error")).when(stackDao).update(any());
    stackLoader = new StackLoader(url.getPath(), urlFolder.getPath(), stackDao);
    stackLoader.start();
    verify(stackDao, times(2)).update(any());
    verify(stackDao, times(2)).create(any());
}