Example #1
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;
 }
  @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;
  }
  /**
   * Creates the HttpMethod to use to call the remote server, either its GET or POST.
   *
   * @param exchange the exchange
   * @return the created method as either GET or POST
   * @throws CamelExchangeException is thrown if error creating RequestEntity
   */
  @SuppressWarnings("deprecation")
  protected HttpMethod createMethod(Exchange exchange) throws Exception {
    // creating the url to use takes 2-steps
    String url = HttpHelper.createURL(exchange, getEndpoint());
    URI uri = HttpHelper.createURI(exchange, url, getEndpoint());
    // get the url and query string from the uri
    url = uri.toASCIIString();
    String queryString = uri.getRawQuery();

    // execute any custom url rewrite
    String rewriteUrl = HttpHelper.urlRewrite(exchange, url, getEndpoint(), this);
    if (rewriteUrl != null) {
      // update url and query string from the rewritten url
      url = rewriteUrl;
      uri = new URI(url);
      // use raw query to have uri decimal encoded which http client requires
      queryString = uri.getRawQuery();
    }

    // remove query string as http client does not accept that
    if (url.indexOf('?') != -1) {
      url = url.substring(0, url.indexOf('?'));
    }

    // create http holder objects for the request
    RequestEntity requestEntity = createRequestEntity(exchange);
    HttpMethods methodToUse =
        HttpHelper.createMethod(exchange, getEndpoint(), requestEntity != null);
    HttpMethod method = methodToUse.createMethod(url);
    if (queryString != null) {
      // need to encode query string
      queryString = UnsafeUriCharactersEncoder.encode(queryString);
      method.setQueryString(queryString);
    }

    LOG.trace("Using URL: {} with method: {}", url, method);

    if (methodToUse.isEntityEnclosing()) {
      ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
      if (requestEntity != null && requestEntity.getContentType() == null) {
        LOG.debug("No Content-Type provided for URL: {} with exchange: {}", url, exchange);
      }
    }

    // there must be a host on the method
    if (method.getHostConfiguration().getHost() == null) {
      throw new IllegalArgumentException(
          "Invalid uri: "
              + url
              + ". If you are forwarding/bridging http endpoints, then enable the bridgeEndpoint option on the endpoint: "
              + getEndpoint());
    }

    return method;
  }
Example #5
0
  public FileChunk get() throws IOException {
    if (useLocalFile) {
      startTime = System.currentTimeMillis();
      finishTime = System.currentTimeMillis();
      state = TajoProtos.FetcherState.FETCH_FINISHED;
      return fileChunk;
    }

    this.startTime = System.currentTimeMillis();
    this.state = TajoProtos.FetcherState.FETCH_FETCHING;
    ChannelFuture future = null;
    try {
      future =
          bootstrap
              .clone()
              .connect(new InetSocketAddress(host, port))
              .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);

      // Wait until the connection attempt succeeds or fails.
      Channel channel = future.awaitUninterruptibly().channel();
      if (!future.isSuccess()) {
        state = TajoProtos.FetcherState.FETCH_FAILED;
        throw new IOException(future.cause());
      }

      String query = uri.getPath() + (uri.getRawQuery() != null ? "?" + uri.getRawQuery() : "");
      // Prepare the HTTP request.
      HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, query);
      request.headers().set(HttpHeaders.Names.HOST, host);
      request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
      request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

      LOG.info("Status: " + getState() + ", URI:" + uri);
      // Send the HTTP request.
      channel.writeAndFlush(request);

      // Wait for the server to close the connection. throw exception if failed
      channel.closeFuture().syncUninterruptibly();

      fileChunk.setLength(fileChunk.getFile().length());
      return fileChunk;
    } finally {
      if (future != null && future.channel().isOpen()) {
        // Close the channel to exit.
        future.channel().close().awaitUninterruptibly();
      }

      this.finishTime = System.currentTimeMillis();
      LOG.info(
          "Fetcher finished:" + (finishTime - startTime) + " ms, " + getState() + ", URI:" + uri);
    }
  }
