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

5. 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);
}

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. 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));
}

8. 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());
}

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. 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);
}

13. PortletApplicationContextTest#testGetResource()

View license
/**
     * Test method for [email protected] [email protected]ource(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);
}

14. 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);
}

15. 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] });
}

16. 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) {
    }
}

17. 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);
}

18. ResourceBundleWrapper#removeCodeBase()

View license
/**
     * Instantiate a [email protected] 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
     * [email protected] 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);
}

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. 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");
}

21. 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();
}

22. 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);
    }
}

23. HaskellCatalog#getDocument()

Project: viskell
Source File: HaskellCatalog.java
View license
/**
     * Loads the given XML catalog into a document.
     * @param XMLPath The path to the XML file.
     * @param XSDPath The path to the XSD file.
     * @return The document for the XML file.
     */
protected static Document getDocument(final String XMLPath, final String XSDPath) {
    URL xmlFile = HaskellCatalog.class.getResource(XMLPath);
    URL schemaFile = HaskellCatalog.class.getResource(XSDPath);
    try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        SchemaFactory sFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        dbFactory.setIgnoringElementContentWhitespace(true);
        dbFactory.setIgnoringComments(true);
        dbFactory.setSchema(sFactory.newSchema(schemaFile));
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        return dBuilder.parse(xmlFile.openStream());
    } catch (IOExceptionParserConfigurationException | SAXException |  e) {
        throw new RuntimeException("could not read or parse catalog file", e);
    }
}

24. StreamTest#findNewsUcareAbout()

Project: XueQiuSuperSpider
Source File: StreamTest.java
View license
//????????
@Test
public void findNewsUcareAbout() throws RemoteException {
    List<URL> news = new HuShenNewsRefCollector(HuShenNewsRefCollector.Topic.TOTAL, 2).get();
    List<URL> res = news.parallelStream().filter(new PageKeyFilter("????", false)).collect(Collectors.toList());
    List<URL> regexRes = news.parallelStream().filter(new PageKeyFilter("????", true)).collect(Collectors.toList());
    for (URL re : regexRes) {
        System.out.println("Regex : " + re);
    }
    for (URL re : res) {
        System.out.println("nonRegex : " + re);
    }
}

25. TestReplicationHandler#pullFromTo()

View license
private void pullFromTo(JettySolrRunner from, JettySolrRunner to) throws IOException {
    String masterUrl;
    URL url;
    InputStream stream;
    masterUrl = buildUrl(to.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME + ReplicationHandler.PATH + "?wait=true&command=fetchindex&masterUrl=" + buildUrl(from.getLocalPort()) + "/" + DEFAULT_TEST_CORENAME + ReplicationHandler.PATH;
    url = new URL(masterUrl);
    stream = url.openStream();
    stream.close();
}

26. ObjectMessageTest#newClassLoader()

View license
protected static ClassLoader newClassLoader(final Class anyUserClass) throws Exception {
    URL classLocation = anyUserClass.getProtectionDomain().getCodeSource().getLocation();
    StringTokenizer tokenString = new StringTokenizer(System.getProperty("java.class.path"), File.pathSeparator);
    String pathIgnore = System.getProperty("java.home");
    if (pathIgnore == null) {
        pathIgnore = classLocation.toString();
    }
    ArrayList<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;
}

27. 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;
}

28. 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();
}

29. 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;
}

30. 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;
}

31. 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());
}

32. 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;
}

33. 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();
}

34. 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;
}

35. 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;
}

36. 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());
}

37. 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;
}

38. ServiceClientTest#testWSDLWithImportsFromZIP()

Project: axis2-java
Source File: ServiceClientTest.java
View license
/**
     * Tests that imported schemas are correctly resolved if the WSDL is loaded from a ZIP file.
     * This is a regression test for AXIS2-4353 and checks that WSDLs (with imports) can be loaded
     * from the class path (which usually means a JAR file).
     * 
     * @throws Exception
     */
