Java Code Examples for java.net.URL
The following examples show how to use
java.net.URL.
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: product-ei Author: wso2 File: InMemoryDSSampleTestCase.java License: Apache License 2.0 | 7 votes |
@BeforeClass(alwaysRun = true) public void initialize() throws Exception { super.init(userMode); String resourceFileLocation; resourceFileLocation = getResourceLocation(); //DataSource already exist by default for super user. if (userMode == TestUserMode.TENANT_ADMIN || userMode == TestUserMode.TENANT_USER) { addDataSources(); } deployService(serviceName, new DataHandler(new URL("file:///" + resourceFileLocation + File.separator + "samples" + File.separator + "dbs" + File.separator + "inmemory" + File.separator + "InMemoryDSSample.dbs"))); log.info(serviceName + " uploaded"); serviceUrl = getServiceUrlHttp(serviceName); }
Example #2
Source Project: stocator Author: CODAIT File: SwiftAPIClient.java License: Apache License 2.0 | 7 votes |
/** * Direct HTTP PUT request without JOSS package * * @param objName name of the object * @param contentType content type * @return HttpURLConnection */ @Override public FSDataOutputStream createObject(String objName, String contentType, Map<String, String> metadata, Statistics statistics, boolean overwrite) throws IOException { final URL url = new URL(mJossAccount.getAccessURL() + "/" + getURLEncodedObjName(objName)); LOG.debug("PUT {}. Content-Type : {}", url.toString(), contentType); // When overwriting an object, cached metadata will be outdated String cachedName = getObjName(container + "/", objName); objectCache.remove(cachedName); try { final OutputStream sos; if (nonStreamingUpload) { sos = new SwiftNoStreamingOutputStream(mJossAccount, url, contentType, metadata, swiftConnectionManager, this); } else { sos = new SwiftOutputStream(mJossAccount, url, contentType, metadata, swiftConnectionManager); } return new FSDataOutputStream(sos, statistics); } catch (IOException e) { LOG.error(e.getMessage()); throw e; } }
Example #3
Source Project: knox Author: apache File: TopologyRulesModuleTest.java License: Apache License 2.0 | 6 votes |
@Test public void testParseTopologyWithDispatchParameters() throws IOException, SAXException { final Digester digester = loader.newDigester(); final String name = "topology-with-dispatch-parameters.xml"; final URL url = TestUtils.getResourceUrl( TopologyRulesModuleTest.class, name ); assertThat( "Failed to find URL for resource " + name, url, notNullValue() ); final File file = new File( url.getFile() ); final TopologyBuilder topologyBuilder = digester.parse( url ); final Topology topology = topologyBuilder.build(); assertThat( "Failed to parse resource " + name, topology, notNullValue() ); topology.setTimestamp( file.lastModified() ); final Collection<Service> services = topology.getServices(); final CustomDispatch dispatch = services.iterator().next().getDispatch(); assertThat( "Failed to find dispatch", dispatch, notNullValue() ); assertThat( dispatch.getContributorName(), is("testContributor") ); assertThat( dispatch.getHaContributorName(), is("testHAContributor") ); assertThat( dispatch.getClassName(), is("org.apache.hadoop.gateway.hbase.HBaseDispatch") ); assertThat( dispatch.getHaClassName(), is("testHAClassName") ); assertThat( dispatch.getHttpClientFactory(), is("testHttpClientFactory") ); assertThat( dispatch.getUseTwoWaySsl(), is(true) ); assertThat( dispatch.getParams().size(), is(2) ); assertThat( dispatch.getParams().get("abc"), is("def") ); assertThat( dispatch.getParams().get("ghi"), is("123") ); }
Example #4
Source Project: netbeans Author: apache File: MainProjectManager.java License: Apache License 2.0 | 6 votes |
/** * Test whether one project is dependent on the other. * @param p1 dependent project * @param p2 main project * @return <code>true</code> if project <code>p1</code> depends on project <code>p2</code> */ @SuppressWarnings("DMI_COLLECTION_OF_URLS") private static boolean isDependent(Project p1, Project p2) { Set<URL> p1Roots = getProjectRoots(p1); Set<URL> p2Roots = getProjectRoots(p2); for (URL root : p2Roots) { Set<URL> dependentRoots = SourceUtils.getDependentRoots(root); for (URL sr : p1Roots) { if (dependentRoots.contains(sr)) { return true; } } } return false; }
Example #5
Source Project: CrazyAlpha Author: Deali-Axy File: ResouceManager.java License: GNU General Public License v2.0 | 6 votes |
/** * 获取音频资源 * * @param musicName 名称 * @return Media对象 */ public Media getMedia(String musicName) { if (media.containsKey(musicName)) { String relativePath = media.get(musicName); URL musicRes = getClass().getClassLoader().getResource(relativePath); if (musicRes == null) { logger.error("cannot get media resource {}", relativePath); return null; } if (inJar) { String path = String.format("jar:file:%s!/%s", jarPath, relativePath); logger.debug("the Fuck media path: {}", path); return new Media(path); } else return new Media("file:" + musicRes.getPath()); } else return null; }
Example #6
Source Project: development Author: servicecatalog File: WSPortConnector.java License: Apache License 2.0 | 6 votes |
/** * Creates an instance of port connector. * * @param remoteWsdlUrl * The URL at which the WSDL can be accessed. * @param userName * The userName to be used for authentication. <code>null</code> * if no authentication is required. * @param password * The password for the user. <code>null</code> if not required. * @param host * optional - if specified, this host will be used instead the * one from the wsdl * * @throws IOException * @throws WSDLException */ public WSPortConnector(String remoteWsdlUrl, String userName, String password, String host) throws IOException, WSDLException { this.userName = userName; this.password = password; URL url = new URL(remoteWsdlUrl); if (requiresUserAuthentication(userName, password)) { url = BasicAuthLoader.load(url, userName, password); } WSDLLocator locator = new BasicAuthWSDLLocator(remoteWsdlUrl, userName, password); try { details = getServiceDetails(locator, host); } finally { locator.close(); } }
Example #7
Source Project: deltaspike Author: apache File: ViewAccessScopedWithFViewActionWebAppTest.java License: Apache License 2.0 | 6 votes |
@Test @RunAsClient public void testForward() throws Exception { driver.get(new URL(contextPath, "index.xhtml").toString()); WebElement inputFieldX = driver.findElement(By.id("form:firstValue")); inputFieldX.sendKeys("abc"); WebElement inputFieldY = driver.findElement(By.id("form:secondValue")); inputFieldY.sendKeys("xyz"); WebElement button = driver.findElement(By.id("form:next")); button.click(); Assert.assertTrue(ExpectedConditions.textToBePresentInElement(By.id("firstValue"), "abc").apply(driver)); Assert.assertTrue(ExpectedConditions.textToBePresentInElement(By.id("secondValue"), "xyz").apply(driver)); }
Example #8
Source Project: datacollector Author: streamsets File: TestRemoteLocationExecutor.java License: Apache License 2.0 | 6 votes |
private void setupServer(String homeDir, boolean absolutePath) throws Exception { if (!absolutePath) { URL url = Thread.currentThread().getContextClassLoader().getResource(homeDir); homeDir = url.getPath(); } switch (scheme) { case sftp: setupSSHD(homeDir); break; case ftp: setupFTPServer(homeDir); break; case ftps: setupFTPSServer(homeDir, KeyStoreType.JKS, null, false); break; default: Assert.fail("Missing Server setup for scheme " + scheme); } }
Example #9
Source Project: htmlunit Author: HtmlUnit File: WebClient8Test.java License: Apache License 2.0 | 6 votes |
/** * @throws Exception if something goes wrong */ @Test public void link() throws Exception { final String html = "<html>\n" + "<head>\n" + " <title>foo</title>\n" + " <link rel='stylesheet' href='simple.css'>\n" + "</head>\n" + "<body>\n" + "</body></html>"; try (WebClient webClient = new WebClient(getBrowserVersion(), false, null, -1)) { final MockWebConnection webConnection = getMockWebConnection(); webConnection.setResponse(URL_FIRST, html); webConnection.setResponse(new URL(URL_FIRST, "simple.css"), ""); webClient.setWebConnection(webConnection); webClient.getPage(URL_FIRST); } }
Example #10
Source Project: ModPackDownloader Author: Nincraft File: CurseFile.java License: MIT License | 6 votes |
@Override public void init() { setProjectUrl(buildProjectUrl()); try { if (Strings.isNullOrEmpty(getProjectName()) || Strings.isNullOrEmpty(getName())) { val conn = (HttpURLConnection) new URL(getProjectUrl()).openConnection(); conn.setInstanceFollowRedirects(false); conn.connect(); val newProjectName = conn.getHeaderField("Location").split("/")[5]; if (Strings.isNullOrEmpty(getProjectName())) { setProjectName(newProjectName); } if (Strings.isNullOrEmpty(getName())) { setName(newProjectName); } } } catch (final IOException e) { log.error(e); } setDownloadUrl(getDownloadUrl()); }
Example #11
Source Project: openjdk-jdk9 Author: AdoptOpenJDK File: BootstrapResolver.java License: GNU General Public License v2.0 | 6 votes |
/** Constructor. */ public BootstrapResolver() { URL url = this.getClass().getResource("/com/sun/org/apache/xml/internal/resolver/etc/catalog.dtd"); if (url != null) { publicMap.put(xmlCatalogPubId, url.toString()); systemMap.put(xmlCatalogSysId, url.toString()); } url = this.getClass().getResource("/com/sun/org/apache/xml/internal/resolver/etc/catalog.rng"); if (url != null) { uriMap.put(xmlCatalogRNG, url.toString()); } url = this.getClass().getResource("/com/sun/org/apache/xml/internal/resolver/etc/catalog.xsd"); if (url != null) { uriMap.put(xmlCatalogXSD, url.toString()); } url = this.getClass().getResource("/com/sun/org/apache/xml/internal/resolver/etc/xcatalog.dtd"); if (url != null) { publicMap.put(xCatalogPubId, url.toString()); } }
Example #12
Source Project: swellrt Author: SwellRT File: AbstractRobotTest.java License: Apache License 2.0 | 6 votes |
public void testSubmit() throws Exception { HttpFetcher fetcher = mock(HttpFetcher.class); when(fetcher.execute(any(HttpMessage.class), anyMapOf(String.class, Object.class))) .thenReturn(new HttpResponse("POST", new URL("http://foo.google.com"), 0, new ByteArrayInputStream("[{\"id\":\"op1\",\"data\":{}}]".getBytes()))); MockRobot robot = new MockRobot(); robot.setupOAuth("consumerKey", "consumerSecret", "http://gmodules.com/api/rpc"); WaveService service = new WaveService(fetcher, robot.computeHash()); service.setupOAuth("consumerKey", "consumerSecret", "http://gmodules.com/api/rpc"); OperationQueue opQueue = new OperationQueue(); opQueue.appendOperation(OperationType.ROBOT_NOTIFY, Parameter.of(ParamsProperty.CAPABILITIES_HASH, "123")); Wavelet wavelet = mock(Wavelet.class); when(wavelet.getOperationQueue()).thenReturn(opQueue); assertEquals(1, opQueue.getPendingOperations().size()); robot.submit(wavelet, "http://gmodules.com/api/rpc", service); assertEquals(0, opQueue.getPendingOperations().size()); verify(fetcher, times(1)).execute(any(HttpMessage.class), anyMapOf(String.class, Object.class)); }
Example #13
Source Project: nopol Author: SpoonLabs File: FileLibrary.java License: GNU General Public License v2.0 | 5 votes |
public static URL urlFrom(String path) { URL url = null; try { url = openFrom(path).toURI().toURL(); } catch (MalformedURLException e) { fail("Illegal name for '" + path + "' while converting to URL"); } return url; }
Example #14
Source Project: consulo Author: consulo File: PluginClassLoaderImpl.java License: Apache License 2.0 | 5 votes |
@Override public URL findResource(String name) { URL resource = findOwnResource(name); if (resource != null) return resource; return processResourcesInParents(name, findResourceInPluginCL, findResourceInCl, null, null); }
Example #15
Source Project: cxf Author: apache File: ValidationClientServerTest.java License: Apache License 2.0 | 5 votes |
private SchemaValidation createService(Object validationConfig, String postfix) throws Exception { URL wsdl = getClass().getResource("/wsdl/schema_validation.wsdl"); assertNotNull(wsdl); SchemaValidationService service = new SchemaValidationService(wsdl, serviceName); assertNotNull(service); SchemaValidation validation = service.getPort(portName, SchemaValidation.class); setAddress(validation, "http://localhost:" + PORT + "/SoapContext/" + postfix); ((BindingProvider)validation).getRequestContext().put(Message.SCHEMA_VALIDATION_ENABLED, validationConfig); ((BindingProvider)validation).getResponseContext().put(Message.SCHEMA_VALIDATION_ENABLED, validationConfig); new LoggingFeature().initialize((Client)validation, getBus()); return validation; }
Example #16
Source Project: juddi Author: apache File: Install.java License: Apache License 2.0 | 5 votes |
private static Object buildInstallEntityAlt(final String fileName, Class outputtype, Configuration config) throws JAXBException, IOException, ConfigurationException { InputStream resourceStream = null; // First try the custom install directory URL url = ClassUtil.getResource(JUDDI_CUSTOM_INSTALL_DATA_DIR + fileName, Install.class); if (url != null) { resourceStream = url.openStream(); } // If the custom install directory doesn't exist, then use the standard install directory where the resource is guaranteed to exist. if (resourceStream == null) { url = ClassUtil.getResource(JUDDI_INSTALL_DATA_DIR + fileName, Install.class); if (url != null) { resourceStream = url.openStream(); } // If file still does not exist then return null; if (url == null || resourceStream == null) { if (fileName.endsWith(FILE_PUBLISHER)) { throw new ConfigurationException("Could not locate " + JUDDI_INSTALL_DATA_DIR + fileName); } else { log.debug("Could not locate: " + url); } return null; } } log.info("Loading the content of file: " + url); StringBuilder xml = new StringBuilder(); byte[] b = new byte[4096]; for (int n; (n = resourceStream.read(b)) != -1;) { xml.append(new String(b, 0, n, AuthenticatedService.UTF8)); } log.debug("inserting: " + xml.toString()); StringReader reader = new StringReader(xml.toString()); Object obj= XmlUtils.unmarshal(reader, outputtype); reader.close(); return obj; }
Example #17
Source Project: box-java-sdk Author: box File: BoxFolder.java License: Apache License 2.0 | 5 votes |
/** * Deletes the metadata on this folder associated with a specified scope and template. * * @param templateName the metadata template type name. * @param scope the scope of the template (usually "global" or "enterprise"). */ public void deleteMetadata(String templateName, String scope) { URL url = METADATA_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID(), scope, templateName); BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE"); BoxAPIResponse response = request.send(); response.disconnect(); }
Example #18
Source Project: picocli Author: remkop File: Resources.java License: Apache License 2.0 | 5 votes |
public static String slurp(String resource) { try { URL url = Resources.class.getResource(resource); if (url == null) { throw new FileNotFoundException(resource); } return slurp(url.openStream()); } catch (IOException ex) { throw new IllegalStateException(ex); } }
Example #19
Source Project: fabric-installer Author: FabricMC File: MetaHandler.java License: Apache License 2.0 | 5 votes |
public void load() throws IOException { URL url = new URL(metaUrl); URLConnection conn = url.openConnection(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { String json = reader.lines().collect(Collectors.joining("\n")); Type type = new TypeToken<ArrayList<GameVersion>>() {}.getType(); versions = Utils.GSON.fromJson(json, type); complete(versions); } }
Example #20
Source Project: Bytecoder Author: mirkosertic File: Handler.java License: Apache License 2.0 | 5 votes |
@Override protected URLConnection openConnection(URL url) throws IOException { String s = url.toString(); int index = s.indexOf("!/"); if (index == -1) throw new MalformedURLException("no !/ found in url spec:" + s); throw new IOException("Can't connect to jmod URL"); }
Example #21
Source Project: fresco Author: facebook File: HttpUrlConnectionNetworkFetcherTest.java License: MIT License | 5 votes |
@Test public void testHttpUrlConnectionTimeout() throws Exception { URL mockURL = PowerMockito.mock(URL.class); HttpURLConnection mockConnection = PowerMockito.mock(HttpURLConnection.class); mockConnection.setConnectTimeout(30000); PowerMockito.when(mockURL.openConnection()).thenReturn(mockConnection); SocketTimeoutException expectedException = new SocketTimeoutException(); PowerMockito.when(mockConnection.getResponseCode()).thenThrow(expectedException); verify(mockConnection).setConnectTimeout(30000); }
Example #22
Source Project: redisson Author: redisson File: JCachingProvider.java License: Apache License 2.0 | 5 votes |
private Config loadConfig(URI uri) { Config config = null; try { URL jsonUrl = null; if (DEFAULT_URI_PATH.equals(uri.getPath())) { jsonUrl = JCachingProvider.class.getResource("/redisson-jcache.json"); } else { jsonUrl = uri.toURL(); } if (jsonUrl == null) { throw new IOException(); } config = Config.fromJSON(jsonUrl); } catch (IOException e) { try { URL yamlUrl = null; if (DEFAULT_URI_PATH.equals(uri.getPath())) { yamlUrl = JCachingProvider.class.getResource("/redisson-jcache.yaml"); } else { yamlUrl = uri.toURL(); } if (yamlUrl != null) { config = Config.fromYAML(yamlUrl); } } catch (IOException e2) { // skip } } return config; }
Example #23
Source Project: HtmlUnit-Android Author: null-dev File: WebClient.java License: Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override public void webWindowContentChanged(final WebWindowEvent event) { final WebWindow window = event.getWebWindow(); boolean use = false; if (window instanceof DialogWindow) { use = true; } else if (window instanceof TopLevelWindow) { use = event.getOldPage() == null; } else if (window instanceof FrameWindow) { final FrameWindow fw = (FrameWindow) window; final String enclosingPageState = fw.getEnclosingPage().getDocumentElement().getReadyState(); final URL frameUrl = fw.getEnclosedPage().getUrl(); if (!DomNode.READY_STATE_COMPLETE.equals(enclosingPageState) || frameUrl == URL_ABOUT_BLANK) { return; } // now looks at the visibility of the frame window final BaseFrameElement frameElement = fw.getFrameElement(); if (frameElement.isDisplayed()) { final Object element = frameElement.getScriptableObject(); final HTMLElement htmlElement = (HTMLElement) element; final ComputedCSSStyleDeclaration style = htmlElement.getWindow().getComputedStyle(htmlElement, null); use = style.getCalculatedWidth(false, false) != 0 && style.getCalculatedHeight(false, false) != 0; } } if (use) { webClient_.setCurrentWindow(window); } }
Example #24
Source Project: olingo-odata4 Author: apache File: AcceptHeaderAcceptCharsetHeaderITCase.java License: Apache License 2.0 | 5 votes |
@Test public void invalidAcceptHeader2() throws Exception { URL url = new URL(SERVICE_URI + "ESAllPrim"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/xyz"); connection.connect(); assertEquals(HttpStatusCode.NOT_ACCEPTABLE.getStatusCode(), connection.getResponseCode()); final String content = IOUtils.toString(connection.getErrorStream()); assertTrue(content.contains("The content-type range 'application/xyz' is " + "not supported as value of the Accept header.")); }
Example #25
Source Project: netbeans Author: apache File: JspLineBreakpoint.java License: Apache License 2.0 | 5 votes |
private FileObject getFile() { FileObject fo; try { fo = URLMapper.findFileObject(new URL(url)); } catch (MalformedURLException ex) { Exceptions.printStackTrace(ex); fo = null; } return fo; }
Example #26
Source Project: ranger Author: apache File: RangerConfiguration.java License: Apache License 2.0 | 5 votes |
private URL getFileLocation(String fileName) { URL lurl = RangerConfiguration.class.getClassLoader().getResource(fileName); if (lurl == null ) { lurl = RangerConfiguration.class.getClassLoader().getResource("/" + fileName); } return lurl; }
Example #27
Source Project: Pydev Author: fabioz File: ScriptXmlRpcClient.java License: Eclipse Public License 1.0 | 5 votes |
/** * Sets the port where the server is started. * @throws MalformedURLException */ @Override public void setPort(int port) throws MalformedURLException { XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); config.setServerURL(new URL("http://" + LocalHost.getLocalHost() + ":" + port)); this.impl.setConfig(config); }
Example #28
Source Project: openpojo Author: OpenPojo File: JarFileReader.java License: Apache License 2.0 | 5 votes |
public static String getJarFileNameFromURLPath(String name) { String fileName = ""; if (null != name && name.indexOf(Java.JAR_FILE_PATH_SEPARATOR) > 0) { fileName = name.substring(0, name.indexOf(Java.JAR_FILE_PATH_SEPARATOR)); try { URLToFileSystemAdapter urlToFileSystemAdapter = new URLToFileSystemAdapter(new URL(fileName)); fileName = urlToFileSystemAdapter.getAsFile().getAbsolutePath(); } catch (MalformedURLException ignored) { } } return fileName; }
Example #29
Source Project: openjdk-8 Author: bpupadhyaya File: URLClassPath.java License: GNU General Public License v2.0 | 5 votes |
JarLoader(URL url, URLStreamHandler jarHandler, HashMap<String, Loader> loaderMap) throws IOException { super(new URL("jar", "", -1, url + "!/", jarHandler)); csu = url; handler = jarHandler; lmap = loaderMap; if (!isOptimizable(url)) { ensureOpen(); } else { String fileName = url.getFile(); if (fileName != null) { fileName = ParseUtil.decode(fileName); File f = new File(fileName); metaIndex = MetaIndex.forJar(f); // If the meta index is found but the file is not // installed, set metaIndex to null. A typical // senario is charsets.jar which won't be installed // when the user is running in certain locale environment. // The side effect of null metaIndex will cause // ensureOpen get called so that IOException is thrown. if (metaIndex != null && !f.exists()) { metaIndex = null; } } // metaIndex is null when either there is no such jar file // entry recorded in meta-index file or such jar file is // missing in JRE. See bug 6340399. if (metaIndex == null) { ensureOpen(); } } }
Example #30
Source Project: android-codegenerator-library Author: tmorcinek File: ResourceTemplatesProvider.java License: Apache License 2.0 | 5 votes |
@Override public String provideTemplateForName(String templateName) { URL url = Resources.getResource(templateName); try { return Resources.toString(url, Charset.defaultCharset()); } catch (IOException e) { e.printStackTrace(); } return null; }