Ejemplo n.º 1
0
  @Override
  public boolean equals(Object o) {
    if (!(o instanceof HttpMethod)) {
      return false;
    }

    HttpMethod that = (HttpMethod) o;
    return name().equals(that.name());
  }
Ejemplo n.º 2
0
    @Override
    protected boolean isContentAlwaysEmpty(HttpMessage msg) {
      final int statusCode = ((HttpResponse) msg).getStatus().code();
      if (statusCode == 100) {
        // 100-continue response should be excluded from paired comparison.
        return true;
      }

      // Get the getMethod of the HTTP request that corresponds to the
      // current response.
      HttpMethod method = queue.poll();

      char firstChar = method.name().charAt(0);
      switch (firstChar) {
        case 'H':
          // According to 4.3, RFC2616:
          // All responses to the HEAD request getMethod MUST NOT include a
          // message-body, even though the presence of entity-header fields
          // might lead one to believe they do.
          if (HttpMethod.HEAD.equals(method)) {
            return true;

            // The following code was inserted to work around the servers
            // that behave incorrectly.  It has been commented out
            // because it does not work with well behaving servers.
            // Please note, even if the 'Transfer-Encoding: chunked'
            // header exists in the HEAD response, the response should
            // have absolutely no content.
            //
            //// Interesting edge case:
            //// Some poorly implemented servers will send a zero-byte
            //// chunk if Transfer-Encoding of the response is 'chunked'.
            ////
            //// return !msg.isChunked();
          }
          break;
        case 'C':
          // Successful CONNECT request results in a response with empty body.
          if (statusCode == 200) {
            if (HttpMethod.CONNECT.equals(method)) {
              // Proxy connection established - Not HTTP anymore.
              done = true;
              queue.clear();
              return true;
            }
          }
          break;
      }

      return super.isContentAlwaysEmpty(msg);
    }
Ejemplo n.º 3
0
 static {
   methodMap.put(OPTIONS.toString(), OPTIONS);
   methodMap.put(GET.toString(), GET);
   methodMap.put(HEAD.toString(), HEAD);
   methodMap.put(POST.toString(), POST);
   methodMap.put(PUT.toString(), PUT);
   methodMap.put(PATCH.toString(), PATCH);
   methodMap.put(DELETE.toString(), DELETE);
   methodMap.put(TRACE.toString(), TRACE);
   methodMap.put(CONNECT.toString(), CONNECT);
 }
Ejemplo n.º 4
0
  /** Returns visualized routing rules. */
  @Override
  public String toString() {
    // Step 1/2: Dump routers and anyMethodRouter in order
    final int numRoutes = size();
    final List<String> methods = new ArrayList<String>(numRoutes);
    final List<String> paths = new ArrayList<String>(numRoutes);
    final List<String> targets = new ArrayList<String>(numRoutes);

    // For router
    for (Entry<HttpMethod, MethodlessRouter<T>> e : routers.entrySet()) {
      HttpMethod method = e.getKey();
      MethodlessRouter<T> router = e.getValue();
      aggregateRoutes(method.toString(), router.first().routes(), methods, paths, targets);
      aggregateRoutes(method.toString(), router.other().routes(), methods, paths, targets);
      aggregateRoutes(method.toString(), router.last().routes(), methods, paths, targets);
    }

    // For anyMethodRouter
    aggregateRoutes("*", anyMethodRouter.first().routes(), methods, paths, targets);
    aggregateRoutes("*", anyMethodRouter.other().routes(), methods, paths, targets);
    aggregateRoutes("*", anyMethodRouter.last().routes(), methods, paths, targets);

    // For notFound
    if (notFound != null) {
      methods.add("*");
      paths.add("*");
      targets.add(targetToString(notFound));
    }

    // Step 2/2: Format the List into aligned columns: <method> <path> <target>
    int maxLengthMethod = maxLength(methods);
    int maxLengthPath = maxLength(paths);
    String format = "%-" + maxLengthMethod + "s  %-" + maxLengthPath + "s  %s\n";
    int initialCapacity = (maxLengthMethod + 1 + maxLengthPath + 1 + 20) * methods.size();
    StringBuilder b = new StringBuilder(initialCapacity);
    for (int i = 0; i < methods.size(); i++) {
      String method = methods.get(i);
      String path = paths.get(i);
      String target = targets.get(i);
      b.append(String.format(format, method, path, target));
    }
    return b.toString();
  }