@Test
public void testWSDLWithImportsFromZIP() throws Exception {
    ConfigurationContext configContext = ConfigurationContextFactory.createEmptyConfigurationContext();
    String basedir = System.getProperty("basedir");
    if (basedir == null) {
        basedir = ".";
    }
    URL zipUrl = new File(basedir, "target/test-zip.zip").toURL();
    URL wsdlUrl = new URL("jar:" + zipUrl + "!/test.wsdl");
    ServiceClient serviceClient = new ServiceClient(configContext, wsdlUrl, new QName("urn:test", "EchoService"), "EchoPort");
    List<XmlSchema> schemas = serviceClient.getAxisService().getSchema();
    assertEquals(1, schemas.size());
    XmlSchema schema = schemas.get(0);
    assertNotNull(schema.getTypeByName(new QName("urn:test", "echoResponse")));
}

39. URLTemplatingUtilTest#testGetTemplatedURL()

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

40. 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);
}

41. 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);
}

42. 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");
}

43. 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;
}

44. 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);
    }
}

45. 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);
    }
}

46. 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);
    }
}

47. 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);
    }
}

48. 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;
}

49. 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;
        }
}

50. 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;
}

51. 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();
}

52. 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());
}

53. 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;
}

54. 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);
}

55. 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;
}

56. AbstractDistributedProgramRunner#getLogBackURI()

