Beispiel #1
0
  private static MultiMap toMultiMap(Map<String, Object> headers) {
    if (headers == null) {
      return null;
    }

    MultiMap multiMap = new CaseInsensitiveMultiMap();

    for (Map.Entry<String, Object> entry : headers.entrySet()) {
      Object o = entry.getValue();
      if (o != null) {
        if (o instanceof List) {
          List<String> entries = new ArrayList<>();
          for (Object v : (List) o) {
            if (v != null) {
              if (v instanceof String) {
                entries.add((String) v);
                continue;
              }
              entries.add(v.toString());
            }
          }
          multiMap.add(entry.getKey(), entries);
          continue;
        }
        if (o instanceof String) {
          multiMap.add(entry.getKey(), (String) o);
          continue;
        }

        multiMap.add(entry.getKey(), o.toString());
      }
    }

    return multiMap;
  }
  @Override
  public void handle(HttpClientResponse clientResponse) {
    delegate.handle(clientResponse);

    MultiMap headers = clientResponse.headers();
    for (String headerName : rewriteHeaders) {
      List<String> headerValues = headers.getAll(headerName);
      int size = headerValues.size();
      if (size > 0) {
        List<String> newHeaders = new ArrayList<String>(size);
        for (String headerValue : headerValues) {
          String newValue = headerValue;
          if (headerValue != null && headerValue.length() > 0) {
            newValue = proxyMappingDetails.rewriteBackendUrl(headerValue);
          }
        }
        LOG.info(
            "Rewriting header " + headerName + " from: " + headerValues + " to: " + newHeaders);
        headers.set(headerName, newHeaders);
      }
    }
  }
  @Override
  public void write(
      T object, MediaType contentType, HttpClientRequest httpClientRequest, boolean endRequest)
      throws HttpMessageConverterException {
    try {
      final MultiMap headers = httpClientRequest.headers();
      if (headers.get(HttpHeaders.CONTENT_TYPE) == null) {
        MediaType contentTypeToUse = contentType;
        if (contentType == null
            || contentType.isWildcardType()
            || contentType.isWildcardSubtype()) {
          contentTypeToUse = getDefaultContentType(object);
        }
        if (contentTypeToUse != null) {
          headers.set(HttpHeaders.CONTENT_TYPE, contentTypeToUse.toString());
        }
      }

      final byte[] buffer = writeInternal(object, httpClientRequest.headers());
      if (endRequest) {
        if (log.isDebugEnabled()) {
          log.debug("Request body: {}", new String(buffer, Charsets.UTF_8));
        }
        httpClientRequest.end(new Buffer(buffer));
      } else {
        if (log.isDebugEnabled()) {
          log.debug("Partial request body: {}", new String(buffer, Charsets.UTF_8));
        }
        httpClientRequest.write(new Buffer(buffer));
      }
    } catch (HttpMessageConverterException e) {
      throw e;
    } catch (Throwable t) {
      throw new HttpMessageConverterException("Error writing object", t);
    }
  }
Beispiel #4
0
  public URI(String uri) {
    this.uri = uri;
    if (uri == null) throw new IllegalArgumentException("[" + uri + "] is not a valid HTTP URL");
    Matcher httpUrlMatcher = HTTP_URL_PATTERN.matcher(uri);
    if (httpUrlMatcher.matches()) {

      scheme = httpUrlMatcher.group(1);
      userInfo = httpUrlMatcher.group(4);
      host = httpUrlMatcher.group(5);
      if (!Strings.isNullOrEmpty(httpUrlMatcher.group(7))) {
        port = Integer.parseInt(httpUrlMatcher.group(7));
      } else {
        port = (scheme.equals("http") ? 80 : 443);
      }
      path = httpUrlMatcher.group(8);
      Map<String, List<String>> parameters = new QueryStringDecoder(uri).parameters();
      for (String name : parameters.keySet()) {
        params.add(name, parameters.get(name));
      }
    } else {
      throw new IllegalArgumentException("[" + uri + "] is not a valid HTTP URL");
    }
  }
