Example #1
0
  @Test
  public void testCompareTo() {
    GcsPath a = GcsPath.fromComponents("bucket", "a");
    GcsPath b = GcsPath.fromComponents("bucket", "b");
    GcsPath b2 = GcsPath.fromComponents("bucket2", "b");
    GcsPath brel = GcsPath.fromComponents(null, "b");
    GcsPath a2 = GcsPath.fromComponents("bucket", "a");
    GcsPath arel = GcsPath.fromComponents(null, "a");

    assertThat(a.compareTo(b), Matchers.lessThan(0));
    assertThat(b.compareTo(a), Matchers.greaterThan(0));
    assertThat(a.compareTo(a2), Matchers.equalTo(0));

    assertThat(a.hashCode(), Matchers.equalTo(a2.hashCode()));
    assertThat(a.hashCode(), Matchers.not(Matchers.equalTo(b.hashCode())));
    assertThat(b.hashCode(), Matchers.not(Matchers.equalTo(brel.hashCode())));

    assertThat(brel.compareTo(b), Matchers.lessThan(0));
    assertThat(b.compareTo(brel), Matchers.greaterThan(0));
    assertThat(arel.compareTo(brel), Matchers.lessThan(0));
    assertThat(brel.compareTo(arel), Matchers.greaterThan(0));

    assertThat(b.compareTo(b2), Matchers.lessThan(0));
    assertThat(b2.compareTo(b), Matchers.greaterThan(0));
  }
 private void checkExceptions(String script) {
   try {
     SearchResponse sr =
         client()
             .prepareSearch("test")
             .setQuery(QueryBuilders.matchAllQuery())
             .addScriptField("tvtest", script)
             .execute()
             .actionGet();
     assertThat(sr.getHits().hits().length, equalTo(0));
     ShardSearchFailure[] shardFails = sr.getShardFailures();
     for (ShardSearchFailure fail : shardFails) {
       assertThat(
           fail.reason()
               .indexOf(
                   "Cannot iterate twice! If you want to iterate more that once, add _CACHE explicitly."),
           Matchers.greaterThan(-1));
     }
   } catch (SearchPhaseExecutionException ex) {
     assertThat(
         "got " + ex.getDetailedMessage(),
         ex.getDetailedMessage()
             .indexOf(
                 "Cannot iterate twice! If you want to iterate more that once, add _CACHE explicitly."),
         Matchers.greaterThan(-1));
   }
 }
Example #3
0
  @Test
  public void testCompareTo_ordering() {
    GcsPath ab = GcsPath.fromComponents("bucket", "a/b");
    GcsPath abc = GcsPath.fromComponents("bucket", "a/b/c");
    GcsPath a1b = GcsPath.fromComponents("bucket", "a-1/b");

    assertThat(ab.compareTo(a1b), Matchers.lessThan(0));
    assertThat(a1b.compareTo(ab), Matchers.greaterThan(0));

    assertThat(ab.compareTo(abc), Matchers.lessThan(0));
    assertThat(abc.compareTo(ab), Matchers.greaterThan(0));
  }
  @Test
  @SuppressWarnings("unchecked")
  public void testGetTimeSinceLastMeasurement() throws Exception {
    long sleepTime = 20L;
    // fill history with the same value.
    long now = System.nanoTime() - 2 * sleepTime * 1000000;
    for (int i = 0; i < TestUtils.getPropertyValue(history, "retention", Integer.class); i++) {
      history.success(now);
    }
    final Deque<Long> times = TestUtils.getPropertyValue(history, "times", Deque.class);
    assertEquals(Long.valueOf(now), times.peekFirst());
    assertEquals(Long.valueOf(now), times.peekLast());

    // increment just so we'll have a different value between first and last
    history.success(System.nanoTime() - sleepTime * 1000000);
    assertNotEquals(times.peekFirst(), times.peekLast());

    /*
     * We've called Thread.sleep twice with the same value in quick
     * succession. If timeSinceLastSend is pulling off the correct end of
     * the queue, then we should be closer to the sleep time than we are to
     * 2 x sleepTime, but we should definitely be greater than the sleep
     * time.
     */
    double timeSinceLastMeasurement = history.getTimeSinceLastMeasurement();
    assertThat(timeSinceLastMeasurement, Matchers.greaterThan((double) (sleepTime / 100)));
    assertThat(timeSinceLastMeasurement, Matchers.lessThanOrEqualTo(1.5 * sleepTime / 100));
  }