View license
/**
   * Returns a [email protected] 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();
}

57. 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));
    }
}

58. CeylonModuleRunner#getCarUrls()

Project: ceylon
Source File: CeylonModuleRunner.java
View license
private URL[] getCarUrls(final String moduleName, final String[] deps, Set<String> removeAtRuntime, File repo) throws MalformedURLException {
    final URL[] carUrls = new URL[1 + (deps != null ? deps.length : 0) - removeAtRuntime.size()];
    URL carUrl = urlForModule(repo, moduleName);
    carUrls[0] = carUrl;
    if (deps != null) {
        for (int dep = 0, url = 1; dep < deps.length; dep++) {
            if (!removeAtRuntime.contains(deps[dep]))
                carUrls[url++] = urlForModule(repo, deps[dep]);
        }
    }
    return carUrls;
}

59. CeylonModuleRunner#getCarUrls()

View license
private URL[] getCarUrls(final String moduleName, final String[] deps, Set<String> removeAtRuntime, File repo) throws MalformedURLException {
    final URL[] carUrls = new URL[1 + (deps != null ? deps.length : 0) - removeAtRuntime.size()];
    URL carUrl = urlForModule(repo, moduleName);
    carUrls[0] = carUrl;
    if (deps != null) {
        for (int dep = 0, url = 1; dep < deps.length; dep++) {
            if (!removeAtRuntime.contains(deps[dep]))
                carUrls[url++] = urlForModule(repo, deps[dep]);
        }
    }
    return carUrls;
}

60. JREContainer#buildClasspathAttributes()

Project: che
Source File: JREContainer.java
View license
private static IClasspathAttribute[] buildClasspathAttributes(final IVMInstallType vm, final LibraryLocation lib, final boolean overrideJavaDoc) {
    List<IClasspathAttribute> classpathAttributes = new LinkedList<IClasspathAttribute>();
    // process the javadoc location
    URL javadocLocation = lib.getJavadocLocation();
    if (overrideJavaDoc && javadocLocation == null) {
        //vm.getJavadocLocation();
        javadocLocation = null;
    }
    if (javadocLocation != null) {
        IClasspathAttribute javadocCPAttribute = JavaCore.newClasspathAttribute(IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME, javadocLocation.toExternalForm());
        classpathAttributes.add(javadocCPAttribute);
    }
    // process the index location
    URL indexLocation = lib.getIndexLocation();
    if (indexLocation != null) {
        IClasspathAttribute indexCPLocation = JavaCore.newClasspathAttribute(IClasspathAttribute.INDEX_LOCATION_ATTRIBUTE_NAME, indexLocation.toExternalForm());
        classpathAttributes.add(indexCPLocation);
    }
    return classpathAttributes.toArray(new IClasspathAttribute[classpathAttributes.size()]);
}

61. StackLoaderTest#predefinedStackWithValidJsonShouldBeCreated()

Project: che
Source File: StackLoaderTest.java
View license
@Test
public void predefinedStackWithValidJsonShouldBeCreated() throws ServerException, NotFoundException, ConflictException {
    URL url = Resources.getResource("stacks.json");
    URL urlFolder = Thread.currentThread().getContextClassLoader().getResource("stack_img");
    doThrow(new NotFoundException("Stack is already exist")).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());
}

62. 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());
}

63. PlatformConfigGui#activate()

Project: clerezza
Source File: PlatformConfigGui.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());
    logger.debug("Initializing file server for {} ({})", resourceDir, resourceDir.getFile());
    fileServer = new FileServer(pathNode);
    URL template = getClass().getResource("config.ssp");
    renderletManager.registerRenderlet(ScalaServerPagesRenderlet.class.getName(), new UriRef(template.toURI().toString()), CONFIG_PAGE, "naked", MediaType.APPLICATION_XHTML_XML_TYPE, true);
}

64. 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);
}

65. 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"));
}

66. 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);
}

67. 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());
}

68. 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;
}

69. ReplicationTest#testUseRemoteUUID()

View license
// ReplicatorInternal.m: test_UseRemoteUUID
public void testUseRemoteUUID() throws Exception {
    URL remoteURL1 = new URL("http://alice.local:55555/db");
    Replication r1 = database.createPullReplication(remoteURL1);
    r1.setRemoteUUID("cafebabe");
    String check1 = r1.replicationInternal.remoteCheckpointDocID();
    // Different URL, but same remoteUUID:
    URL remoteURL2 = new URL("http://alice17.local:44444/db");
    Replication r2 = database.createPullReplication(remoteURL2);
    r2.setRemoteUUID("cafebabe");
    String check2 = r2.replicationInternal.remoteCheckpointDocID();
    assertEquals(check1, check2);
    // Same UUID but different filter settings:
    Replication r3 = database.createPullReplication(remoteURL2);
    r3.setRemoteUUID("cafebabe");
    r3.setFilter("Melitta");
    String check3 = r3.replicationInternal.remoteCheckpointDocID();
    assertNotSame(check2, check3);
}

70. ShadowMakerTest#testProcessImage()

Project: diablo-js
Source File: ShadowMakerTest.java
View license
@Test
public void testProcessImage() throws IOException {
    URL in = ShadowMakerTest.class.getResource("test.png");
    URL out = ShadowMakerTest.class.getResource("out.png");
    assertNotNull(in);
    assertNotNull(out);
    System.out.println(in.getFile());
    System.out.println(out.getFile());
    ShadowMaker.processImage(in.getFile(), out.getFile());
}

71. TrackerImpl#getURLs()

View license
public URL[] getURLs() {
    URL[][] url_sets = TRTrackerUtils.getAnnounceURLs();
    URL[] res = new URL[url_sets.length];
    for (int i = 0; i < res.length; i++) {
        res[i] = url_sets[i][0];
    }
    return (res);
}

72. ResourceURLTest#isDirectoryThrowsResourceNotFoundExceptionForMissingDirectories()

Project: dropwizard
Source File: ResourceURLTest.java
View license
@Test
public void isDirectoryThrowsResourceNotFoundExceptionForMissingDirectories() throws Exception {
    URL url = Resources.getResource("META-INF/");
    url = new URL(url.toExternalForm() + "missing");
    try {
        ResourceURL.isDirectory(url);
        fail("should have thrown an exception");
    } catch (ResourceNotFoundException ignored) {
    }
}

73. InitializationTest#test06GetClassLoaderForExtension()

Project: druid
Source File: InitializationTest.java
View license
@Test
public void test06GetClassLoaderForExtension() throws IOException {
    final File some_extension_dir = temporaryFolder.newFolder();
    final File a_jar = new File(some_extension_dir, "a.jar");
    final File b_jar = new File(some_extension_dir, "b.jar");
    final File c_jar = new File(some_extension_dir, "c.jar");
    a_jar.createNewFile();
    b_jar.createNewFile();
    c_jar.createNewFile();
    final URLClassLoader loader = Initialization.getClassLoaderForExtension(some_extension_dir);
    final URL[] expectedURLs = new URL[] { a_jar.toURI().toURL(), b_jar.toURI().toURL(), c_jar.toURI().toURL() };
    final URL[] actualURLs = loader.getURLs();
    Arrays.sort(actualURLs, new Comparator<URL>() {

        @Override
        public int compare(URL o1, URL o2) {
            return o1.getPath().compareTo(o2.getPath());
        }
    });
    Assert.assertArrayEquals(expectedURLs, actualURLs);
}

74. ReflectUtils#getCodeBase()

Project: dubbo
Source File: ReflectUtils.java
View license
public static String getCodeBase(Class<?> cls) {
    if (cls == null)
        return null;
    ProtectionDomain domain = cls.getProtectionDomain();
    if (domain == null)
        return null;
    CodeSource source = domain.getCodeSource();
    if (source == null)
        return null;
    URL location = source.getLocation();
    if (location == null)
        return null;
    return location.getFile();
}

75. CacheManagerLifecycleEhcacheIntegrationTest#testAutoCreatedCacheManagerUsingXml()

View license
@Test
public void testAutoCreatedCacheManagerUsingXml() throws Exception {
    URL xml = CacheManagerLifecycleEhcacheIntegrationTest.class.getResource("/configs/clustered.xml");
    URL substitutedXml = substitute(xml, "cluster-uri", CLUSTER.getConnectionURI().toString());
    PersistentCacheManager manager = (PersistentCacheManager) newCacheManager(new XmlConfiguration(substitutedXml));
    assertEntityNotExists(EhcacheClientEntity.class, "testAutoCreatedCacheManagerUsingXml");
    manager.init();
    try {
        assertEntityExists(EhcacheClientEntity.class, "testAutoCreatedCacheManagerUsingXml");
    } finally {
        manager.close();
    }
}

76. JarHellTests#testCrazyEclipseClassPathWindows()

Project: elasticsearch
Source File: JarHellTests.java
View license
/**
     * Make sure a "bogus" windows classpath element is accepted, java's classpath parsing accepts it,
     * therefore eclipse OSGI code does it :)
     */
