private Realm kerberosChallenge(
      List<String> proxyAuth,
      Request request,
      ProxyServer proxyServer,
      FluentCaseInsensitiveStringsMap headers,
      Realm realm,
      NettyResponseFuture<?> future)
      throws NTLMEngineException {

    URI uri = request.getURI();
    String host =
        request.getVirtualHost() == null
            ? AsyncHttpProviderUtils.getHost(uri)
            : request.getVirtualHost();
    String server = proxyServer == null ? host : proxyServer.getHost();
    try {
      String challengeHeader = SpnegoEngine.instance().generateToken(server);
      headers.remove(HttpHeaders.Names.AUTHORIZATION);
      headers.add(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader);

      return newRealmBuilder(realm) //
          .setUri(uri.getRawPath()) //
          .setMethodName(request.getMethod()) //
          .setScheme(Realm.AuthScheme.KERBEROS) //
          .build();

    } catch (Throwable throwable) {
      if (isNTLM(proxyAuth)) {
        return ntlmChallenge(proxyAuth, request, proxyServer, headers, realm, future);
      }
      channels.abort(future, throwable);
      return null;
    }
  }
  @Override
  public String getColumnText(Object element, int columnIndex) {
    if (!(element instanceof IRequestLogRecord)) return null;
    final IRequestLogRecord record = (IRequestLogRecord) element;
    URI uri;
    try {
      uri = new URI(record.getRequest().getRequestLine().getUri());

    } catch (URISyntaxException e) {
      return null;
    }
    switch (columnIndex) {
      case 0:
        return Long.toString(record.getRequestId());
      case 1:
        return record.getHttpHost().toURI();
      case 2:
        return record.getRequest().getRequestLine().getMethod();
      case 3:
        if (uri.getRawQuery() != null) return uri.getRawPath() + "?" + uri.getRawQuery();
        else return uri.getRawPath();
      case 4:
        return Integer.valueOf(record.getResponse().getStatusLine().getStatusCode()).toString();
      case 5:
        return getResponseLength(record.getResponse());
      case 6:
        return Long.toString(record.getRequestMilliseconds());
    }
    return null;
  }
  @Override
  public UriBuilder uri(URI uri) {
    if (uri == null) {
      throw new IllegalArgumentException("URI parameter is null");
    }

    if (uri.getRawFragment() != null) {
      fragment = uri.getRawFragment();
    }

    if (uri.isOpaque()) {
      scheme = uri.getScheme();
      ssp = uri.getRawSchemeSpecificPart();
      return this;
    }

    if (uri.getScheme() == null) {
      if (ssp != null) {
        if (uri.getRawSchemeSpecificPart() != null) {
          ssp = uri.getRawSchemeSpecificPart();
          return this;
        }
      }
    } else {
      scheme = uri.getScheme();
    }

    ssp = null;
    if (uri.getRawAuthority() != null) {
      if (uri.getRawUserInfo() == null && uri.getHost() == null && uri.getPort() == -1) {
        authority = uri.getRawAuthority();
        userInfo = null;
        host = null;
        port = -1;
      } else {
        authority = null;
        if (uri.getRawUserInfo() != null) {
          userInfo = uri.getRawUserInfo();
        }
        if (uri.getHost() != null) {
          host = uri.getHost();
        }
        if (uri.getPort() != -1) {
          port = uri.getPort();
        }
      }
    }

    if (uri.getRawPath() != null && uri.getRawPath().length() > 0) {
      path.setLength(0);
      path.append(uri.getRawPath());
    }
    if (uri.getRawQuery() != null && uri.getRawQuery().length() > 0) {
      query.setLength(0);
      query.append(uri.getRawQuery());
    }

    return this;
  }
