List of usage examples for java.net URI getHost
public String getHost()
From source file:edu.internet2.middleware.openid.message.encoding.EncodingUtils.java
/** * Append the URL encoded OpenID message parameters to the query string of the provided URI. * /*from w w w. ja va2 s .co m*/ * @param uri URI to append OpenID message parameter to * @param message URL encoded OpenID message parameters * @return URI with message parameters appended */ public static URI appendMessageParameters(URI uri, String message) { if (uri == null || message == null) { return uri; } // build new query string StringBuffer queryBuffer = new StringBuffer(); if (uri.getRawQuery() != null) { queryBuffer.append(uri.getRawQuery()); } if (queryBuffer.length() > 0 && queryBuffer.charAt(queryBuffer.length() - 1) != '&') { queryBuffer.append('&'); } queryBuffer.append(message); try { return URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(), queryBuffer.toString(), uri.getFragment()); } catch (URISyntaxException e) { log.error("Unable to append message parameters to URI: {}", e); } return null; }
From source file:com.buaa.cfs.utils.NetUtils.java
/** * Resolve the uri's hostname and add the default port if not in the uri * * @param uri to resolve//from www . j a v a 2 s. c o m * @param defaultPort if none is given * * @return URI */ public static URI getCanonicalUri(URI uri, int defaultPort) { // skip if there is no authority, ie. "file" scheme or relative uri String host = uri.getHost(); if (host == null) { return uri; } String fqHost = canonicalizeHost(host); int port = uri.getPort(); // short out if already canonical with a port if (host.equals(fqHost) && port != -1) { return uri; } // reconstruct the uri with the canonical host and port try { uri = new URI(uri.getScheme(), uri.getUserInfo(), fqHost, (port == -1) ? defaultPort : port, uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } return uri; }
From source file:com.sworddance.util.UriFactoryImpl.java
/** * NOT checking for !uri.{@link java.net.URI#isAbsolute()} because protocol-less uri ( '//example.com' ) is not absolute. * @param uri// w w w .java 2s . co m * @return false if uri == null or the uri.getHost() has no top-level-domain (no '.' in the last 8 characters ) */ public static boolean isNonLocalUri(URI uri) { if (uri != null) { String host = uri.getHost(); if (isNotBlank(host)) { // top-level domains ( .info, .com, .org, etc ) are at most 4 characters long + 1 for the dot. // so checking for a '.' in the last 8 characters is a reasonable quick test to make sure the domain is // a real domain. // Above is not true: internationalized domain names (e.g. xn--80ahbyhddgf2au1c.xn--p1ai ) int dotPos = host.lastIndexOf('.'); if (dotPos >= 0) { // now look for ip address ranges that are declared local Matcher matcher = IPV4_ADDRESSES.matcher(host); if (matcher.matches()) { // ipv4 address // http://en.wikipedia.org/wiki/Reserved_IP_addresses int first = Integer.parseInt(matcher.group(1)); int second = Integer.parseInt(matcher.group(2)); int third = Integer.parseInt(matcher.group(3)); int fourth = Integer.parseInt(matcher.group(4)); if (first >= 224) { // 224.0.0.0 - 255.255.255.255 : various multicast and reserved blocks return false; } else if (first < 0 || first > 255 || second < 0 || second > 255 || third < 0 || third > 255 || fourth < 0 || fourth > 255) { // some out of bounds number for ip address : lets just declare it bad. return false; } else { switch (first) { case 0: // 0.0.0.0 0.255.255.255 : all reserved return false; case 10: // 10.0.0.0 10.255.255.255 : all reserved return false; case 100: // 100.64.0.0 100.127.255.255 // communication between service providers return second < 64 || second > 127; case 127:// 127.0.0.0 127.255.255.255 : all reserved return false; case 169: // 169.254.0.0 169.254.255.255 return second != 254; case 172: // 172.16.0.0 172.31.255.255 return second < 16 || second > 31; case 192: switch (second) { case 0: if (third == 0) { // 192.0.0.0 192.0.0.7 return fourth > 7; } else { // 192.0.2.0 192.0.2.255 return third != 2; } case 88: // 192.88.99.0 192.88.99.255 return third != 99; case 168: // 192.168.0.0 192.168.255.255 return false; default: return true; } case 198: switch (second) { case 18: case 19: // 198.18.0.0 198.19.255.255 return false; case 51: // 198.51.100.0 198.51.100.255 return third != 100; default: return true; } case 203: // 203.0.113.0 203.0.113.255 return second != 0 || third != 113; } return true; } } else if (false/*test for ipv6 */) { } else { return true; } } } } return false; }
From source file:com.sworddance.util.UriFactoryImpl.java
/** * @param originalUri//from www .ja v a2 s . co m * @param uri * @return true if the uri's have the same host / domain. Always returns false if either uri has a "mailTo" scheme. */ public static boolean isSameHost(URI originalUri, URI uri) { if (isWebUri(originalUri) || isWebUri(uri)) { return false; } else { String originalHost = originalUri.getHost(); String host = uri.getHost(); return equalsIgnoreCase(originalHost, host); } }
From source file:edu.washington.cs.mystatus.odk.utilities.WebUtils.java
/** * Common method for returning a parsed xml document given a url and the * http context and client objects involved in the web connection. * * @param urlString/* w w w . j av a 2 s . com*/ * @param localContext * @param httpclient * @return */ public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext, HttpClient httpclient) { URI u = null; try { URL url = new URL(urlString); u = url.toURI(); } catch (Exception e) { e.printStackTrace(); return new DocumentFetchResult(e.getLocalizedMessage() // + app.getString(R.string.while_accessing) + urlString); + ("while accessing") + urlString, 0); } if (u.getHost() == null) { return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0); } // if https then enable preemptive basic auth... if (u.getScheme().equals("https")) { enablePreemptiveBasicAuth(localContext, u.getHost()); } // set up request... HttpGet req = WebUtils.createOpenRosaHttpGet(u); HttpResponse response = null; try { response = httpclient.execute(req, localContext); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (statusCode != HttpStatus.SC_OK) { WebUtils.discardEntityBytes(response); if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // clear the cookies -- should not be necessary? MyStatus.getInstance().getCookieStore().clear(); } String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode); } if (entity == null) { String error = "No entity body returned from: " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH) .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) { WebUtils.discardEntityBytes(response); String error = "ContentType: " + entity.getContentType().getValue() + " returned from: " + u.toString() + " is not text/xml. This is often caused a network proxy. Do you need to login to your network?"; Log.e(t, error); return new DocumentFetchResult(error, 0); } // parse response Document doc = null; try { InputStream is = null; InputStreamReader isr = null; try { is = entity.getContent(); isr = new InputStreamReader(is, "UTF-8"); doc = new Document(); KXmlParser parser = new KXmlParser(); parser.setInput(isr); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); doc.parse(parser); isr.close(); isr = null; } finally { if (isr != null) { try { // ensure stream is consumed... final long count = 1024L; while (isr.skip(count) == count) ; } catch (Exception e) { // no-op } try { isr.close(); } catch (Exception e) { // no-op } } if (is != null) { try { is.close(); } catch (Exception e) { // no-op } } } } catch (Exception e) { e.printStackTrace(); String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } boolean isOR = false; Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER); if (fields != null && fields.length >= 1) { isOR = true; boolean versionMatch = false; boolean first = true; StringBuilder b = new StringBuilder(); for (Header h : fields) { if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) { versionMatch = true; break; } if (!first) { b.append("; "); } first = false; b.append(h.getValue()); } if (!versionMatch) { Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString()); } } return new DocumentFetchResult(doc, isOR); } catch (Exception e) { clearHttpConnectionManager(); e.printStackTrace(); String cause; Throwable c = e; while (c.getCause() != null) { c = c.getCause(); } cause = c.toString(); String error = "Error: " + cause + " while accessing " + u.toString(); Log.w(t, error); return new DocumentFetchResult(error, 0); } }
From source file:org.soyatec.windowsazure.internal.util.HttpUtilities.java
/** * Remove the query part from URI./* w w w .j ava 2s . c om*/ * * @param uri * @return URI after remove the query part. */ public static URI removeQueryPart(URI uri) { try { return URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(), null, null); } catch (URISyntaxException e) { Logger.error("Remove query part from uri failed.", e); return uri; } }
From source file:com.github.diogochbittencourt.googleplaydownloader.downloader.impl.DownloadThread.java
static final private boolean isLocalHost(String url) { if (url == null) { return false; }//from w w w . j a va2s . c o m try { final URI uri = URI.create(url); final String host = uri.getHost(); if (host != null) { // TODO: InetAddress.isLoopbackAddress should be used to check // for localhost. However no public factory methods exist which // can be used without triggering DNS lookup if host is not // localhost. if (host.equalsIgnoreCase("localhost") || host.equals("127.0.0.1") || host.equals("[::1]")) { return true; } } } catch (IllegalArgumentException iex) { // Ignore (URI.create) } return false; }
From source file:org.koboc.collect.android.utilities.WebUtils.java
/** * Common method for returning a parsed xml document given a url and the * http context and client objects involved in the web connection. * * @param urlString//www . j av a 2s .c o m * @param localContext * @param httpclient * @return */ public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext, HttpClient httpclient) { URI u = null; try { URL url = new URL(urlString); u = url.toURI(); } catch (Exception e) { e.printStackTrace(); return new DocumentFetchResult(e.getLocalizedMessage() // + app.getString(R.string.while_accessing) + urlString); + ("while accessing") + urlString, 0); } if (u.getHost() == null) { return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0); } // if https then enable preemptive basic auth... if (u.getScheme().equals("https")) { enablePreemptiveBasicAuth(localContext, u.getHost()); } // set up request... HttpGet req = WebUtils.createOpenRosaHttpGet(u); HttpResponse response = null; try { response = httpclient.execute(req, localContext); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (statusCode != HttpStatus.SC_OK) { WebUtils.discardEntityBytes(response); if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // clear the cookies -- should not be necessary? Collect.getInstance().getCookieStore().clear(); } String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode); } if (entity == null) { String error = "No entity body returned from: " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH) .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) { WebUtils.discardEntityBytes(response); String error = "ContentType: " + entity.getContentType().getValue() + " returned from: " + u.toString() + " is not text/xml. This is often caused a network proxy. Do you need to login to your network?"; Log.e(t, error); return new DocumentFetchResult(error, 0); } // parse response Document doc = null; try { InputStream is = null; InputStreamReader isr = null; try { is = entity.getContent(); isr = new InputStreamReader(is, "UTF-8"); doc = new Document(); KXmlParser parser = new KXmlParser(); parser.setInput(isr); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); doc.parse(parser); isr.close(); isr = null; } finally { if (isr != null) { try { // ensure stream is consumed... final long count = 1024L; while (isr.skip(count) == count) ; } catch (Exception e) { // no-op } try { isr.close(); } catch (Exception e) { // no-op } } if (is != null) { try { is.close(); } catch (Exception e) { // no-op } } } } catch (Exception e) { e.printStackTrace(); String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } boolean isOR = false; Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER); if (fields != null && fields.length >= 1) { isOR = true; boolean versionMatch = false; boolean first = true; StringBuilder b = new StringBuilder(); for (Header h : fields) { if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) { versionMatch = true; break; } if (!first) { b.append("; "); } first = false; b.append(h.getValue()); } if (!versionMatch) { Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString()); } } return new DocumentFetchResult(doc, isOR); } catch (Exception e) { clearHttpConnectionManager(); e.printStackTrace(); String cause; Throwable c = e; while (c.getCause() != null) { c = c.getCause(); } cause = c.toString(); String error = "Error: " + cause + " while accessing " + u.toString(); Log.w(t, error); return new DocumentFetchResult(error, 0); } }
From source file:com.sworddance.util.UriFactoryImpl.java
/** * TODO need to figure out what parts of WebLocationImpl belong here. * @param uri/* w ww .j a v a 2 s. c om*/ * @return uri */ public static URI getNormalizedUri(URI uri) { try { String path = uri.getPath(); // see WebLocationImpl ( this implementation here may not be correct ) return new URI(uri.getScheme(), uri.getHost(), path == null ? PATH_SEPARATOR : PATH_SEPARATOR + path, uri.getQuery()); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
From source file:com.sangupta.jerry.oauth.OAuthUtils.java
/** * Return the signing base URL that is appended after the HTTP VERB in OAuth * header.//from ww w . j a va 2 s.c o m * * @param uri * the {@link URI} instance from which the signing base is * extracted * * @return the extracted signing base from the {@link URI} instance */ public static String getSigningBaseURL(URI uri) { if (uri == null) { throw new IllegalArgumentException("URI cannot be null"); } StringBuilder builder = new StringBuilder(); builder.append(uri.getScheme().toLowerCase()); builder.append("://"); builder.append(uri.getHost().toLowerCase()); int port = uri.getPort(); if (!(port == 80 || port == -1)) { builder.append(':'); builder.append(String.valueOf(port)); } builder.append(uri.getPath()); return builder.toString(); }