Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Small refactoring #2115

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,7 @@ private ActionStatusCreate createConfirmationActionStatus(final long actionId, f
}

private List<Action> giveConfirmationForActiveActions(final AutoConfirmationStatus autoConfirmationStatus) {
final Target target = autoConfirmationStatus.getTarget();
return findActiveActionsHavingStatus(target.getControllerId(), Status.WAIT_FOR_CONFIRMATION).stream()
return findActiveActionsHavingStatus(autoConfirmationStatus.getTarget().getControllerId(), Status.WAIT_FOR_CONFIRMATION).stream()
.map(action -> autoConfirmAction(action, autoConfirmationStatus))
.collect(Collectors.toList());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -298,10 +298,11 @@ public long countByRsqlAndNonDSAndCompatibleAndUpdatable(final long distribution
final DistributionSet jpaDistributionSet = distributionSetManagement.getOrElseThrowException(distributionSetId);
final Long distSetTypeId = jpaDistributionSet.getType().getId();

return targetRepository.count(AccessController.Operation.UPDATE,
return targetRepository.count(
AccessController.Operation.UPDATE,
combineWithAnd(List.of(
RSQLUtility.buildRsqlSpecification(targetFilterQuery, TargetFields.class,
virtualPropertyReplacer, database),
RSQLUtility.buildRsqlSpecification(
targetFilterQuery, TargetFields.class, virtualPropertyReplacer, database),
TargetSpecifications.hasNotDistributionSetInActions(distributionSetId),
TargetSpecifications.isCompatibleWithDistributionSetType(distSetTypeId))));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import java.io.Serial;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
Expand Down Expand Up @@ -148,7 +147,7 @@ public class JpaTarget extends AbstractJpaNamedEntity implements Target, EventAw

@Setter
@Getter
@OneToOne(fetch = FetchType.LAZY, mappedBy = "target", orphanRemoval = true)
@OneToOne(fetch = FetchType.LAZY, mappedBy = "target", cascade = { CascadeType.ALL }, orphanRemoval = true)
@PrimaryKeyJoinColumn
private JpaAutoConfirmationStatus autoConfirmationStatus;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -294,8 +294,7 @@ static <T extends AbstractJpaTenantAwareBaseEntity, R extends BaseEntityReposito
final R repository, @NonNull final AccessController<T> accessController) {
Objects.requireNonNull(repository);
Objects.requireNonNull(accessController);
final BaseEntityRepositoryACM<T> repositoryACM =
new BaseEntityRepositoryACM<>(repository, accessController);
final BaseEntityRepositoryACM<T> repositoryACM = new BaseEntityRepositoryACM<>(repository, accessController);
final R acmProxy = (R) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
repository.getClass().getInterfaces(),
Expand All @@ -312,6 +311,7 @@ static <T extends AbstractJpaTenantAwareBaseEntity, R extends BaseEntityReposito
}
if (method.getName().startsWith("find") || method.getName().startsWith("get")) {
final Object result = method.invoke(repository, args);
// Iterable, List, Page, Slice
if (Iterable.class.isAssignableFrom(method.getReturnType())) {
for (final Object e : (Iterable<?>) result) {
if (repository.getDomainClass().isAssignableFrom(e.getClass())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@
* Spring data repositories for {@link TargetFilterQuery}s.
*/
@Transactional(readOnly = true)
public interface TargetFilterQueryRepository
extends BaseEntityRepository<JpaTargetFilterQuery> {
public interface TargetFilterQueryRepository extends BaseEntityRepository<JpaTargetFilterQuery> {

/**
* Find customer target filter by name
Expand All @@ -37,21 +36,19 @@ public interface TargetFilterQueryRepository
Optional<TargetFilterQuery> findByName(String name);

/**
* Sets the auto assign distribution sets and action types to null which
* match the ds ids.
* Sets the auto assign distribution sets and action types to null which match the ds ids.
* <p/>
* No access control applied
*
* @param dsIds distribution set ids to be set to null
*/
@Modifying
@Transactional
@Query("update JpaTargetFilterQuery d set d.autoAssignDistributionSet = NULL, d.autoAssignActionType = NULL, d.accessControlContext = NULL where d.autoAssignDistributionSet in :ids")
@Query("UPDATE JpaTargetFilterQuery d SET d.autoAssignDistributionSet = NULL, d.autoAssignActionType = NULL, d.accessControlContext = NULL WHERE d.autoAssignDistributionSet.id IN :ids")
void unsetAutoAssignDistributionSetAndActionTypeAndAccessContext(@Param("ids") Long... dsIds);

/**
* Counts all target filters that have a given auto assign distribution set
* assigned.
* Counts all target filters that have a given auto assign distribution set assigned.
* <p/>
* No access control applied
*
Expand All @@ -61,15 +58,13 @@ public interface TargetFilterQueryRepository
long countByAutoAssignDistributionSetId(long autoAssignDistributionSetId);

/**
* Deletes all {@link TenantAwareBaseEntity} of a given tenant. For safety
* reasons (this is a "delete everything" query after all) we add the tenant
* manually to query even if this will by done by {@link EntityManager}
* anyhow. The DB should take care of optimizing this away.
* Deletes all {@link TenantAwareBaseEntity} of a given tenant. For safety reasons (this is a "delete everything" query after all) we add
* the tenant manually to query even if this will by done by {@link EntityManager} anyhow. The DB should take care of optimizing this away.
*
* @param tenant to delete data from
*/
@Modifying
@Transactional
@Query("DELETE FROM JpaTargetFilterQuery t WHERE t.tenant = :tenant")
void deleteByTenant(@Param("tenant") String tenant);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -863,21 +863,18 @@ void findOrRegisterTargetIfItDoesNotExistDoesNotThrowExceptionBeforeMaxRetries()
@Expect(type = TargetPollEvent.class, count = 3),
@Expect(type = TargetUpdatedEvent.class, count = 1) })
void findOrRegisterTargetIfItDoesNotExistDoesUpdateNameOnExistingTargetProperly() {

final String controllerId = "12345";
final String targetName = "UpdatedName";

final Target newTarget = controllerManagement.findOrRegisterTargetIfItDoesNotExist(controllerId, LOCALHOST);
assertThat(newTarget.getName()).isEqualTo(controllerId);

final Target firstTimeUpdatedTarget = controllerManagement.findOrRegisterTargetIfItDoesNotExist(controllerId,
LOCALHOST, targetName, null);
final Target firstTimeUpdatedTarget = controllerManagement.findOrRegisterTargetIfItDoesNotExist(
controllerId, LOCALHOST, targetName, null);
assertThat(firstTimeUpdatedTarget.getName()).isEqualTo(targetName);

// Name should not change to default (name=targetId) if target is
// updated without new name provided
final Target secondTimeUpdatedTarget = controllerManagement.findOrRegisterTargetIfItDoesNotExist(controllerId,
LOCALHOST);
// Name should not change to default (name=targetId) if target is updated without new name provided
final Target secondTimeUpdatedTarget = controllerManagement.findOrRegisterTargetIfItDoesNotExist(controllerId, LOCALHOST);
assertThat(secondTimeUpdatedTarget.getName()).isEqualTo(targetName);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
import org.springframework.test.context.support.AbstractTestExecutionListener;

/**
* Test rule to setup and verify the event count for a method.
* Test rule to set up and verify the event count for a method.
*/
@Slf4j
public class EventVerifier extends AbstractTestExecutionListener {
Expand All @@ -53,7 +53,7 @@ public class EventVerifier extends AbstractTestExecutionListener {
* {@code @Before} annotations which are actually counted to the executed
* test-method and maybe fire events which are not covered / recognized by
* the test-method itself and reset the counter again.
*
* <p/>
* Note that this approach is only working when using a single-thread
* executor in the ApplicationEventMultiCaster, so the order of the events
* keep the same.
Expand All @@ -74,7 +74,7 @@ public void beforeTestMethod(final TestContext testContext) {
public void afterTestMethod(final TestContext testContext) {
final Optional<Expect[]> expectedEvents = getExpectationsFrom(testContext.getTestMethod());
try {
expectedEvents.ifPresent(events -> afterTest(events));
expectedEvents.ifPresent(this::afterTest);
} finally {
expectedEvents.ifPresent(listener -> removeEventListener(testContext));
}
Expand All @@ -85,10 +85,8 @@ private Optional<Expect[]> getExpectationsFrom(final Method testMethod) {
}

private void beforeTest(final TestContext testContext) {
final ConfigurableApplicationContext context = (ConfigurableApplicationContext) testContext
.getApplicationContext();
eventCaptor = new EventCaptor();
context.addApplicationListener(eventCaptor);
((ConfigurableApplicationContext) testContext.getApplicationContext()).addApplicationListener(eventCaptor);
}

private void afterTest(final Expect[] expectedEvents) {
Expand All @@ -97,39 +95,33 @@ private void afterTest(final Expect[] expectedEvents) {
}

private void verifyRightCountOfEvents(final Expect[] expectedEvents) {

for (final Expect expectedEvent : expectedEvents) {
try {
Awaitility.await().atMost(5, TimeUnit.SECONDS)
Awaitility.await()
.atMost(5, TimeUnit.SECONDS)
.until(() -> eventCaptor.getCountFor(expectedEvent.type()), equalTo(expectedEvent.count()));

} catch (final ConditionTimeoutException ex) {
fail("Did not receive the expected amount of events form " + expectedEvent.type() + " Expected: "
+ expectedEvent.count() + " but was: " + eventCaptor.getCountFor(expectedEvent.type()));
fail(String.format(
"Did not receive the expected amount of events form %s Expected: %d but was: %d",
expectedEvent.type(), expectedEvent.count(), eventCaptor.getCountFor(expectedEvent.type())));
}
}
}

private void verifyAllEventsCounted(final Expect[] expectedEvents) {

final Set<Class<?>> diffSet = eventCaptor.diff(expectedEvents);
if (diffSet.size() > 0) {
if (!diffSet.isEmpty()) {
final StringBuilder failMessage = new StringBuilder("Missing event verification for ");
final Iterator<Class<?>> itr = diffSet.iterator();
while (itr.hasNext()) {
final Class<?> element = itr.next();
for (final Class<?> element : diffSet) {
final int count = eventCaptor.getCountFor(element);
failMessage.append(element + " with count: " + count + " ");
failMessage.append(element).append(" with count: ").append(count).append(" ");
}
fail(failMessage.toString());
}

}

private void removeEventListener(final TestContext testContext) {
final ApplicationEventMulticaster multicaster = testContext.getApplicationContext()
.getBean(ApplicationEventMulticaster.class);
multicaster.removeApplicationListener(eventCaptor);
testContext.getApplicationContext().getBean(ApplicationEventMulticaster.class).removeApplicationListener(eventCaptor);
}

private static class EventCaptor implements ApplicationListener<RemoteApplicationEvent> {
Expand Down
Loading