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

The following are Jave code examples for showing how to use getScheme() 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-oss   File: FileSystem.java   View Source Code Vote up 6 votes
/** Returns the FileSystem for this URI's scheme and authority.  The scheme
 * of the URI determines a configuration property name,
 * <tt>fs.<i>scheme</i>.class</tt> whose value names the FileSystem class.
 * The entire URI is passed to the FileSystem instance's initialize method.
 * This always returns a new FileSystem object.
 */
public static FileSystem newInstance(URI uri, Configuration conf) throws IOException {
  String scheme = uri.getScheme();
  String authority = uri.getAuthority();

  if (scheme == null) {                       // no scheme: use default FS
    return newInstance(conf);
  }

  if (authority == null) {                       // no authority
    URI defaultUri = getDefaultUri(conf);
    if (scheme.equals(defaultUri.getScheme())    // if scheme matches default
        && defaultUri.getAuthority() != null) {  // & default has authority
      return newInstance(defaultUri, conf);              // return default
    }
  }
  return CACHE.getUnique(uri, conf);
}
 
Example 2
Project: OpenJSharp   File: ZipFileSystemProvider.java   View Source Code Vote up 6 votes
protected Path uriToPath(URI uri) {
    String scheme = uri.getScheme();
    if ((scheme == null) || !scheme.equalsIgnoreCase(getScheme())) {
        throw new IllegalArgumentException("URI scheme is not '" + getScheme() + "'");
    }
    try {
        // only support legacy JAR URL syntax  jar:{uri}!/{entry} for now
        String spec = uri.getRawSchemeSpecificPart();
        int sep = spec.indexOf("!/");
        if (sep != -1)
            spec = spec.substring(0, sep);
        return Paths.get(new URI(spec)).toAbsolutePath();
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}
 
Example 3
Project: manifold   File: UrlClassLoaderWrapper.java   View Source Code Vote up 5 votes
private void wrapReaders()
{
  Map/*<ModuleReference, ModuleReader>*/ moduleToReader = (Map)ReflectUtil.field( _loader, "moduleToReader" ).get();
  for( Object mr: moduleToReader.keySet() )
  {
    //noinspection unchecked
    Optional<URI> location = (Optional<URI>)ReflectUtil.method( mr, "location" ).invoke();
    URI uri = location.orElse( null );
    if( uri == null )
    {
      continue;
    }

    //## note: "jmod" files are not supported here because they are currently (2018) supported exclusively at compiler/linker time
    String scheme = uri.getScheme();
    if( scheme.equalsIgnoreCase( "file" ) || scheme.equalsIgnoreCase( "jar" ) )
    {
      Object reader = moduleToReader.get( mr );
      Class<?> moduleReaderClass = ReflectUtil.type( "java.lang.module.ModuleReader" );
      ManModuleReader wrapper = new ManModuleReader( reader, ReflectUtil.field( _loader, "ucp" ).get() );
      Object/*ModuleReader*/ proxy = Proxy.newProxyInstance( moduleReaderClass.getClassLoader(), new Class<?>[]{moduleReaderClass},
        new ManModuleReaderInvocationHandler( wrapper ) );
      //noinspection unchecked
      moduleToReader.put( mr, proxy );
    }
  }
}
 
Example 4
Project: hadoop   File: PathData.java   View Source Code Vote up 5 votes
/**
 * Expand the given path as a glob pattern.  Non-existent paths do not
 * throw an exception because creation commands like touch and mkdir need
 * to create them.  The "stat" field will be null if the path does not
 * exist.
 * @param pattern the pattern to expand as a glob
 * @param conf the hadoop configuration
 * @return list of {@link PathData} objects.  if the pattern is not a glob,
 * and does not exist, the list will contain a single PathData with a null
 * stat 
 * @throws IOException anything else goes wrong...
 */
public static PathData[] expandAsGlob(String pattern, Configuration conf)
throws IOException {
  Path globPath = new Path(pattern);
  FileSystem fs = globPath.getFileSystem(conf);    
  FileStatus[] stats = fs.globStatus(globPath);
  PathData[] items = null;
  
  if (stats == null) {
    // remove any quoting in the glob pattern
    pattern = pattern.replaceAll("\\\\(.)", "$1");
    // not a glob & file not found, so add the path with a null stat
    items = new PathData[]{ new PathData(fs, pattern, null) };
  } else {
    // figure out what type of glob path was given, will convert globbed
    // paths to match the type to preserve relativity
    PathType globType;
    URI globUri = globPath.toUri();
    if (globUri.getScheme() != null) {
      globType = PathType.HAS_SCHEME;
    } else if (!globUri.getPath().isEmpty() &&
               new Path(globUri.getPath()).isAbsolute()) {
      globType = PathType.SCHEMELESS_ABSOLUTE;
    } else {
      globType = PathType.RELATIVE;
    }

    // convert stats to PathData
    items = new PathData[stats.length];
    int i=0;
    for (FileStatus stat : stats) {
      URI matchUri = stat.getPath().toUri();
      String globMatch = null;
      switch (globType) {
        case HAS_SCHEME: // use as-is, but remove authority if necessary
          if (globUri.getAuthority() == null) {
            matchUri = removeAuthority(matchUri);
          }
          globMatch = uriToString(matchUri, false);
          break;
        case SCHEMELESS_ABSOLUTE: // take just the uri's path
          globMatch = matchUri.getPath();
          break;
        case RELATIVE: // make it relative to the current working dir
          URI cwdUri = fs.getWorkingDirectory().toUri();
          globMatch = relativize(cwdUri, matchUri, stat.isDirectory());
          break;
      }
      items[i++] = new PathData(fs, globMatch, stat);
    }
  }
  Arrays.sort(items);
  return items;
}
 
Example 5
Project: osc-core   File: PluginsLayout.java   View Source Code Vote up 5 votes
private Button getDownloadSdkButtonForManager() throws URISyntaxException, MalformedURLException {
    SdkUtil sdkUtil = new SdkUtil();
    Button downloadSdk = new Button(VmidcMessages.getString(VmidcMessages_.MAINTENANCE_MANAGERPLUGIN_DOWNLOAD_SDK));
    URI currentLocation = UI.getCurrent().getPage().getLocation();
    URI downloadLocation = new URI(currentLocation.getScheme(), null, currentLocation.getHost(),
            currentLocation.getPort(), sdkUtil.getSdk(SdkUtil.sdkType.MANAGER), null, null);
    FileDownloader downloader = new FileDownloader(new ExternalResource(downloadLocation.toURL().toString()));
    downloader.extend(downloadSdk);
    return downloadSdk;
}
 
Example 6
Project: cloud-cf-feature-flags-sample   File: FeatureFlagsServiceConnectorCreator.java   View Source Code Vote up 5 votes
private URI createBaseUri(String serviceInfoUri) {
	try {
		URI basicAuthEncodedUri = URI.create(serviceInfoUri);
		return new URI(basicAuthEncodedUri.getScheme(), basicAuthEncodedUri.getHost(),
				basicAuthEncodedUri.getPath(), basicAuthEncodedUri.getFragment());
	} catch (URISyntaxException x) {
		throw new IllegalArgumentException(x.getMessage(), x);
	}
}
 
Example 7
Project: hadoop   File: FileSystem.java   View Source Code Vote up 5 votes
Key(URI uri, Configuration conf, long unique) throws IOException {
  scheme = uri.getScheme()==null ?
      "" : StringUtils.toLowerCase(uri.getScheme());
  authority = uri.getAuthority()==null ?
      "" : StringUtils.toLowerCase(uri.getAuthority());
  this.unique = unique;
  
  this.ugi = UserGroupInformation.getCurrentUser();
}
 
Example 8
Project: lams   File: URIUtils.java   View Source Code Vote up 5 votes
/**
 * Removes dot segments according to RFC 3986, section 5.2.4
 *
 * @param uri the original URI
 * @return the URI without dot segments
 */
private static URI removeDotSegments(URI uri) {
    String path = uri.getPath();
    if ((path == null) || (path.indexOf("/.") == -1)) {
        // No dot segments to remove
        return uri;
    }
    String[] inputSegments = path.split("/");
    Stack<String> outputSegments = new Stack<String>();
    for (int i = 0; i < inputSegments.length; i++) {
        if ((inputSegments[i].length() == 0)
            || (".".equals(inputSegments[i]))) {
            // Do nothing
        } else if ("..".equals(inputSegments[i])) {
            if (!outputSegments.isEmpty()) {
                outputSegments.pop();
            }
        } else {
            outputSegments.push(inputSegments[i]);
        }
    }
    StringBuilder outputBuffer = new StringBuilder();
    for (String outputSegment : outputSegments) {
        outputBuffer.append('/').append(outputSegment);
    }
    try {
        return new URI(uri.getScheme(), uri.getAuthority(),
            outputBuffer.toString(), uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 9
Project: FirefoxData-android   File: AutoRetryHttpClient.java   View Source Code Vote up 5 votes
public HttpResponse execute(final HttpUriRequest request, final HttpContext context)
        throws IOException {
    final URI uri = request.getURI();
    final HttpHost httpHost = new HttpHost(uri.getHost(), uri.getPort(),
            uri.getScheme());
    return execute(httpHost, request, context);
}
 
Example 10
Project: hadoop-oss   File: FileSystem.java   View Source Code Vote up 5 votes
Key(URI uri, Configuration conf, long unique) throws IOException {
  scheme = uri.getScheme()==null ?
      "" : StringUtils.toLowerCase(uri.getScheme());
  authority = uri.getAuthority()==null ?
      "" : StringUtils.toLowerCase(uri.getAuthority());
  this.unique = unique;
  
  this.ugi = UserGroupInformation.getCurrentUser();
}
 
Example 11
Project: FirefoxData-android   File: HMACAuthHeaderProvider.java   View Source Code Vote up 5 votes
/**
 * Generate an HMAC request string.
 * <p>
 * This method trusts its inputs to be valid as per the MAC Authentication spec.
 *
 * @param request HTTP request.
 * @param timestamp to use.
 * @param nonce to use.
 * @param extra to use.
 * @return request string.
 */
protected static String getRequestString(HttpUriRequest request, long timestamp, String nonce, String extra) {
  String method = request.getMethod().toUpperCase();

  URI uri = request.getURI();
  String host = uri.getHost();

  String path = uri.getRawPath();
  if (uri.getRawQuery() != null) {
    path += "?";
    path += uri.getRawQuery();
  }
  if (uri.getRawFragment() != null) {
    path += "#";
    path += uri.getRawFragment();
  }

  int port = uri.getPort();
  String scheme = uri.getScheme();
  if (port != -1) {
  } else if ("http".equalsIgnoreCase(scheme)) {
    port = 80;
  } else if ("https".equalsIgnoreCase(scheme)) {
    port = 443;
  } else {
    throw new IllegalArgumentException("Unsupported URI scheme: " + scheme + ".");
  }

  String requestString = timestamp + "\n" +
      nonce       + "\n" +
      method      + "\n" +
      path        + "\n" +
      host        + "\n" +
      port        + "\n" +
      extra       + "\n";

  return requestString;
}
 
Example 12
Project: ChatBot   File: WebSocket.java   View Source Code Vote up 5 votes
private static int getPort(URI uri){
	switch(uri.getScheme()){
		case "wss":
			return 443;
		case "ws":
			return 80;
		default:
			throw new IllegalArgumentException();
	}
}
 
Example 13
Project: pooled-jms   File: SocketProxy.java   View Source Code Vote up 4 votes
private URI urlFromSocket(URI uri, ServerSocket serverSocket) throws Exception {
    int listenPort = serverSocket.getLocalPort();

    return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), listenPort, uri.getPath(), uri.getQuery(),
            uri.getFragment());
}
 
Example 14
Project: openjdk-jdk10   File: Canonicalizer11.java   View Source Code Vote up 4 votes
private static String joinURI(String baseURI, String relativeURI) throws URISyntaxException {
    String bscheme = null;
    String bauthority = null;
    String bpath = "";
    String bquery = null;

    // pre-parse the baseURI
    if (baseURI != null) {
        if (baseURI.endsWith("..")) {
            baseURI = baseURI + "/";
        }
        URI base = new URI(baseURI);
        bscheme = base.getScheme();
        bauthority = base.getAuthority();
        bpath = base.getPath();
        bquery = base.getQuery();
    }

    URI r = new URI(relativeURI);
    String rscheme = r.getScheme();
    String rauthority = r.getAuthority();
    String rpath = r.getPath();
    String rquery = r.getQuery();

    String tscheme, tauthority, tpath, tquery;
    if (rscheme != null && rscheme.equals(bscheme)) {
        rscheme = null;
    }
    if (rscheme != null) {
        tscheme = rscheme;
        tauthority = rauthority;
        tpath = removeDotSegments(rpath);
        tquery = rquery;
    } else {
        if (rauthority != null) {
            tauthority = rauthority;
            tpath = removeDotSegments(rpath);
            tquery = rquery;
        } else {
            if (rpath.length() == 0) {
                tpath = bpath;
                if (rquery != null) {
                    tquery = rquery;
                } else {
                    tquery = bquery;
                }
            } else {
                if (rpath.startsWith("/")) {
                    tpath = removeDotSegments(rpath);
                } else {
                    if (bauthority != null && bpath.length() == 0) {
                        tpath = "/" + rpath;
                    } else {
                        int last = bpath.lastIndexOf('/');
                        if (last == -1) {
                            tpath = rpath;
                        } else {
                            tpath = bpath.substring(0, last+1) + rpath;
                        }
                    }
                    tpath = removeDotSegments(tpath);
                }
                tquery = rquery;
            }
            tauthority = bauthority;
        }
        tscheme = bscheme;
    }
    return new URI(tscheme, tauthority, tpath, tquery, null).toString();
}
 
Example 15
Project: manifold   File: JavacPlugin.java   View Source Code Vote up 4 votes
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean isPhysicalFile( JavaFileObject inputFile )
{
  URI uri = inputFile.toUri();
  return uri != null && uri.getScheme() != null && uri.getScheme().equalsIgnoreCase( "file" );
}
 
Example 16
Project: shibboleth-idp-oidc-extension   File: CheckRedirectURIs.java   View Source Code Vote up 4 votes
/** {@inheritDoc} */
@Override
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext) {
    final OIDCClientMetadata metadata = request.getOIDCClientMetadata();
    if (metadata == null) {
        log.warn("{} No client metadata found in the request", getLogPrefix());
        ActionSupport.buildEvent(profileRequestContext, EventIds.INVALID_MESSAGE);
        return;
    }
    final Set<URI> redirectURIs = metadata.getRedirectionURIs();
    if (redirectURIs == null || redirectURIs.isEmpty()) {
        log.warn("{} No redirection URIs found in the request", getLogPrefix());
        ActionSupport.buildEvent(profileRequestContext, OidcEventIds.MISSING_REDIRECT_URIS);
        return;
    }
    final URI sectorIdUri = metadata.getSectorIDURI();
    if (sectorIdUri != null) {
        log.debug("{} Found sector_identifier_uri {}", getLogPrefix(), sectorIdUri);
        if (!sectorIdUri.getScheme().equals("https")) {
            log.warn("{} Invalid sector_identifier_uri scheme {}", getLogPrefix(), sectorIdUri.getScheme());
            ActionSupport.buildEvent(profileRequestContext, EventIds.INVALID_MESSAGE);
            return;
        }
        if (!verifySectorIdUri(sectorIdUri, redirectURIs)) {
            log.warn("{} All redirect URIs are not found from sector_identifier_uri", getLogPrefix());
            ActionSupport.buildEvent(profileRequestContext, OidcEventIds.INVALID_REDIRECT_URIS);
            return;                
        }
    }
    final ApplicationType applicationType = metadata.getApplicationType();
    if (applicationType == null || applicationType.equals(ApplicationType.WEB)) {
        final Set<GrantType> grantTypes = metadata.getGrantTypes();
        // if implicit, only https
        if (grantTypes != null && grantTypes.contains(GrantType.IMPLICIT) 
                && !checkScheme(redirectURIs, "https")) {
            log.warn("{} Only https-scheme is allowed for implicit flow", getLogPrefix());
            ActionSupport.buildEvent(profileRequestContext, OidcEventIds.INVALID_REDIRECT_URIS);
            return;
        }
        // no localhost as the hostname
        if (checkForbiddenHostname(redirectURIs, "localhost")) {
            log.warn("{} localhost as the hostname in the redirect URI for a Web app", getLogPrefix());
            ActionSupport.buildEvent(profileRequestContext, OidcEventIds.INVALID_REDIRECT_URIS);
            return;
        }
    } else {
        // native application
        // http://localhost or custom scheme
        if (checkForbiddenScheme(redirectURIs, "https")) {
            log.warn("{} https-scheme is not allowed for a native application", getLogPrefix());
            ActionSupport.buildEvent(profileRequestContext, OidcEventIds.INVALID_REDIRECT_URIS);
            return;                                    
        }
        for (final URI redirectUri : redirectURIs) {
            final String scheme = redirectUri.getScheme();
            if (scheme.equalsIgnoreCase("http") && !redirectUri.getHost().equalsIgnoreCase("localhost")) {
                log.warn("{} http-scheme is only allowed to localhost for a native application", getLogPrefix());
                ActionSupport.buildEvent(profileRequestContext, OidcEventIds.INVALID_REDIRECT_URIS);
                return;                                        
            }
            log.debug("{} Accepting a redirect URI {} for a native application", getLogPrefix(), redirectUri);
        }
    }
    //TODO: should the URIs be checked against black/white-lists?
    log.debug("{} Redirect URIs ({}) checked", getLogPrefix(), redirectURIs.size());
}
 
Example 17
Project: kafka-streams-on-heroku   File: AggregatorConfig.java   View Source Code Vote up 4 votes
private Properties buildHerokuKafkaConfigVars() throws URISyntaxException, CertificateException,
    NoSuchAlgorithmException, KeyStoreException, IOException {
  Properties properties = new Properties();
  List<String> bootstrapServerList = Lists.newArrayList();

  Iterable<String> kafkaUrl = Splitter.on(",")
      .split(Preconditions.checkNotNull(System.getenv(HEROKU_KAFKA_URL)));

  for (String url : kafkaUrl) {
    URI uri = new URI(url);
    bootstrapServerList.add(String.format("%s:%d", uri.getHost(), uri.getPort()));

    switch (uri.getScheme()) {
    case "kafka":
      properties.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "PLAINTEXT");
      break;
    case "kafka+ssl":
      properties.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
      EnvKeyStore envTrustStore = EnvKeyStore.createWithRandomPassword(
          HEROKU_KAFKA_TRUSTED_CERT);
      EnvKeyStore envKeyStore = EnvKeyStore.createWithRandomPassword(
          HEROKU_KAFKA_CLIENT_CERT_KEY, HEROKU_KAFKA_CLIENT_CERT);

      File trustStoreFile = envTrustStore.storeTemp();
      File keyStoreFile = envKeyStore.storeTemp();

      properties.put(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, envTrustStore.type());
      properties.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG,
          trustStoreFile.getAbsolutePath());
      properties.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, envTrustStore.password());
      properties.put(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, envKeyStore.type());
      properties.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, keyStoreFile.getAbsolutePath());
      properties.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, envKeyStore.password());
      break;
    default:
      throw new URISyntaxException(uri.getScheme(), "Unknown URI scheme");
    }
  }

  bootstrapServers = Joiner.on(",").join(bootstrapServerList);

  return properties;
}
 