public void testCrazyEclipseClassPathWindows() throws Exception {
    assumeTrue("test is designed for windows-like systems only", ";".equals(System.getProperty("path.separator")));
    assumeTrue("test is designed for windows-like systems only", "\\".equals(System.getProperty("file.separator")));
    URL expected[] = { PathUtils.get("c:\\element1").toUri().toURL(), PathUtils.get("c:\\element2").toUri().toURL(), PathUtils.get("c:\\element3").toUri().toURL(), PathUtils.get("c:\\element 4").toUri().toURL() };
    URL actual[] = JarHell.parseClassPath("c:\\element1;c:\\element2;/c:/element3;/c:/element 4");
    assertArrayEquals(expected, actual);
}

77. SimpleHttpTest#httpPost()

View license
@Test
public void httpPost() throws IOException {
    InetSocketTransportAddress httpAddress = findHttpAddress(client());
    if (httpAddress == null) {
        throw new IllegalArgumentException("no HTTP address found");
    }
    URL base = new URL("http://" + httpAddress.getHost() + ":" + httpAddress.getPort());
    URL url = new URL(base, "_langdetect");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    Streams.copy(new StringReader("Das ist ein Text"), new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
    StringWriter response = new StringWriter();
    Streams.copy(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8), response);
    assertEquals("{\"languages\":[{\"language\":\"de\",\"probability\":0.9999967609942226}]}", response.toString());
}

78. SimpleHttpTest#httpPostShortProfile()

View license
@Test
public void httpPostShortProfile() throws IOException {
    InetSocketTransportAddress httpAddress = findHttpAddress(client());
    if (httpAddress == null) {
        throw new IllegalArgumentException("no HTTP address found");
    }
    URL base = new URL("http://" + httpAddress.getHost() + ":" + httpAddress.getPort());
    URL url = new URL(base, "_langdetect?profile=short-text");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    Streams.copy(new StringReader("Das ist ein Text"), new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
    StringWriter response = new StringWriter();
    Streams.copy(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8), response);
    assertEquals("{\"profile\":\"short-text\",\"languages\":[{\"language\":\"de\",\"probability\":0.9999968539079941}]}", response.toString());
}

