Exemplo n.º 1
0
  @Test
  public void shouldUseDifferentBucketsWhenUsingValidPartitionKey() throws Exception {
    FakeTimeService time = new FakeTimeService(0);
    Expression<String> expr =
        Expression.valueOf("${matches(exchange.foo, 'bar-00') ?'bucket-00' :''}", String.class);
    ThrottlingFilter filter = new ThrottlingFilter(time, 1, duration("3 seconds"), expr);

    Handler handler = new ResponseHandler(Status.OK);

    // The time does not need to advance
    Exchange exchange = new Exchange();
    Promise<Response, NeverThrowsException> promise;

    exchange.put("foo", "bar-00");
    promise = filter.filter(exchange, new Request(), handler);
    assertThat(promise.get().getStatus()).isEqualTo(Status.OK);

    exchange.put("foo", "bar-00");
    promise = filter.filter(exchange, new Request(), handler);
    assertThat(promise.get().getStatus()).isEqualTo(Status.TOO_MANY_REQUESTS);

    exchange.put("foo", "bar-01");
    promise = filter.filter(exchange, new Request(), handler);
    assertThat(promise.get().getStatus()).isEqualTo(Status.OK);
  }
Exemplo n.º 2
0
  @Test
  public void shouldThrottleRequests() throws Exception {
    FakeTimeService time = new FakeTimeService(0);
    ThrottlingFilter filter =
        new ThrottlingFilter(time, 1, duration("3 seconds"), DEFAULT_PARTITION_EXPR);

    // This one has to call the handler as there are enough tokens in the bucket.
    Handler handler1 = mock(Handler.class, "handler1");
    filter.filter(mock(Context.class), new Request(), handler1);
    verify(handler1).handle(any(Context.class), any(Request.class));

    time.advance(duration("2 seconds"));
    // This one does not have to be called as there is no token anymore in the bucket.
    Handler handler2 = mock(Handler.class, "handler2");
    Promise<Response, NeverThrowsException> promise2 =
        filter.filter(mock(Context.class), new Request(), handler2);
    verifyZeroInteractions(handler2);
    assertThat(promise2.get().getStatus()).isEqualTo(Status.TOO_MANY_REQUESTS);

    time.advance(duration("4 seconds"));
    // This one has to call the handler as the bucket has been refilled.
    Handler handler3 = mock(Handler.class, "handler3");
    filter.filter(mock(Context.class), new Request(), handler3);
    verify(handler3).handle(any(Context.class), any(Request.class));
  }
  @Test(description = "OPENDJ-1197")
  public void testClientSideConnectTimeout() throws Exception {
    // Use an non-local unreachable network address.
    final ConnectionFactory factory =
        new LDAPConnectionFactory(
            "10.20.30.40", 1389, new LDAPOptions().setConnectTimeout(1, TimeUnit.MILLISECONDS));
    try {
      for (int i = 0; i < ITERATIONS; i++) {
        final PromiseImpl<LdapException, NeverThrowsException> promise = PromiseImpl.create();
        final Promise<? extends Connection, LdapException> connectionPromise =
            factory.getConnectionAsync();
        connectionPromise.onFailure(getFailureHandler(promise));

        ConnectionException e =
            (ConnectionException) promise.getOrThrow(TEST_TIMEOUT, TimeUnit.SECONDS);
        assertThat(e.getResult().getResultCode()).isEqualTo(ResultCode.CLIENT_SIDE_CONNECT_ERROR);
        // Wait for the connect to timeout.
        try {
          connectionPromise.getOrThrow(TEST_TIMEOUT, TimeUnit.SECONDS);
          fail("The connect request succeeded unexpectedly");
        } catch (ConnectionException ce) {
          assertThat(ce.getResult().getResultCode())
              .isEqualTo(ResultCode.CLIENT_SIDE_CONNECT_ERROR);
        }
      }
    } finally {
      factory.close();
    }
  }
  @Test
  public void testReadSchedule() throws Exception {
    // given
    final ReadRequest readRequest = Requests.newReadRequest("test1");

    // when
    Promise<ResourceResponse, ResourceException> promise =
        schedulerService.handleRead(new RootContext(), readRequest);

    // then
    AssertJPromiseAssert.assertThat(promise).isNotNull().succeeded();
    ResourceResponse resourceResponse = promise.getOrThrow();
    assertThat(resourceResponse.getContent().asMap()).isEqualTo(testScheduleConfig.asMap());
  }
