Search in sources :

Example 66 with Collections

use of java.util.Collections in project syncope by apache.

the class UserDataBinderImpl method getUserTO.

@Transactional(readOnly = true)
@Override
public UserTO getUserTO(final User user, final boolean details) {
    UserTO userTO = new UserTO();
    BeanUtils.copyProperties(user, userTO, IGNORE_PROPERTIES);
    userTO.setSuspended(BooleanUtils.isTrue(user.isSuspended()));
    if (user.getSecurityQuestion() != null) {
        userTO.setSecurityQuestion(user.getSecurityQuestion().getKey());
    }
    Map<VirSchema, List<String>> virAttrValues = details ? virAttrHandler.getValues(user) : Collections.<VirSchema, List<String>>emptyMap();
    fillTO(userTO, user.getRealm().getFullPath(), user.getAuxClasses(), user.getPlainAttrs(), derAttrHandler.getValues(user), virAttrValues, userDAO.findAllResources(user), details);
    if (details) {
        // dynamic realms
        userTO.getDynRealms().addAll(userDAO.findDynRealms(user.getKey()));
        // roles
        userTO.getRoles().addAll(user.getRoles().stream().map(Entity::getKey).collect(Collectors.toList()));
        // dynamic roles
        userTO.getDynRoles().addAll(userDAO.findDynRoles(user.getKey()).stream().map(Entity::getKey).collect(Collectors.toList()));
        // privileges
        userTO.getPrivileges().addAll(userDAO.findAllRoles(user).stream().flatMap(role -> role.getPrivileges().stream()).map(Entity::getKey).collect(Collectors.toSet()));
        // relationships
        userTO.getRelationships().addAll(user.getRelationships().stream().map(relationship -> getRelationshipTO(relationship.getType().getKey(), relationship.getRightEnd())).collect(Collectors.toList()));
        // memberships
        userTO.getMemberships().addAll(user.getMemberships().stream().map(membership -> {
            return getMembershipTO(user.getPlainAttrs(membership), derAttrHandler.getValues(user, membership), virAttrHandler.getValues(user, membership), membership);
        }).collect(Collectors.toList()));
        // dynamic memberships
        userTO.getDynMemberships().addAll(userDAO.findDynGroups(user.getKey()).stream().map(group -> {
            return new MembershipTO.Builder().group(group.getKey(), group.getName()).build();
        }).collect(Collectors.toList()));
    }
    return userTO;
}
Also used : StringPatchItem(org.apache.syncope.common.lib.patch.StringPatchItem) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) SecurityQuestionDAO(org.apache.syncope.core.persistence.api.dao.SecurityQuestionDAO) Date(java.util.Date) Realm(org.apache.syncope.core.persistence.api.entity.Realm) Autowired(org.springframework.beans.factory.annotation.Autowired) UserPatch(org.apache.syncope.common.lib.patch.UserPatch) Entity(org.apache.syncope.core.persistence.api.entity.Entity) ResourceOperation(org.apache.syncope.common.lib.types.ResourceOperation) StringUtils(org.apache.commons.lang3.StringUtils) RoleDAO(org.apache.syncope.core.persistence.api.dao.RoleDAO) AnyTypeKind(org.apache.syncope.common.lib.types.AnyTypeKind) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) UserDataBinder(org.apache.syncope.core.provisioning.api.data.UserDataBinder) PropagationByResource(org.apache.syncope.core.provisioning.api.PropagationByResource) AuthContextUtils(org.apache.syncope.core.spring.security.AuthContextUtils) Role(org.apache.syncope.core.persistence.api.entity.Role) Collection(java.util.Collection) Resource(javax.annotation.Resource) Set(java.util.Set) Collectors(java.util.stream.Collectors) AnyTypeDAO(org.apache.syncope.core.persistence.api.dao.AnyTypeDAO) List(java.util.List) Provision(org.apache.syncope.core.persistence.api.entity.resource.Provision) AttrPatch(org.apache.syncope.common.lib.patch.AttrPatch) Group(org.apache.syncope.core.persistence.api.entity.group.Group) PlainSchema(org.apache.syncope.core.persistence.api.entity.PlainSchema) Optional(java.util.Optional) ConfDAO(org.apache.syncope.core.persistence.api.dao.ConfDAO) UPlainAttr(org.apache.syncope.core.persistence.api.entity.user.UPlainAttr) AccessToken(org.apache.syncope.core.persistence.api.entity.AccessToken) HashMap(java.util.HashMap) BooleanUtils(org.apache.commons.lang3.BooleanUtils) BeanUtils(org.apache.syncope.core.spring.BeanUtils) URelationship(org.apache.syncope.core.persistence.api.entity.user.URelationship) HashSet(java.util.HashSet) SyncopeClientCompositeException(org.apache.syncope.common.lib.SyncopeClientCompositeException) ClientExceptionType(org.apache.syncope.common.lib.types.ClientExceptionType) UMembership(org.apache.syncope.core.persistence.api.entity.user.UMembership) MembershipTO(org.apache.syncope.common.lib.to.MembershipTO) CipherAlgorithm(org.apache.syncope.common.lib.types.CipherAlgorithm) Encryptor(org.apache.syncope.core.spring.security.Encryptor) AnyObject(org.apache.syncope.core.persistence.api.entity.anyobject.AnyObject) User(org.apache.syncope.core.persistence.api.entity.user.User) AccessTokenDAO(org.apache.syncope.core.persistence.api.dao.AccessTokenDAO) VirSchema(org.apache.syncope.core.persistence.api.entity.VirSchema) ExternalResource(org.apache.syncope.core.persistence.api.entity.resource.ExternalResource) Component(org.springframework.stereotype.Component) PasswordPatch(org.apache.syncope.common.lib.patch.PasswordPatch) PatchOperation(org.apache.syncope.common.lib.types.PatchOperation) RelationshipType(org.apache.syncope.core.persistence.api.entity.RelationshipType) UserTO(org.apache.syncope.common.lib.to.UserTO) AnyUtils(org.apache.syncope.core.persistence.api.entity.AnyUtils) Collections(java.util.Collections) SecurityQuestion(org.apache.syncope.core.persistence.api.entity.user.SecurityQuestion) Transactional(org.springframework.transaction.annotation.Transactional) Entity(org.apache.syncope.core.persistence.api.entity.Entity) VirSchema(org.apache.syncope.core.persistence.api.entity.VirSchema) UserTO(org.apache.syncope.common.lib.to.UserTO) List(java.util.List) Transactional(org.springframework.transaction.annotation.Transactional)