79. SourceFactoryTest#getSourceFromFile_contextAbsoluteFileUrl_locationAbsoluteUrl()

Project: exist
Source File: SourceFactoryTest.java
View license
@Test
public void getSourceFromFile_contextAbsoluteFileUrl_locationAbsoluteUrl() throws IOException, PermissionDeniedException, URISyntaxException {
    final URL mainUrl = getClass().getResource("main.xq");
    final String contextPath = mainUrl.toString();
    final URL libraryUrl = getClass().getResource("library.xqm");
    final String location = libraryUrl.toString();
    final Source source = SourceFactory.getSource(null, contextPath, location, false);
    assertTrue(source instanceof FileSource);
    assertEquals(new java.io.File(libraryUrl.toURI()).getAbsolutePath(), source.getKey());
}

80. SourceFactoryTest#getSourceFromFile_contextAbsoluteFile_locationAbsoluteFile()

Project: exist
Source File: SourceFactoryTest.java
View license
@Test
public void getSourceFromFile_contextAbsoluteFile_locationAbsoluteFile() throws IOException, PermissionDeniedException, URISyntaxException {
    final URL mainUrl = getClass().getResource("main.xq");
    final String contextPath = new File(mainUrl.toURI()).getAbsolutePath();
    final URL libraryUrl = getClass().getResource("library.xqm");
    final String location = new File(libraryUrl.toURI()).getAbsolutePath();
    final Source source = SourceFactory.getSource(null, contextPath, location, false);
    assertTrue(source instanceof FileSource);
    assertEquals(new java.io.File(libraryUrl.toURI()).getAbsolutePath(), source.getKey());
}

81. 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);
    }
}

82. 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;
}

83. 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);
}

84. 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);
}

85. 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);
}

86. 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);
}

87. 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);
}

88. 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);
}

89. RecordDemo#loadSheet()

Project: gdata-java-client
Source File: RecordDemo.java
View license
/**
   * Uses the user's credentials to get a list of spreadsheets. Then asks the
   * user which spreadsheet to load. If the selected spreadsheet has multiple
   * worksheets then the user will also be prompted to select what sheet to use.
   * 
   * @param reader to read input from the keyboard
   * @throws ServiceException when the request causes an error in the Google
   *         Spreadsheets service.
   * @throws IOException when an error occurs in communication with the Google
   *         Spreadsheets service.
   * 
   */
public void loadSheet(BufferedReader reader) throws IOException, ServiceException {
    // Get the spreadsheet to load
    SpreadsheetFeed feed = service.getFeed(factory.getSpreadsheetsFeedUrl(), SpreadsheetFeed.class);
    List spreadsheets = feed.getEntries();
    int spreadsheetIndex = getIndexFromUser(reader, spreadsheets, "spreadsheet");
    SpreadsheetEntry spreadsheet = (SpreadsheetEntry) spreadsheets.get(spreadsheetIndex);
    URL spreadsheetUrl = new java.net.URL(spreadsheet.getSpreadsheetLink().getHref());
    this.baseUrl = spreadsheetUrl.getProtocol() + "://" + spreadsheetUrl.getHost();
    this.spreadsheetKey = spreadsheet.getKey();
    tablesFeedUrl = new java.net.URL(this.baseUrl + "/feeds/" + spreadsheet.getKey() + "/tables");
    out.println("Sheet loaded.");
}

90. TableDemo#loadSheet()

Project: gdata-java-client
Source File: TableDemo.java
View license
/**
   * Uses the user's credentials to get a list of spreadsheets. Then asks the
   * user which spreadsheet to load. If the selected spreadsheet has multiple
   * worksheets then the user will also be prompted to select what sheet to use.
   * 
   * @param reader to read input from the keyboard
   * @throws ServiceException when the request causes an error in the Google
   *         Spreadsheets service.
   * @throws IOException when an error occurs in communication with the Google
   *         Spreadsheets service.
   * 
   */