Example #5
0
  /* ------------------------------------------------------------ */
  @Test
  @Slow
  public void testDateCache() throws Exception {
    // @WAS: Test t = new Test("org.eclipse.jetty.util.DateCache");
    //                            012345678901234567890123456789
    DateCache dc =
        new DateCache("EEE, dd MMM yyyy HH:mm:ss zzz ZZZ", Locale.US, TimeZone.getTimeZone("GMT"));

    Thread.sleep(2000);

    long now = System.currentTimeMillis();
    long end = now + 3000;
    String f = dc.formatNow(now);
    String last = f;

    int hits = 0;
    int misses = 0;

    while (now < end) {
      last = f;
      f = dc.formatNow(now);
      // System.err.printf("%s %s%n",f,last==f);
      if (last == f) hits++;
      else misses++;

      TimeUnit.MILLISECONDS.sleep(100);
      now = System.currentTimeMillis();
    }
    Assert.assertThat(hits, Matchers.greaterThan(misses));
  }
  @Test
  public void testCallWithDifferentFlagsFails() throws Exception {

    initTestData();

    // should throw an exception, we cannot call with different flags twice
    // if the flags of the second call were not included in the first call.
    String script =
        "term = _index['int_payload_field']['b']; return _index['int_payload_field'].get('b', _POSITIONS).tf();";
    try {
      client()
          .prepareSearch("test")
          .setQuery(QueryBuilders.matchAllQuery())
          .addScriptField("tvtest", script)
          .execute()
          .actionGet();
    } catch (SearchPhaseExecutionException e) {
      assertThat(
          "got: " + e.getDetailedMessage(),
          e.getDetailedMessage()
              .indexOf(
                  "You must call get with all required flags! Instead of  _index['int_payload_field'].get('b', _FREQUENCIES) and _index['int_payload_field'].get('b', _POSITIONS) call  _index['int_payload_field'].get('b', _FREQUENCIES | _POSITIONS)  once]"),
          Matchers.greaterThan(-1));
    }

    // Should not throw an exception this way round
    script =
        "term = _index['int_payload_field'].get('b', _POSITIONS | _FREQUENCIES);return _index['int_payload_field']['b'].tf();";
    client()
        .prepareSearch("test")
        .setQuery(QueryBuilders.matchAllQuery())
        .addScriptField("tvtest", script)
        .execute()
        .actionGet();
  }
  @BenchmarkOptions(benchmarkRounds = 1, warmupRounds = 0)
  @Test
  public void validateRetieveItemWithLastAccessUpdateTimeDelay() throws Exception {
    // need to ensure we wait 100 ms
    int wait = 100;

    ((DefaultAttributesHandler) repository.getAttributesHandler()).setLastRequestedResolution(wait);
    Thread.sleep(wait);

    AttributeStorage attributeStorageSpy =
        Mockito.spy(repository.getAttributesHandler().getAttributeStorage());
    repository.getAttributesHandler().setAttributeStorage(attributeStorageSpy);

    ResourceStoreRequest resourceRequest = new ResourceStoreRequest(testFilePath);
    resourceRequest.getRequestContext().put(AccessManager.REQUEST_REMOTE_ADDRESS, "127.0.0.1");

    AbstractStorageItem storageItem =
        localRepositoryStorageUnderTest.retrieveItem(repository, resourceRequest);

    MatcherAssert.assertThat(storageItem, Matchers.notNullValue());
    MatcherAssert.assertThat(
        storageItem.getLastRequested(), Matchers.greaterThan(originalLastAccessTime));

    Mockito.verify(attributeStorageSpy, Mockito.times(1))
        .putAttributes(Mockito.<RepositoryItemUid>any(), Mockito.<Attributes>any());
    Mockito.verify(attributeStorageSpy, Mockito.times(1))
        .getAttributes(Mockito.<RepositoryItemUid>any());
  }