Example #4
0
  /**
   * Returns results from parsing a {@link java.net.URI} with this pattern. If the URI doesn't match
   * the pattern, this will return null.
   *
   * @param uri A URI to match against this URIPattern
   * @return A Map of the pattern's variable names to values from the parsed URI
   */
  public Map<String, String> getMatch(URI uri) {
    // verify that the schemes match
    if (pattern.isAbsolute()) {
      // if there should be a scheme, make sure it matches
      if (!pattern.getScheme().equalsIgnoreCase(uri.getScheme())) {
        return null;
      }
    } else if (uri.getScheme() != null) {
      return null;
    }

    Map<String, String> result = Maps.newLinkedHashMap(defaults);

    if (pattern.isOpaque()) {
      if (!uri.isOpaque()) {
        return null;
      }

      Iterator<String> pathQuery =
          PATH_QUERY_SPLITTER.split(uri.getRawSchemeSpecificPart()).iterator();

      if (!addPath(patternPath, Iterators.getNext(pathQuery, null), result)) {
        return null;
      }

      addQuery(Iterators.getNext(pathQuery, null), result);

    } else if (!uri.isOpaque()) {
      addAuthority(uri, result);

      if (patternPath.isEmpty() && !uri.getRawPath().isEmpty()) {
        return null;
      }

      if (!addPath(patternPath, uri.getRawPath(), result)) {
        return null;
      }

      addQuery(uri.getRawQuery(), result);

    } else {
      return null;
    }

    if (!addComplexMatch(pattern.getFragment(), uri.getFragment(), result)) {
      return null;
    }

    // save this match
    this.lastMatch = result;

    // return the new result, so that this is thread-safe
    return result;
  }
  public void testToUri() {
    if (!SystemInfo.isWindows) {
      assertEquals("file:///asd", VfsUtil.toUri(new File("/asd")).toASCIIString());
      assertEquals("file:///asd%20/sd", VfsUtil.toUri(new File("/asd /sd")).toASCIIString());
    }

    URI uri = VfsUtil.toUri("file:///asd");
    assertNotNull(uri);
    assertEquals("file", uri.getScheme());
    assertEquals("/asd", uri.getPath());

    uri = VfsUtil.toUri("file:///asd/ ads/ad#test");
    assertNotNull(uri);
    assertEquals("file", uri.getScheme());
    assertEquals("/asd/ ads/ad", uri.getPath());
    assertEquals("test", uri.getFragment());

    uri = VfsUtil.toUri("file:///asd/ ads/ad#");
    assertNotNull(uri);
    assertEquals("file:///asd/%20ads/ad#", uri.toString());

    uri = VfsUtil.toUri("mailto:[email protected]");
    assertNotNull(uri);
    assertEquals("*****@*****.**", uri.getSchemeSpecificPart());

    if (SystemInfo.isWindows) {
      uri = VfsUtil.toUri("file://C:/p");
      assertNotNull(uri);
      assertEquals("file", uri.getScheme());
      assertEquals("/C:/p", uri.getPath());
    }

    uri = VfsUtil.toUri("file:///Users/S pace");
    assertNotNull(uri);
    assertEquals("file", uri.getScheme());
    assertEquals("/Users/S pace", uri.getPath());
    assertEquals("/Users/S%20pace", uri.getRawPath());
    assertEquals("file:///Users/S%20pace", uri.toString());

    uri = VfsUtil.toUri("http://developer.android.com/guide/developing/tools/avd.html");
    assertNotNull(uri);
    assertEquals("http", uri.getScheme());
    assertEquals("/guide/developing/tools/avd.html", uri.getRawPath());
    assertEquals("http://developer.android.com/guide/developing/tools/avd.html", uri.toString());

    uri = VfsUtil.toUri("http://developer.android.com/guide/developing/tools/avd.html?f=23r2ewd");
    assertNotNull(uri);
    assertEquals("http", uri.getScheme());
    assertEquals("/guide/developing/tools/avd.html", uri.getRawPath());
    assertEquals(
        "http://developer.android.com/guide/developing/tools/avd.html?f=23r2ewd", uri.toString());
    assertEquals("f=23r2ewd", uri.getQuery());
  }
Example #6
0
    private URI toURI(boolean encode) {

      if (originalUri == null) {
        logger.debug("setUrl hasn't been invoked. Using http://localhost");
        originalUri = DEFAULT_REQUEST_URL;
      }

      AsyncHttpProviderUtils.validateSupportedScheme(originalUri);

      StringBuilder builder = new StringBuilder();
      builder.append(originalUri.getScheme()).append("://").append(originalUri.getAuthority());
      if (isNonEmpty(originalUri.getRawPath())) {
        builder.append(originalUri.getRawPath());
      } else {
        builder.append("/");
      }

      if (isNonEmpty(queryParams)) {

        builder.append("?");

        for (Iterator<Entry<String, List<String>>> i = queryParams.iterator(); i.hasNext(); ) {
          Entry<String, List<String>> param = i.next();
          String name = param.getKey();
          for (Iterator<String> j = param.getValue().iterator(); j.hasNext(); ) {
            String value = j.next();
            if (encode) {
              UTF8UrlEncoder.appendEncoded(builder, name);
            } else {
              builder.append(name);
            }
            if (value != null) {
              builder.append('=');
              if (encode) {
                UTF8UrlEncoder.appendEncoded(builder, value);
              } else {
                builder.append(value);
              }
            }
            if (j.hasNext()) {
              builder.append('&');
            }
          }
          if (i.hasNext()) {
            builder.append('&');
          }
        }
      }

      return URI.create(builder.toString());
    }