Example #6
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;
  }
  public URI generateRedirectUri(String samlParameterName, String redirectUri, Document document)
      throws ConfigurationException, ProcessingException, IOException {
    KeycloakUriBuilder builder =
        KeycloakUriBuilder.fromUri(redirectUri)
            .replaceQuery(null)
            .queryParam(samlParameterName, base64Encoded(document));
    if (relayState != null) {
      builder.queryParam("RelayState", relayState);
    }

    if (sign) {
      builder.queryParam(
          GeneralConstants.SAML_SIG_ALG_REQUEST_KEY, signatureAlgorithm.getXmlSignatureMethod());
      URI uri = builder.build();
      String rawQuery = uri.getRawQuery();
      Signature signature = signatureAlgorithm.createSignature();
      byte[] sig = new byte[0];
      try {
        signature.initSign(signingKeyPair.getPrivate());
        signature.update(rawQuery.getBytes("UTF-8"));
        sig = signature.sign();
      } catch (InvalidKeyException | UnsupportedEncodingException | SignatureException e) {
        throw new ProcessingException(e);
      }
      String encodedSig = RedirectBindingUtil.base64URLEncode(sig);
      builder.queryParam(GeneralConstants.SAML_SIGNATURE_REQUEST_KEY, encodedSig);
    }
    return builder.build();
  }
Example #8
0
 /**
  * Ctor.
  *
  * @param txt Text of the link
  * @todo #558:30min Href ctor. According to new qulice version, constructor must contain only
  *     variables initialization and other constructor calls. Refactor code according to that rule
  *     and remove `ConstructorOnlyInitializesOrCallOtherConstructors` warning suppression.
  */
 @SuppressWarnings({
   "PMD.AvoidInstantiatingObjectsInLoops",
   "PMD.ConstructorOnlyInitializesOrCallOtherConstructors"
 })
 public Href(final CharSequence txt) {
   this.params = new ConcurrentHashMap<String, List<String>>(0);
   final URI link = Href.createURI(txt.toString());
   final String query = link.getRawQuery();
   if (query == null) {
     this.uri = link;
   } else {
     final String href = link.toString();
     this.uri = URI.create(href.substring(0, href.length() - query.length() - 1));
     final String[] pairs = query.split("&");
     for (final String pair : pairs) {
       final String[] parts = pair.split("=", 2);
       final String key = Href.decode(parts[0]);
       final String value;
       if (parts.length > 1) {
         value = Href.decode(parts[1]);
       } else {
         value = "";
       }
       this.params.putIfAbsent(key, new LinkedList<String>());
       this.params.get(key).add(value);
     }
   }
 }
  /**
   * Maps ugly urls to pretty urls as specified in the Google specification for Making AJAX
   * Applications Crawlable:
   * https://developers.google.com/webmasters/ajax-crawling/docs/specification?hl=en
   *
   * @param ugly the ugly url that the search engine crawler is requesting
   * @return pretty url
   */
  public static URI uglyToPretty(URI ugly) {
    String uglyQuery = ugly.getRawQuery();
    List<NameValuePair> uglyParams = URLEncodedUtils.parse(uglyQuery, Charset.forName("utf-8"));
    URIBuilder uriBuilder = new URIBuilder(ugly);

    // rebuild the query using the rules from Google's Spec.
    uriBuilder.removeQuery();
    for (NameValuePair uglyParamPair : uglyParams) {
      String lowerCaseParamName = uglyParamPair.getName().toLowerCase(Locale.ENGLISH);
      if (SEARCHBOT_ESCAPED_FRAGMENT_PARAM_NAME.equals(lowerCaseParamName)) {
        String fragmentValue = uglyParamPair.getValue();
        if (!fragmentValue.isEmpty()) {
          uriBuilder.setFragment(BANG + uglyParamPair.getValue());
        }
      } else {
        uriBuilder.addParameter(uglyParamPair.getName(), uglyParamPair.getValue());
      }
    }

    URI builtUri;
    try {
      builtUri = uriBuilder.build();
    } catch (URISyntaxException ex) {
      throw new IllegalArgumentException(ex);
    }

    return builtUri;
  }