Example #8
0
  @Test
  public void testCompareTo() {
    Path rootPath = Paths.get(clusterUri);
    Path path1 = rootPath.resolve("file1.txt");
    Path path2 = rootPath.resolve("file2.txt");

    assertThat(path2, Matchers.greaterThan(path1));
  }
Example #9
0
  @Test
  public void testCompareTo_buckets() {
    GcsPath a = GcsPath.fromComponents(null, "a/b/c");
    GcsPath b = GcsPath.fromComponents("bucket", "a/b/c");

    assertThat(a.compareTo(b), Matchers.lessThan(0));
    assertThat(b.compareTo(a), Matchers.greaterThan(0));
  }
  @Test
  public void testIntegrationConverter() {
    this.numberChannel.send(new GenericMessage<Integer>(10));
    this.numberChannel.send(new GenericMessage<Boolean>(true));
    assertThat(this.testConverter.getInvoked(), Matchers.greaterThan(0));

    assertTrue(this.bytesChannel.send(new GenericMessage<byte[]>("foo".getBytes())));
    assertTrue(
        this.bytesChannel.send(
            new GenericMessage<>(MutableMessageBuilder.withPayload("").build())));
  }
Example #11
0
 @Test
 public void lengthFromCreate() {
   XMLDocument doc =
       db.createFolder("/top")
           .documents()
           .build(Name.create(db, "foo"))
           .elem("root")
           .end("root")
           .commit();
   assertThat(doc.length(), Matchers.greaterThan(0L));
 }
 @Test
 public void testOnlyOneNull() {
   ProductDimension dimension = createOtherProductDimension();
   assertThat(
       "Null should be greater than non-null",
       comparator.compare(null, dimension),
       Matchers.greaterThan(0));
   assertThat(
       "Non-null should be less than null",
       comparator.compare(dimension, null),
       Matchers.lessThan(0));
 }
  @BenchmarkOptions(benchmarkRounds = 10, warmupRounds = 1)
  @Test
  public void testRetieveItemWithLastAccessUpdate()
      throws LocalStorageException, ItemNotFoundException {
    ResourceStoreRequest resourceRequest = new ResourceStoreRequest(testFilePath);
    resourceRequest.getRequestContext().put(AccessManager.REQUEST_REMOTE_ADDRESS, "127.0.0.1");

    AbstractStorageItem storageItem =
        localRepositoryStorageUnderTest.retrieveItem(repository, resourceRequest);

    MatcherAssert.assertThat(storageItem, Matchers.notNullValue());
    MatcherAssert.assertThat(
        storageItem.getLastRequested(), Matchers.greaterThan(originalLastAccessTime));
  }
Example #14
0
  @Test
  public void testImplicitGrant() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token id_token");
    postBody.add("source", "credentials");
    postBody.add("username", user.getUserName());
    postBody.add("password", secret);

    ResponseEntity<Void> responseEntity =
        restOperations.exchange(
            loginUrl + "/oauth/authorize",
            HttpMethod.POST,
            new HttpEntity<>(postBody, headers),
            Void.class);

    Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode());

    UriComponents locationComponents =
        UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation()).build();
    Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost());
    Assert.assertEquals("/redirect/cf", locationComponents.getPath());

    MultiValueMap<String, String> params = parseFragmentParams(locationComponents);

    Assert.assertThat(params.get("jti"), not(empty()));
    Assert.assertEquals("bearer", params.getFirst("token_type"));
    Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode(params.getFirst("scope"), "UTF-8").split(" ");
    Assert.assertThat(
        Arrays.asList(scopes),
        containsInAnyOrder(
            "scim.userids",
            "password.write",
            "cloud_controller.write",
            "openid",
            "cloud_controller.read",
            "uaa.user"));

    validateToken("access_token", params.toSingleValueMap(), scopes, aud);
    validateToken("id_token", params.toSingleValueMap(), openid, new String[] {"cf"});
  }