Example 67 with Collections

use of java.util.Collections in project openflowplugin by opendaylight.

the class SalTableServiceImplTest method testUpdateTableSuccess.

@Test
public void testUpdateTableSuccess() throws ExecutionException, InterruptedException {
    Mockito.doAnswer((Answer<Void>) invocation -> {
        TableFeaturesBuilder tableFeaturesBld = new TableFeaturesBuilder().setTableId((short) 0).setName("Zafod").setMaxEntries(42L).setTableFeatureProperties(Collections.<TableFeatureProperties>emptyList());
        MultipartReplyTableFeaturesBuilder mpTableFeaturesBld = new MultipartReplyTableFeaturesBuilder().setTableFeatures(Collections.singletonList(tableFeaturesBld.build()));
        MultipartReplyTableFeaturesCaseBuilder mpBodyBld = new MultipartReplyTableFeaturesCaseBuilder().setMultipartReplyTableFeatures(mpTableFeaturesBld.build());
        MultipartReplyMessageBuilder mpResultBld = new MultipartReplyMessageBuilder().setType(MultipartType.OFPMPTABLEFEATURES).setMultipartReplyBody(mpBodyBld.build()).setXid(21L);
        final RpcResult<List<MultipartReply>> rpcResult = RpcResultBuilder.success(Collections.singletonList((MultipartReply) mpResultBld.build())).build();
        handleResultFuture.set(rpcResult);
        return null;
    }).when(multiMessageCollector).endCollecting(Matchers.<EventIdentifier>any());
    final Future<RpcResult<UpdateTableOutput>> rpcResultFuture = salTableService.updateTable(prepareUpdateTable());
    Assert.assertNotNull(rpcResultFuture);
    verify(mockedRequestContextStack).createRequestContext();
}
Also used : UpdateTableInput(org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableInput) TableFeaturesBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.multipart.reply.table.features.TableFeaturesBuilder) TableFeatures(org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures) RpcResult(org.opendaylight.yangtools.yang.common.RpcResult) ServiceMocking(org.opendaylight.openflowplugin.impl.services.ServiceMocking) UpdatedTableBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.table.update.UpdatedTableBuilder) Matchers(org.mockito.Matchers) Mock(org.mockito.Mock) RpcProviderRegistry(org.opendaylight.controller.sal.binding.api.RpcProviderRegistry) MultipartWriterProviderFactory(org.opendaylight.openflowplugin.impl.datastore.MultipartWriterProviderFactory) MultipartReplyTableFeaturesCaseBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyTableFeaturesCaseBuilder) SettableFuture(com.google.common.util.concurrent.SettableFuture) Answer(org.mockito.stubbing.Answer) MultipartReplyTableFeaturesBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.MultipartReplyTableFeaturesBuilder) Future(java.util.concurrent.Future) OfHeader(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader) ConvertorManagerFactory(org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory) UpdateTableInputBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableInputBuilder) UpdateTableOutput(org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableOutput) Test(org.junit.Test) MultipartReplyMessageBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder) Mockito.when(org.mockito.Mockito.when) FutureCallback(com.google.common.util.concurrent.FutureCallback) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) Mockito(org.mockito.Mockito) List(java.util.List) ConvertorManager(org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager) TableFeatureProperties(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.table.features.properties.grouping.TableFeatureProperties) EventIdentifier(org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.EventIdentifier) MultipartReply(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply) RpcResultBuilder(org.opendaylight.yangtools.yang.common.RpcResultBuilder) MultipartType(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType) Assert(org.junit.Assert) Collections(java.util.Collections) MultipartReplyMessageBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder) MultipartReply(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply) TableFeatureProperties(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.table.features.properties.grouping.TableFeatureProperties) RpcResult(org.opendaylight.yangtools.yang.common.RpcResult) TableFeaturesBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.multipart.reply.table.features.TableFeaturesBuilder) MultipartReplyTableFeaturesBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.MultipartReplyTableFeaturesBuilder) MultipartReplyTableFeaturesCaseBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyTableFeaturesCaseBuilder) MultipartReplyTableFeaturesBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.MultipartReplyTableFeaturesBuilder) Test(org.junit.Test)

