@Override
  public void handle(RoutingContext context) {
    HttpServerRequest req = context.request();
    String remainingPath = Utils.pathOffset(req.path(), context);

    if (req.method() != HttpMethod.GET && req.method() != HttpMethod.POST) {
      context.next();
    }

    JSONAware json = null;
    try {
      // Check access policy
      requestHandler.checkAccess(
          req.remoteAddress().host(), req.remoteAddress().host(), getOriginOrReferer(req));
      if (req.method() == HttpMethod.GET) {
        json = requestHandler.handleGetRequest(req.uri(), remainingPath, getParams(req.params()));
      } else {
        Arguments.require(
            context.getBody() != null, "Missing body, make sure that BodyHandler is used before");
        // TODO how to get Stream ?
        InputStream inputStream = new ByteBufInputStream(context.getBody().getByteBuf());
        json =
            requestHandler.handlePostRequest(
                req.uri(), inputStream, StandardCharsets.UTF_8.name(), getParams(req.params()));
      }
    } catch (Throwable exp) {
      json =
          requestHandler.handleThrowable(
              exp instanceof RuntimeMBeanException
                  ? ((RuntimeMBeanException) exp).getTargetException()
                  : exp);
    } finally {
      if (json == null)
        json =
            requestHandler.handleThrowable(
                new Exception("Internal error while handling an exception"));

      context
          .response()
          .setStatusCode(getStatusCode(json))
          .putHeader(HttpHeaders.CONTENT_TYPE, contentType)
          .end(json.toJSONString());
    }
  }
Exemplo n.º 2
0
  public HttpRequest createRequest(
      final HttpServerRequest request,
      final Buffer buffer,
      final CopyOnWriteArrayList<HttpResponseDecorator> decorators,
      final HttpResponseCreator httpResponseCreator) {

    final MultiMap<String, String> headers =
        request.headers().size() == 0 ? MultiMap.empty() : new MultiMapWrapper(request.headers());

    final String contentType = request.headers().get("Content-Type");

    final byte[] body =
        HttpContentTypes.isFormContentType(contentType) || buffer == null
            ? new byte[0]
            : buffer.getBytes();

    final MultiMap<String, String> params = buildParams(request, contentType);

    final HttpRequestBuilder httpRequestBuilder = HttpRequestBuilder.httpRequestBuilder();

    final String requestPath = request.path();

    httpRequestBuilder
        .setId(requestId.incrementAndGet())
        .setUri(requestPath)
        .setMethod(request.method().toString())
        .setParams(params)
        .setBodyBytes(body)
        .setRemoteAddress(request.remoteAddress().toString())
        .setResponse(
            createResponse(
                requestPath, headers, params, request.response(), decorators, httpResponseCreator))
        .setTimestamp(time == 0L ? Timer.timer().now() : time)
        .setHeaders(headers);

    return httpRequestBuilder.build();
  }
Exemplo n.º 3
0
  synchronized boolean matches(RoutingContext context, String mountPoint, boolean failure) {

    if (failure && failureHandler == null || !failure && contextHandler == null) {
      return false;
    }
    if (!enabled) {
      return false;
    }
    HttpServerRequest request = context.request();
    if (!methods.isEmpty() && !methods.contains(request.method())) {
      return false;
    }
    if (path != null && pattern == null && !pathMatches(mountPoint, context)) {
      return false;
    }
    if (pattern != null) {
      String path =
          useNormalisedPath
              ? Utils.normalisePath(context.request().path(), false)
              : context.request().path();
      if (mountPoint != null) {
        path = path.substring(mountPoint.length());
      }

      Matcher m = pattern.matcher(path);
      if (m.matches()) {
        if (m.groupCount() > 0) {
          Map<String, String> params = new HashMap<>(m.groupCount());
          if (groups != null) {
            // Pattern - named params
            // decode the path as it could contain escaped chars.
            try {
              for (int i = 0; i < groups.size(); i++) {
                final String k = groups.get(i);
                final String value =
                    URLDecoder.decode(URLDecoder.decode(m.group("p" + i), "UTF-8"), "UTF-8");
                if (!request.params().contains(k)) {
                  params.put(k, value);
                } else {
                  context.pathParams().put(k, value);
                }
              }
            } catch (UnsupportedEncodingException e) {
              context.fail(e);
              return false;
            }
          } else {
            // Straight regex - un-named params
            // decode the path as it could contain escaped chars.
            try {
              for (int i = 0; i < m.groupCount(); i++) {
                String group = m.group(i + 1);
                if (group != null) {
                  final String k = "param" + i;
                  final String value = URLDecoder.decode(group, "UTF-8");
                  if (!request.params().contains(k)) {
                    params.put(k, value);
                  } else {
                    context.pathParams().put(k, value);
                  }
                }
              }
            } catch (UnsupportedEncodingException e) {
              context.fail(e);
              return false;
            }
          }
          request.params().addAll(params);
          context.pathParams().putAll(params);
        }
      } else {
        return false;
      }
    }
    if (!consumes.isEmpty()) {
      // Can this route consume the specified content type
      String contentType = request.headers().get("content-type");
      boolean matches = false;
      for (String ct : consumes) {
        if (ctMatches(contentType, ct)) {
          matches = true;
          break;
        }
      }
      if (!matches) {
        return false;
      }
    }
    if (!produces.isEmpty()) {
      String accept = request.headers().get("accept");
      if (accept != null) {
        List<String> acceptableTypes = Utils.getSortedAcceptableMimeTypes(accept);
        for (String acceptable : acceptableTypes) {
          for (String produce : produces) {
            if (ctMatches(produce, acceptable)) {
              context.setAcceptableContentType(produce);
              return true;
            }
          }
        }
      } else {
        // According to rfc2616-sec14,
        // If no Accept header field is present, then it is assumed that the client accepts all
        // media types.
        context.setAcceptableContentType(produces.iterator().next());
        return true;
      }
      return false;
    }
    return true;
  }