Example #7
0
 /**
  * Compares the URI with the given object for equality. If the object is not a <code>URI</code>,
  * then the method returns false. Otherwise, the following criteria are observed:
  *
  * <ul>
  *   <li>The scheme of the URIs must either be null (undefined) in both cases, or equal, ignorant
  *       of case.
  *   <li>The raw fragment of the URIs must either be null (undefined) in both cases, or equal,
  *       ignorant of case.
  *   <li>Both URIs must be of the same type (opaque or hierarchial)
  *   <li><strong>For opaque URIs:</strong>
  *       <ul>
  *         <li>The raw scheme-specific parts must be equal.
  *       </ul>
  *   <li>For hierarchical URIs:
  *       <ul>
  *         <li>The raw paths must be equal, ignorant of case.
  *         <li>The raw queries are either both undefined or both equal, ignorant of case.
  *         <li>The raw authority sections are either both undefined or:
  *         <li><strong>For registry-based authorities:</strong>
  *             <ul>
  *               <li>they are equal.
  *             </ul>
  *         <li><strong>For server-based authorities:</strong>
  *             <ul>
  *               <li>the hosts are equal, ignoring case
  *               <li>the ports are equal
  *               <li>the user information components are equal
  *             </ul>
  *       </ul>
  * </ul>
  *
  * @param obj the obj to compare the URI with.
  * @return <code>true</code> if the objects are equal, according to the specification above.
  */
 public boolean equals(Object obj) {
   if (!(obj instanceof URI)) return false;
   URI uriObj = (URI) obj;
   if (scheme == null) {
     if (uriObj.getScheme() != null) return false;
   } else if (!(scheme.equalsIgnoreCase(uriObj.getScheme()))) return false;
   if (rawFragment == null) {
     if (uriObj.getRawFragment() != null) return false;
   } else if (!(rawFragment.equalsIgnoreCase(uriObj.getRawFragment()))) return false;
   boolean opaqueThis = isOpaque();
   boolean opaqueObj = uriObj.isOpaque();
   if (opaqueThis && opaqueObj)
     return rawSchemeSpecificPart.equals(uriObj.getRawSchemeSpecificPart());
   else if (!opaqueThis && !opaqueObj) {
     boolean common =
         rawPath.equalsIgnoreCase(uriObj.getRawPath())
             && ((rawQuery == null && uriObj.getRawQuery() == null)
                 || rawQuery.equalsIgnoreCase(uriObj.getRawQuery()));
     if (rawAuthority == null && uriObj.getRawAuthority() == null) return common;
     if (host == null) return common && rawAuthority.equalsIgnoreCase(uriObj.getRawAuthority());
     return common
         && host.equalsIgnoreCase(uriObj.getHost())
         && port == uriObj.getPort()
         && (rawUserInfo == null
             ? uriObj.getRawUserInfo() == null
             : rawUserInfo.equalsIgnoreCase(uriObj.getRawUserInfo()));
   } else return false;
 }
Example #8
0
  public static ResteasyUriInfo extractUriInfo(HttpExchange exchange) {
    String host = exchange.getLocalAddress().getHostName();
    if (exchange.getLocalAddress().getPort() != 80 && exchange.getLocalAddress().getPort() != 443) {
      host += ":" + exchange.getLocalAddress().getPort();
    }
    String uri = exchange.getRequestURI().toString();

    String protocol =
        exchange.getHttpContext().getServer() instanceof HttpsServer ? "https" : "http";

    URI absoluteURI = URI.create(protocol + "://" + host + uri);

    String contextPath = exchange.getHttpContext().getPath();
    String path = PathHelper.getEncodedPathInfo(absoluteURI.getRawPath(), contextPath);
    if (!path.startsWith("/")) {
      path = "/" + path;
    }

    URI baseURI = absoluteURI;
    if (!path.trim().equals("")) {
      String tmpContextPath = contextPath;
      if (!tmpContextPath.endsWith("/")) tmpContextPath += "/";
      baseURI =
          UriBuilder.fromUri(absoluteURI).replacePath(tmpContextPath).replaceQuery(null).build();
    } else {
      baseURI = UriBuilder.fromUri(absoluteURI).replaceQuery(null).build();
    }
    URI relativeURI = UriBuilder.fromUri(path).replaceQuery(absoluteURI.getRawQuery()).build();
    // System.out.println("path: " + path);
    // System.out.println("query string: " + request.getQueryString());
    ResteasyUriInfo uriInfo = new ResteasyUriInfo(baseURI, relativeURI);
    return uriInfo;
  }
  @Override
  public UriBuilder schemeSpecificPart(String ssp) {
    if (ssp == null) {
      throw new IllegalArgumentException("Scheme specific part parameter is null");
    }

    // TODO encode or validate scheme specific part
    // This will not work for template variables present in the spp
    StringBuilder sb = new StringBuilder();
    if (scheme != null) {
      sb.append(scheme).append(':');
    }
    if (ssp != null) {
      sb.append(ssp);
    }
    if (fragment != null && fragment.length() > 0) {
      sb.append('#').append(fragment);
    }
    URI uri = createURI(sb.toString());

    if (uri.getRawSchemeSpecificPart() != null && uri.getRawPath() == null) {
      this.ssp = uri.getRawSchemeSpecificPart();
    } else {
      this.ssp = null;

      if (uri.getRawAuthority() != null) {
        if (uri.getRawUserInfo() == null && uri.getHost() == null && uri.getPort() == -1) {
          authority = uri.getRawAuthority();
          userInfo = null;
          host = null;
          port = -1;
        } else {
          authority = null;
          userInfo = uri.getRawUserInfo();
          host = uri.getHost();
          port = uri.getPort();
        }
      }

      path.setLength(0);
      path.append(replaceNull(uri.getRawPath()));

      query.setLength(0);
      query.append(replaceNull(uri.getRawQuery()));
    }
    return this;
  }
