/** * Obtain the TCP port number from the URI. If the port number is * defined in the URI then that value is used. If the URI contains no * port number but a default value is known for the schema, then that * default value is returned; otherwise, otherwise -1 is returned. */ public static int portWithDefault(URI uri) { return portWithDefault(uri, null, -1); }
/** * Obtain an optional port number based on supplied URI. Use the * defined port number, if the URI defines one; otherwise use the default * port number for URI's schema, if one is known. Otherwise return an * empty Optional. */ public static Optional<Integer> optionalPortWithDefault(URI uri) { int port = portWithDefault(uri, null, -1); return port > -1 ? Optional.of(port) : Optional.<Integer>empty(); }
/** * Return a URI with a defined port number, if possible. If the URI * has no port number then the argument-supplied (schema,port) mapping is * used if the scheme matches, otherwise default port numbers are used if a * default port is known for this scheme. */ public static URI withDefaultPort(URI uri, String scheme, int port) { if (isDefaultPortNeeded(uri)) { int defaultPort = portWithDefault(uri, scheme, port); if (defaultPort != -1) { try { return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), defaultPort, uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { throw new RuntimeException("Failed to add default port: " + e.getMessage(), e); } } } return uri; }