public void loadSheet(BufferedReader reader) throws IOException, ServiceException {
    // Get the spreadsheet to load
    SpreadsheetFeed feed = service.getFeed(factory.getSpreadsheetsFeedUrl(), SpreadsheetFeed.class);
    List spreadsheets = feed.getEntries();
    int spreadsheetIndex = getIndexFromUser(reader, spreadsheets, "spreadsheet");
    SpreadsheetEntry spreadsheet = (SpreadsheetEntry) spreadsheets.get(spreadsheetIndex);
    URL spreadsheetUrl = new java.net.URL(spreadsheet.getSpreadsheetLink().getHref());
    String baseUrl = new java.net.URL(spreadsheetUrl.getProtocol() + "://" + spreadsheetUrl.getHost()).toString();
    tablesFeedUrl = new java.net.URL(baseUrl + "/feeds/" + spreadsheet.getKey() + "/tables");
    System.out.println("Sheet loaded.");
}

91. SchemaConversionUtilsTest#testOrderDescriptionGroup()

View license
public void testOrderDescriptionGroup() throws Exception {
    URL srcXml = classLoader.getResource("j2ee_1_3dtd/DescriptionGroupTestSource.xml");
    URL expectedOutputXml = classLoader.getResource("j2ee_1_3dtd/DescriptionGroupTestExpected.xml");
    XmlObject srcObject = XmlObject.Factory.parse(srcXml);
    XmlCursor srcCursor = srcObject.newCursor();
    XmlCursor moveable = srcObject.newCursor();
    try {
        srcCursor.toFirstChild();
        srcCursor.toFirstChild();
        assertTrue(srcCursor.getName().toString(), "filter".equals(srcCursor.getName().getLocalPart()));
        do {
            srcCursor.push();
            srcCursor.toFirstChild();
            SchemaConversionUtils.convertToDescriptionGroup(srcCursor, moveable);
            srcCursor.pop();
        } while (srcCursor.toNextSibling());
    } finally {
        srcCursor.dispose();
    }
    //        System.out.println(srcObject.toString());
    XmlObject expected = XmlObject.Factory.parse(expectedOutputXml);
    List problems = new ArrayList();
    boolean ok = compareXmlObjects(srcObject, expected, problems);
    assertTrue("Differences: " + problems, ok);
}

92. SchemaConversionUtilsTest#testWeb23To24Transform()

View license
public void testWeb23To24Transform() throws Exception {
    URL srcXml = classLoader.getResource("j2ee_1_3dtd/web-23.xml");
    URL expectedOutputXml = classLoader.getResource("j2ee_1_3dtd/web-24.xml");
    XmlObject xmlObject = XmlObject.Factory.parse(srcXml);
    xmlObject = SchemaConversionUtils.convertToServletSchema(xmlObject);
    XmlObject expected = XmlObject.Factory.parse(expectedOutputXml);
    //        System.out.println(xmlObject.toString());
    //        System.out.println(expected.toString());
    List problems = new ArrayList();
    boolean ok = compareXmlObjects(xmlObject, expected, problems);
    assertTrue("Differences: " + problems, ok);
    xmlObject = SchemaConversionUtils.convertToServletSchema(xmlObject);
    boolean ok2 = compareXmlObjects(xmlObject, expected, problems);
    assertTrue("Differences: " + problems, ok2);
}

93. SchemaConversionUtilsTest#testWeb23To24OtherTransform()

View license
public void testWeb23To24OtherTransform() throws Exception {
    URL srcXml = classLoader.getResource("j2ee_1_3dtd/web-1-23.xml");
    URL expectedOutputXml = classLoader.getResource("j2ee_1_3dtd/web-1-24.xml");
    XmlObject xmlObject = XmlObject.Factory.parse(srcXml);
    xmlObject = SchemaConversionUtils.convertToServletSchema(xmlObject);
    //        System.out.println(xmlObject.toString());
    XmlObject expected = XmlObject.Factory.parse(expectedOutputXml);
    List problems = new ArrayList();
    boolean ok = compareXmlObjects(xmlObject, expected, problems);
    assertTrue("Differences: " + problems, ok);
    xmlObject = SchemaConversionUtils.convertToServletSchema(xmlObject);
    boolean ok2 = compareXmlObjects(xmlObject, expected, problems);
    assertTrue("Differences: " + problems, ok2);
}

94. SchemaConversionUtilsTest#testWeb22To24Transform1()