Example 18
Project: hadoop   File: TestUrlStreamHandler.java   View Source Code Vote up 4 votes
/**
 * Test opening and reading from an InputStream through a hdfs:// URL.
 * <p>
 * First generate a file with some content through the FileSystem API, then
 * try to open and read the file through the URL stream API.
 * 
 * @throws IOException
 */
@Test
public void testDfsUrls() throws IOException {

  Configuration conf = new HdfsConfiguration();
  MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
  FileSystem fs = cluster.getFileSystem();

  // Setup our own factory
  // setURLSteramHandlerFactor is can be set at most once in the JVM
  // the new URLStreamHandler is valid for all tests cases 
  // in TestStreamHandler
  FsUrlStreamHandlerFactory factory =
      new org.apache.hadoop.fs.FsUrlStreamHandlerFactory();
  java.net.URL.setURLStreamHandlerFactory(factory);

  Path filePath = new Path("/thefile");

  try {
    byte[] fileContent = new byte[1024];
    for (int i = 0; i < fileContent.length; ++i)
      fileContent[i] = (byte) i;

    // First create the file through the FileSystem API
    OutputStream os = fs.create(filePath);
    os.write(fileContent);
    os.close();

    // Second, open and read the file content through the URL API
    URI uri = fs.getUri();
    URL fileURL =
        new URL(uri.getScheme(), uri.getHost(), uri.getPort(), filePath
            .toString());

    InputStream is = fileURL.openStream();
    assertNotNull(is);

    byte[] bytes = new byte[4096];
    assertEquals(1024, is.read(bytes));
    is.close();

    for (int i = 0; i < fileContent.length; ++i)
      assertEquals(fileContent[i], bytes[i]);

    // Cleanup: delete the file
    fs.delete(filePath, false);

  } finally {
    fs.close();
    cluster.shutdown();
  }

}
 
