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;
}
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();
}
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());
}
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()));
}
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));
}
}
Aggregations