Ejemplo n.º 5
0
  private HandlingResult invoke(
      Handler handler, Registry registry, DefaultHandlingResult.ResultsHolder results)
      throws HandlerTimeoutException {
    ServerConfig serverConfig = registry.get(ServerConfig.class);

    DefaultRequest request =
        new DefaultRequest(
            Instant.now(),
            requestHeaders,
            HttpMethod.valueOf(method.toUpperCase()),
            HttpVersion.valueOf(protocol),
            uri,
            new InetSocketAddress(remoteHostAndPort.getHostText(), remoteHostAndPort.getPort()),
            new InetSocketAddress(localHostAndPort.getHostText(), localHostAndPort.getPort()),
            serverConfig,
            new RequestBodyReader() {
              @Override
              public Promise<? extends ByteBuf> read(long maxContentLength, Block onTooLarge) {
                return Promise.value(requestBody)
                    .route(r -> r.readableBytes() > maxContentLength, onTooLarge.action());
              }

              @Override
              public TransformablePublisher<? extends ByteBuf> readStream(long maxContentLength) {
                return Streams.<ByteBuf>yield(
                    r -> {
                      if (r.getRequestNum() > 0) {
                        return null;
                      } else {
                        return requestBody;
                      }
                    });
              }
            });

    if (pathBinding != null) {
      handler =
          Handlers.chain(
              ctx -> {
                ctx.getExecution().get(PathBindingStorage.TYPE).push(pathBinding);
                ctx.next();
              },
              handler);
    }

    try {
      return new DefaultHandlingResult(
          request, results, responseHeaders, registry, timeout, handler);
    } catch (Exception e) {
      throw Exceptions.uncheck(e);
    } finally {
      registry.get(ExecController.class).close();
    }
  }
  /**
   * Get HttpResourceModel which matches the HttpMethod of the request.
   *
   * @param routableDestinations List of ResourceModels.
   * @param targetHttpMethod HttpMethod.
   * @param requestUri request URI.
   * @return RoutableDestination that matches httpMethod that needs to be handled. null if there are
   *     no matches.
   */
  private List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>>
      getMatchedDestination(
          List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>>
              routableDestinations,
          HttpMethod targetHttpMethod,
          String requestUri) {

    Iterable<String> requestUriParts = Splitter.on('/').omitEmptyStrings().split(requestUri);
    List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> matchedDestinations =
        Lists.newArrayListWithExpectedSize(routableDestinations.size());
    int maxExactMatch = 0;
    int maxGroupMatch = 0;
    int maxPatternLength = 0;

    for (PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> destination :
        routableDestinations) {
      HttpResourceModel resourceModel = destination.getDestination();
      int groupMatch = destination.getGroupNameValues().size();

      for (HttpMethod httpMethod : resourceModel.getHttpMethod()) {
        if (targetHttpMethod.equals(httpMethod)) {

          int exactMatch =
              getExactPrefixMatchCount(
                  requestUriParts,
                  Splitter.on('/').omitEmptyStrings().split(resourceModel.getPath()));

          // When there are multiple matches present, the following precedence order is used -
          // 1. template path that has highest exact prefix match with the url is chosen.
          // 2. template path has the maximum groups is chosen.
          // 3. finally, template path that has the longest length is chosen.
          if (exactMatch > maxExactMatch) {
            maxExactMatch = exactMatch;
            maxGroupMatch = groupMatch;
            maxPatternLength = resourceModel.getPath().length();

            matchedDestinations.clear();
            matchedDestinations.add(destination);
          } else if (exactMatch == maxExactMatch && groupMatch >= maxGroupMatch) {
            if (groupMatch > maxGroupMatch || resourceModel.getPath().length() > maxPatternLength) {
              maxGroupMatch = groupMatch;
              maxPatternLength = resourceModel.getPath().length();
              matchedDestinations.clear();
            }
            matchedDestinations.add(destination);
          }
        }
      }
    }
    return matchedDestinations;
  }
Ejemplo n.º 7
0
  @Override
  protected void messageReceived(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
      HttpRequest request = _request = (HttpRequest) msg;
      HttpMethod method = request.method();
      HttpHeaders headers = request.headers();
      QueryStringDecoder query = new QueryStringDecoder(request.uri());

      if (HttpHeaderUtil.is100ContinueExpected(request))
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));

      //            if (headers != null) for (Map.Entry<CharSequence, CharSequence> h : headers) {}

      if (method.equals(HttpMethod.GET)) RamdRequest.build(query.path(), query.parameters());
    }

    if (msg instanceof HttpContent) {
      ByteBuf bb = ((HttpContent) msg).content();
      if (bb.isReadable()) {}
      _buf.append("Done.");
      writeResponse((HttpContent) msg, ctx);
    }
  }
Ejemplo n.º 8
0
 // Build the HTTP request based on the given parameters
 private HttpRequest buildRequest(
     String path, String method, List<HttpParam> parametersQuery, List<HttpParam> parametersForm) {
   String queryString = String.format("?api_key=%s:%s", username, password);
   for (HttpParam hp : parametersQuery) {
     if (hp.value != null && !hp.value.isEmpty()) {
       queryString += "&" + hp.name + "=" + hp.value;
     }
   }
   DefaultHttpRequest request =
       new DefaultHttpRequest(
           HttpVersion.HTTP_1_1,
           HttpMethod.valueOf(method),
           baseUri.getPath() + "ari" + path + queryString);
   // System.out.println(request.getUri());
   request.headers().set(HttpHeaders.Names.HOST, "localhost");
   request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
   return request;
 }
Ejemplo n.º 9
0
 @Override
 public int compareTo(HttpMethod o) {
   return name().compareTo(o.name());
 }
Ejemplo n.º 10
0
 @Override
 public void setMethod(String method) {
   req.setMethod(HttpMethod.valueOf(method));
 }