Exemplo n.º 5
0
  @Test
  public void shouldUseDefaultValueWithExpressionEvaluatingNull() throws Exception {
    FakeTimeService time = new FakeTimeService(0);
    Expression<String> expr = Expression.valueOf("${exchange.bar}", String.class);
    ThrottlingFilter filter = new ThrottlingFilter(time, 1, duration("3 seconds"), expr);

    Handler handler = new ResponseHandler(Status.OK);

    // The time does not need to advance
    Exchange exchange = new Exchange();
    Promise<Response, NeverThrowsException> promise;

    promise = filter.filter(exchange, new Request(), handler);
    assertThat(promise.get().getStatus()).isEqualTo(Status.INTERNAL_SERVER_ERROR);
  }
  @Test
  public void testListCurrentlyExecutingJobsAction() throws Exception {
    // given
    final ActionRequest readRequest =
        Requests.newActionRequest("", SchedulerAction.listCurrentlyExecutingJobs.toString());

    // when
    Promise<ActionResponse, ResourceException> promise =
        schedulerService.handleAction(new RootContext(), readRequest);

    // then
    AssertJPromiseAssert.assertThat(promise).isNotNull().succeeded();
    ActionResponse resourceResponse = promise.getOrThrow();
    assertThat(resourceResponse.getJsonContent().asList().size()).isEqualTo(0);
  }
  @Test
  public void testResumeJobsAction() throws Exception {
    // given
    final ActionRequest readRequest =
        Requests.newActionRequest("", SchedulerAction.resumeJobs.toString());

    // when
    Promise<ActionResponse, ResourceException> promise =
        schedulerService.handleAction(new RootContext(), readRequest);

    // then
    AssertJPromiseAssert.assertThat(promise).isNotNull().succeeded();
    ActionResponse resourceResponse = promise.getOrThrow();
    assertThat(resourceResponse.getJsonContent().get("success").getObject())
        .isEqualTo(new Boolean(true));
  }
Exemplo n.º 8
0
  @Test
  public void shouldThrottleConcurrentRequests() throws Exception {
    CountDownLatch latch1 = new CountDownLatch(1);
    CountDownLatch latch2 = new CountDownLatch(1);

    FakeTimeService time = new FakeTimeService(0);
    final ThrottlingFilter filter =
        new ThrottlingFilter(time, 1, duration("3 seconds"), DEFAULT_PARTITION_EXPR);

    // This one has to be called as there are enough tokens in the bucket.
    final Handler handler1 = new LatchHandler(latch1, latch2);

    Runnable r =
        new Runnable() {

          @Override
          public void run() {
            filter.filter(mock(Context.class), new Request(), handler1);
          }
        };
    Thread t1 = new Thread(r);
    t1.setName("Filter for request #1");
    t1.start();
    latch2.await();

    time.advance(duration("2 seconds"));
    try {
      // This one does not have to be called as there no token anymore in the bucket.
      Handler handler2 = mock(Handler.class, "handler2");
      Promise<Response, NeverThrowsException> promise2 =
          filter.filter(mock(Context.class), new Request(), handler2);

      verifyZeroInteractions(handler2);

      Response response = promise2.get(20, TimeUnit.SECONDS);
      assertThat(response.getStatus()).isEqualTo(Status.TOO_MANY_REQUESTS);
      assertThat(response.getHeaders().getFirst("Retry-After")).isEqualTo("1");
    } finally {
      latch1.countDown();
      t1.join();
    }
  }