Example #10
0
  public void run() {
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "localhost" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
      if (scheme.equalsIgnoreCase("http")) {
        port = 80;
      } else if (scheme.equalsIgnoreCase("https")) {
        port = 443;
      }
    }

    if (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https")) {
      logger.error("Only HTTP(S) is supported.");
      return;
    }

    boolean ssl = scheme.equalsIgnoreCase("https");

    // Configure the client.
    ClientBootstrap bootstrap =
        new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool()));

    // Set up the event pipeline factory.
    bootstrap.setPipelineFactory(new HttpSnoopClientPipelineFactory(ssl));

    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.awaitUninterruptibly().getChannel();
    if (!future.isSuccess()) {
      future.getCause().printStackTrace();
      bootstrap.releaseExternalResources();
      return;
    }

    // Prepare the HTTP request.
    HttpRequest request =
        new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
    request.setHeader(HttpHeaders.Names.HOST, host);
    request.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

    // Set some example cookies.
    CookieEncoder httpCookieEncoder = new CookieEncoder(false);
    httpCookieEncoder.addCookie("my-cookie", "foo");
    httpCookieEncoder.addCookie("another-cookie", "bar");
    request.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());

    // Send the HTTP request.
    channel.write(request);

    // Wait for the server to close the connection.
    channel.getCloseFuture().awaitUninterruptibly();

    // Shut down executor threads to exit.
    bootstrap.releaseExternalResources();
  }
Example #11
0
 @Override
 protected boolean handlesUri(URI resourceUri) {
   if ("tcp".equals(resourceUri.getScheme()) || "tcps".equals(resourceUri.getScheme())) {
     return resourceUri.getHost() != null && resourceUri.getRawPath() == null;
   } else {
     return false;
   }
 }
Example #12
0
  private String encodedRelativePath() {
    if (encodedRelativePath != null) {
      return encodedRelativePath;
    }

    String requestUriRawPath = requestUri.getRawPath();

    if (baseUri == null) {
      return encodedRelativePath = requestUriRawPath;
    }

    final int baseUriRawPathLength = baseUri.getRawPath().length();
    return encodedRelativePath =
        baseUriRawPathLength < requestUriRawPath.length()
            ? requestUriRawPath.substring(baseUriRawPathLength)
            : "";
  }
  public static void newHttpClientBootstrap(String url, ChannelHandler handler) throws Exception {
    URI uri = new URI(url);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
      if ("http".equalsIgnoreCase(scheme)) {
        port = 80;
      } else if ("https".equalsIgnoreCase(scheme)) {
        port = 443;
      }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
      System.err.println("Only HTTP(S) is supported.");
      return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
      sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
      sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .handler(new HttpDownloadertInitializer(sslCtx, handler));
      // Make the connection attempt.
      Channel ch = b.connect(host, port).sync().channel();
      // Prepare the HTTP request.
      HttpRequest request =
          new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
      HttpHeaders headers = request.headers();
      headers.set(HttpHeaders.Names.HOST, host);
      headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
      headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
      // Set some example cookies.
      headers.set(
          HttpHeaders.Names.COOKIE,
          ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo")));
      ch.writeAndFlush(request);
      // Wait for the server to close the connection.
      ch.closeFuture().sync();
      Thread.sleep(1000);
    } finally {
      // Shut down executor threads to exit.
      group.shutdownGracefully();
    }
  }
