List of usage examples for java.net URI getHost
public String getHost()
From source file:com.knowledgecode.cordova.websocket.ConnectionTask.java
/** * Complement default port number.//from ww w .j av a2 s. c om * * @param url * @return URI * @throws URISyntaxException */ private static URI complementPort(String url) throws URISyntaxException { URI uri = new URI(url); int port = uri.getPort(); if (port < 0) { if ("ws".equals(uri.getScheme())) { port = 80; } else if ("wss".equals(uri.getScheme())) { port = 443; } uri = new URI(uri.getScheme(), "", uri.getHost(), port, uri.getPath(), uri.getQuery(), ""); } return uri; }
From source file:Main.java
/** * Extract the UUID part from a MusicBrainz identifier. * // ww w. jav a2 s.c om * This function takes a MusicBrainz ID (an absolute URI) as the input * and returns the UUID part of the URI, thus turning it into a relative * URI. If <code>uriStr</code> is null or a relative URI, then it is * returned unchanged. * * The <code>resType</code> parameter can be used for error checking. * Set it to 'artist', 'release', or 'track' to make sure * <code>uriStr</code> is a syntactically valid MusicBrainz identifier * of the given resource type. If it isn't, an * <code>IllegalArgumentException</code> exception is raised. This error * checking only works if <code>uriStr</code> is an absolute URI, of course. * * Example: * >>> MBUtils.extractUuid('http://musicbrainz.org/artist/c0b2500e-0cef-4130-869d-732b23ed9df5', 'artist') * 'c0b2500e-0cef-4130-869d-732b23ed9df5' * * @param uriStr A string containing a MusicBrainz ID (an URI), or null * @param resType A string containing a resource type * @return A String containing a relative URI or null * @throws URISyntaxException */ public static String extractUuid(String uriStr, String resType) { if (uriStr == null) { return null; } URI uri; try { uri = new URI(uriStr); } catch (URISyntaxException e) { return uriStr; // not really a valid URI, probably the UUID } if (uri.getScheme() == null) { return uriStr; // not really a valid URI, probably the UUID } if (!"http".equals(uri.getScheme()) || !"musicbrainz.org".equals(uri.getHost())) { throw new IllegalArgumentException(uri.toString() + " is no MB ID"); } String regex = "^/(label|artist|release-group|release|recording|work|collection)/([^/]*)$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(uri.getPath()); if (m.matches()) { if (resType == null) { return m.group(2); } else { if (resType.equals(m.group(1))) { return m.group(2); } else { throw new IllegalArgumentException("expected '" + resType + "' Id"); } } } else { throw new IllegalArgumentException("'" + uriStr + " is no valid MB id"); } }
From source file:com.eucalyptus.www.X509Download.java
@SuppressWarnings("ConstantConditions") private static URI hostMap(final URI uri) { final Optional<Cidr> hostMatcher = InetAddresses.isInetAddress(uri.getHost()) ? Cidr.parse().apply(AuthenticationProperties.CREDENTIAL_DOWNLOAD_HOST_MATCH) : Optional.<Cidr>absent(); if (hostMatcher.isPresent()) { final Host host = Hosts.lookup(InetAddresses.forString(uri.getHost())); if (host != null) { final Optional<InetAddress> mappedHost = Iterables.tryFind(host.getHostAddresses(), hostMatcher.get());/*from w ww . ja va 2 s. com*/ if (mappedHost.isPresent()) { return URI .create(uri.toString().replaceFirst(uri.getHost(), mappedHost.get().getHostAddress())); } } } return uri; }
From source file:mitm.common.util.URIUtils.java
/** * Checks whether the given identifier is a valid URI. If type is null, a FULL check will be done. * If identifier is null, false will be returned. *///from w w w .j a va2s . c om public static boolean isValidURI(String identifier, URIType type) { if (identifier == null) { return false; } if (type == null) { type = URIType.FULL; } boolean valid = false; try { URI uri = new URI(identifier); if (type == URIType.BASE) { /* * Only accepts URI of the form [scheme:][//authority][path] */ if (StringUtils.isNotEmpty(uri.getScheme()) && StringUtils.isNotEmpty(uri.getHost()) && StringUtils.isEmpty(uri.getQuery()) && StringUtils.isEmpty(uri.getFragment())) { valid = true; } } else if (type == URIType.RELATIVE) { /* * Only accepts URI of the form [path][?query][#fragment] */ if (StringUtils.isEmpty(uri.getScheme()) && StringUtils.isEmpty(uri.getAuthority()) && StringUtils.isEmpty(uri.getHost())) { valid = true; } } else if (type == URIType.FULL) { /* * Only accepts URI of the form [scheme:][//authority][path][?query][#fragment] */ if (StringUtils.isNotEmpty(uri.getScheme()) && StringUtils.isNotEmpty(uri.getHost())) { valid = true; } } else { valid = true; } } catch (URISyntaxException e) { // ignore } return valid; }
From source file:com.microsoft.alm.common.utils.UrlHelper.java
public static boolean isVSO(final URI uri) { if (uri != null && uri.getHost() != null) { final String host = uri.getHost().toLowerCase(); if (StringUtils.endsWith(host, HOST_VSO) || StringUtils.endsWith(host, HOST_TFS_ALL_IN)) { return true; }/*from ww w .ja va 2s . c o m*/ } return false; }
From source file:com.google.android.mms.transaction.HttpUtils.java
/** * A helper method to send or retrieve data through HTTP protocol. * * @param token The token to identify the sending progress. * @param url The URL used in a GET request. Null when the method is * HTTP_POST_METHOD.//ww w . jav a 2 s . c o m * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD. * @param method HTTP_POST_METHOD or HTTP_GET_METHOD. * @return A byte array which contains the response data. * If an HTTP error code is returned, an IOException will be thrown. * @throws IOException if any error occurred on network interface or * an HTTP error code(>=400) returned from the server. */ public static byte[] httpConnection(Context context, long token, String url, byte[] pdu, int method, boolean isProxySet, String proxyHost, int proxyPort) throws IOException { if (url == null) { throw new IllegalArgumentException("URL must not be null."); } if (LOCAL_LOGV) { Log.v(TAG, "httpConnection: params list"); Log.v(TAG, "\ttoken\t\t= " + token); Log.v(TAG, "\turl\t\t= " + url); Log.v(TAG, "\tmethod\t\t= " + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN"))); Log.v(TAG, "\tisProxySet\t= " + isProxySet); Log.v(TAG, "\tproxyHost\t= " + proxyHost); Log.v(TAG, "\tproxyPort\t= " + proxyPort); // TODO Print out binary data more readable. //Log.v(TAG, "\tpdu\t\t= " + Arrays.toString(pdu)); } AndroidHttpClient client = null; try { // Make sure to use a proxy which supports CONNECT. URI hostUrl = new URI(url); HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME); client = createHttpClient(context); HttpRequest req = null; switch (method) { case HTTP_POST_METHOD: ProgressCallbackEntity entity = new ProgressCallbackEntity(context, token, pdu); // Set request content type. entity.setContentType("application/vnd.wap.mms-message"); HttpPost post = new HttpPost(url); post.setEntity(entity); req = post; break; case HTTP_GET_METHOD: req = new HttpGet(url); break; default: Log.e(TAG, "Unknown HTTP method: " + method + ". Must be one of POST[" + HTTP_POST_METHOD + "] or GET[" + HTTP_GET_METHOD + "]."); return null; } // Set route parameters for the request. HttpParams params = client.getParams(); if (isProxySet) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort)); } req.setParams(params); // Set necessary HTTP headers for MMS transmission. req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT); { String xWapProfileTagName = MmsConfig.getUaProfTagName(); String xWapProfileUrl = MmsConfig.getUaProfUrl(); if (xWapProfileUrl != null) { if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { Log.d(LogTag.TRANSACTION, "[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl); } req.addHeader(xWapProfileTagName, xWapProfileUrl); } } // Extra http parameters. Split by '|' to get a list of value pairs. // Separate each pair by the first occurrence of ':' to obtain a name and // value. Replace the occurrence of the string returned by // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside // the value. String extraHttpParams = MmsConfig.getHttpParams(); if (extraHttpParams != null) { String line1Number = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)) .getLine1Number(); String line1Key = MmsConfig.getHttpParamsLine1Key(); String paramList[] = extraHttpParams.split("\\|"); for (String paramPair : paramList) { String splitPair[] = paramPair.split(":", 2); if (splitPair.length == 2) { String name = splitPair[0].trim(); String value = splitPair[1].trim(); if (line1Key != null) { value = value.replace(line1Key, line1Number); } if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) { req.addHeader(name, value); } } } } req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE); HttpResponse response = client.execute(target, req); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { // HTTP 200 is success. throw new IOException("HTTP error: " + status.getReasonPhrase()); } HttpEntity entity = response.getEntity(); byte[] body = null; if (entity != null) { try { if (entity.getContentLength() > 0) { body = new byte[(int) entity.getContentLength()]; DataInputStream dis = new DataInputStream(entity.getContent()); try { dis.readFully(body); } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "Error closing input stream: " + e.getMessage()); } } } } finally { if (entity != null) { entity.consumeContent(); } } } return body; } catch (URISyntaxException e) { handleHttpConnectionException(e, url); } catch (IllegalStateException e) { handleHttpConnectionException(e, url); } catch (IllegalArgumentException e) { handleHttpConnectionException(e, url); } catch (SocketException e) { handleHttpConnectionException(e, url); } catch (Exception e) { handleHttpConnectionException(e, url); } finally { if (client != null) { client.close(); } } return null; }
From source file:ws.wamp.jawampa.transport.WampClientChannelFactoryResolver.java
public static WampClientChannelFactory getFactory(final URI uri, final SslContext sslCtx) throws ApplicationError { String scheme = uri.getScheme(); scheme = scheme != null ? scheme : ""; if (scheme.equalsIgnoreCase("ws") || scheme.equalsIgnoreCase("wss")) { // Check the host and port field for validity if (uri.getHost() == null || uri.getPort() == 0) { throw new ApplicationError(ApplicationError.INVALID_URI); }/*from www .ja va 2 s .co m*/ // Return a factory that creates a channel for websocket connections return new WampClientChannelFactory() { @Override public ChannelFuture createChannel(final ChannelHandler handler, final EventLoopGroup eventLoop, final ObjectMapper objectMapper) throws Exception { // Initialize SSL when required final boolean needSsl = uri.getScheme().equalsIgnoreCase("wss"); final SslContext sslCtx0; if (needSsl && sslCtx == null) { // Create a default SslContext when we got none provided through the constructor try { sslCtx0 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } catch (SSLException e) { throw e; } } else if (needSsl) { sslCtx0 = sslCtx; } else { sslCtx0 = null; } // Use well-known ports if not explicitly specified final int port; if (uri.getPort() == -1) { if (needSsl) port = 443; else port = 80; } else port = uri.getPort(); final WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, WampHandlerConfiguration.WAMP_WEBSOCKET_PROTOCOLS, false, new DefaultHttpHeaders()); Bootstrap b = new Bootstrap(); b.group(eventLoop).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx0 != null) { p.addLast(sslCtx0.newHandler(ch.alloc(), uri.getHost(), port)); } p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), new WebSocketClientProtocolHandler(handshaker, false), new WebSocketFrameAggregator( WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE), new WampClientWebsocketHandler(handshaker, objectMapper), handler); } }); return b.connect(uri.getHost(), port); } }; } throw new ApplicationError(ApplicationError.INVALID_URI); }
From source file:edu.usc.goffish.gofs.namenode.DataNode.java
private static Path convertLocalURIToPath(URI localURI) throws IOException { if (localURI == null || localURI.isOpaque() || !localURI.isAbsolute() || !"file".equalsIgnoreCase(localURI.getScheme())) { throw new IllegalArgumentException(); }// w ww .j a v a 2 s . co m if (!URIHelper.isLocalURI(localURI)) { throw new IOException("uri host " + localURI.getHost() + " is not local"); } String path = localURI.getPath(); if (path == null) { path = "/"; } return Paths.get(URI.create("file://" + path)); }
From source file:fedora.server.utilities.ServerUtility.java
/** * Tell whether the given URL appears to be referring to somewhere within * the Fedora webapp.//from w w w . ja v a 2 s.co m */ public static boolean isURLFedoraServer(String url) { // scheme must be http or https URI uri = URI.create(url); String scheme = uri.getScheme(); if (!scheme.equals("http") && !scheme.equals("https")) { return false; } // host must be configured hostname or localhost String fHost = CONFIG.getParameter(FEDORA_SERVER_HOST).getValue(); String host = uri.getHost(); if (!host.equals(fHost) && !host.equals("localhost")) { return false; } // path must begin with configured webapp context String path = uri.getPath(); String fedoraContext = CONFIG.getParameter(FEDORA_SERVER_CONTEXT).getValue(); if (!path.startsWith("/" + fedoraContext + "/")) { return false; } // port specification must match http or https port as appropriate String httpPort = CONFIG.getParameter(FEDORA_SERVER_PORT).getValue(); String httpsPort = CONFIG.getParameter(FEDORA_REDIRECT_PORT).getValue(); if (uri.getPort() == -1) { // unspecified, so fedoraPort must be 80 (http), or 443 (https) if (scheme.equals("http")) { return httpPort.equals("80"); } else { return httpsPort.equals("443"); } } else { // specified, so must match appropriate http or https port String port = "" + uri.getPort(); if (scheme.equals("http")) { return port.equals(httpPort); } else { return port.equals(httpsPort); } } }
From source file:com.microsoft.alm.common.utils.UrlHelper.java
/** * This method returns the account name based on the VSO url provided. * * @param vsoUri the VSO url to parse/*from w ww. j a v a 2 s . co m*/ * @return the string after the "http://" and before the first "/". */ public static String getVSOAccountName(final URI vsoUri) { final String[] hostParts = vsoUri.getHost().split("\\."); final String accountName = hostParts.length > 0 ? hostParts[0] : ""; return accountName; }