List of usage examples for java.net URL toExternalForm
public String toExternalForm()
From source file:org.jboss.as.test.integration.domain.management.cli.DomainDeploymentOverlayTestCase.java
private String performHttpCall(String host, String server, String deployment) throws Exception { ModelNode op = new ModelNode(); op.get(OP).set(READ_RESOURCE_OPERATION); op.get(OP_ADDR).add(HOST, host).add(SERVER, server).add(SOCKET_BINDING_GROUP, SOCKET_BINDING_GROUP_NAME) .add(SOCKET_BINDING, "http"); op.get(INCLUDE_RUNTIME).set(true);/*from w w w. j a v a 2 s . c om*/ ModelNode socketBinding = validateResponse(client.execute(op)); URL url = new URL("http", org.jboss.as.arquillian.container.NetworkUtils.formatPossibleIpv6Address( socketBinding.get("bound-address").asString()), socketBinding.get("bound-port").asInt(), "/" + deployment + "/SimpleServlet?env-entry=overlay-test"); return HttpRequest.get(url.toExternalForm(), 10, TimeUnit.SECONDS).trim(); }
From source file:com.madrobot.net.client.XMLRPCClient.java
/** * Convenience constructor. Creates new instance based on server String address * /*from w w w .j a v a2s.c om*/ * @param XMLRPC * server url * @param HTTP * Server - Basic Authentication - Username * @param HTTP * Server - Basic Authentication - Password */ public XMLRPCClient(URL url, String username, String password) { this(URI.create(url.toExternalForm()), username, password); }
From source file:org.jboss.as.test.integration.security.picketlink.SAML2KerberosAuthenticationTestCase.java
/** * Test principal for jduke user./*from w w w . j a v a 2 s. c o m*/ * * @throws Exception */ @Test @OperateOnDeployment(SERVICE_PROVIDER_NAME) public void testJDukePrincipal(@ArquillianResource URL webAppURL, @ArquillianResource @OperateOnDeployment(IDENTITY_PROVIDER_NAME) URL idpURL) throws Exception { final String cannonicalHost = Utils.getCannonicalHost(mgmtClient); final URI principalPrintingURL = new URI(webAppURL.toExternalForm() + PrincipalPrintingServlet.SERVLET_PATH.substring(1) + "?test=testDeploymentViaKerberos"); String responseBody = makeCallWithKerberosAuthn(principalPrintingURL, Utils.replaceHost(idpURL.toURI(), cannonicalHost), "jduke", DUKE_PASSWORD); assertThat("Unexpected principal", responseBody, equalTo("jduke")); }
From source file:com.agilejava.maven.docbkx.GeneratorMojo.java
/** * Creates a {@link Transformer} with the ability to transitively detect the * names of all parameters defined on global level for a certain XSLT * stylesheet.//from w ww . j a va 2s. com * * @return The {@link Transformer} that takes a stylesheet as input, and * outputs a text stream containing the parameter names. * @throws TransformerConfigurationException * If we can't create the <code>Transformer</code>. */ private Transformer createParamListTransformer() throws TransformerConfigurationException { TransformerFactory factory = new TransformerFactoryImpl(); URL stylesheet = Thread.currentThread().getContextClassLoader().getResource(TRANSFORMER_LOCATION); Source source = new StreamSource(stylesheet.toExternalForm()); return factory.newTransformer(source); }
From source file:com.gargoylesoftware.htmlunit.WebRequest.java
private URL buildUrlWithNewFile(URL url, String newFile) { try {/*from ww w.jav a 2 s . c om*/ if (url.getRef() != null) { newFile += '#' + url.getRef(); } url = new URL(url.getProtocol(), url.getHost(), url.getPort(), newFile); } catch (final Exception e) { throw new RuntimeException("Cannot set URL: " + url.toExternalForm(), e); } return url; }
From source file:ca.nrc.cadc.caom2.pkg.TarWriter.java
public void write(String path, URL url) throws TarProxyException, IOException { TarContent item = new TarContent(); addItem(path, item);// w w w . j ava 2 s . c om item.url = url; boolean openEntry = false; try { // HEAD to get entry metadata ByteArrayOutputStream tmp = new ByteArrayOutputStream(); HttpDownload get = new HttpDownload(url, tmp); get.setHeadOnly(true); get.run(); if (get.getThrowable() != null) { item.emsg = "HEAD " + url.toExternalForm() + " failed, reason: " + get.getThrowable().getMessage(); throw new TarProxyException("HEAD " + url.toExternalForm() + " failed", get.getThrowable()); } item.filename = get.getFilename(); String filename = path + "/" + item.filename; long contentLength = get.getContentLength(); Date lastModified = get.getLastModified(); item.contentMD5 = get.getContentMD5(); // create entry log.debug("tar entry: " + filename + "," + contentLength + "," + lastModified); ArchiveEntry e = new DynamicTarEntry(filename, contentLength, lastModified); tout.putArchiveEntry(e); openEntry = true; // stream content get = new HttpDownload(url, new TarStreamWrapper(tout)); // wrapper suppresses close() by HttpDownload get.run(); if (get.getThrowable() != null) { item.emsg = "GET " + url.toExternalForm() + " failed, reason: " + get.getThrowable().toString(); throw new TarProxyException("GET " + url.toExternalForm() + " failed", get.getThrowable()); } log.debug("server response: " + get.getResponseCode() + "," + get.getContentLength()); } finally { if (openEntry) tout.closeArchiveEntry(); } }
From source file:com.couchbase.lite.performance.Test7_PullReplication.java
private void pushDocumentToSyncGateway(String docId, final String docJson) throws MalformedURLException { // push a document to server URL replicationUrlTrailingDoc1 = new URL( String.format("%s/%s", getReplicationURL().toExternalForm(), docId)); final URL pathToDoc1 = new URL(replicationUrlTrailingDoc1, docId); Log.d(TAG, "Send http request to " + pathToDoc1); final CountDownLatch httpRequestDoneSignal = new CountDownLatch(1); BackgroundTask getDocTask = new BackgroundTask() { @Override// ww w . j a v a 2 s. com public void run() { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response; String responseString = null; try { HttpPut post = new HttpPut(pathToDoc1.toExternalForm()); StringEntity se = new StringEntity(docJson.toString()); se.setContentType(new BasicHeader("content_type", "application/json")); post.setEntity(se); response = httpclient.execute(post); StatusLine statusLine = response.getStatusLine(); Log.d(TAG, "Got response: " + statusLine); assertTrue(statusLine.getStatusCode() == HttpStatus.SC_CREATED); } catch (ClientProtocolException e) { assertNull("Got ClientProtocolException: " + e.getLocalizedMessage(), e); } catch (IOException e) { assertNull("Got IOException: " + e.getLocalizedMessage(), e); } httpRequestDoneSignal.countDown(); } }; getDocTask.execute(); Log.d(TAG, "Waiting for http request to finish"); try { httpRequestDoneSignal.await(300, TimeUnit.SECONDS); Log.d(TAG, "http request finished"); } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:io.apicurio.hub.api.rest.impl.DesignsResourceTest.java
@Test public void testImportDesign_Url() throws ServerError, AlreadyExistsException, NotFoundException, ApiValidationException { URL resourceUrl = getClass().getResource("DesignsResourceTest_import.json"); ImportApiDesign info = new ImportApiDesign(); info.setUrl(resourceUrl.toExternalForm()); ApiDesign design = resource.importDesign(info); Assert.assertNotNull(design);//from w w w .ja va 2s . co m Assert.assertEquals("1", design.getId()); Assert.assertEquals("user", design.getCreatedBy()); Assert.assertEquals("Rate Limiter API", design.getName()); Assert.assertEquals("A REST API used by clients to access the standalone Rate Limiter micro-service.", design.getDescription()); String ghLog = github.auditLog(); Assert.assertNotNull(ghLog); Assert.assertEquals("---\n" + "---", ghLog); }
From source file:com.madrobot.net.client.XMLRPCClient.java
/** * Convenience constructor. Creates new instance based on server String address * /* w ww . j a va 2 s. co m*/ * @param XMLRPC * server url * @param HTTP * Server - Basic Authentication - Username * @param HTTP * Server - Basic Authentication - Password * @param HttpClient * to use */ public XMLRPCClient(URL url, String username, String password, HttpClient client) { this(URI.create(url.toExternalForm()), username, password, client); }
From source file:com.dtolabs.client.utils.BaseFormAuthenticator.java
/** * Authenticate the client http state so that the colony requests can be made. * * @param baseURL URL requested for colony * @param client HttpClient instance/* w ww . ja v a2s.c o m*/ * * @return true if authentication succeeded. * * @throws com.dtolabs.client.utils.HttpClientException * */ public boolean authenticate(final URL baseURL, final HttpClient client) throws HttpClientException { final HttpState state = client.getState(); if (hasSessionCookie(baseURL, state, basePath)) { return true; } final byte[] buffer = new byte[1024]; boolean doPostLogin = false; boolean isLoginFormContent = false; logger.debug("No session found, must login..."); try { final URL newUrl = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(), basePath + getInitialPath()); //load welcome page, which should forward to form based logon page. final GetMethod get = new GetMethod(newUrl.toExternalForm()); get.setDoAuthentication(false); get.setFollowRedirects(false); logger.debug("Requesting: " + newUrl); int res = client.executeMethod(get); logger.debug("Result is: " + res); /* Tomcat container auth behaves differently than Jetty. Tomcat will respond 200 OK and include the login form when auth is required, as well as on auth failure, it will also require complete GET of original URL after successful auth. Jetty will redirect to login page when auth is required, and will redirect to error page on failure. */ String body = get.getResponseBodyAsString(); if (null != body && body.contains(J_SECURITY_CHECK) && body.contains(JAVA_USER_PARAM) && body.contains(JAVA_PASS_PARAM)) { isLoginFormContent = true; } get.releaseConnection(); if ((res == HttpStatus.SC_UNAUTHORIZED)) { if (get.getResponseHeader("WWW-Authenticate") != null && get.getResponseHeader("WWW-Authenticate").getValue().matches("^Basic.*")) { logger.warn("Form-based login received UNAUTHORIZED, trying to use Basic authentication"); final BasicAuthenticator auth = new BasicAuthenticator(username, password); return auth.authenticate(baseURL, client); } else { throw new HttpClientException( "Form-based login received UNAUTHORIZED, but didn't recognize it as Basic authentication: unable to get a session"); } } //should now have the proper session cookie if (!hasSessionCookie(baseURL, state, basePath)) { throw new HttpClientException("Unable to get a session from URL : " + newUrl); } if (res == HttpStatus.SC_OK && isLoginFormContent) { doPostLogin = true; } else if ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY) || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header locHeader = get.getResponseHeader("Location"); if (locHeader == null) { throw new HttpClientException("Redirect with no Location header, request URL: " + newUrl); } String location = locHeader.getValue(); if (!isValidLoginRedirect(get)) { //unexpected response throw new HttpClientException("Unexpected redirection when getting session: " + location); } logger.debug("Follow redirect: " + res + ": " + location); final GetMethod redir = new GetMethod(location); redir.setFollowRedirects(true); res = client.executeMethod(redir); InputStream ins = redir.getResponseBodyAsStream(); while (ins.available() > 0) { //read and discard response body ins.read(buffer); } redir.releaseConnection(); if (res != HttpStatus.SC_OK) { throw new HttpClientException("Login page status was not OK: " + res); } logger.debug("Result: " + res); doPostLogin = true; } else if (res != HttpStatus.SC_OK) { //if request to welcome page was OK, we figure that the session is already set throw new HttpClientException("Request to welcome page returned error: " + res + ": " + get); } if (doPostLogin) { //now post login final URL loginUrl = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(), basePath + JAVA_AUTH_PATH); final PostMethod login = new PostMethod(loginUrl.toExternalForm()); login.setRequestBody(new NameValuePair[] { new NameValuePair(JAVA_USER_PARAM, getUsername()), new NameValuePair(JAVA_PASS_PARAM, getPassword()) }); login.setFollowRedirects(false); logger.debug("Post login info to URL: " + loginUrl); res = client.executeMethod(login); final InputStream ins = login.getResponseBodyAsStream(); while (ins.available() > 0) { //read and discard response body ins.read(buffer); } login.releaseConnection(); Header locHeader = login.getResponseHeader("Location"); String location = null != locHeader ? locHeader.getValue() : null; if (isLoginError(login)) { logger.error("Form-based auth failed"); return false; } else if (null != location && !location.equals(newUrl.toExternalForm())) { logger.warn("Form-based auth succeeded, but last URL was unexpected"); } if (isFollowLoginRedirect() && ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY) || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT))) { if (location == null) { throw new HttpClientException("Redirect with no Location header, request URL: " + newUrl); } final GetMethod get2 = new GetMethod(location); // logger.debug("Result: " + res + ": " + location + ", following redirect"); res = client.executeMethod(get2); } else if (res != HttpStatus.SC_OK) { throw new HttpClientException( "Login didn't seem to work: " + res + ": " + login.getResponseBodyAsString()); } logger.debug("Result: " + res); } } catch (MalformedURLException e) { throw new HttpClientException("Bad URL", e); } catch (HttpException e) { throw new HttpClientException("HTTP Error: " + e.getMessage(), e); } catch (IOException e) { throw new HttpClientException( "Error occurred while trying to authenticate to server: " + e.getMessage(), e); } return true; }