List of usage examples for java.net URL getHost
public String getHost()
From source file:org.picketbox.http.test.authentication.jetty.DelegatingSecurityFilterHTTPBasicUnitTestCase.java
@Test public void testBasicAuth() throws Exception { URL url = new URL(this.urlStr); DefaultHttpClient httpclient = null; try {/*from w w w.ja va2s . c om*/ String user = "Aladdin"; String pass = "Open Sesame"; httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(user, pass)); HttpGet httpget = new HttpGet(url.toExternalForm()); System.out.println("executing request" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); StatusLine statusLine = response.getStatusLine(); System.out.println(statusLine); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } assertEquals(200, statusLine.getStatusCode()); EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:com.googlesource.gerrit.plugins.github.oauth.OAuthGitFilter.java
private URI getRequestUrlWithAlternatePath(HttpServletRequest httpRequest, String alternatePath) throws MalformedURLException { URL originalUrl = new URL(httpRequest.getRequestURL().toString()); String contextPath = httpRequest.getContextPath(); return URI.create(originalUrl.getProtocol() + "://" + originalUrl.getHost() + ":" + getPort(originalUrl) + contextPath + alternatePath); }
From source file:com.jfrog.bintray.client.impl.HttpClientConfigurator.java
/** * May throw a runtime exception when the given URL is invalid. *//*from w w w. j av a 2 s . co m*/ public HttpClientConfigurator hostFromUrl(String urlStr) throws IllegalArgumentException { if (StringUtils.isNotBlank(urlStr)) { try { URL url = new URL(urlStr); host(url.getHost()); } catch (MalformedURLException e) { throw new IllegalArgumentException("Cannot parse the url " + urlStr, e); } } return this; }
From source file:io.cloudslang.content.utilities.services.osdetector.NmapOsDetectorService.java
@NotNull public String appendProxyArgument(String nmapArguments, String proxyHost, String proxyPort) { try {/*from w w w.jav a 2 s. co m*/ URL proxyUrl = new URL(proxyHost); if (!isValidIpPort(proxyPort)) { throw new IllegalArgumentException( format("The '%s' input does not contain a valid port.", PROXY_PORT)); } nmapArguments += " --proxies " + proxyUrl.getProtocol() + "://" + proxyUrl.getHost() + ":" + proxyPort; } catch (MalformedURLException e) { throw new IllegalArgumentException( format("The '%s' input does not contain a valid URL: %s.", PROXY_HOST, e.getMessage())); } return nmapArguments; }
From source file:org.aludratest.service.gui.web.selenium.TAFMSSeleniumResourceService.java
@Override public String acquire() { // prepare a JSON query to the given TAFMS server JSONObject query = new JSONObject(); try {/*from w w w . ja v a2s . c o m*/ query.put("resourceType", "selenium"); query.put("niceLevel", configuration.getIntValue("tafms.niceLevel", 0)); String jobName = configuration.getStringValue("tafms.jobName"); if (jobName != null && !"".equals(jobName)) { query.put("jobName", jobName); } } catch (JSONException e) { } // prepare authentication BasicCredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( configuration.getStringValue("tafms.user"), configuration.getStringValue("tafms.password"))); CloseableHttpClient client = HttpClientBuilder.create() .setConnectionReuseStrategy(new NoConnectionReuseStrategy()).disableConnectionState() .disableAutomaticRetries().setDefaultCredentialsProvider(provider).build(); String message = null; try { boolean wait; // use preemptive authentication to avoid double connection count AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); URL url = new URL(getTafmsUrl()); HttpHost host = new HttpHost(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort(), url.getProtocol()); authCache.put(host, basicAuth); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache); do { // send a POST request to resource URL HttpPost request = new HttpPost(getTafmsUrl() + "resource"); // attach query as JSON string data request.setEntity(new StringEntity(query.toString(), ContentType.APPLICATION_JSON)); CloseableHttpResponse response = null; // fire request response = client.execute(request, localcontext); try { if (response.getStatusLine() == null) { throw new ClientProtocolException("No HTTP status line transmitted"); } message = extractMessage(response); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { LOG.error("Exception when querying TAFMS server for resource. HTTP Status: " + response.getStatusLine().getStatusCode() + ", message: " + message); return null; } JSONObject object = new JSONObject(message); if (object.has("errorMessage")) { LOG.error("TAFMS server reported an error: " + object.get("errorMessage")); return null; } // continue wait? if (object.has("waiting") && object.getBoolean("waiting")) { wait = true; query.put("requestId", object.getString("requestId")); } else { JSONObject resource = object.optJSONObject("resource"); if (resource == null) { LOG.error("TAFMS server response did not provide a resource. Message was: " + message); return null; } String sUrl = resource.getString("url"); hostResourceIds.put(sUrl, object.getString("requestId")); return sUrl; } } finally { IOUtils.closeQuietly(response); } } while (wait); // should never come here return null; } catch (ClientProtocolException e) { LOG.error("Exception in HTTP transmission", e); return null; } catch (IOException e) { LOG.error("Exception in communication with TAFMS server", e); return null; } catch (JSONException e) { LOG.error("Invalid JSON received from TAFMS server. JSON message was: " + message, e); return null; } finally { IOUtils.closeQuietly(client); } }
From source file:org.seedstack.w20.internal.W20BridgeIT.java
@Test @RunAsClient/*from ww w. ja v a 2 s . c o m*/ public void paths_are_correctly_built(@ArquillianResource URL baseUrl) { String response = given().auth().basic("ThePoltergeist", "bouh").expect().statusCode(200).when() .get(baseUrl.toString() + "seed-w20/application/configuration").getBody().asString(); String prefix = baseUrl.toString().substring( (baseUrl.getProtocol() + "://" + baseUrl.getHost() + ":" + baseUrl.getPort()).length(), baseUrl.toString().length() - 1); assertThat(response).contains("\"components-path\":\"" + prefix + "/bower_components\""); assertThat(response).contains("\"components-path-slash\":\"" + prefix + "/bower_components/\""); assertThat(response).contains("\"seed-base-path\":\"" + prefix + "\""); assertThat(response).contains("\"seed-base-path-slash\":\"" + prefix + "/\""); assertThat(response).contains("\"seed-rest-path\":\"" + prefix + "\""); assertThat(response).contains("\"seed-rest-path-slash\":\"" + prefix + "/\""); }
From source file:org.jboss.as.test.integration.security.loginmodules.IdentityLoginModuleTestCase.java
/** * Calls {@link PrincipalPrintingServlet} and checks if the returned principal name is the expected one. * /*from w w w .j av a 2s .c o m*/ * @param url * @param expectedPrincipal * @return Principal name returned from {@link PrincipalPrintingServlet} */ private String assertPrincipal(URL url, String expectedPrincipal) { DefaultHttpClient httpclient = new DefaultHttpClient(); Credentials creds = new UsernamePasswordCredentials("anyUsername"); httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), creds); HttpGet httpget = new HttpGet(url.toExternalForm() + PrincipalPrintingServlet.SERVLET_PATH); String text; try { HttpResponse response = httpclient.execute(httpget); assertEquals("Unexpected status code", HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); text = EntityUtils.toString(response.getEntity()); } catch (IOException e) { throw new RuntimeException("Servlet response IO exception", e); } assertEquals("Unexpected principal name assigned by IdentityLoinModule", expectedPrincipal, text); return text; }
From source file:de.yaio.commons.net.NetFirewall.java
/** * checks if url is allowed/*from w w w .jav a 2 s . c om*/ * @param url url to check (check protocoll, hostname and ip) * @return true/false if it is allowed * @throws MalformedURLException parsing the url * @throws UnknownHostException parsing the url */ public boolean isAllowed(final URL url) throws UnknownHostException, MalformedURLException { // check protocol if (!isInProtocolList(url.getProtocol())) { return false; } // check inetAddr InetAddress inetAddr = NetUtils.parseAddress(url.getHost()); String hostName = inetAddr.getHostName(); String ip = inetAddr.getHostAddress(); if (isInHostBlackList(hostName) || isInIPBlackList(ip)) { // blacklisted: but check for override by whitelist if (isInHostWhiteList(hostName) || isInIPWhiteList(ip)) { return true; } // blacklisted return false; } return true; }
From source file:org.talend.librariesmanager.maven.ArtifactsDeployer.java
private void installToRemote(HttpEntity entity, URL targetURL) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); try {/*w ww.jav a2s . c om*/ httpClient.getCredentialsProvider().setCredentials( new AuthScope(targetURL.getHost(), targetURL.getPort()), new UsernamePasswordCredentials(nexusServer.getUserName(), nexusServer.getPassword())); HttpPut httpPut = new HttpPut(targetURL.toString()); httpPut.setEntity(entity); HttpResponse response = httpClient.execute(httpPut); StatusLine statusLine = response.getStatusLine(); int responseCode = statusLine.getStatusCode(); EntityUtils.consume(entity); if (responseCode > 399) { if (responseCode == 500) { // ignor this error , if .pom already exist on server and deploy again will get this error } else if (responseCode == 401) { throw new BusinessException("Authrity failed"); } else { throw new BusinessException( "Deploy failed: " + responseCode + ' ' + statusLine.getReasonPhrase()); } } } catch (Exception e) { throw new Exception(targetURL.toString(), e); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:org.modeshape.web.jcr.rest.client.http.HttpClientConnection.java
/** * @param server the server with the host and port information (never <code>null</code>) * @param url the URL that will be used in the request (never <code>null</code>) * @param method the HTTP request method (never <code>null</code>) * @throws Exception if there is a problem establishing the connection *//*from w ww .j av a 2s.c om*/ public HttpClientConnection(Server server, URL url, RequestMethod method) throws Exception { assert server != null; assert url != null; assert method != null; this.httpClient = new DefaultHttpClient(); this.httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(server.getUser(), server.getPassword())); // determine the request type if (RequestMethod.GET == method) { this.request = new HttpGet(); } else if (RequestMethod.DELETE == method) { this.request = new HttpDelete(); } else if (RequestMethod.POST == method) { this.request = new HttpPost(); } else if (RequestMethod.PUT == method) { this.request = new HttpPut(); } else { throw new RuntimeException(unknownHttpRequestMethodMsg.text(method)); } //set the accepts header to application/json this.request.setHeader("Accept", MediaType.APPLICATION_JSON); // set request URI this.request.setURI(url.toURI()); }