View license
public void testWeb22To24Transform1() throws Exception {
    URL srcXml = classLoader.getResource("j2ee_1_2dtd/web-1-22.xml");
    URL expectedOutputXml = classLoader.getResource("j2ee_1_2dtd/web-1-24.xml");
    XmlObject xmlObject = XmlObject.Factory.parse(srcXml);
    xmlObject = SchemaConversionUtils.convertToServletSchema(xmlObject);
    XmlObject expected = XmlObject.Factory.parse(expectedOutputXml);
    //        System.out.println(xmlObject.toString());
    //        System.out.println(expected.toString());
    List problems = new ArrayList();
    boolean ok = compareXmlObjects(xmlObject, expected, problems);
    assertTrue("Differences: " + problems, ok);
    xmlObject = SchemaConversionUtils.convertToServletSchema(xmlObject);
    boolean ok2 = compareXmlObjects(xmlObject, expected, problems);
    assertTrue("Differences: " + problems, ok2);
}

95. SchemaConversionUtilsTest#testGeronimoNamingNamespaceChange()

View license
public void testGeronimoNamingNamespaceChange() throws Exception {
    URL srcXml = classLoader.getResource("geronimo/ejb-naming-pre.xml");
    URL expectedOutputXml = classLoader.getResource("geronimo/ejb-naming-post.xml");
    XmlObject xmlObject = XmlObject.Factory.parse(srcXml);
    XmlCursor cursor = xmlObject.newCursor();
    try {
        SchemaConversionUtils.convertToGeronimoSubSchemas(cursor);
        //        System.out.println(xmlObject.toString());
        XmlObject expected = XmlObject.Factory.parse(expectedOutputXml);
        List problems = new ArrayList();
        boolean ok = compareXmlObjects(xmlObject, expected, problems);
        assertTrue("Differences: " + problems, ok);
        SchemaConversionUtils.convertToGeronimoSubSchemas(cursor);
        boolean ok2 = compareXmlObjects(xmlObject, expected, problems);
        assertTrue("Differences: " + problems, ok2);
    } finally {
        cursor.dispose();
    }
}

96. SchemaConversionUtilsTest#testSecurityElementConverter()

View license
public void testSecurityElementConverter() throws Exception {
    URL srcXml = classLoader.getResource("geronimo/security-pre.xml");
    URL expectedOutputXml = classLoader.getResource("geronimo/security-post.xml");
    XmlObject xmlObject = XmlObject.Factory.parse(srcXml);
    ElementConverter elementConverter = new SecurityElementConverter();
    XmlCursor cursor = xmlObject.newCursor();
    XmlCursor end = cursor.newCursor();
    try {
        elementConverter.convertElement(cursor, end);
        //        System.out.println(xmlObject.toString());
        XmlObject expected = XmlObject.Factory.parse(expectedOutputXml);
        List problems = new ArrayList();
        boolean ok = compareXmlObjects(xmlObject, expected, problems);
        assertTrue("Differences: " + problems, ok);
        SchemaConversionUtils.convertToGeronimoSubSchemas(cursor);
        boolean ok2 = compareXmlObjects(xmlObject, expected, problems);
        assertTrue("Differences: " + problems, ok2);
    } finally {
        cursor.dispose();
        end.dispose();
    }
}

97. SchemaConversionUtilsTest#testGBeanElementConverter()

View license
public void testGBeanElementConverter() throws Exception {
    URL srcXml = classLoader.getResource("geronimo/gbean-pre.xml");
    URL expectedOutputXml = classLoader.getResource("geronimo/gbean-post.xml");
    XmlObject xmlObject = XmlObject.Factory.parse(srcXml);
    ElementConverter elementConverter = new GBeanElementConverter();
    XmlCursor cursor = xmlObject.newCursor();
    XmlCursor end = cursor.newCursor();
    try {
        elementConverter.convertElement(cursor, end);
        //        System.out.println(xmlObject.toString());
        XmlObject expected = XmlObject.Factory.parse(expectedOutputXml);
        List problems = new ArrayList();
        boolean ok = compareXmlObjects(xmlObject, expected, problems);
        assertTrue("Differences: " + problems, ok);
        SchemaConversionUtils.convertToGeronimoSubSchemas(cursor);
        boolean ok2 = compareXmlObjects(xmlObject, expected, problems);
        assertTrue("Differences: " + problems, ok2);
    } finally {
        cursor.dispose();
        end.dispose();
    }
}