Beispiel #5
0
  private void route(
      final YokeRequest request, final PatternBinding binding, final Handler<Object> next) {
    final Matcher m = binding.pattern.matcher(request.path());
    final Vertx vertx = vertx();

    if (m.matches()) {
      final MultiMap params = request.params();

      if (binding.paramNames != null) {
        // Named params
        new AsyncIterator<String>(binding.paramNames) {
          @Override
          public void handle(String param) {
            if (hasNext()) {
              params.set(param, m.group(param));
              final Middleware paramMiddleware = paramProcessors.get(param);
              if (paramMiddleware != null) {
                // do not block main loop
                vertx.runOnContext(
                    new Handler<Void>() {
                      @Override
                      public void handle(Void event) {
                        paramMiddleware.handle(
                            request,
                            new Handler<Object>() {
                              @Override
                              public void handle(Object err) {
                                if (err == null) {
                                  next();
                                } else {
                                  next.handle(err);
                                }
                              }
                            });
                      }
                    });
              } else {
                next();
              }
            } else {
              // middlewares
              new AsyncIterator<Middleware>(binding.middleware) {
                @Override
                public void handle(final Middleware middleware) {
                  if (hasNext()) {
                    // do not block main loop
                    vertx.runOnContext(
                        new Handler<Void>() {
                          @Override
                          public void handle(Void event) {
                            middleware.handle(
                                request,
                                new Handler<Object>() {
                                  @Override
                                  public void handle(Object err) {
                                    if (err == null) {
                                      next();
                                    } else {
                                      next.handle(err);
                                    }
                                  }
                                });
                          }
                        });
                  } else {
                    next.handle(null);
                  }
                }
              };
            }
          }
        };
      } else {
        // Un-named params
        for (int i = 0; i < m.groupCount(); i++) {
          params.set("param" + i, m.group(i + 1));
        }

        // middlewares
        new AsyncIterator<Middleware>(binding.middleware) {
          @Override
          public void handle(final Middleware middleware) {
            if (hasNext()) {
              // do not block main loop
              vertx.runOnContext(
                  new Handler<Void>() {
                    @Override
                    public void handle(Void event) {
                      middleware.handle(
                          request,
                          new Handler<Object>() {
                            @Override
                            public void handle(Object err) {
                              if (err == null) {
                                next();
                              } else {
                                next.handle(err);
                              }
                            }
                          });
                    }
                  });
            } else {
              next.handle(null);
            }
          }
        };
      }
    } else {
      next.handle(null);
    }
  }
Beispiel #6
0
  public void request(
      final String method,
      final String url,
      final MultiMap headers,
      final Buffer body,
      final Handler<Response> handler) {
    try {
      final URI uri = new URI(url);
      final boolean urlEncoded =
          "application/x-www-form-urlencoded".equalsIgnoreCase(headers.get("content-type"));

      final Response response = new Response(vertx, handler);

      // start yoke
      fakeServer
          .requestHandler()
          .handle(
              new HttpServerRequest() {

                MultiMap params = null;
                MultiMap attributes = null;

                @Override
                public HttpVersion version() {
                  return HttpVersion.HTTP_1_1;
                }

                @Override
                public String method() {
                  return method.toUpperCase();
                }

                @Override
                public String uri() {
                  return uri.getPath() + "?" + uri.getQuery() + "#" + uri.getFragment();
                }

                @Override
                public String path() {
                  return uri.getPath();
                }

                @Override
                public String query() {
                  return uri.getQuery();
                }

                @Override
                public HttpServerResponse response() {
                  return response;
                }

                @Override
                public MultiMap headers() {
                  return headers;
                }

                @Override
                public MultiMap params() {
                  if (params == null) {
                    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri());
                    Map<String, List<String>> prms = queryStringDecoder.parameters();
                    params = new CaseInsensitiveMultiMap();

                    if (!prms.isEmpty()) {
                      for (Map.Entry<String, List<String>> entry : prms.entrySet()) {
                        params.add(entry.getKey(), entry.getValue());
                      }
                    }
                  }
                  return params;
                }

                @Override
                public InetSocketAddress remoteAddress() {
                  return new InetSocketAddress("127.0.0.1", 80);
                }

                @Override
                public X509Certificate[] peerCertificateChain() throws SSLPeerUnverifiedException {
                  return null;
                }

                @Override
                public URI absoluteURI() {
                  return uri;
                }

                @Override
                public HttpServerRequest bodyHandler(Handler<Buffer> bodyHandler) {
                  bodyHandler.handle(body);
                  return this;
                }

                @Override
                public HttpServerRequest dataHandler(Handler<Buffer> handler) {
                  handler.handle(body);
                  return this;
                }

                @Override
                public HttpServerRequest pause() {
                  throw new UnsupportedOperationException("This mock does not support pause");
                }

                @Override
                public HttpServerRequest resume() {
                  throw new UnsupportedOperationException("This mock does not support resume");
                }

                @Override
                public HttpServerRequest endHandler(Handler<Void> endHandler) {
                  endHandler.handle(null);
                  return this;
                }

                @Override
                public NetSocket netSocket() {
                  throw new UnsupportedOperationException("This mock does not support netSocket");
                }

                @Override
                public HttpServerRequest expectMultiPart(boolean expect) {
                  // NOOP
                  return this;
                }

                @Override
                public HttpServerRequest uploadHandler(
                    Handler<HttpServerFileUpload> uploadHandler) {
                  throw new UnsupportedOperationException(
                      "This mock does not support uploadHandler");
                }

                @Override
                public MultiMap formAttributes() {
                  if (attributes == null) {
                    attributes = new CaseInsensitiveMultiMap();
                    if (urlEncoded) {
                      QueryStringDecoder queryStringDecoder =
                          new QueryStringDecoder(body.toString(), false);

                      Map<String, List<String>> prms = queryStringDecoder.parameters();

                      if (!prms.isEmpty()) {
                        for (Map.Entry<String, List<String>> entry : prms.entrySet()) {
                          attributes.add(entry.getKey(), entry.getValue());
                        }
                      }
                    }
                  }
                  return attributes;
                }

                @Override
                public HttpServerRequest exceptionHandler(Handler<Throwable> handler) {
                  throw new UnsupportedOperationException(
                      "This mock does not support exceptionHandler");
                }
              });
    } catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }
  }