Java Code Examples for java.net.URI.getHost()

The following are Jave code examples for showing how to use getHost() of the java.net.URI class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: hadoop   File: DistributedFileSystem.java   View Source Code Vote up 6 votes
@Override
public void initialize(URI uri, Configuration conf) throws IOException {
  super.initialize(uri, conf);
  setConf(conf);

  String host = uri.getHost();
  if (host == null) {
    throw new IOException("Incomplete HDFS URI, no host: "+ uri);
  }
  homeDirPrefix = conf.get(
      DFSConfigKeys.DFS_USER_HOME_DIR_PREFIX_KEY,
      DFSConfigKeys.DFS_USER_HOME_DIR_PREFIX_DEFAULT);
  
  this.dfs = new DFSClient(uri, conf, statistics);
  this.uri = URI.create(uri.getScheme()+"://"+uri.getAuthority());
  this.workingDir = getHomeDirectory();
}
 
Example 2
Project: burstcoin   File: Peers.java   View Source Code Vote up 6 votes
static String normalizeHostAndPort(String address) {
    try {
        if (address == null) {
            return null;
        }
        URI uri = new URI("http://" + address.trim());
        String host = uri.getHost();
        if (host == null || host.equals("") || host.equals("localhost") ||
                            host.equals("127.0.0.1") || host.equals("[0:0:0:0:0:0:0:1]")) {
            return null;
        }
        InetAddress inetAddress = InetAddress.getByName(host);
        if (inetAddress.isAnyLocalAddress() || inetAddress.isLoopbackAddress() ||
                                               inetAddress.isLinkLocalAddress()) {
            return null;
        }
        int port = uri.getPort();
        return port == -1 ? host : host + ':' + port;
    } catch (URISyntaxException |UnknownHostException e) {
        return null;
    }
}
 
Example 3
Project: mensa-api   File: WebUtils.java   View Source Code Vote up 6 votes
/**
 * Get the base url from a valid url
 * @param url to get the base url from
 * @return the base url if available, empty otherwise
 */
public Optional<String> getBaseUrl(String url) {
	Optional<String> result = Optional.empty();
	try {
		URI uri = new URI(url);
		String scheme = uri.getScheme();
		String host = uri.getHost();
		if (StringUtils.isNotBlank(scheme) && StringUtils.isNotBlank(host)) {
		    result = Optional.of(scheme + "://" + host + "/");
           } else {
		    logger.warn("Failed to get baseUrl from {} because scheme (\"{}\") or host (\"{}\") could not be read", url, scheme, host);
           }
	} catch (URISyntaxException e) {
           logger.warn("Failed to get baseUrl from {} due to error: {}", url, e.getMessage());
	}
	return result;
}
 
Example 4
Project: x7   File: BinaryJedis.java   View Source Code Vote up 6 votes
private void initializeClientFromURI(URI uri) {
  if (!JedisURIHelper.isValid(uri)) {
    throw new InvalidURIException(String.format(
      "Cannot open Redis connection due invalid URI. %s", uri.toString()));
  }

  client = new Client(uri.getHost(), uri.getPort());

  String password = JedisURIHelper.getPassword(uri);
  if (password != null) {
    client.auth(password);
    client.getStatusCodeReply();
  }

  int dbIndex = JedisURIHelper.getDBIndex(uri);
  if (dbIndex > 0) {
    client.select(dbIndex);
    client.getStatusCodeReply();
    client.setDb(dbIndex);
  }
}
 
Example 5
Project: hadoop   File: HostFileManager.java   View Source Code Vote up 6 votes
@VisibleForTesting
static InetSocketAddress parseEntry(String type, String fn, String line) {
  try {
    URI uri = new URI("dummy", line, null, null, null);
    int port = uri.getPort() == -1 ? 0 : uri.getPort();
    InetSocketAddress addr = new InetSocketAddress(uri.getHost(), port);
    if (addr.isUnresolved()) {
      LOG.warn(String.format("Failed to resolve address `%s` in `%s`. " +
              "Ignoring in the %s list.", line, fn, type));
      return null;
    }
    return addr;
  } catch (URISyntaxException e) {
    LOG.warn(String.format("Failed to parse `%s` in `%s`. " + "Ignoring in " +
            "the %s list.", line, fn, type));
  }
  return null;
}
 
Example 6
Project: openjdk-jdk10   File: HttpRequestImpl.java   View Source Code Vote up 6 votes
public InetSocketAddress getAddress(HttpClientImpl client) {
    URI uri = uri();
    if (uri == null) {
        return authority();
    }
    int port = uri.getPort();
    if (port == -1) {
        if (uri.getScheme().equalsIgnoreCase("https")) {
            port = 443;
        } else {
            port = 80;
        }
    }
    String host = uri.getHost();
    if (proxy(client) == null) {
        return new InetSocketAddress(host, port);
    } else {
        return InetSocketAddress.createUnresolved(host, port);
    }
}
 