Example #14
0
 /**
  * Relativizes the given URI against this URI. The following algorithm is used:
  *
  * <ul>
  *   <li>If either URI is opaque, the given URI is returned.
  *   <li>If the schemes of the URIs differ, the given URI is returned.
  *   <li>If the authority components of the URIs differ, then the given URI is returned.
  *   <li>If the path of this URI is not a prefix of the supplied URI, then the given URI is
  *       returned.
  *   <li>If all the above conditions hold, a new URI is created using the query and fragment
  *       components of the given URI, along with a path computed by removing the path of this URI
  *       from the start of the path of the supplied URI.
  * </ul>
  *
  * @param uri the URI to relativize agsint this URI
  * @return the resulting URI
  * @throws NullPointerException if the uri is null
  */
 public URI relativize(URI uri) {
   if (isOpaque() || uri.isOpaque()) return uri;
   if (scheme == null && uri.getScheme() != null) return uri;
   if (scheme != null && !(scheme.equals(uri.getScheme()))) return uri;
   if (rawAuthority == null && uri.getRawAuthority() != null) return uri;
   if (rawAuthority != null && !(rawAuthority.equals(uri.getRawAuthority()))) return uri;
   if (!(uri.getRawPath().startsWith(rawPath))) return uri;
   try {
     return new URI(
         null,
         null,
         uri.getRawPath().substring(rawPath.length()),
         uri.getRawQuery(),
         uri.getRawFragment());
   } catch (URISyntaxException e) {
     throw (Error)
         new InternalError("Relativized URI variant could not " + "be constructed").initCause(e);
   }
 }
Example #15
0
 /**
  * Compare the URI with another object that must also be a URI. Undefined components are taken to
  * be less than any other component. The following criteria are observed:
  *
  * <ul>
  *   <li>Two URIs with different schemes are compared according to their scheme, regardless of
  *       case.
  *   <li>A hierarchical URI is less than an opaque URI with the same scheme.
  *   <li><strong>For opaque URIs:</strong>
  *       <ul>
  *         <li>URIs with differing scheme-specific parts are ordered according to the ordering of
  *             the scheme-specific part.
  *         <li>URIs with the same scheme-specific part are ordered by the raw fragment.
  *       </ul>
  *   <li>For hierarchical URIs:
  *       <ul>
  *         <li>URIs are ordered according to their raw authority sections, if they are unequal.
  *         <li><strong>For registry-based authorities:</strong>
  *             <ul>
  *               <li>they are ordered according to the ordering of the authority component.
  *             </ul>
  *         <li><strong>For server-based authorities:</strong>
  *             <ul>
  *               <li>URIs are ordered according to the raw user information.
  *               <li>URIs with the same user information are ordered by the host, ignoring case.
  *               <lI>URIs with the same host are ordered by the port.
  *             </ul>
  *         <li>URIs with the same authority section are ordered by the raw path.
  *         <li>URIs with the same path are ordered by their raw query.
  *         <li>URIs with the same query are ordered by their raw fragments.
  *       </ul>
  * </ul>
  *
  * @param obj This object to compare this URI with
  * @return a negative integer, zero or a positive integer depending on whether this URI is less
  *     than, equal to or greater than that supplied, respectively.
  * @throws ClassCastException if the given object is not a URI
  */
 public int compareTo(Object obj) throws ClassCastException {
   URI uri = (URI) obj;
   if (scheme == null && uri.getScheme() != null) return -1;
   if (scheme != null) {
     int sCompare = scheme.compareToIgnoreCase(uri.getScheme());
     if (sCompare != 0) return sCompare;
   }
   boolean opaqueThis = isOpaque();
   boolean opaqueObj = uri.isOpaque();
   if (opaqueThis && !opaqueObj) return 1;
   if (!opaqueThis && opaqueObj) return -1;
   if (opaqueThis) {
     int ssCompare = rawSchemeSpecificPart.compareTo(uri.getRawSchemeSpecificPart());
     if (ssCompare == 0) return compareFragments(uri);
     else return ssCompare;
   }
   if (rawAuthority == null && uri.getRawAuthority() != null) return -1;
   if (rawAuthority != null) {
     int aCompare = rawAuthority.compareTo(uri.getRawAuthority());
     if (aCompare != 0) {
       if (host == null) return aCompare;
       if (rawUserInfo == null && uri.getRawUserInfo() != null) return -1;
       int uCompare = rawUserInfo.compareTo(uri.getRawUserInfo());
       if (uCompare != 0) return uCompare;
       if (host == null && uri.getHost() != null) return -1;
       int hCompare = host.compareTo(uri.getHost());
       if (hCompare != 0) return hCompare;
       return new Integer(port).compareTo(new Integer(uri.getPort()));
     }
   }
   if (rawPath == null && uri.getRawPath() != null) return -1;
   if (rawPath != null) {
     int pCompare = rawPath.compareTo(uri.getRawPath());
     if (pCompare != 0) return pCompare;
   }
   if (rawQuery == null && uri.getRawQuery() != null) return -1;
   if (rawQuery != null) {
     int qCompare = rawQuery.compareTo(uri.getRawQuery());
     if (qCompare != 0) return qCompare;
   }
   return compareFragments(uri);
 }