Example #10
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;
  }
Example #11
0
  private void parseGetParameters(HttpExchange exchange) throws UnsupportedEncodingException {

    Map<String, Object> parameters = new HashMap<String, Object>();
    URI requestedUri = exchange.getRequestURI();
    String query = requestedUri.getRawQuery();
    parseQuery(query, parameters);
    exchange.setAttribute("parameters", parameters);
  }
  /**
   * Run the query that has been set up in this instance. Next step would be to get the results with
   * {@link getQueryResult()}
   */
  public void doQuery() {
    DefaultHttpClient client = new DefaultHttpClient();

    client
        .getCredentialsProvider()
        .setCredentials(
            new AuthScope(_targetHost.getHostName(), _targetHost.getPort()),
            new UsernamePasswordCredentials(this.getAppid(), this.getAppid()));

    URI uri;
    try {
      String full_path = getQueryPath();
      String full_query = getUrlQuery();
      uri = new URI(AZURESEARCH_SCHEME, AZURESEARCH_AUTHORITY, full_path, full_query, null);
      // Bing and java URI disagree about how to represent + in query
      // parameters. This is what we have to do instead...
      uri =
          new URI(
              uri.getScheme()
                  + "://"
                  + uri.getAuthority()
                  + uri.getPath()
                  + "?"
                  + uri.getRawQuery().replace("+", "%2b"));

      // log.log(Level.WARNING, uri.toString());
    } catch (URISyntaxException e1) {
      e1.printStackTrace();
      return;
    }

    HttpGet get = new HttpGet(uri);

    get.addHeader("Accept", "application/xml");
    get.addHeader("Content-Type", "application/xml");

    try {
      _responsePost = client.execute(get);
      _resEntity = _responsePost.getEntity();

      if (this.getProcessHTTPResults()) {
        _rawResult = loadXMLFromStream(_resEntity.getContent());
        this.loadResultsFromRawResults();
      }

      // Adding an automatic HTTP Result to String really requires
      // Apache Commons IO. That would break
      // Android compatibility. I'm not going to do that unless I
      // re-implement IOUtils.
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (IllegalStateException e) {
      e.printStackTrace();
    }
  }
Example #13
0
 /**
  * Returns a list of {@link NameValuePair NameValuePairs} as built from the URI's query portion.
  * For example, a URI of http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three
  * NameValuePairs, one for a=1, one for b=2, and one for c=3.
  *
  * <p>This is typically useful while parsing an HTTP PUT.
  *
  * @param uri uri to parse
  * @param encoding encoding to use while parsing the query
  */
 public static List<NameValuePair> parse(final URI uri, final String encoding) {
   List<NameValuePair> result = Collections.emptyList();
   final String query = uri.getRawQuery();
   if (query != null && query.length() > 0) {
     result = new ArrayList<NameValuePair>();
     parse(result, new Scanner(query), encoding);
   }
   return result;
 }
Example #14
0
 private static String ensureNonemptyUrlPath(String url) {
   if (url == null) return null;
   final URI uri = URI.create(url);
   if (uri.getPath().isEmpty()) {
     url = uri.getScheme() + "://" + uri.getRawAuthority() + '/';
     if (uri.getRawQuery() != null) url += '?' + uri.getQuery();
   }
   return url;
 }
Example #15
0
  public static ResteasyUriInfo extractUriInfo(
      HttpRequest request, String contextPath, String protocol) {
    String host = HttpHeaders.getHost(request, "unknown");
    String uri = request.getUri();

    String uriString = protocol + "://" + host + uri;
    URI absoluteURI = URI.create(uriString);
    URI noQuery = UriBuilder.fromUri(uriString).replaceQuery(null).build();
    return new ResteasyUriInfo(uriString, absoluteURI.getRawQuery(), contextPath);
  }
Example #16
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 #17
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);
 }