Example 7
Project: cf-java-client-sap   File: LoggregatorClient.java   View Source Code Vote up 5 votes
public String getRecentHttpEndpoint(String endpoint) {
    URI uri = stringToUri(endpoint);

    String scheme = uri.getScheme();
    String host = uri.getHost();

    if ("wss".equals(scheme)) {
        scheme = "https";
    } else {
        scheme = "http";
    }

    return loggregatorRecentUriTemplate.expand(scheme, host).toString();
}
 
Example 8
Project: FirefoxData-android   File: FirefoxDataRequestUtils.java   View Source Code Vote up 5 votes
public static HawkAuthHeaderProvider getAuthHeaderProvider(final URI serverURI, final String tokenId, final byte[] reqHMACKey,
        final boolean includePayloadVerificationHash) {
    // We compute skew over time using SkewHandler. This yields an unchanging
    // skew adjustment that the HawkAuthHeaderProvider uses to adjust its
    // timestamps.
    final String storageHostname = serverURI.getHost();
    final SkewHandler storageServerSkewHandler = SkewHandler.getSkewHandlerForHostname(storageHostname);
    final long storageServerSkew = storageServerSkewHandler.getSkewInSeconds();

    return new HawkAuthHeaderProvider(tokenId, reqHMACKey, includePayloadVerificationHash, storageServerSkew);
}
 
Example 9
Project: xlight_android_native   File: WebSocketNativeDelegateHandler.java   View Source Code Vote up 5 votes
public static String getCanonicalHostPort(URI uri) {
    int port = uri.getPort();
    if (port == -1) {
        String scheme = uri.getScheme();
        if (scheme.equals("https") || scheme.equals("wss") || scheme.equals("wse+ssl")) {
            port = 443;
        }
        else {
            port = 80;
        }
    }
    return uri.getHost()+":"+port;
}
 
Example 10
Project: AndroidBackendlessChat   File: ImageResponseCache.java   View Source Code Vote up 5 votes
private static boolean isCDNURL(URI url) {
    if (url != null) {
        String uriHost = url.getHost();

        if (uriHost.endsWith("fbcdn.net")) {
            return true;
        }

        if (uriHost.startsWith("fbcdn") && uriHost.endsWith("akamaihd.net")) {
            return true;
        }
    }

    return false;
}
 
Example 11
Project: BUbiNG   File: HostEquals.java   View Source Code Vote up 5 votes
/**
 * Apply the filter to a given URI
 *
 * @param uri the URI to be filtered
 * @return true if the host part of <code>uri</code> is equal to the inner host
 */
@Override
public boolean apply(final URI uri) {
	if (uri.getHost() == null) throw new IllegalArgumentException("URI \"" + uri + "\" has no host");
	// BURL hosts are always lower cased
	return uri.getHost().equals(host);
}
 
Example 12
Project: aidos-node   File: PD.java   View Source Code Vote up 5 votes
public static Optional<InetSocketAddress> getAddress(String address) {
	// URI automatically validates schemes and returns ipv4 and ipv6 host and port in the right way
	try {
		String[] values = address.split("|");
		URI uri = new URI("tcp://" + values[0]);
		String host = uri.getHost();
		int port = uri.getPort();
		return Optional.of(new InetSocketAddress(host, port));
	} catch (URISyntaxException e) {
		log.debug("Failed to retrieve InetSocketAddress from String: {}", address);
	}
	return Optional.empty();
}
 
Example 13
Project: angel   File: HdfsUtil.java   View Source Code Vote up 5 votes
public static Path generateTmpDirectory(Configuration conf, String appId, Path outputPath) {
  URI uri = outputPath.toUri();
  String path = (uri.getScheme() != null ? uri.getScheme() : "hdfs") + "://"
           + (uri.getHost() != null ? uri.getHost() : "")
           + (uri.getPort() > 0 ? (":" + uri.getPort()) : "");
  String user = conf.get(AngelConf.USER_NAME, "");
  String tmpDir = conf.get(AngelConf.ANGEL_JOB_TMP_OUTPUT_PATH_PREFIX, "/tmp/" + user);
  String finalTmpDirForApp = path + tmpDir + "/" + appId + "_" + UUID.randomUUID().toString();
  LOG.info("tmp output dir is " + finalTmpDirForApp);
  return new Path(finalTmpDirForApp);
}
 
Example 14
Project: springboot-security-wechat   File: MyOAuth2RestTemplate.java   View Source Code Vote up 5 votes
@Override
protected URI appendQueryParameter(URI uri, OAuth2AccessToken accessToken) {
    try {
        String query = uri.getRawQuery();
        String queryFragment = this.resource.getTokenName() + "=" + URLEncoder.encode(accessToken.getValue(), "UTF-8");
        if(query == null) {
            query = queryFragment;
        } else {
            query = query + "&" + queryFragment;
        }
        String openid = (String) accessToken
                .getAdditionalInformation().get("openid");
        System.out.println("openid == " + openid);
        String openIdQueryFragment = "openid=" + URLEncoder.encode(openid, "UTF-8");
        query = query + "&" + openIdQueryFragment;
        URI update = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), (String)null, (String)null);
        StringBuffer sb = new StringBuffer(update.toString());
        sb.append("?");
        sb.append(query);
        if(uri.getFragment() != null) {
            sb.append("#");
            sb.append(uri.getFragment());
        }
        System.out.println("appendQueryParameter == " + sb.toString());
        return new URI(sb.toString());
    } catch (URISyntaxException var7) {
        throw new IllegalArgumentException("Could not parse URI", var7);
    } catch (UnsupportedEncodingException var8) {
        throw new IllegalArgumentException("Could not encode URI", var8);
    }
}
 