Example 68 with Collections

use of java.util.Collections in project pravega by pravega.

the class SynchronizerTest method testConcurrentFetchUpdatesAfterTruncation.

@Test(timeout = 20000)
@SuppressWarnings("unchecked")
public void testConcurrentFetchUpdatesAfterTruncation() {
    String streamName = "streamName";
    String scope = "scope";
    // Mock of the RevisionedStreamClient.
    RevisionedStreamClient<UpdateOrInit<RevisionedImpl>> revisionedStreamClient = mock(RevisionedStreamClient.class);
    final Segment segment = new Segment(scope, streamName, 0L);
    @Cleanup StateSynchronizerImpl<RevisionedImpl> syncA = new StateSynchronizerImpl<>(segment, revisionedStreamClient);
    Revision firstMark = new RevisionImpl(segment, 10L, 1);
    Revision secondMark = new RevisionImpl(segment, 20L, 2);
    final AbstractMap.SimpleImmutableEntry<Revision, UpdateOrInit<RevisionedImpl>> entry = new AbstractMap.SimpleImmutableEntry<>(secondMark, new UpdateOrInit<>(new RegularUpdate("x")));
    // Mock iterators to simulate concurrent revisionedStreamClient.readFrom(firstMark) call.
    Iterator<Entry<Revision, UpdateOrInit<RevisionedImpl>>> iterator1 = Collections.<Entry<Revision, UpdateOrInit<RevisionedImpl>>>singletonList(entry).iterator();
    Iterator<Entry<Revision, UpdateOrInit<RevisionedImpl>>> iterator2 = Collections.<Entry<Revision, UpdateOrInit<RevisionedImpl>>>singletonList(entry).iterator();
    // Latch to ensure both the thread encounter truncation exception.
    CountDownLatch truncationLatch = new CountDownLatch(2);
    // Latch to ensure both the threads invoke read attempt reading from same revision.
    // This will simulate the race condition where the in-memory state is newer than the state returned by RevisionedStreamClient.
    CountDownLatch raceLatch = new CountDownLatch(2);
    // Setup Mock
    when(revisionedStreamClient.getMark()).thenReturn(firstMark);
    when(revisionedStreamClient.readFrom(firstMark)).thenAnswer(invocation -> {
        truncationLatch.countDown();
        // wait until the other thread encounters the TruncationDataException.
        truncationLatch.await();
        throw new TruncatedDataException();
    }).thenAnswer(invocation -> {
        throw new TruncatedDataException();
    }).thenAnswer(invocation -> {
        truncationLatch.countDown();
        // wait until the other thread attempts to fetch updates from SSS post truncation and updates internal state.
        raceLatch.await();
        return iterator1;
    }).thenAnswer(invocation -> {
        raceLatch.countDown();
        return iterator2;
    });
    // Return an iterator whose hasNext is false.
    when(revisionedStreamClient.readFrom(secondMark)).thenAnswer(invocation -> {
        // release the waiting thread which is fetching updates from SSS when the internal state is already updated.
        raceLatch.countDown();
        return iterator2;
    });
    // Simulate concurrent invocations of fetchUpdates API.
    @Cleanup("shutdownNow") ScheduledExecutorService exec = ExecutorServiceHelpers.newScheduledThreadPool(2, "test-pool");
    CompletableFuture<Void> cf1 = CompletableFuture.supplyAsync(() -> {
        syncA.fetchUpdates();
        return null;
    }, exec);
    CompletableFuture<Void> cf2 = CompletableFuture.supplyAsync(() -> {
        syncA.fetchUpdates();
        return null;
    }, exec);
    // Wait until the completion of both the fetchUpdates() API.
    CompletableFuture.allOf(cf1, cf2).join();
    assertEquals("x", syncA.getState().getValue());
}
Also used : AssertExtensions(io.pravega.test.common.AssertExtensions) Cleanup(lombok.Cleanup) JavaSerializer(io.pravega.client.stream.impl.JavaSerializer) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) StreamSegments(io.pravega.client.stream.impl.StreamSegments) ClientFactoryImpl(io.pravega.client.stream.impl.ClientFactoryImpl) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) URI(java.net.URI) InitialUpdate(io.pravega.client.state.InitialUpdate) MockSegmentStreamFactory(io.pravega.client.stream.mock.MockSegmentStreamFactory) Serializable(java.io.Serializable) CountDownLatch(java.util.concurrent.CountDownLatch) SetSynchronizer(io.pravega.client.state.examples.SetSynchronizer) Assert.assertFalse(org.junit.Assert.assertFalse) Entry(java.util.Map.Entry) SegmentAttribute(io.pravega.client.segment.impl.SegmentAttribute) Controller(io.pravega.client.control.impl.Controller) MockClientFactory(io.pravega.client.stream.mock.MockClientFactory) Mockito.mock(org.mockito.Mockito.mock) StateSynchronizer(io.pravega.client.state.StateSynchronizer) NotImplementedException(org.apache.commons.lang3.NotImplementedException) Segment(io.pravega.client.segment.impl.Segment) TruncatedDataException(io.pravega.client.stream.TruncatedDataException) CompletableFuture(java.util.concurrent.CompletableFuture) ConnectionPoolImpl(io.pravega.client.connection.impl.ConnectionPoolImpl) ByteArraySerializer(io.pravega.client.stream.impl.ByteArraySerializer) Update(io.pravega.client.state.Update) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) RevisionedStreamClient(io.pravega.client.state.RevisionedStreamClient) SynchronizerConfig(io.pravega.client.state.SynchronizerConfig) ReusableLatch(io.pravega.common.util.ReusableLatch) Iterator(java.util.Iterator) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Revisioned(io.pravega.client.state.Revisioned) AtomicLong(java.util.concurrent.atomic.AtomicLong) AbstractMap(java.util.AbstractMap) Assert.assertNull(org.junit.Assert.assertNull) TreeMap(java.util.TreeMap) SynchronizerClientFactory(io.pravega.client.SynchronizerClientFactory) Data(lombok.Data) Revision(io.pravega.client.state.Revision) InvalidStreamException(io.pravega.client.stream.InvalidStreamException) ExecutorServiceHelpers(io.pravega.common.concurrent.ExecutorServiceHelpers) Collections(java.util.Collections) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) Assert.assertEquals(org.junit.Assert.assertEquals) ClientConfig(io.pravega.client.ClientConfig) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) CountDownLatch(java.util.concurrent.CountDownLatch) Cleanup(lombok.Cleanup) Segment(io.pravega.client.segment.impl.Segment) AbstractMap(java.util.AbstractMap) Entry(java.util.Map.Entry) Revision(io.pravega.client.state.Revision) TruncatedDataException(io.pravega.client.stream.TruncatedDataException) Test(org.junit.Test)