Example #16
0
 /**
  * Update the fragment (encoded) of this MutableUri.
  *
  * @param rawFragment new framgent element (encoded)
  * @throws URISyntaxException if the new equivalent URI is invalid
  */
 public void setRawFragment(String rawFragment) throws URISyntaxException {
   uri =
       create(
           uri.getScheme(),
           uri.getRawUserInfo(),
           uri.getHost(),
           uri.getPort(),
           uri.getRawPath(),
           uri.getRawQuery(),
           rawFragment);
 }
  public Backend getBackend(String elementSE) {
    Backend b = entities.get(elementSE);
    if (b == null) {
      URI uri = URI.create(SSP_DNS_NAME).resolve(elementSE).normalize();
      String path = uri.getRawPath();

      String pathPart = path.substring(0, path.indexOf("/"));
      b = backends.get(pathPart);
    }
    return b;
  }
 /** Convert a java.net.URI to a Uri. */
 public static Uri fromJavaUri(URI uri) {
   if (uri.isOpaque()) {
     throw new IllegalArgumentException("No support for opaque Uris " + uri.toString());
   }
   return new UriBuilder()
       .setScheme(uri.getScheme())
       .setAuthority(uri.getRawAuthority())
       .setPath(uri.getRawPath())
       .setQuery(uri.getRawQuery())
       .setFragment(uri.getRawFragment())
       .toUri();
 }
Example #19
0
File: Mac.java Project: dyglcc/mmwd
  /*
   * makes an access token.
   */
  public String signRequest(HttpPost post) throws AuthException {
    URI uri = post.getURI();
    String path = uri.getRawPath();
    String query = uri.getRawQuery();
    HttpEntity entity = post.getEntity();

    byte[] secretKey = this.secretKey.getBytes();
    javax.crypto.Mac mac = null;
    try {
      mac = javax.crypto.Mac.getInstance("HmacSHA1");
    } catch (NoSuchAlgorithmException e) {
      throw new AuthException("No algorithm called HmacSHA1!", e);
    }

    SecretKeySpec keySpec = new SecretKeySpec(secretKey, "HmacSHA1");
    try {
      mac.init(keySpec);
      mac.update(path.getBytes());
    } catch (InvalidKeyException e) {
      throw new AuthException("You've passed an invalid secret key!", e);
    } catch (IllegalStateException e) {
      throw new AuthException(e);
    }

    if (query != null && query.length() != 0) {
      mac.update((byte) ('?'));
      mac.update(query.getBytes());
    }
    mac.update((byte) '\n');
    if (entity != null) {
      org.apache.http.Header ct = entity.getContentType();
      if (ct != null && ct.getValue() == "application/x-www-form-urlencoded") {
        ByteArrayOutputStream w = new ByteArrayOutputStream();
        try {
          entity.writeTo(w);
        } catch (IOException e) {
          throw new AuthException(e);
        }
        mac.update(w.toByteArray());
      }
    }

    byte[] digest = mac.doFinal();
    byte[] digestBase64 = EncodeUtils.urlsafeEncodeBytes(digest);

    StringBuffer b = new StringBuffer();
    b.append(this.accessKey);
    b.append(':');
    b.append(new String(digestBase64));

    return b.toString();
  }
Example #20
0
  @Override
  public void handleResponse(
      String requestMethod,
      URI requestURI,
      Headers requestHeaders,
      Headers responseHeaders,
      InputStream body)
      throws IOException {

    String path = requestURI.getRawPath();
    if (path.equalsIgnoreCase("/http-bind/")) {
      this.parseChat(body);
    }
  }
 private String extractFullPath(String uriString) {
   URI uri = validateAndConvertToURI(uriString);
   StringBuilder pathBuilder = new StringBuilder(uri.getRawPath());
   String query = uri.getRawQuery();
   if (query != null) {
     pathBuilder.append('?');
     pathBuilder.append(query);
   }
   String fragment = uri.getRawFragment();
   if (fragment != null) {
     pathBuilder.append(fragment);
   }
   return pathBuilder.toString();
 }
Example #22
0
  private URI calculateNewRequestURI(URI newBaseURI, URI requestURI, boolean proxy) {
    String baseURIPath = newBaseURI.getRawPath();
    String reqURIPath = requestURI.getRawPath();

    UriBuilder builder = new UriBuilderImpl().uri(newBaseURI);
    String basePath = reqURIPath.startsWith(baseURIPath) ? baseURIPath : getBaseURI().getRawPath();
    builder.path(reqURIPath.equals(basePath) ? "" : reqURIPath.substring(basePath.length()));

    String newQuery = newBaseURI.getRawQuery();
    if (newQuery == null) {
      builder.replaceQuery(requestURI.getRawQuery());
    } else {
      builder.replaceQuery(newQuery);
    }

    URI newRequestURI = builder.build();

    resetBaseAddress(newBaseURI);
    URI current = proxy ? newBaseURI : newRequestURI;
    resetCurrentBuilder(current);

    return newRequestURI;
  }
