Пример #1
0
  private Registry getEffectiveRegistry(final DefaultHandlingResult.ResultsHolder results) {

    ClientErrorHandler clientErrorHandler =
        (context, statusCode) -> {
          results.setClientError(statusCode);
          context.getResponse().status(statusCode);
          results.getLatch().countDown();
        };

    ServerErrorHandler serverErrorHandler =
        (context, throwable1) -> {
          results.setThrowable(throwable1);
          results.getLatch().countDown();
        };

    final Registry userRegistry =
        Registry.builder()
            .add(ClientErrorHandler.class, clientErrorHandler)
            .add(ServerErrorHandler.class, serverErrorHandler)
            .build();
    return Exceptions.uncheck(
        () -> {
          ServerConfig serverConfig = serverConfigBuilder.build();
          DefaultExecController execController =
              new DefaultExecController(serverConfig.getThreads());
          return ServerRegistry.serverRegistry(
              new TestServer(),
              Impositions.none(),
              execController,
              serverConfig,
              r -> userRegistry.join(registryBuilder.build()));
        });
  }
Пример #2
0
 @Override
 public <O> Promise<O> transform(
     Function<? super Upstream<? extends T>, ? extends Upstream<O>> upstreamTransformer) {
   try {
     return new DefaultPromise<>(upstreamTransformer.apply(upstream));
   } catch (Exception e) {
     throw Exceptions.uncheck(e);
   }
 }
Пример #3
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();
    }
  }
Пример #4
0
 static BaseDirBuilder tmpJar() {
   return jar(Exceptions.uncheck(() -> File.createTempFile("ratpack", ".jar")));
 }
Пример #5
0
  public ReceivedResponse request(URI uri, Duration duration, Action<? super RequestSpec> action)
      throws Throwable {
    CountDownLatch latch = new CountDownLatch(1);
    AtomicReference<ExecResult<ReceivedResponse>> result = new AtomicReference<>();

    try (ExecController execController = new DefaultExecController(2)) {
      execController
          .fork()
          .onComplete(e -> {})
          .start(
              e -> {
                HttpClient.httpClient(UnpooledByteBufAllocator.DEFAULT, Integer.MAX_VALUE)
                    .request(uri, action.prepend(s -> s.readTimeout(Duration.ofHours(1))))
                    .map(
                        response -> {
                          TypedData responseBody = response.getBody();
                          ByteBuf responseBodyBuffer = responseBody.getBuffer();
                          responseBodyBuffer =
                              Unpooled.unreleasableBuffer(responseBodyBuffer.retain());

                          return new DefaultReceivedResponse(
                              response.getStatus(),
                              response.getHeaders(),
                              new ByteBufBackedTypedData(
                                  responseBodyBuffer, responseBody.getContentType()));
                        })
                    .connect(
                        new Downstream<DefaultReceivedResponse>() {
                          @Override
                          public void success(DefaultReceivedResponse value) {
                            result.set(ExecResult.of(Result.success(value)));
                            latch.countDown();
                          }

                          @Override
                          public void error(Throwable throwable) {
                            result.set(ExecResult.of(Result.error(throwable)));
                            latch.countDown();
                          }

                          @Override
                          public void complete() {
                            result.set(ExecResult.complete());
                            latch.countDown();
                          }
                        });
              });

      try {
        if (!latch.await(duration.toNanos(), TimeUnit.NANOSECONDS)) {
          TemporalUnit unit = duration.getUnits().get(0);
          throw new IllegalStateException(
              "Request to "
                  + uri
                  + " took more than "
                  + duration.get(unit)
                  + " "
                  + unit.toString()
                  + " to complete");
        }
      } catch (InterruptedException e) {
        throw Exceptions.uncheck(e);
      }

      return result.get().getValueOrThrow();
    }
  }