Example 69 with Collections

use of java.util.Collections in project pravega by pravega.

the class ThrottlerTests method testInterruptedDecreasingDelayMetrics.

/**
 * Tests if interruptible throttlers are correctly reporting the time spent throttled.
 *
 * @throws Exception
 */
@Test
public void testInterruptedDecreasingDelayMetrics() throws Exception {
    // Supply monotonically decreasing delays.
    val suppliedDelays = Arrays.asList(5000, 4000, 3000);
    val delays = Collections.<Integer>synchronizedList(new ArrayList<>());
    val calculator = new TestCalculatorThrottler(ThrottlerCalculator.ThrottlerName.Cache);
    val nextDelay = suppliedDelays.iterator();
    Consumer<Integer> recordDelay = delayMillis -> {
        delays.add(delayMillis);
        // 0 means we're done (no more throttling).
        calculator.setDelayMillis(nextDelay.hasNext() ? nextDelay.next() : 0);
    };
    @Cleanup TestThrottler t = new TestThrottler(this.containerId, wrap(calculator), executorService(), metrics, recordDelay);
    // Set a non-maximum delay and ask to throttle, then verify we throttled the correct amount.
    calculator.setDelayMillis(nextDelay.next());
    val t1 = t.throttle();
    Assert.assertFalse("Not expected throttle future to be completed yet.", t1.isDone());
    // currently running throttle cycle and request the next throttling value.
    for (int i = 1; i < suppliedDelays.size(); i++) {
        // Interrupt the current throttle cycle.
        t.notifyThrottleSourceChanged();
        // Wait for the new cycle to begin (we use the recordDelay consumer above to figure this out).
        int expectedDelayCount = i + 1;
        TestUtils.await(() -> delays.size() == expectedDelayCount, 5, TIMEOUT_MILLIS);
    }
    TestUtils.await(t1::isDone, 5, TIMEOUT_MILLIS);
    // Because the supplied delays is monotonically decreasing, only the first delay value should be used to calculate
    // the duration supplied.
    AssertExtensions.assertGreaterThanOrEqual("Excepted delay to be at least the smallest value.", suppliedDelays.get(2), (int) getThrottlerMetric(calculator.getName()));
    AssertExtensions.assertLessThan("Excepted delay to be strictly less than the max.", suppliedDelays.get(0), (int) getThrottlerMetric(calculator.getName()));
}
Also used : lombok.val(lombok.val) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Arrays(java.util.Arrays) Setter(lombok.Setter) Getter(lombok.Getter) AssertExtensions(io.pravega.test.common.AssertExtensions) RequiredArgsConstructor(lombok.RequiredArgsConstructor) RunWith(org.junit.runner.RunWith) TimeoutException(java.util.concurrent.TimeoutException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cleanup(lombok.Cleanup) Random(java.util.Random) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) MetricsNames(io.pravega.shared.MetricsNames) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ConfigurationException(io.pravega.common.util.ConfigurationException) Before(org.junit.Before) MetricsTags(io.pravega.shared.MetricsTags) SegmentStoreMetrics(io.pravega.segmentstore.server.SegmentStoreMetrics) SerializedClassRunner(io.pravega.test.common.SerializedClassRunner) lombok.val(lombok.val) Test(org.junit.Test) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) MetricsProvider(io.pravega.shared.metrics.MetricsProvider) ThreadPooledTestSuite(io.pravega.test.common.ThreadPooledTestSuite) MetricRegistryUtils(io.pravega.shared.metrics.MetricRegistryUtils) MetricsConfig(io.pravega.shared.metrics.MetricsConfig) TestUtils(io.pravega.test.common.TestUtils) Assert(org.junit.Assert) Collections(java.util.Collections) Cleanup(lombok.Cleanup) Test(org.junit.Test)