Example #23
0
  private URI buildURI(String url) {
    URI uri = URI.create(url);

    if (uri.getRawPath() == null) {
      // AHC-96
      // Let's try to derive it
      StringBuilder buildedUrl = new StringBuilder();

      if (uri.getScheme() != null) {
        buildedUrl.append(uri.getScheme());
        buildedUrl.append("://");
      }

      if (uri.getAuthority() != null) {
        buildedUrl.append(uri.getAuthority());
      }
      if (url.indexOf("://") == -1) {
        String s = buildedUrl.toString();
        url = s + url.substring(uri.getScheme().length() + 1);
        return buildURI(url);
      } else {
        throw new IllegalArgumentException("Invalid url " + uri.toString());
      }
    }

    if (isNonEmpty(uri.getRawQuery())) {
      String[] queries = uri.getRawQuery().split("&");
      int pos;
      for (String query : queries) {
        pos = query.indexOf('=');
        if (pos <= 0) {
          addQueryParameter(query, null);
        } else {
          try {
            if (useRawUrl) {
              addQueryParameter(query.substring(0, pos), query.substring(pos + 1));
            } else {
              addQueryParameter(
                  URLDecoder.decode(query.substring(0, pos), "UTF-8"),
                  URLDecoder.decode(query.substring(pos + 1), "UTF-8"));
            }
          } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
          }
        }
      }
    }
    return uri;
  }