Example #15
0
  @Test
  public void testPasswordGrant() throws Exception {
    String basicDigestHeaderValue = "Basic " + new String(Base64.encodeBase64(("cf:").getBytes()));

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.set("Authorization", basicDigestHeaderValue);

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token id_token");
    postBody.add("grant_type", "password");
    postBody.add("username", user.getUserName());
    postBody.add("password", secret);

    ResponseEntity<Map> responseEntity =
        restOperations.exchange(
            loginUrl + "/oauth/token",
            HttpMethod.POST,
            new HttpEntity<>(postBody, headers),
            Map.class);

    Assert.assertEquals(HttpStatus.OK, responseEntity.getStatusCode());

    Map<String, Object> params = responseEntity.getBody();

    Assert.assertTrue(params.get("jti") != null);
    Assert.assertEquals("bearer", params.get("token_type"));
    Assert.assertThat((Integer) params.get("expires_in"), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode((String) params.get("scope"), "UTF-8").split(" ");
    Assert.assertThat(
        Arrays.asList(scopes),
        containsInAnyOrder(
            "scim.userids",
            "password.write",
            "cloud_controller.write",
            "openid",
            "cloud_controller.read",
            "uaa.user"));

    validateToken("access_token", params, scopes, aud);
    validateToken("id_token", params, openid, new String[] {"cf"});
  }
  @Test
  public void testValuesSmokeScreen() {
    cluster().ensureAtMostNumNodes(5);
    cluster().ensureAtLeastNumNodes(1);
    SigarService sigarService = cluster().getInstance(SigarService.class);
    index("test1", "type", "1", "f", "f");

    ClusterStatsResponse response = client().admin().cluster().prepareClusterStats().get();
    assertThat(response.getTimestamp(), Matchers.greaterThan(946681200000l)); // 1 Jan 2000
    assertThat(response.indicesStats.getStore().getSizeInBytes(), Matchers.greaterThan(0l));

    assertThat(response.nodesStats.getFs().getTotal().bytes(), Matchers.greaterThan(0l));
    assertThat(response.nodesStats.getJvm().getVersions().size(), Matchers.greaterThan(0));
    if (sigarService.sigarAvailable()) {
      // We only get those if we have sigar
      assertThat(response.nodesStats.getOs().getAvailableProcessors(), Matchers.greaterThan(0));
      assertThat(
          response.nodesStats.getOs().getAvailableMemory().bytes(), Matchers.greaterThan(0l));
      assertThat(response.nodesStats.getOs().getCpus().size(), Matchers.greaterThan(0));
    }
    assertThat(response.nodesStats.getVersions().size(), Matchers.greaterThan(0));
    assertThat(response.nodesStats.getVersions().contains(Version.CURRENT), Matchers.equalTo(true));
    assertThat(response.nodesStats.getPlugins().size(), Matchers.greaterThanOrEqualTo(0));

    assertThat(response.nodesStats.getProcess().count, Matchers.greaterThan(0));
    // 0 happens when not supported on platform
    assertThat(
        response.nodesStats.getProcess().getAvgOpenFileDescriptors(),
        Matchers.greaterThanOrEqualTo(0L));
    // these can be -1 if not supported on platform
    assertThat(
        response.nodesStats.getProcess().getMinOpenFileDescriptors(),
        Matchers.greaterThanOrEqualTo(-1L));
    assertThat(
        response.nodesStats.getProcess().getMaxOpenFileDescriptors(),
        Matchers.greaterThanOrEqualTo(-1L));
  }
Example #17
0
  @Test
  public void producedZipFilesAreTimezoneAgnostic() throws Exception {
    HashCode referenceHash = writeSimpleJarAndGetHash();
    TimeZone previousDefault = TimeZone.getDefault();
    try {
      String[] availableIDs = TimeZone.getAvailableIDs();
      assertThat(availableIDs.length, Matchers.greaterThan(1));

      for (String timezoneID : availableIDs) {
        TimeZone timeZone = TimeZone.getTimeZone(timezoneID);
        TimeZone.setDefault(timeZone);

        assertThat(writeSimpleJarAndGetHash(), Matchers.equalTo(referenceHash));
      }
    } finally {
      TimeZone.setDefault(previousDefault);
    }
  }
  @Test
  public void testIdle() throws Exception {
    Socket client = newClient();

    client.setSoTimeout(3000);

    SocketChannel server = _connector.accept();
    server.configureBlocking(false);

    _manager.register(server);

    // Write client to server
    client.getOutputStream().write("HelloWorld".getBytes("UTF-8"));

    // Verify echo server to client
    for (char c : "HelloWorld".toCharArray()) {
      int b = client.getInputStream().read();
      assertTrue(b > 0);
      assertEquals(c, (char) b);
    }

    // Set Max idle
    _lastEndp.setMaxIdleTime(500);

    // read until idle shutdown received
    long start = System.currentTimeMillis();
    int b = client.getInputStream().read();
    assertEquals(-1, b);
    long idle = System.currentTimeMillis() - start;
    assertThat(idle, Matchers.greaterThan(400L));
    assertThat(idle, Matchers.lessThan(3000L));

    if (_lastEndp.isOpen()) {
      // half close so wait another idle period
      assertTrue(_lastEndp.isOutputShutdown());
      Thread.sleep(2000);
    }

    // endpoint is closed.
    assertFalse(_lastEndp.isOpen());
  }
  @BenchmarkOptions(benchmarkRounds = 10, warmupRounds = 1)
  @Test
  public void validateRetieveItemWithLastAccessUpdate()
      throws LocalStorageException, ItemNotFoundException, IOException {
    AttributeStorage attributeStorageSpy =
        Mockito.spy(repository.getAttributesHandler().getAttributeStorage());
    repository.getAttributesHandler().setAttributeStorage(attributeStorageSpy);

    ResourceStoreRequest resourceRequest = new ResourceStoreRequest(testFilePath);
    resourceRequest.getRequestContext().put(AccessManager.REQUEST_REMOTE_ADDRESS, "127.0.0.1");

    AbstractStorageItem storageItem =
        localRepositoryStorageUnderTest.retrieveItem(repository, resourceRequest);

    MatcherAssert.assertThat(storageItem, Matchers.notNullValue());
    MatcherAssert.assertThat(
        storageItem.getLastRequested(), Matchers.greaterThan(originalLastAccessTime));

    Mockito.verify(attributeStorageSpy, Mockito.times(1))
        .putAttributes(Mockito.<RepositoryItemUid>any(), Mockito.<Attributes>any());
    Mockito.verify(attributeStorageSpy, Mockito.times(1))
        .getAttributes(Mockito.<RepositoryItemUid>any());
  }
Example #20
0
 @Test
 public void lengthFromLoad() {
   XMLDocument doc =
       db.createFolder("/top").documents().load(Name.create(db, "foo"), Source.xml("<root/>"));
   assertThat(doc.length(), Matchers.greaterThan(0L));
 }
Example #21
0
 @Factory
 public static <T extends Comparable<T>> Matcher<T> greaterThan(final T c) {
   return Matchers.greaterThan(c);
 }
  // TODO make this test reliable
  @Test
  @Ignore
  public void testRejectedExecution() throws Exception {
    _manager.stop();
    _threadPool.stop();

    final CountDownLatch latch = new CountDownLatch(1);

    BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(4);
    _threadPool = new QueuedThreadPool(4, 4, 60000, q);
    _manager =
        new SelectorManager(_threadPool, _scheduler, 1) {

          @Override
          protected EndPoint newEndPoint(
              SelectableChannel channel, ManagedSelector selector, SelectionKey selectionKey)
              throws IOException {
            SocketChannelEndPoint endp =
                new SocketChannelEndPoint(channel, selector, selectionKey, getScheduler());
            _lastEndPoint = endp;
            _lastEndPointLatch.countDown();
            return endp;
          }

          @Override
          public Connection newConnection(
              SelectableChannel channel, EndPoint endpoint, Object attachment) throws IOException {
            return new TestConnection(endpoint, latch);
          }
        };

    _threadPool.start();
    _manager.start();

    AtomicInteger timeout = new AtomicInteger();
    AtomicInteger rejections = new AtomicInteger();
    AtomicInteger echoed = new AtomicInteger();

    CountDownLatch closed = new CountDownLatch(20);
    for (int i = 0; i < 20; i++) {
      new Thread() {
        public void run() {
          try (Socket client = newClient(); ) {
            client.setSoTimeout(5000);

            SocketChannel server = _connector.accept();
            server.configureBlocking(false);

            _manager.accept(server);

            // Write client to server
            client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));
            client.getOutputStream().flush();
            client.shutdownOutput();

            // Verify echo server to client
            for (char c : "HelloWorld".toCharArray()) {
              int b = client.getInputStream().read();
              assertTrue(b > 0);
              assertEquals(c, (char) b);
            }
            assertEquals(-1, client.getInputStream().read());
            echoed.incrementAndGet();
          } catch (SocketTimeoutException x) {
            x.printStackTrace();
            timeout.incrementAndGet();
          } catch (Throwable x) {
            rejections.incrementAndGet();
          } finally {
            closed.countDown();
          }
        }
      }.start();
    }

    // unblock the handling
    latch.countDown();

    // wait for all clients to complete or fail
    closed.await();

    // assert some clients must have been rejected
    Assert.assertThat(rejections.get(), Matchers.greaterThan(0));
    // but not all of them
    Assert.assertThat(rejections.get(), Matchers.lessThan(20));
    // none should have timed out
    Assert.assertThat(timeout.get(), Matchers.equalTo(0));
    // and the rest should have worked
    Assert.assertThat(echoed.get(), Matchers.equalTo(20 - rejections.get()));

    // and the selector is still working for new requests
    try (Socket client = newClient(); ) {
      client.setSoTimeout(5000);

      SocketChannel server = _connector.accept();
      server.configureBlocking(false);

      _manager.accept(server);

      // Write client to server
      client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));
      client.getOutputStream().flush();
      client.shutdownOutput();

      // Verify echo server to client
      for (char c : "HelloWorld".toCharArray()) {
        int b = client.getInputStream().read();
        assertTrue(b > 0);
        assertEquals(c, (char) b);
      }
      assertEquals(-1, client.getInputStream().read());
    }
  }
  @Test
  public void testAnnotatedServiceActivator() throws Exception {
    this.serviceActivatorEndpoint.setReceiveTimeout(10000);
    this.serviceActivatorEndpoint.start();
    assertTrue(this.inputReceiveLatch.await(10, TimeUnit.SECONDS));

    assertEquals(
        10L, TestUtils.getPropertyValue(this.serviceActivatorEndpoint, "maxMessagesPerPoll"));

    Trigger trigger =
        TestUtils.getPropertyValue(this.serviceActivatorEndpoint, "trigger", Trigger.class);
    assertThat(trigger, Matchers.instanceOf(PeriodicTrigger.class));
    assertEquals(100L, TestUtils.getPropertyValue(trigger, "period"));
    assertFalse(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class));

    assertTrue(this.annotationTestService.isRunning());
    Log logger =
        spy(TestUtils.getPropertyValue(this.serviceActivatorEndpoint, "logger", Log.class));
    when(logger.isDebugEnabled()).thenReturn(true);
    final CountDownLatch pollerInterruptedLatch = new CountDownLatch(1);
    doAnswer(
            new Answer<Void>() {

              @Override
              public Void answer(InvocationOnMock invocation) throws Throwable {
                pollerInterruptedLatch.countDown();
                invocation.callRealMethod();
                return null;
              }
            })
        .when(logger)
        .debug("Received no Message during the poll, returning 'false'");
    new DirectFieldAccessor(this.serviceActivatorEndpoint).setPropertyValue("logger", logger);

    this.serviceActivatorEndpoint.stop();
    assertFalse(this.annotationTestService.isRunning());

    // wait until the service activator's poller is interrupted.
    assertTrue(pollerInterruptedLatch.await(10, TimeUnit.SECONDS));
    this.serviceActivatorEndpoint.start();
    assertTrue(this.annotationTestService.isRunning());

    trigger = TestUtils.getPropertyValue(this.serviceActivatorEndpoint1, "trigger", Trigger.class);
    assertThat(trigger, Matchers.instanceOf(PeriodicTrigger.class));
    assertEquals(100L, TestUtils.getPropertyValue(trigger, "period"));
    assertTrue(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class));

    trigger = TestUtils.getPropertyValue(this.serviceActivatorEndpoint2, "trigger", Trigger.class);
    assertThat(trigger, Matchers.instanceOf(CronTrigger.class));
    assertEquals(
        "0 5 7 * * *", TestUtils.getPropertyValue(trigger, "sequenceGenerator.expression"));

    trigger = TestUtils.getPropertyValue(this.serviceActivatorEndpoint3, "trigger", Trigger.class);
    assertThat(trigger, Matchers.instanceOf(PeriodicTrigger.class));
    assertEquals(11L, TestUtils.getPropertyValue(trigger, "period"));
    assertFalse(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class));

    trigger = TestUtils.getPropertyValue(this.serviceActivatorEndpoint4, "trigger", Trigger.class);
    assertThat(trigger, Matchers.instanceOf(PeriodicTrigger.class));
    assertEquals(1000L, TestUtils.getPropertyValue(trigger, "period"));
    assertFalse(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class));
    assertSame(this.myTrigger, trigger);

    trigger = TestUtils.getPropertyValue(this.transformer, "trigger", Trigger.class);
    assertThat(trigger, Matchers.instanceOf(PeriodicTrigger.class));
    assertEquals(10L, TestUtils.getPropertyValue(trigger, "period"));
    assertFalse(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class));

    this.input.send(MessageBuilder.withPayload("Foo").build());

    Message<?> interceptedMessage = this.wireTapChannel.receive(10000);
    assertNotNull(interceptedMessage);
    assertEquals("Foo", interceptedMessage.getPayload());

    Message<?> receive = this.output.receive(10000);
    assertNotNull(receive);
    assertEquals("FOO", receive.getPayload());

    MessageHistory messageHistory =
        receive.getHeaders().get(MessageHistory.HEADER_NAME, MessageHistory.class);
    assertNotNull(messageHistory);
    String messageHistoryString = messageHistory.toString();
    assertThat(messageHistoryString, Matchers.containsString("input"));
    assertThat(
        messageHistoryString,
        Matchers.containsString("annotationTestService.handle.serviceActivator.handler"));
    assertThat(messageHistoryString, Matchers.not(Matchers.containsString("output")));

    receive = this.publishedChannel.receive(10000);

    assertNotNull(receive);
    assertEquals("foo", receive.getPayload());

    messageHistory = receive.getHeaders().get(MessageHistory.HEADER_NAME, MessageHistory.class);
    assertNotNull(messageHistory);
    messageHistoryString = messageHistory.toString();
    assertThat(messageHistoryString, Matchers.not(Matchers.containsString("input")));
    assertThat(messageHistoryString, Matchers.not(Matchers.containsString("output")));
    assertThat(messageHistoryString, Matchers.containsString("publishedChannel"));

    assertNull(this.wireTapChannel.receive(0));
    assertThat(this.testChannelInterceptor.getInvoked(), Matchers.greaterThan(0));
    assertThat(this.fbInterceptorCounter.get(), Matchers.greaterThan(0));

    assertTrue(
        this.context.containsBean("annotationTestService.count.inboundChannelAdapter.source"));
    Object messageSource =
        this.context.getBean("annotationTestService.count.inboundChannelAdapter.source");
    assertThat(messageSource, Matchers.instanceOf(MethodInvokingMessageSource.class));

    assertNull(this.counterChannel.receive(10));

    SmartLifecycle countSA =
        this.context.getBean(
            "annotationTestService.count.inboundChannelAdapter", SmartLifecycle.class);
    assertFalse(countSA.isAutoStartup());
    assertEquals(23, countSA.getPhase());
    countSA.start();

    for (int i = 0; i < 10; i++) {
      Message<?> message = this.counterChannel.receive(1000);
      assertNotNull(message);
      assertEquals(i + 1, message.getPayload());
    }

    Message<?> message = this.fooChannel.receive(1000);
    assertNotNull(message);
    assertEquals("foo", message.getPayload());
    message = this.fooChannel.receive(1000);
    assertNotNull(message);
    assertEquals("foo", message.getPayload());
    assertNull(this.fooChannel.receive(10));

    message = this.messageChannel.receive(1000);
    assertNotNull(message);
    assertEquals("bar", message.getPayload());
    assertTrue(message.getHeaders().containsKey("foo"));
    assertEquals("FOO", message.getHeaders().get("foo"));

    MessagingTemplate messagingTemplate = new MessagingTemplate(this.controlBusChannel);
    assertFalse(messagingTemplate.convertSendAndReceive("@lifecycle.isRunning()", Boolean.class));
    this.controlBusChannel.send(new GenericMessage<String>("@lifecycle.start()"));
    assertTrue(messagingTemplate.convertSendAndReceive("@lifecycle.isRunning()", Boolean.class));
    this.controlBusChannel.send(new GenericMessage<String>("@lifecycle.stop()"));
    assertFalse(messagingTemplate.convertSendAndReceive("@lifecycle.isRunning()", Boolean.class));
  }
  @Test
  public void getUniqueDeclaredMethods_isFastEnough() {
    Assume.group(TestGroup.PERFORMANCE);

    @SuppressWarnings("unused")
    class C {
      void m00() {}

      void m01() {}

      void m02() {}

      void m03() {}

      void m04() {}

      void m05() {}

      void m06() {}

      void m07() {}

      void m08() {}

      void m09() {}

      void m10() {}

      void m11() {}

      void m12() {}

      void m13() {}

      void m14() {}

      void m15() {}

      void m16() {}

      void m17() {}

      void m18() {}

      void m19() {}

      void m20() {}

      void m21() {}

      void m22() {}

      void m23() {}

      void m24() {}

      void m25() {}

      void m26() {}

      void m27() {}

      void m28() {}

      void m29() {}

      void m30() {}

      void m31() {}

      void m32() {}

      void m33() {}

      void m34() {}

      void m35() {}

      void m36() {}

      void m37() {}

      void m38() {}

      void m39() {}

      void m40() {}

      void m41() {}

      void m42() {}

      void m43() {}

      void m44() {}

      void m45() {}

      void m46() {}

      void m47() {}

      void m48() {}

      void m49() {}

      void m50() {}

      void m51() {}

      void m52() {}

      void m53() {}

      void m54() {}

      void m55() {}

      void m56() {}

      void m57() {}

      void m58() {}

      void m59() {}

      void m60() {}

      void m61() {}

      void m62() {}

      void m63() {}

      void m64() {}

      void m65() {}

      void m66() {}

      void m67() {}

      void m68() {}

      void m69() {}

      void m70() {}

      void m71() {}

      void m72() {}

      void m73() {}

      void m74() {}

      void m75() {}

      void m76() {}

      void m77() {}

      void m78() {}

      void m79() {}

      void m80() {}

      void m81() {}

      void m82() {}

      void m83() {}

      void m84() {}

      void m85() {}

      void m86() {}

      void m87() {}

      void m88() {}

      void m89() {}

      void m90() {}

      void m91() {}

      void m92() {}

      void m93() {}

      void m94() {}

      void m95() {}

      void m96() {}

      void m97() {}

      void m98() {}

      void m99() {}
    }

    StopWatch sw = new StopWatch();
    sw.start();
    Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(C.class);
    sw.stop();
    long totalMs = sw.getTotalTimeMillis();
    assertThat(methods.length, Matchers.greaterThan(100));
    assertThat(totalMs, Matchers.lessThan(10L));
  }
 public ComparableExpectation<T> isGreaterThan(final T value) {
   return matches(Matchers.greaterThan(value));
 }