Example 19
Project: OpenJSharp   File: FileSystems.java   View Source Code Vote up 3 votes
/**
 * Returns a reference to an existing {@code FileSystem}.
 *
 * <p> This method iterates over the {@link FileSystemProvider#installedProviders()
 * installed} providers to locate the provider that is identified by the URI
 * {@link URI#getScheme scheme} of the given URI. URI schemes are compared
 * without regard to case. The exact form of the URI is highly provider
 * dependent. If found, the provider's {@link FileSystemProvider#getFileSystem
 * getFileSystem} method is invoked to obtain a reference to the {@code
 * FileSystem}.
 *
 * <p> Once a file system created by this provider is {@link FileSystem#close
 * closed} it is provider-dependent if this method returns a reference to
 * the closed file system or throws {@link FileSystemNotFoundException}.
 * If the provider allows a new file system to be created with the same URI
 * as a file system it previously created then this method throws the
 * exception if invoked after the file system is closed (and before a new
 * instance is created by the {@link #newFileSystem newFileSystem} method).
 *
 * <p> If a security manager is installed then a provider implementation
 * may require to check a permission before returning a reference to an
 * existing file system. In the case of the {@link FileSystems#getDefault
 * default} file system, no permission check is required.
 *
 * @param   uri  the URI to locate the file system
 *
 * @return  the reference to the file system
 *
 * @throws  IllegalArgumentException
 *          if the pre-conditions for the {@code uri} parameter are not met
 * @throws  FileSystemNotFoundException
 *          if the file system, identified by the URI, does not exist
 * @throws  ProviderNotFoundException
 *          if a provider supporting the URI scheme is not installed
 * @throws  SecurityException
 *          if a security manager is installed and it denies an unspecified
 *          permission
 */
