Пример #1
0
 private static String createBaseUri(org.apache.commons.httpclient.URI uri) throws URIException {
   StringBuilder baseUriBuilder = new StringBuilder();
   baseUriBuilder.append(uri.getScheme()).append("://").append(uri.getHost());
   if (uri.getPort() != -1) {
     baseUriBuilder.append(':').append(uri.getPort());
   }
   return baseUriBuilder.toString();
 }
  /**
   * Constructs a {@code HttpPrefixFetchFilter} using the given {@code URI} as prefix.
   *
   * <p>The user info, query component and fragment of the given {@code URI} are discarded. The
   * scheme and domain comparisons are done in a case insensitive way while the path component
   * comparison is case sensitive.
   *
   * @param prefix the {@code URI} that will be used as prefix
   * @throws IllegalArgumentException if any of the following conditions is {@code true}:
   *     <ul>
   *       <li>The given {@code prefix} is {@code null};
   *       <li>The given {@code prefix} has {@code null} scheme;
   *       <li>The scheme of the given {@code prefix} is not HTTP or HTTPS;
   *       <li>The given {@code prefix} has {@code null} host;
   *       <li>The given {@code prefix} has malformed host.
   *     </ul>
   */
  public HttpPrefixUriValidator(URI prefix) {
    if (prefix == null) {
      throw new IllegalArgumentException("Parameter prefix must not be null.");
    }

    char[] rawScheme = prefix.getRawScheme();
    if (rawScheme == null) {
      throw new IllegalArgumentException("Parameter prefix must have a scheme.");
    }
    String normalisedScheme = normalisedScheme(rawScheme);
    if (!isHttpOrHttps(normalisedScheme)) {
      throw new IllegalArgumentException("The prefix's scheme must be HTTP or HTTPS.");
    }
    scheme = normalisedScheme;

    if (prefix.getRawHost() == null) {
      throw new IllegalArgumentException("Parameter prefix must have a host.");
    }
    try {
      host = normalisedHost(prefix);
    } catch (URIException e) {
      throw new IllegalArgumentException("Failed to obtain the host from the prefix:", e);
    }

    port = normalisedPort(scheme, prefix.getPort());
    path = prefix.getRawPath();
  }
  /**
   * Tells whether or not the given URI is valid, by starting or not with the defined prefix.
   *
   * @param uri the uri to be validated
   * @return {@code true} if valid, that is, the {@code uri} starts with the {@code prefix}, {@code
   *     false} otherwise
   */
  public boolean isValid(URI uri) {
    if (uri == null) {
      return false;
    }

    String otherScheme = normalisedScheme(uri.getRawScheme());
    if (port != normalisedPort(otherScheme, uri.getPort())) {
      return false;
    }

    if (!scheme.equals(otherScheme)) {
      return false;
    }

    if (!hasSameHost(uri)) {
      return false;
    }

    if (!startsWith(uri.getRawPath(), path)) {
      return false;
    }

    return true;
  }