Example #18
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;
  }
 /** 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 #20
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();
  }
 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;
  }
 /**
  * Returns a list of {@link NameValuePair NameValuePairs} as built from the URI's query portion.
  * For example, a URI of http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three
  * NameValuePairs, one for a=1, one for b=2, and one for c=3.
  *
  * <p>This is typically useful while parsing an HTTP PUT.
  *
  * @param uri uri to parse
  * @param encoding encoding to use while parsing the query
  */
 @DSGenerator(
     tool_name = "Doppelganger",
     tool_version = "2.0",
     generated_on = "2013-12-30 13:01:44.452 -0500",
     hash_original_method = "75763A91BDF0B02A517E106BC03551A8",
     hash_generated_method = "9C1AB2355DE68597D0C7FD33A48C9930")
 public static List<NameValuePair> parse(final URI uri, final String encoding) {
   List<NameValuePair> result = Collections.emptyList();
   final String query = uri.getRawQuery();
   if (query != null && query.length() > 0) {
     result = new ArrayList<NameValuePair>();
     parse(result, new Scanner(query), encoding);
   }
   return result;
 }
 private void addQueryParameters(URI uri) {
   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), StandardCharsets.UTF_8.name()),
                 URLDecoder.decode(query.substring(pos + 1), StandardCharsets.UTF_8.name()));
           }
         } catch (UnsupportedEncodingException e) {
           throw new RuntimeException(e);
         }
       }
     }
   }
 }
Example #25
0
 /**
  * Creates the URI to invoke.
  *
  * @param exchange the exchange
  * @param url the url to invoke
  * @param endpoint the endpoint
  * @return the URI to invoke
  */
 public static URI createURI(Exchange exchange, String url, NettyHttpEndpoint endpoint)
     throws URISyntaxException {
   URI uri = new URI(url);
   // is a query string provided in the endpoint URI or in a header (header overrules endpoint)
   String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
   if (queryString == null) {
     // use raw as we encode just below
     queryString = uri.getRawQuery();
   }
   if (queryString != null) {
     // need to encode query string
     queryString = UnsafeUriCharactersEncoder.encodeHttpURI(queryString);
     uri = URISupport.createURIWithQuery(uri, queryString);
   }
   return uri;
 }
  @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 #27
0
  private URI rewriteUri(URI uri) {
    assert _serviceName.equals(LoadBalancerUtil.getServiceNameFromUri(uri));

    String path = LoadBalancerUtil.getRawPathFromUri(uri);

    UriBuilder builder = UriBuilder.fromUri(_uri);
    if (path != null) {
      builder.path(path);
    }
    builder.replaceQuery(uri.getRawQuery());
    builder.fragment(uri.getRawFragment());
    URI rewrittenUri = builder.build();

    debug(_log, "rewrite uri ", uri, " -> ", rewrittenUri);

    return rewrittenUri;
  }
Example #28
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 #29
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 #30
0
 private static Map<String, List<String>> getRequestParameters(final URI requestUri) {
   final Map<String, List<String>> requestParameters = new LinkedHashMap<>();
   final String requestQuery = requestUri.getRawQuery();
   if (requestQuery != null) {
     final String[] rawRequestParameters = requestQuery.split("[&;]", -1);
     for (final String rawRequestParameter : rawRequestParameters) {
       final String[] requestParameter = rawRequestParameter.split("=", 2);
       final String requestParameterName = decodeUrlComponent(requestParameter[0]);
       List<String> parameters = new ArrayList<>();
       for (final String value : requestParameter[1].split("[,]", -1)) {
         System.out.println("value = " + value);
         final String requestParameterValue = decodeUrlComponent(value);
         parameters.add(requestParameterValue);
       }
       requestParameters.put(requestParameterName, parameters);
     }
   }
   return requestParameters;
 }