Example #24
0
 @Override
 public boolean matches(HttpRequest request) {
   URI uri = URI.create(request.getRequestLine().getUri());
   if (method != null && !method.equals(request.getRequestLine().getMethod())) {
     return false;
   }
   if (hostname != null && !hostname.equals(uri.getHost())) {
     return false;
   }
   if (path != null && !path.equals(uri.getRawPath())) {
     return false;
   }
   if (noParams && !uri.getRawQuery().equals(null)) {
     return false;
   }
   if (params.size() > 0) {
     Map<String, String> requestParams = ParamsParser.parseParams(request);
     if (!requestParams.equals(params)) {
       return false;
     }
   }
   if (headers.size() > 0) {
     Map<String, String> actualRequestHeaders = new HashMap<>();
     for (Header header : request.getAllHeaders()) {
       actualRequestHeaders.put(header.getName(), header.getValue());
     }
     if (!headers.equals(actualRequestHeaders)) {
       return false;
     }
   }
   if (postBodyMatcher != null) {
     if (!(request instanceof HttpEntityEnclosingRequestBase)) {
       return false;
     }
     HttpEntityEnclosingRequestBase postOrPut = (HttpEntityEnclosingRequestBase) request;
     try {
       if (!postBodyMatcher.matches(postOrPut.getEntity())) {
         return false;
       }
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
   }
   return true;
 }
Example #25
0
  public URIPattern(URI uri) {
    this.pattern = uri;

    Map<String, String> accumulator = Maps.newHashMap();
    if (pattern.isOpaque()) {
      Iterator<String> pathQuery =
          PATH_QUERY_SPLITTER.split(pattern.getSchemeSpecificPart()).iterator();
      this.patternPath = Iterators.getNext(pathQuery, null);
      addQuery(Iterators.getNext(pathQuery, null), accumulator);
    } else {
      patternPath = pattern.getRawPath();
      addQuery(pattern.getRawQuery(), accumulator);
      addAuthority(pattern, accumulator);
    }
    if (pattern.getScheme() != null) {
      accumulator.put(SCHEME, pattern.getScheme());
    }
    this.defaults = ImmutableMap.copyOf(accumulator);
  }
  /**
   * Convenience method for setting the fields in an AMQP URI: host, port, username, password and
   * virtual host. If any part of the URI is ommited, the ConnectionFactory's corresponding variable
   * is left unchanged.
   *
   * @param uri is the AMQP URI containing the data
   */
  public void setUri(URI uri)
      throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException {
    if ("amqp".equals(uri.getScheme().toLowerCase())) {
      // nothing special to do
    } else if ("amqps".equals(uri.getScheme().toLowerCase())) {
      setPort(DEFAULT_AMQP_OVER_SSL_PORT);
      useSslProtocol();
    } else {
      throw new IllegalArgumentException("Wrong scheme in AMQP URI: " + uri.getScheme());
    }

    String host = uri.getHost();
    if (host != null) {
      setHost(host);
    }

    int port = uri.getPort();
    if (port != -1) {
      setPort(port);
    }

    String userInfo = uri.getRawUserInfo();
    if (userInfo != null) {
      String userPass[] = userInfo.split(":");
      if (userPass.length > 2) {
        throw new IllegalArgumentException("Bad user info in AMQP " + "URI: " + userInfo);
      }

      setUsername(uriDecode(userPass[0]));
      if (userPass.length == 2) {
        setPassword(uriDecode(userPass[1]));
      }
    }

    String path = uri.getRawPath();
    if (path != null && path.length() > 0) {
      if (path.indexOf('/', 1) != -1) {
        throw new IllegalArgumentException("Multiple segments in " + "path of AMQP URI: " + path);
      }

      setVirtualHost(uriDecode(uri.getPath().substring(1)));
    }
  }
  private static MockHttpRequest initWithUri(URI absoluteUri, URI baseUri) {
    if (baseUri == null) baseUri = EMPTY_URI;
    MockHttpRequest request = new MockHttpRequest();
    request.httpHeaders = new ResteasyHttpHeaders(new CaseInsensitiveMap<String>());
    // request.uri = new UriInfoImpl(absoluteUri, absoluteUri, absoluteUri.getPath(),
    // absoluteUri.getQuery(), PathSegmentImpl.parseSegments(absoluteUri.getPath()));

    // remove query part
    URI absolutePath = UriBuilder.fromUri(absoluteUri).replaceQuery(null).build();
    // path must be relative to the application's base uri
    URI relativeUri = baseUri.relativize(absoluteUri);
    relativeUri =
        UriBuilder.fromUri(relativeUri.getRawPath())
            .replaceQuery(absoluteUri.getRawQuery())
            .build();

    request.uri = new ResteasyUriInfo(baseUri, relativeUri);
    return request;
  }
Example #28
0
 public String normalizeRequestUrl() throws URISyntaxException {
   URI uri = new URI(request.getRequestUrl());
   String scheme = uri.getScheme().toLowerCase();
   String authority = uri.getAuthority().toLowerCase();
   boolean dropPort =
       (scheme.equals("http") && uri.getPort() == 80)
           || (scheme.equals("https") && uri.getPort() == 443);
   if (dropPort) {
     // find the last : in the authority
     int index = authority.lastIndexOf(":");
     if (index >= 0) {
       authority = authority.substring(0, index);
     }
   }
   String path = uri.getRawPath();
   if (path == null || path.length() <= 0) {
     path = "/"; // conforms to RFC 2616 section 3.2.2
   }
   // we know that there is no query and no fragment here.
   return scheme + "://" + authority + path;
 }
  private Realm ntlmChallenge(
      List<String> wwwAuth,
      Request request,
      ProxyServer proxyServer,
      FluentCaseInsensitiveStringsMap headers,
      Realm realm,
      NettyResponseFuture<?> future)
      throws NTLMEngineException {

    boolean useRealm = proxyServer == null && realm != null;

    String ntlmDomain = useRealm ? realm.getNtlmDomain() : proxyServer.getNtlmDomain();
    String ntlmHost = useRealm ? realm.getNtlmHost() : proxyServer.getHost();
    String principal = useRealm ? realm.getPrincipal() : proxyServer.getPrincipal();
    String password = useRealm ? realm.getPassword() : proxyServer.getPassword();

    if (realm != null && !realm.isNtlmMessageType2Received()) {
      String challengeHeader = NTLMEngine.INSTANCE.generateType1Msg(ntlmDomain, ntlmHost);

      URI uri = request.getURI();
      addNTLMAuthorizationHeader(headers, challengeHeader);
      future.getAndSetAuth(false);
      return newRealmBuilder(realm) //
          .setScheme(realm.getAuthScheme()) //
          .setUri(uri.getRawPath()) //
          .setMethodName(request.getMethod()) //
          .setNtlmMessageType2Received(true) //
          .build();

    } else {
      addType3NTLMAuthorizationHeader(wwwAuth, headers, principal, password, ntlmDomain, ntlmHost);
      Realm.AuthScheme authScheme = realm != null ? realm.getAuthScheme() : Realm.AuthScheme.NTLM;
      return newRealmBuilder(realm) //
          .setScheme(authScheme) //
          .setUri(request.getURI().getPath()) //
          .setMethodName(request.getMethod()) //
          .build();
    }
  }
 private void setHeaders(MultivaluedMap<String, Object> headers) {
   this.headers = headers;
   Object location = headers.getFirst(HttpHeaders.LOCATION);
   if (location != null) {
     if (location instanceof URI) {
       final URI locationUri = (URI) location;
       if (!locationUri.isAbsolute()) {
         final URI base =
             (statusType.getStatusCode() == Status.CREATED.getStatusCode())
                 ? request.getAbsolutePath()
                 : request.getBaseUri();
         location =
             UriBuilder.fromUri(base)
                 .path(locationUri.getRawPath())
                 .replaceQuery(locationUri.getRawQuery())
                 .fragment(locationUri.getRawFragment())
                 .build();
       }
       headers.putSingle(HttpHeaders.LOCATION, location);
     }
   }
 }