Example 70 with Collections

use of java.util.Collections in project pravega by pravega.

the class ThrottlerTests method testMaximumDelay.

/**
 * Tests the case when {@link ThrottlerCalculator#getThrottlingDelay()} returns a value which requires repeated
 * delays (Maximum Delay == True).
 *
 * @throws Exception
 */
@Test
public void testMaximumDelay() throws Exception {
    final int repeatCount = 3;
    val delays = Collections.<Integer>synchronizedList(new ArrayList<>());
    val calculator = new TestCalculatorThrottler(THROTTLER_NAME);
    val nextDelay = new AtomicInteger(MAX_THROTTLE_MILLIS + repeatCount - 1);
    Consumer<Integer> recordDelay = delayMillis -> {
        delays.add(delayMillis);
        calculator.setDelayMillis(nextDelay.decrementAndGet());
    };
    // Request a throttling delay. Since we begin with a value higher than the MAX, we expect the throttler to
    // block as long as necessary; at each throttle cycle it should check the calculator for a new value, which we
    // will decrease an expect to unblock once we got a value smaller than MAX.
    @Cleanup Throttler t = new AutoCompleteTestThrottler(this.containerId, wrap(calculator), executorService(), metrics, recordDelay);
    calculator.setDelayMillis(nextDelay.get());
    t.throttle().get(SHORT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    Assert.assertEquals("Unexpected number of delays recorded.", repeatCount, delays.size());
    for (int i = 0; i < repeatCount; i++) {
        // Delays are capped.
        int expectedDelay = MAX_THROTTLE_MILLIS + Math.min(0, repeatCount - i);
        Assert.assertEquals("Unexpected delay recorded for step " + i, expectedDelay, (int) delays.get(i));
    }
}
Also used : lombok.val(lombok.val) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Arrays(java.util.Arrays) Setter(lombok.Setter) Getter(lombok.Getter) AssertExtensions(io.pravega.test.common.AssertExtensions) RequiredArgsConstructor(lombok.RequiredArgsConstructor) RunWith(org.junit.runner.RunWith) TimeoutException(java.util.concurrent.TimeoutException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cleanup(lombok.Cleanup) Random(java.util.Random) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) MetricsNames(io.pravega.shared.MetricsNames) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ConfigurationException(io.pravega.common.util.ConfigurationException) Before(org.junit.Before) MetricsTags(io.pravega.shared.MetricsTags) SegmentStoreMetrics(io.pravega.segmentstore.server.SegmentStoreMetrics) SerializedClassRunner(io.pravega.test.common.SerializedClassRunner) lombok.val(lombok.val) Test(org.junit.Test) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) MetricsProvider(io.pravega.shared.metrics.MetricsProvider) ThreadPooledTestSuite(io.pravega.test.common.ThreadPooledTestSuite) MetricRegistryUtils(io.pravega.shared.metrics.MetricRegistryUtils) MetricsConfig(io.pravega.shared.metrics.MetricsConfig) TestUtils(io.pravega.test.common.TestUtils) Assert(org.junit.Assert) Collections(java.util.Collections) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Cleanup(lombok.Cleanup) Test(org.junit.Test)

Aggregations

Collections (java.util.Collections)113 List (java.util.List)59 ArrayList (java.util.ArrayList)41 Test (org.junit.Test)39 Map (java.util.Map)37 Collectors (java.util.stream.Collectors)34 Arrays (java.util.Arrays)28 HashMap (java.util.HashMap)26 Set (java.util.Set)25 HashSet (java.util.HashSet)23 IOException (java.io.IOException)19 Collection (java.util.Collection)19 Optional (java.util.Optional)19 TimeUnit (java.util.concurrent.TimeUnit)16 URI (java.net.URI)13 Assert (org.junit.Assert)13 Function (java.util.function.Function)12 Stream (java.util.stream.Stream)12 Before (org.junit.Before)12 Logger (org.slf4j.Logger)12