98. SchemaConversionUtilsTest#testQNameConverter1()

View license
public void testQNameConverter1() throws Exception {
    URL srcXml = classLoader.getResource("geronimo/qname1-pre.xml");
    URL expectedOutputXml = classLoader.getResource("geronimo/qname1-post.xml");
    XmlObject xmlObject = XmlObject.Factory.parse(srcXml);
    ElementConverter elementConverter = new QNameConverter("import", "http://geronimo.apache.org/xml/ns/deployment-1.0", "parent");
    XmlCursor cursor = xmlObject.newCursor();
    XmlCursor end = cursor.newCursor();
    try {
        elementConverter.convertElement(cursor, end);
        //        System.out.println(xmlObject.toString());
        XmlObject expected = XmlObject.Factory.parse(expectedOutputXml);
        List problems = new ArrayList();
        boolean ok = compareXmlObjects(xmlObject, expected, problems);
        assertTrue("Differences: " + problems, ok);
        SchemaConversionUtils.convertToGeronimoSubSchemas(cursor);
        boolean ok2 = compareXmlObjects(xmlObject, expected, problems);
        assertTrue("Differences: " + problems, ok2);
    } finally {
        cursor.dispose();
        end.dispose();
    }
}

99. SchemaConversionUtilsTest#testQNameConverter2()

View license
public void testQNameConverter2() throws Exception {
    URL srcXml = classLoader.getResource("geronimo/qname2-pre.xml");
    URL expectedOutputXml = classLoader.getResource("geronimo/qname2-post.xml");
    XmlObject xmlObject = XmlObject.Factory.parse(srcXml);
    ElementConverter elementConverter = new QNameConverter("import", "http://geronimo.apache.org/xml/ns/deployment-1.0", "parent");
    XmlCursor cursor = xmlObject.newCursor();
    XmlCursor end = cursor.newCursor();
    try {
        elementConverter.convertElement(cursor, end);
        //        System.out.println(xmlObject.toString());
        XmlObject expected = XmlObject.Factory.parse(expectedOutputXml);
        List problems = new ArrayList();
        boolean ok = compareXmlObjects(xmlObject, expected, problems);
        assertTrue("Differences: " + problems, ok);
        SchemaConversionUtils.convertToGeronimoSubSchemas(cursor);
        boolean ok2 = compareXmlObjects(xmlObject, expected, problems);
        assertTrue("Differences: " + problems, ok2);
    } finally {
        cursor.dispose();
        end.dispose();
    }
}

100. JettyModuleBuilder#getWebClassLoader()

Project: geronimo
Source File: JettyModuleBuilder.java
View license
private ClassLoader getWebClassLoader(EARContext earContext, WebModule webModule, ClassLoader cl, boolean contextPriorityClassLoader) throws DeploymentException {
    getWebClassPath(earContext, webModule);
    URI[] webClassPath = webModule.getWebClasspath();
    URI baseUri = earContext.getBaseDir().toURI();
    URL baseUrl = null;
    try {
        baseUrl = baseUri.resolve(webModule.getTargetPathURI()).toURL();
    } catch (MalformedURLException e) {
        throw new DeploymentException("Invalid module location: " + webModule.getTargetPathURI() + ", baseUri: " + baseUri);
    }
    URL[] webClassPathURLs = new URL[webClassPath.length];
    for (int i = 0; i < webClassPath.length; i++) {
        URI path = baseUri.resolve(webClassPath[i]);
        try {
            webClassPathURLs[i] = path.toURL();
        } catch (MalformedURLException e) {
            throw new DeploymentException("Invalid web class path element: path=" + path + ", baseUri=" + baseUri);
        }
    }
    ClassLoader webClassLoader = new JettyClassLoader(webClassPathURLs, baseUrl, cl, contextPriorityClassLoader);
    return webClassLoader;
}