public static FileSystem getFileSystem(URI uri) {
    String scheme = uri.getScheme();
    for (FileSystemProvider provider: FileSystemProvider.installedProviders()) {
        if (scheme.equalsIgnoreCase(provider.getScheme())) {
            return provider.getFileSystem(uri);
        }
    }
    throw new ProviderNotFoundException("Provider \"" + scheme + "\" not found");
}
 
Example 20
Project: incubator-netbeans   File: PacUtils.java   View Source Code Vote up 3 votes
/**
 * Cleans a URI into a format suitable for passing to the PAC script.
 * (meaning suitable for passing as {@code url} argument to 
 * {@code FindProxyForURL(url, host)} or {@code FindProxyForURLEx(url, host)} 
 * functions).
 * <p>
 * Because a PAC script is downloaded from a potentially malicious source it
 * may contain harmful code. Therefore, the amount of information passed to
 * the script should be limited to what is strictly necessary for the script
 * to make decisions about choice of proxy. Anything in the URL which can
 * potentially identity the user or which may contain session specific
 * information should be removed before passing to script.
 * 
 * <p>
 * The following is removed:
 * <ul>
 *   <li><i>{@code user-info}</i></li>
 *   <li><i>{@code path}</i> and everything that follows after</li>
 * </ul>
 * 
 * <p>
 * Example:
 * <pre>
 *    https://[email protected]:8081/path/to/something?x1=Christmas&amp;user=unknown
 * becomes
 *    https://netbeans.apache.org:8081/
 * </pre>
 * 
 * <p>
 * Note that the majority of PAC scripts out there do not make use of the
 * {@code url} parameter at all. Instead they only use the {@code host}
 * parameter. The stripping of information means that the {@code url}
 * parameter only has two pieces of information that the {@code host} 
 * parameter doesn't have: protocol and port number.
 * <br>
 *
 * @param uri URL to be cleansed
 * @return stripped URL string
 */
public static String toStrippedURLStr(URI uri) {
    
    String portStr = (uri.getPort() == -1) ? "" : ":" + uri.getPort();
    return
            uri.getScheme()
            + "://"
            + uri.getHost()
            + portStr
            + "/";  // Chrome seems to always append the slash so we do it too
}