Exemplo n.º 9
0
  @Test(dataProvider = "annotatedRequestHandlerData")
  public void testQueryCollectionAnnotatedRequestHandler(
      Class<?> requestHandler,
      boolean collection,
      boolean create,
      boolean read,
      boolean update,
      boolean delete,
      boolean patch,
      boolean resourceAction,
      boolean collectionAction,
      boolean query)
      throws Exception {

    // Given
    Object provider = requestHandler.newInstance();
    Connection connection = Resources.newInternalConnection(createHandler(collection, provider));
    QueryRequest req = Requests.newQueryRequest("/test");

    // When
    Promise<QueryResult, ResourceException> promise =
        connection.queryAsync(new RootContext(), req, mock(QueryResourceHandler.class));

    // Then
    if (query && collection) {
      AssertJPromiseAssert.assertThat(promise).succeeded();
      QueryResult result = promise.get();
      Assertions.assertThat(result.getPagedResultsCookie()).isEqualTo("query");
    } else if (collection) {
      AssertJPromiseAssert.assertThat(promise)
          .failedWithException()
          .isInstanceOf(NotSupportedException.class);
    } else {
      AssertJPromiseAssert.assertThat(promise)
          .failedWithException()
          .isInstanceOf(BadRequestException.class);
    }
  }
Exemplo n.º 10
0
 protected static void assertQueryPromiseFailedWithCodes(
     Promise<QueryResponse, ResourceException> promise,
     int resourceErrorCode,
     int entitlementErrorCode) {
   try {
     promise.getOrThrowUninterruptibly();
     fail("Should throw ResourceException");
   } catch (ResourceException e) {
     Assertions.assertThat(e.getCode()).isEqualTo(resourceErrorCode);
     Assertions.assertThat(e.getCause()).isInstanceOf(EntitlementException.class);
     Assertions.assertThat(((EntitlementException) e.getCause()).getErrorCode())
         .isEqualTo(entitlementErrorCode);
   }
 }
Exemplo n.º 11
0
  @Test
  public void crestQueryIsAllowed() throws SSOException, DelegationException, ResourceException {
    // Given...
    final Set<String> actions = new HashSet<>(Arrays.asList("READ"));
    final DelegationPermission permission =
        new DelegationPermission(
            "/abc", "rest", "1.0", "policies", "read", actions, EXTENSIONS, DUMB_FUNC);
    given(factory.newInstance("/abc", "rest", "1.0", "policies", "read", actions, EXTENSIONS))
        .willReturn(permission);

    given(subjectContext.getCallerSSOToken()).willReturn(token);
    given(evaluator.isAllowed(eq(token), eq(permission), eq(ENVIRONMENT))).willReturn(true);

    QueryResourceHandler handler = mock(QueryResourceHandler.class);
    Promise<QueryResponse, ResourceException> promise =
        Promises.newResultPromise(Responses.newQueryResponse("abc-def"));
    given(
            provider.queryCollection(
                isA(Context.class), isA(QueryRequest.class), isA(QueryResourceHandler.class)))
        .willReturn(promise);

    // When...
    final FilterChain chain = AuthorizationFilters.createAuthorizationFilter(provider, module);
    final Router router = new Router();
    router.addRoute(RoutingMode.STARTS_WITH, Router.uriTemplate("/policies"), chain);

    final RealmContext context = new RealmContext(subjectContext);
    context.setSubRealm("abc", "abc");
    final QueryRequest request = Requests.newQueryRequest("/policies");
    Promise<QueryResponse, ResourceException> result =
        router.handleQuery(context, request, handler);

    // Then...
    QueryResponse response = result.getOrThrowUninterruptibly();
    assertThat(response.getPagedResultsCookie()).isEqualTo("abc-def");
  }
Exemplo n.º 12
0
 private <T extends Response> Promise<T, ResourceException> auditResponse(
     Promise<T, ResourceException> promise, final AuditingResultHandler auditingHandler) {
   return promise
       .thenOnResult(
           new ResultHandler<Response>() {
             @Override
             public void handleResult(Response response) {
               auditingHandler.auditAccessSuccess();
             }
           })
       .thenOnException(
           new ExceptionHandler<ResourceException>() {
             @Override
             public void handleException(ResourceException exception) {
               auditingHandler.auditAccessFailure(exception.getCode(), exception.getMessage());
             }
           });
 }