Example 15
Project: syndesis   File: Urls.java   View Source Code Vote up 5 votes
public static URI apiBase(final HttpServletRequest httpRequest) {
    final URI current = currentUri(httpRequest);

    try {
        return new URI(current.getScheme(), null, current.getHost(), current.getPort(), basePath(current.getPath()),
            null, null);
    } catch (final URISyntaxException e) {
        throw new IllegalArgumentException("Unable to generate base URI based on the current (`" + current + "`)",
            e);
    }
}
 
Example 16
Project: hadoop-oss   File: FTPFileSystem.java   View Source Code Vote up 5 votes
@Override
public void initialize(URI uri, Configuration conf) throws IOException { // get
  super.initialize(uri, conf);
  // get host information from uri (overrides info in conf)
  String host = uri.getHost();
  host = (host == null) ? conf.get(FS_FTP_HOST, null) : host;
  if (host == null) {
    throw new IOException("Invalid host specified");
  }
  conf.set(FS_FTP_HOST, host);

  // get port information from uri, (overrides info in conf)
  int port = uri.getPort();
  port = (port == -1) ? FTP.DEFAULT_PORT : port;
  conf.setInt("fs.ftp.host.port", port);

  // get user/password information from URI (overrides info in conf)
  String userAndPassword = uri.getUserInfo();
  if (userAndPassword == null) {
    userAndPassword = (conf.get("fs.ftp.user." + host, null) + ":" + conf
        .get("fs.ftp.password." + host, null));
  }
  String[] userPasswdInfo = userAndPassword.split(":");
  Preconditions.checkState(userPasswdInfo.length > 1,
                           "Invalid username / password");
  conf.set(FS_FTP_USER_PREFIX + host, userPasswdInfo[0]);
  conf.set(FS_FTP_PASSWORD_PREFIX + host, userPasswdInfo[1]);
  setConf(conf);
  this.uri = uri;
}
 
Example 17
Project: Hotspot-master-devp   File: URIBuilder.java   View Source Code Vote up 5 votes
private void digestURI(final URI uri) {
    this.scheme = uri.getScheme();
    this.encodedSchemeSpecificPart = uri.getRawSchemeSpecificPart();
    this.encodedAuthority = uri.getRawAuthority();
    this.host = uri.getHost();
    this.port = uri.getPort();
    this.encodedUserInfo = uri.getRawUserInfo();
    this.userInfo = uri.getUserInfo();
    this.encodedPath = uri.getRawPath();
    this.path = uri.getPath();
    this.encodedQuery = uri.getRawQuery();
    this.queryParams = parseQuery(uri.getRawQuery(), Charset.forName(HTTP.UTF_8));
    this.encodedFragment = uri.getRawFragment();
    this.fragment = uri.getFragment();
}
 
Example 18
Project: Snow-Globe   File: TestRequest.java   View Source Code Vote up 5 votes
public String getHealthCheckUrl() {
    if (null != this.healthCheckUrl) {
        try {
            URI o = new URI(this.url + this.healthCheckUrl);
            URI injected = new URI("http", null, o.getHost(), reverseProxy.getPortForUrl(this.url),
                    o.getPath(), o.getQuery(), o.getFragment());
            return injected.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return this.healthCheckUrl;
}
 
Example 19
Project: RLibrary   File: Misc.java   View Source Code Vote up 5 votes
public static String extractHost(URI uri)
{
    // Extract the host part from the URI.
    String host = uri.getHost();

    if (host != null)
    {
        return host;
    }

    // According to Issue#74, URI.getHost() method returns null in
    // the following environment when the host part of the URI is
    // a host name.
    //
    //   - Samsung Galaxy S3 + Android API 18
    //   - Samsung Galaxy S4 + Android API 21
    //
    // The following is a workaround for the issue.

    // Extract the host part from the authority part of the URI.
    host = extractHostFromAuthorityPart(uri.getRawAuthority());

    if (host != null)
    {
        return host;
    }

    // Extract the host part from the entire URI.
    return extractHostFromEntireUri(uri.toString());
}
 
Example 20
Project: xlight_android_native   File: WebSocketCompositeChannel.java   View Source Code Vote up 4 votes
public String getOrigin() {
    URI uri = getLocation().getURI();
    return uri.getScheme()+"://"+uri.getHost()+":"+uri.getPort();
}