introduced open actionIds in MgmtTargetAssignmentResponseBody (#864)

* introduced open actionIds in MgmtTargetAssignmentResponseBody

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>

* fixed SonarQube issues

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>

* removed unused method parameter

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>

* updated documentation tests

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>

* added limit to the alreadyAssignedActions in the AssignmentResult

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>

* moved alreadyAssignedActions limitation to MgmtDistributionSetMapper

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>

* fixed review findings

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>

* removed alreadyAssignedActions

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>

* fixed sonarQube issues

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>

* fixed compilation error

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>

* fixed PR review findings

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>

* fixed PR review findings

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>

* Renamed AssignmentResult to AbstractAssignmentResult

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>

* fixed review findings

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>

* fixed formatting

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>

* reverted method visibility

Signed-off-by: Ahmed Sayed <ahmed.sayed@bosch-si.com>
This commit is contained in:
Ahmed Sayed
2019-08-20 11:31:20 +02:00
committed by Dominic Schabel
parent 973f1952c7
commit d40b11d2ab
43 changed files with 580 additions and 402 deletions

View File

@@ -85,11 +85,10 @@ public class PropertyBasedArtifactUrlHandler implements ArtifactUrlHandler {
@Override
public List<ArtifactUrl> getUrls(final URLPlaceholder placeholder, final ApiType api, final URI requestUri) {
return urlHandlerProperties.getProtocols().entrySet().stream()
.filter(entry -> entry.getValue().getSupports().contains(api))
.filter(entry -> entry.getValue().isEnabled())
.map(entry -> new ArtifactUrl(entry.getValue().getProtocol().toUpperCase(), entry.getValue().getRel(),
generateUrl(entry.getValue(), placeholder, requestUri)))
return urlHandlerProperties.getProtocols().values().stream()
.filter(urlProtocol -> urlProtocol.getSupports().contains(api) && urlProtocol.isEnabled())
.map(urlProtocol -> new ArtifactUrl(urlProtocol.getProtocol().toUpperCase(), urlProtocol.getRel(),
generateUrl(urlProtocol, placeholder, requestUri)))
.collect(Collectors.toList());
}

View File

@@ -124,7 +124,7 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
}
private Action createAction(final DistributionSet testDs) {
return deploymentManagement.findAction(assignDistributionSet(testDs, testTarget).getActionIds().get(0)).get();
return getFirstAssignedAction(assignDistributionSet(testDs, testTarget));
}
@Test

View File

@@ -235,7 +235,7 @@ public abstract class AbstractAmqpServiceIntegrationTest extends AbstractAmqpInt
protected Long registerTargetAndCancelActionId(final String controllerId) {
final DistributionSetAssignmentResult assignmentResult = registerTargetAndAssignDistributionSet(controllerId);
return cancelAction(assignmentResult.getActionIds().get(0), controllerId);
return cancelAction(getFirstAssignedActionId(assignmentResult), controllerId);
}
protected void assertAllTargetsCount(final long expectedTargetsCount) {

View File

@@ -150,12 +150,11 @@ public class AmqpMessageDispatcherServiceIntegrationTest extends AbstractAmqpSer
testdataFactory.addSoftwareModuleMetadata(distributionSet2);
assignDistributionSet(distributionSet2.getId(), controllerId);
assertDownloadAndInstallMessage(distributionSet2.getModules(), controllerId);
assertCancelActionMessage(assignmentResult.getActionIds().get(0), controllerId);
assertCancelActionMessage(getFirstAssignedActionId(assignmentResult), controllerId);
createAndSendThingCreated(controllerId, TENANT_EXIST);
waitUntilTargetHasStatus(controllerId, TargetUpdateStatus.PENDING);
assertCancelActionMessage(assignmentResult.getActionIds().get(0), controllerId);
assertCancelActionMessage(getFirstAssignedActionId(assignmentResult), controllerId);
}
@Test
@@ -258,9 +257,9 @@ public class AmqpMessageDispatcherServiceIntegrationTest extends AbstractAmqpSer
registerAndAssertTargetWithExistingTenant(controllerId);
final DistributionSet ds = testdataFactory.createDistributionSet(UUID.randomUUID().toString());
final Long actionId1 = assignDistributionSet(ds.getId(), controllerId).getActionIds().get(0);
final Long actionId1 = getFirstAssignedActionId(assignDistributionSet(ds.getId(), controllerId));
waitUntilEventMessagesAreDispatchedToTarget(EventTopic.MULTI_ACTION);
final Long actionId2 = assignDistributionSet(ds.getId(), controllerId).getActionIds().get(0);
final Long actionId2 = getFirstAssignedActionId(assignDistributionSet(ds.getId(), controllerId));
waitUntilEventMessagesAreDispatchedToTarget(EventTopic.MULTI_ACTION);
final Entry<Long, EventTopic> action1Install = new SimpleEntry<>(actionId1, EventTopic.DOWNLOAD_AND_INSTALL);
@@ -275,7 +274,7 @@ public class AmqpMessageDispatcherServiceIntegrationTest extends AbstractAmqpSer
private Long assignNewDsToTarget(final String controllerId) {
final DistributionSet ds = testdataFactory.createDistributionSet(UUID.randomUUID().toString());
final Long actionId = assignDistributionSet(ds.getId(), controllerId).getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(assignDistributionSet(ds.getId(), controllerId));
waitUntilTargetHasStatus(controllerId, TargetUpdateStatus.PENDING);
return actionId;
}

View File

@@ -589,13 +589,13 @@ public class AmqpMessageHandlerServiceIntegrationTest extends AbstractAmqpServic
final DistributionSet distributionSet = testdataFactory.createDistributionSet(UUID.randomUUID().toString());
final DistributionSetAssignmentResult distributionSetAssignmentResult = assignDistributionSet(
distributionSet.getId(), controllerId);
deploymentManagement.cancelAction(distributionSetAssignmentResult.getActionIds().get(0));
deploymentManagement.cancelAction(getFirstAssignedActionId(distributionSetAssignmentResult));
// test
registerSameTargetAndAssertBasedOnVersion(controllerId, 1, TargetUpdateStatus.PENDING);
// verify
assertCancelActionMessage(distributionSetAssignmentResult.getActionIds().get(0), controllerId);
assertCancelActionMessage(getFirstAssignedActionId(distributionSetAssignmentResult), controllerId);
Mockito.verifyZeroInteractions(getDeadletterListener());
}
@@ -947,7 +947,7 @@ public class AmqpMessageHandlerServiceIntegrationTest extends AbstractAmqpServic
private Long registerTargetAndSendActionStatus(final DmfActionStatus sendActionStatus, final String controllerId) {
final DistributionSetAssignmentResult assignmentResult = registerTargetAndAssignDistributionSet(controllerId);
final Long actionId = assignmentResult.getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(assignmentResult);
sendActionUpdateStatus(new DmfActionUpdateStatus(actionId, sendActionStatus));
return actionId;
}

View File

@@ -18,35 +18,24 @@ import java.util.List;
* type of the assigned and unassigned {@link BaseEntity}s.
*
*/
public class AssignmentResult<T extends BaseEntity> {
public abstract class AbstractAssignmentResult<T extends BaseEntity> {
private final int total;
private final int assigned;
private final int alreadyAssigned;
private final int unassigned;
private final List<T> assignedEntity;
private final List<T> unassignedEntity;
private final List<? extends T> assignedEntity;
private final List<? extends T> unassignedEntity;
/**
* Constructor.
*
* @param assigned
* is the number of newly assigned elements.
* @param alreadyAssigned
* number of already assigned/ignored elements
* @param unassigned
* number of newly assigned elements
* count of already assigned entities
* @param assignedEntity
* {@link List} of assigned entity.
* @param unassignedEntity
* {@link List} of unassigned entity.
*/
public AssignmentResult(final int assigned, final int alreadyAssigned, final int unassigned,
final List<T> assignedEntity, final List<T> unassignedEntity) {
this.assigned = assigned;
public AbstractAssignmentResult(final int alreadyAssigned, final List<? extends T> assignedEntity,
final List<? extends T> unassignedEntity) {
this.alreadyAssigned = alreadyAssigned;
total = assigned + alreadyAssigned;
this.unassigned = unassigned;
this.assignedEntity = assignedEntity;
this.unassignedEntity = unassignedEntity;
}
@@ -55,14 +44,14 @@ public class AssignmentResult<T extends BaseEntity> {
* @return number of newly assigned elements.
*/
public int getAssigned() {
return assigned;
return getAssignedEntity().size();
}
/**
* @return total number (assigned and already assigned).
*/
public int getTotal() {
return total;
return getAssigned() + alreadyAssigned;
}
/**
@@ -76,7 +65,7 @@ public class AssignmentResult<T extends BaseEntity> {
* @return number of unsassigned elements
*/
public int getUnassigned() {
return unassigned;
return getUnassignedEntity().size();
}
/**

View File

@@ -10,10 +10,6 @@ package org.eclipse.hawkbit.repository.model;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.repository.TargetManagement;
import org.springframework.util.CollectionUtils;
/**
* A bean which holds a complex result of an service operation to combine the
@@ -21,41 +17,24 @@ import org.springframework.util.CollectionUtils;
* how much of the assignments had already been existed.
*
*/
public class DistributionSetAssignmentResult extends AssignmentResult<Target> {
private final List<String> assignedTargets;
private final List<Action> actions;
public class DistributionSetAssignmentResult extends AbstractAssignmentResult<Action> {
private final DistributionSet distributionSet;
private final TargetManagement targetManagement;
/**
*
* Constructor.
*
* @param distributionSet
* @param distributionSet
* that has been assigned
* @param assignedTargets
* the target objects which have been assigned to the
* distribution set
* @param assigned
* count of the assigned targets
* @param alreadyAssigned
* the count of the already assigned targets
* @param actions
* of the assignment
* @param targetManagement
* to retrieve the assigned targets
* the the count of already assigned targets
* @param assigned
* the assigned actions
*/
public DistributionSetAssignmentResult(final DistributionSet distributionSet, final List<String> assignedTargets,
final int assigned, final int alreadyAssigned, final List<Action> actions,
final TargetManagement targetManagement) {
super(assigned, alreadyAssigned, 0, Collections.emptyList(), Collections.emptyList());
public DistributionSetAssignmentResult(final DistributionSet distributionSet, final int alreadyAssigned,
final List<? extends Action> assigned) {
super(alreadyAssigned, assigned, Collections.emptyList());
this.distributionSet = distributionSet;
this.assignedTargets = assignedTargets;
this.actions = actions;
this.targetManagement = targetManagement;
}
/**
@@ -65,32 +44,4 @@ public class DistributionSetAssignmentResult extends AssignmentResult<Target> {
return distributionSet;
}
/**
* @return the actionIds
*/
public List<Long> getActionIds() {
if (actions == null) {
return Collections.emptyList();
}
return actions.stream().map(Action::getId).collect(Collectors.toList());
}
/**
* @return the actions
*/
public List<Action> getActions() {
if (actions == null) {
return Collections.emptyList();
}
return actions;
}
@Override
public List<Target> getAssignedEntity() {
if (CollectionUtils.isEmpty(assignedTargets)) {
return Collections.emptyList();
}
return targetManagement.getByControllerID(assignedTargets);
}
}

View File

@@ -14,7 +14,7 @@ import java.util.List;
* Result object for {@link DistributionSetTag} assignments.
*
*/
public class DistributionSetTagAssignmentResult extends AssignmentResult<DistributionSet> {
public class DistributionSetTagAssignmentResult extends AbstractAssignmentResult<DistributionSet> {
private final DistributionSetTag distributionSetTag;
@@ -24,20 +24,16 @@ public class DistributionSetTagAssignmentResult extends AssignmentResult<Distrib
* @param alreadyAssigned
* number of already assigned/ignored elements
* @param assigned
* number of newly assigned elements
* newly assigned elements
* @param unassigned
* number of newly assigned elements
* @param assignedDs
* {@link List} of assigned {@link DistributionSet}s.
* @param unassignedDs
* {@link List} of unassigned {@link DistributionSet}s.
* unassigned elements
* @param distributionSetTag
* the assigned or unassigned tag
*/
public DistributionSetTagAssignmentResult(final int alreadyAssigned, final int assigned, final int unassigned,
final List<DistributionSet> assignedDs, final List<DistributionSet> unassignedDs,
public DistributionSetTagAssignmentResult(final int alreadyAssigned,
final List<DistributionSet> assigned, final List<DistributionSet> unassigned,
final DistributionSetTag distributionSetTag) {
super(assigned, alreadyAssigned, unassigned, assignedDs, unassignedDs);
super(alreadyAssigned, assigned, unassigned);
this.distributionSetTag = distributionSetTag;
}

View File

@@ -14,7 +14,7 @@ import java.util.List;
* Result object for {@link TargetTag} assignments.
*
*/
public class TargetTagAssignmentResult extends AssignmentResult<Target> {
public class TargetTagAssignmentResult extends AbstractAssignmentResult<Target> {
private final TargetTag targetTag;
@@ -22,21 +22,17 @@ public class TargetTagAssignmentResult extends AssignmentResult<Target> {
* Constructor.
*
* @param alreadyAssigned
* number of already assigned/ignored elements
* count of already assigned (ignored) elements
* @param assigned
* number of newly assigned elements
* @param unassigned
* number of newly assigned elements
* @param assignedTargets
* {@link List} of assigned {@link Target}s.
* @param unassignedTargets
* @param unassigned
* {@link List} of unassigned {@link Target}s.
* @param targetTag
* the assigned or unassigned tag
*/
public TargetTagAssignmentResult(final int alreadyAssigned, final int assigned, final int unassigned,
final List<Target> assignedTargets, final List<Target> unassignedTargets, final TargetTag targetTag) {
super(assigned, alreadyAssigned, unassigned, assignedTargets, unassignedTargets);
public TargetTagAssignmentResult(final int alreadyAssigned, final List<? extends Target> assigned,
final List<? extends Target> unassigned, final TargetTag targetTag) {
super(alreadyAssigned, assigned, unassigned);
this.targetTag = targetTag;
}

View File

@@ -37,7 +37,6 @@ import org.eclipse.hawkbit.repository.ActionFields;
import org.eclipse.hawkbit.repository.DeploymentManagement;
import org.eclipse.hawkbit.repository.QuotaManagement;
import org.eclipse.hawkbit.repository.RepositoryConstants;
import org.eclipse.hawkbit.repository.TargetManagement;
import org.eclipse.hawkbit.repository.TenantConfigurationManagement;
import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.exception.CancelActionNotAllowedException;
@@ -122,7 +121,6 @@ public class JpaDeploymentManagement implements DeploymentManagement {
private final DistributionSetRepository distributionSetRepository;
private final TargetRepository targetRepository;
private final ActionStatusRepository actionStatusRepository;
private final TargetManagement targetManagement;
private final AuditorAware<String> auditorProvider;
private final VirtualPropertyReplacer virtualPropertyReplacer;
private final PlatformTransactionManager txManager;
@@ -136,10 +134,9 @@ public class JpaDeploymentManagement implements DeploymentManagement {
protected JpaDeploymentManagement(final EntityManager entityManager, final ActionRepository actionRepository,
final DistributionSetRepository distributionSetRepository, final TargetRepository targetRepository,
final ActionStatusRepository actionStatusRepository, final TargetManagement targetManagement,
final AuditorAware<String> auditorProvider, final EventPublisherHolder eventPublisherHolder,
final AfterTransactionCommitExecutor afterCommit, final VirtualPropertyReplacer virtualPropertyReplacer,
final PlatformTransactionManager txManager,
final ActionStatusRepository actionStatusRepository, final AuditorAware<String> auditorProvider,
final EventPublisherHolder eventPublisherHolder, final AfterTransactionCommitExecutor afterCommit,
final VirtualPropertyReplacer virtualPropertyReplacer, final PlatformTransactionManager txManager,
final TenantConfigurationManagement tenantConfigurationManagement, final QuotaManagement quotaManagement,
final SystemSecurityContext systemSecurityContext, final TenantAware tenantAware, final Database database) {
this.entityManager = entityManager;
@@ -147,7 +144,6 @@ public class JpaDeploymentManagement implements DeploymentManagement {
this.distributionSetRepository = distributionSetRepository;
this.targetRepository = targetRepository;
this.actionStatusRepository = actionStatusRepository;
this.targetManagement = targetManagement;
this.auditorProvider = auditorProvider;
this.virtualPropertyReplacer = virtualPropertyReplacer;
this.txManager = txManager;
@@ -263,50 +259,70 @@ public class JpaDeploymentManagement implements DeploymentManagement {
final AbstractDsAssignmentStrategy assignmentStrategy) {
final JpaDistributionSet distributionSetEntity = getAndValidateDsById(dsID);
final List<String> controllerIDs = getControllerIdsForAssignmentAndCheckQuota(targetsWithActionType,
distributionSetEntity);
final List<JpaTarget> targetEntities = assignmentStrategy.findTargetsForAssignment(controllerIDs,
checkQuotaForAssignment(targetsWithActionType, distributionSetEntity);
final List<JpaTarget> targetEntities = assignmentStrategy.findTargetsForAssignment(
targetsWithActionType.stream().map(TargetWithActionType::getControllerId).collect(Collectors.toList()),
distributionSetEntity.getId());
if (targetEntities.isEmpty()) {
// detaching as it is not necessary to persist the set itself
entityManager.detach(distributionSetEntity);
// return with nothing as all targets had the DS already assigned
return new DistributionSetAssignmentResult(distributionSetEntity, Collections.emptyList(), 0,
targetsWithActionType.size(), Collections.emptyList(), targetManagement);
return allTargetsAlreadyAssignedResult(distributionSetEntity, targetsWithActionType.size());
}
// split tIDs length into max entries in-statement because many database
// have constraint of max entries in in-statements e.g. Oracle with
// maximum 1000 elements, so we need to split the entries here and
// execute multiple statements
final List<List<Long>> targetEntitiesIdsChunks = Lists.partition(
targetEntities.stream().map(Target::getId).collect(Collectors.toList()),
Constants.MAX_ENTRIES_IN_STATEMENT);
final List<JpaAction> assignedActions = doAssignDistributionSetToTargets(targetsWithActionType,
actionMessage, assignmentStrategy, distributionSetEntity, targetEntities);
return buildAssignmentResult(distributionSetEntity, assignedActions, targetsWithActionType.size());
}
private DistributionSetAssignmentResult allTargetsAlreadyAssignedResult(
final JpaDistributionSet distributionSetEntity, final int alreadyAssignedCount) {
// detaching as it is not necessary to persist the set itself
entityManager.detach(distributionSetEntity);
// return with nothing as all targets had the DS already assigned
return new DistributionSetAssignmentResult(distributionSetEntity, alreadyAssignedCount,
Collections.emptyList());
}
private List<JpaAction> doAssignDistributionSetToTargets(
final Collection<TargetWithActionType> targetsWithActionType, final String actionMessage,
final AbstractDsAssignmentStrategy assignmentStrategy, final JpaDistributionSet distributionSetEntity,
final List<JpaTarget> targetEntities) {
final List<List<Long>> targetEntitiesIdsChunks = getTargetEntitiesAsChunks(targetEntities);
closeOrCancelActiveActions(assignmentStrategy, targetEntitiesIdsChunks);
// cancel all scheduled actions which are in-active, these actions were
// not active before and the manual assignment which has been done
// cancels them
targetEntitiesIdsChunks.forEach(this::cancelInactiveScheduledActionsForTargets);
setAssignedDistributionSetAndTargetUpdateStatus(assignmentStrategy, distributionSetEntity,
targetEntitiesIdsChunks);
final Map<String, JpaAction> controllerIdsToActions = createActions(targetsWithActionType, targetEntities,
assignmentStrategy, distributionSetEntity);
final List<JpaAction> assignedActions = createActions(targetsWithActionType, targetEntities, assignmentStrategy,
distributionSetEntity);
// create initial action status when action is created so we remember
// the initial running status because we will change the status
// of the action itself and with this action status we have a nicer
// action history.
createActionsStatus(controllerIdsToActions.values(), assignmentStrategy, actionMessage);
createActionsStatus(assignedActions, assignmentStrategy, actionMessage);
detachEntitiesAndSendTargetUpdatedEvents(distributionSetEntity, targetEntities, assignmentStrategy);
return assignedActions;
}
return new DistributionSetAssignmentResult(distributionSetEntity,
targetEntities.stream().map(Target::getControllerId).collect(Collectors.toList()),
targetEntities.size(), controllerIDs.size() - targetEntities.size(),
Lists.newArrayList(controllerIdsToActions.values()), targetManagement);
/**
* split tIDs length into max entries in-statement because many database
* have constraint of max entries in in-statements e.g. Oracle with maximum
* 1000 elements, so we need to split the entries here and execute multiple
* statements
*/
private static List<List<Long>> getTargetEntitiesAsChunks(final List<JpaTarget> targetEntities) {
return Lists.partition(targetEntities.stream().map(Target::getId).collect(Collectors.toList()),
Constants.MAX_ENTRIES_IN_STATEMENT);
}
private static DistributionSetAssignmentResult buildAssignmentResult(final JpaDistributionSet distributionSet,
final List<JpaAction> assignedActions, final int totalTargetsForAssignment) {
int alreadyAssignedTargetsCount = totalTargetsForAssignment - assignedActions.size();
return new DistributionSetAssignmentResult(distributionSet, alreadyAssignedTargetsCount, assignedActions);
}
private JpaDistributionSet getAndValidateDsById(final Long dsID) {
@@ -321,17 +337,12 @@ public class JpaDeploymentManagement implements DeploymentManagement {
return distributionSet;
}
private List<String> getControllerIdsForAssignmentAndCheckQuota(
final Collection<TargetWithActionType> targetsWithActionType, final JpaDistributionSet distributionSet) {
final List<String> controllerIDs = targetsWithActionType.stream().map(TargetWithActionType::getControllerId)
.collect(Collectors.toList());
private void checkQuotaForAssignment(final Collection<TargetWithActionType> targetsWithActionType,
final JpaDistributionSet distributionSet) {
// enforce the 'max targets per manual assignment' quota
if (!controllerIDs.isEmpty()) {
assertMaxTargetsPerManualAssignmentQuota(distributionSet.getId(), controllerIDs.size());
if (!targetsWithActionType.isEmpty()) {
assertMaxTargetsPerManualAssignmentQuota(distributionSet.getId(), targetsWithActionType.size());
}
return controllerIDs;
}
/**
@@ -382,15 +393,14 @@ public class JpaDeploymentManagement implements DeploymentManagement {
assignmentStrategy.setAssignedDistributionSetAndTargetStatus(set, targetIdsChunks, currentUser);
}
private Map<String, JpaAction> createActions(final Collection<TargetWithActionType> targetsWithActionType,
private List<JpaAction> createActions(final Collection<TargetWithActionType> targetsWithActionType,
final List<JpaTarget> targets, final AbstractDsAssignmentStrategy assignmentStrategy,
final JpaDistributionSet set) {
final Map<String, TargetWithActionType> targetsWithActionMap = targetsWithActionType.stream()
.collect(Collectors.toMap(TargetWithActionType::getControllerId, Function.identity()));
return targets.stream().map(trg -> assignmentStrategy.createTargetAction(targetsWithActionMap, trg, set))
.filter(Objects::nonNull).map(actionRepository::save)
.collect(Collectors.toMap(action -> action.getTarget().getControllerId(), Function.identity()));
.filter(Objects::nonNull).map(actionRepository::save).collect(Collectors.toList());
}
private void createActionsStatus(final Collection<JpaAction> actions,
@@ -590,7 +600,7 @@ public class JpaDeploymentManagement implements DeploymentManagement {
@Override
public Optional<Action> findAction(final long actionId) {
return actionRepository.findById(actionId).map(a -> (Action) a);
return actionRepository.findById(actionId).map(a -> a);
}
@Override
@@ -703,8 +713,8 @@ public class JpaDeploymentManagement implements DeploymentManagement {
final CriteriaQuery<String> selMsgQuery = msgQuery.select(join);
selMsgQuery.where(cb.equal(as.get(JpaActionStatus_.id), actionStatusId));
final List<String> result = entityManager.createQuery(selMsgQuery).setFirstResult((int) pageable.getOffset())
.setMaxResults(pageable.getPageSize()).getResultList().stream().collect(Collectors.toList());
final List<String> result = new ArrayList<>(entityManager.createQuery(selMsgQuery)
.setFirstResult((int) pageable.getOffset()).setMaxResults(pageable.getPageSize()).getResultList());
return new PageImpl<>(result, pageable, totalCount);
}

View File

@@ -188,14 +188,13 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
toBeChangedDSs.add(set);
}
}
result = new DistributionSetTagAssignmentResult(dsIds.size() - toBeChangedDSs.size(), 0,
toBeChangedDSs.size(), Collections.emptyList(),
result = new DistributionSetTagAssignmentResult(dsIds.size() - toBeChangedDSs.size(),
Collections.emptyList(),
Collections.unmodifiableList(
toBeChangedDSs.stream().map(distributionSetRepository::save).collect(Collectors.toList())),
myTag);
} else {
result = new DistributionSetTagAssignmentResult(dsIds.size() - toBeChangedDSs.size(), toBeChangedDSs.size(),
0,
result = new DistributionSetTagAssignmentResult(dsIds.size() - toBeChangedDSs.size(),
Collections.unmodifiableList(
toBeChangedDSs.stream().map(distributionSetRepository::save).collect(Collectors.toList())),
Collections.emptyList(), myTag);
@@ -386,7 +385,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
specList = Arrays.asList(DistributionSetSpecification.isDeleted(false),
DistributionSetSpecification.isCompleted(complete));
} else {
specList = Arrays.asList(DistributionSetSpecification.isDeleted(false));
specList = Collections.singletonList(DistributionSetSpecification.isDeleted(false));
}
return convertDsPage(findByCriteriaAPI(pageReq, specList), pageReq);
@@ -754,7 +753,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
public void delete(final long setId) {
throwExceptionIfDistributionSetDoesNotExist(setId);
delete(Arrays.asList(setId));
delete(Collections.singletonList(setId));
}
private void throwExceptionIfDistributionSetDoesNotExist(final Long setId) {
@@ -811,7 +810,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Override
public Optional<DistributionSet> get(final long id) {
return distributionSetRepository.findById(id).map(d -> (DistributionSet) d);
return distributionSetRepository.findById(id).map(d -> d);
}
@Override

View File

@@ -294,7 +294,7 @@ public class JpaTargetManagement implements TargetManagement {
final Long targetId = getByControllerIdAndThrowIfNotFound(controllerId).getId();
return targetMetadataRepository.findById(new TargetMetadataCompositeKey(targetId, key))
.map(t -> (TargetMetadata) t);
.map(t -> t);
}
@Override
@@ -470,14 +470,14 @@ public class JpaTargetManagement implements TargetManagement {
specList.add(TargetSpecifications
.likeIdOrNameOrDescriptionOrAttributeValue(filterParams.getFilterBySearchText()));
}
if (isHasTagsFilterActive(filterParams)) {
if (hasTagsFilterActive(filterParams)) {
specList.add(TargetSpecifications.hasTags(filterParams.getFilterByTagNames(),
filterParams.getSelectTargetWithNoTag()));
}
return specList;
}
private static boolean isHasTagsFilterActive(final FilterParams filterParams) {
private static boolean hasTagsFilterActive(final FilterParams filterParams) {
return ((filterParams.getSelectTargetWithNoTag() != null) && filterParams.getSelectTargetWithNoTag())
|| ((filterParams.getFilterByTagNames() != null) && (filterParams.getFilterByTagNames().length > 0));
}
@@ -520,7 +520,7 @@ public class JpaTargetManagement implements TargetManagement {
// all are already assigned -> unassign
if (alreadyAssignedTargets.size() == allTargets.size()) {
alreadyAssignedTargets.forEach(target -> target.removeTag(tag));
return new TargetTagAssignmentResult(0, 0, alreadyAssignedTargets.size(), Collections.emptyList(),
return new TargetTagAssignmentResult(0, Collections.emptyList(),
Collections.unmodifiableList(alreadyAssignedTargets), tag);
}
@@ -528,7 +528,6 @@ public class JpaTargetManagement implements TargetManagement {
// some or none are assigned -> assign
allTargets.forEach(target -> target.addTag(tag));
final TargetTagAssignmentResult result = new TargetTagAssignmentResult(alreadyAssignedTargets.size(),
allTargets.size(), 0,
Collections
.unmodifiableList(allTargets.stream().map(targetRepository::save).collect(Collectors.toList())),
Collections.emptyList(), tag);
@@ -776,7 +775,7 @@ public class JpaTargetManagement implements TargetManagement {
@Override
public Optional<Target> get(final long id) {
return targetRepository.findById(id).map(t -> (Target) t);
return targetRepository.findById(id).map(t -> t);
}
@Override

View File

@@ -59,7 +59,7 @@ public class OnlineDsAssignmentStrategy extends AbstractDsAssignmentStrategy {
@Override
void sendTargetUpdatedEvents(final DistributionSet set, final List<JpaTarget> targets) {
targets.stream().forEach(target -> {
targets.forEach(target -> {
target.setUpdateStatus(TargetUpdateStatus.PENDING);
sendTargetUpdatedEvent(target);
});
@@ -77,7 +77,7 @@ public class OnlineDsAssignmentStrategy extends AbstractDsAssignmentStrategy {
@Override
void sendDeploymentEvents(final List<DistributionSetAssignmentResult> assignmentResults) {
if (isMultiAssignmentsEnabled()) {
sendDeploymentEvent(assignmentResults.stream().flatMap(result -> result.getActions().stream())
sendDeploymentEvent(assignmentResults.stream().flatMap(result -> result.getAssignedEntity().stream())
.collect(Collectors.toList()));
} else {
assignmentResults.forEach(this::sendDistributionSetAssignedEvent);
@@ -170,7 +170,7 @@ public class OnlineDsAssignmentStrategy extends AbstractDsAssignmentStrategy {
private DistributionSetAssignmentResult sendDistributionSetAssignedEvent(
final DistributionSetAssignmentResult assignmentResult) {
final List<Action> filteredActions = filterCancellations(assignmentResult.getActions())
final List<Action> filteredActions = filterCancellations(assignmentResult.getAssignedEntity())
.filter(action -> !hasPendingCancellations(action.getTarget())).collect(Collectors.toList());
final DistributionSet set = assignmentResult.getDistributionSet();
sendTargetAssignDistributionSetEvent(set.getTenant(), set.getId(), filteredActions);

View File

@@ -666,16 +666,16 @@ public class RepositoryApplicationConfiguration extends JpaBaseConfiguration {
DeploymentManagement deploymentManagement(final EntityManager entityManager,
final ActionRepository actionRepository, final DistributionSetRepository distributionSetRepository,
final TargetRepository targetRepository, final ActionStatusRepository actionStatusRepository,
final TargetManagement targetManagement, final AuditorAware<String> auditorProvider,
final EventPublisherHolder eventPublisherHolder, final AfterTransactionCommitExecutor afterCommit,
final VirtualPropertyReplacer virtualPropertyReplacer, final PlatformTransactionManager txManager,
final AuditorAware<String> auditorProvider, final EventPublisherHolder eventPublisherHolder,
final AfterTransactionCommitExecutor afterCommit, final VirtualPropertyReplacer virtualPropertyReplacer,
final PlatformTransactionManager txManager,
final TenantConfigurationManagement tenantConfigurationManagement, final QuotaManagement quotaManagement,
final SystemSecurityContext systemSecurityContext, final TenantAware tenantAware,
final JpaProperties properties) {
return new JpaDeploymentManagement(entityManager, actionRepository, distributionSetRepository, targetRepository,
actionStatusRepository, targetManagement, auditorProvider, eventPublisherHolder, afterCommit,
virtualPropertyReplacer, txManager, tenantConfigurationManagement, quotaManagement,
systemSecurityContext, tenantAware, properties.getDatabase());
actionStatusRepository, auditorProvider, eventPublisherHolder, afterCommit, virtualPropertyReplacer,
txManager, tenantConfigurationManagement, quotaManagement, systemSecurityContext, tenantAware,
properties.getDatabase());
}
/**

View File

@@ -493,8 +493,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(
controllerManagement.hasTargetArtifactAssigned(savedTarget.getControllerId(), artifact.getSha1Hash()))
.isFalse();
savedTarget = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getAssignedEntity().iterator()
.next();
savedTarget = getFirstAssignedTarget(assignDistributionSet(ds.getId(), savedTarget.getControllerId()));
assertThat(
controllerManagement.hasTargetArtifactAssigned(savedTarget.getControllerId(), artifact.getSha1Hash()))
.isTrue();
@@ -1056,7 +1055,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet testDs = testdataFactory.createDistributionSet("1");
final List<Target> testTarget = testdataFactory.createTargets(1);
final Long actionId = assignDistributionSet(testDs, testTarget).getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(assignDistributionSet(testDs, testTarget));
controllerManagement.addUpdateActionStatus(entityFactory.actionStatus().create(actionId)
.status(Action.Status.RUNNING).messages(Lists.newArrayList("proceeding message 1")));
@@ -1084,8 +1083,8 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
final int maxStatusEntries = quotaManagement.getMaxStatusEntriesPerAction() - 1;
// test for informational status
final Long actionId1 = assignDistributionSet(testdataFactory.createDistributionSet("ds1"),
testdataFactory.createTargets(1, "t1")).getActionIds().get(0);
final Long actionId1 = getFirstAssignedActionId(assignDistributionSet(
testdataFactory.createDistributionSet("ds1"), testdataFactory.createTargets(1, "t1")));
assertThat(actionId1).isNotNull();
for (int i = 0; i < maxStatusEntries; ++i) {
controllerManagement.addInformationalActionStatus(entityFactory.actionStatus().create(actionId1)
@@ -1095,8 +1094,8 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
.addInformationalActionStatus(entityFactory.actionStatus().create(actionId1).status(Status.WARNING)));
// test for update status (and mixed case)
final Long actionId2 = assignDistributionSet(testdataFactory.createDistributionSet("ds2"),
testdataFactory.createTargets(1, "t2")).getActionIds().get(0);
final Long actionId2 = getFirstAssignedActionId(assignDistributionSet(
testdataFactory.createDistributionSet("ds2"), testdataFactory.createTargets(1, "t2")));
assertThat(actionId2).isNotEqualTo(actionId1);
for (int i = 0; i < maxStatusEntries; ++i) {
controllerManagement.addUpdateActionStatus(entityFactory.actionStatus().create(actionId2)
@@ -1118,8 +1117,8 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
final int maxMessages = quotaManagement.getMaxMessagesPerActionStatus();
final Long actionId = assignDistributionSet(testdataFactory.createDistributionSet("ds1"),
testdataFactory.createTargets(1)).getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(
assignDistributionSet(testdataFactory.createDistributionSet("ds1"), testdataFactory.createTargets(1)));
assertThat(actionId).isNotNull();
final List<String> messages = Lists.newArrayList();
@@ -1331,7 +1330,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
testdataFactory.createTarget(knownControllerId);
final DistributionSetAssignmentResult assignmentResult = deploymentManagement.assignDistributionSet(
knownDistributionSet.getId(), ActionType.FORCED, 0, Collections.singleton(knownControllerId));
final Long actionId = assignmentResult.getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(assignmentResult);
controllerManagement.updateActionExternalRef(actionId, knownExternalref);
allExternalRef.add(knownExternalref);
@@ -1432,7 +1431,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
final Long forcedDistributionSetId = testdataFactory.createDistributionSet("forcedDs1").getId();
final DistributionSetAssignmentResult assignmentResult = assignDistributionSet(forcedDistributionSetId,
DEFAULT_CONTROLLER_ID, Action.ActionType.SOFT);
addUpdateActionStatus(assignmentResult.getActions().get(0).getId(), DEFAULT_CONTROLLER_ID, Status.FINISHED);
addUpdateActionStatus(getFirstAssignedActionId(assignmentResult), DEFAULT_CONTROLLER_ID, Status.FINISHED);
assertAssignedDistributionSetId(DEFAULT_CONTROLLER_ID, forcedDistributionSetId);
assertInstalledDistributionSetId(DEFAULT_CONTROLLER_ID, forcedDistributionSetId);
assertNoActiveActionsExistsForControllerId(DEFAULT_CONTROLLER_ID);

View File

@@ -98,13 +98,14 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) })
public void entityQueriesReferringToNotExistingEntitiesThrowsException() {
final Target target = testdataFactory.createTarget();
final String dsName = "DistributionSet";
verifyThrownExceptionBy(() -> deploymentManagement.assignDistributionSet(NOT_EXIST_IDL,
Arrays.asList(new TargetWithActionType(target.getControllerId()))), "DistributionSet");
Collections.singletonList(new TargetWithActionType(target.getControllerId()))), dsName);
verifyThrownExceptionBy(() -> deploymentManagement.assignDistributionSet(NOT_EXIST_IDL,
Arrays.asList(new TargetWithActionType(target.getControllerId())), "xxx"), "DistributionSet");
Collections.singletonList(new TargetWithActionType(target.getControllerId())), "xxx"), dsName);
verifyThrownExceptionBy(() -> deploymentManagement.assignDistributionSet(NOT_EXIST_IDL, ActionType.FORCED,
System.currentTimeMillis(), Arrays.asList(target.getControllerId())), "DistributionSet");
System.currentTimeMillis(), Collections.singletonList(target.getControllerId())), dsName);
verifyThrownExceptionBy(() -> deploymentManagement.cancelAction(NOT_EXIST_IDL), "Action");
verifyThrownExceptionBy(() -> deploymentManagement.countActionsByTarget(NOT_EXIST_ID), "Target");
@@ -128,7 +129,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
new ArrayList<DistributionSetTag>());
final List<Target> testTarget = testdataFactory.createTargets(1);
// one action with one action status is generated
final Long actionId = assignDistributionSet(testDs, testTarget).getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(assignDistributionSet(testDs, testTarget));
final Action action = deploymentManagement.findActionWithDetails(actionId).get();
assertThat(action.getDistributionSet()).as("DistributionSet in action").isNotNull();
@@ -145,7 +146,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
new ArrayList<DistributionSetTag>());
final List<Target> testTarget = testdataFactory.createTargets(1);
// one action with one action status is generated
final Long actionId = assignDistributionSet(testDs, testTarget).getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(assignDistributionSet(testDs, testTarget));
// act
final Slice<Action> actions = deploymentManagement.findActionsByTarget(testTarget.get(0).getControllerId(),
@@ -190,11 +191,10 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test verifies that action-states of an action are found by using id-based search.")
public void findActionStatusByActionId() {
final DistributionSet testDs = testdataFactory.createDistributionSet("TestDs", "1.0",
new ArrayList<DistributionSetTag>());
final DistributionSet testDs = testdataFactory.createDistributionSet("TestDs", "1.0", Collections.emptyList());
final List<Target> testTarget = testdataFactory.createTargets(1);
// one action with one action status is generated
final Long actionId = assignDistributionSet(testDs, testTarget).getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(assignDistributionSet(testDs, testTarget));
final Slice<Action> actions = deploymentManagement.findActionsByTarget(testTarget.get(0).getControllerId(),
PAGE);
final ActionStatus expectedActionStatus = ((JpaAction) actions.getContent().get(0)).getActionStatus().get(0);
@@ -213,10 +213,10 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
new ArrayList<DistributionSetTag>());
final List<Target> testTarget = testdataFactory.createTargets(1);
// one action with one action status is generated
final Long actionId = assignDistributionSet(testDs, testTarget).getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(assignDistributionSet(testDs, testTarget));
// create action-status entry with one message
controllerManagement.addUpdateActionStatus(entityFactory.actionStatus().create(actionId)
.status(Action.Status.FINISHED).messages(Arrays.asList("finished message")));
.status(Action.Status.FINISHED).messages(Collections.singletonList("finished message")));
final Page<ActionStatus> actionStates = deploymentManagement.findActionStatusByAction(PAGE, actionId);
// find newly created action-status entry with message
@@ -465,12 +465,14 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final long current = System.currentTimeMillis();
final List<Target> targets = deploymentManagement.offlineAssignedDistributionSet(ds.getId(), controllerIds)
.getAssignedEntity();
.getAssignedEntity().stream().map(Action::getTarget).collect(Collectors.toList());;
assertThat(actionRepository.count()).isEqualTo(20);
assertThat(actionRepository.findByDistributionSetId(PAGE, ds.getId())).as("Offline actions are not active")
.allMatch(action -> !action.isActive());
assertThat(targetManagement.findByInstalledDistributionSet(PAGE, ds.getId()).getContent()).containsAll(targets)
.hasSize(10).containsAll(targetManagement.findByAssignedDistributionSet(PAGE, ds.getId()))
assertThat(targetManagement.findByInstalledDistributionSet(PAGE, ds.getId()).getContent())
.usingElementComparator(controllerIdComparator()).containsAll(targets).hasSize(10)
.containsAll(targetManagement.findByAssignedDistributionSet(PAGE, ds.getId()))
.as("InstallationDate set").allMatch(target -> target.getInstallationDate() >= current)
.as("TargetUpdateStatus IN_SYNC")
.allMatch(target -> TargetUpdateStatus.IN_SYNC.equals(target.getUpdateStatus()))
@@ -630,7 +632,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final SoftwareModule os = testdataFactory.createSoftwareModuleOs();
final DistributionSet incomplete = distributionSetManagement.create(entityFactory.distributionSet().create()
.name("incomplete").version("v1").type(standardDsType).modules(Arrays.asList(ah.getId())));
.name("incomplete").version("v1").type(standardDsType).modules(Collections.singletonList(ah.getId())));
try {
assignDistributionSet(incomplete, targets);
@@ -698,7 +700,9 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
// test the content of different lists
assertThat(allFoundTargets).as("content of founded target is wrong").containsAll(deployedTargetsFromDB)
.containsAll(undeployedTargetsFromDB);
assertThat(deployedTargetsFromDB).as("content of deployed target is wrong").containsAll(savedDeployedTargets)
assertThat(deployedTargetsFromDB).as("content of deployed target is wrong")
.usingElementComparator(controllerIdComparator()).containsAll(savedDeployedTargets)
.doesNotContain(Iterables.toArray(undeployedTargetsFromDB, JpaTarget.class));
assertThat(undeployedTargetsFromDB).as("content of undeployed target is wrong").containsAll(savedNakedTargets)
.doesNotContain(Iterables.toArray(deployedTargetsFromDB, JpaTarget.class));
@@ -769,15 +773,16 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
// remove updActB from
// activeActions, add a corresponding cancelAction and another
// UpdateAction for dsA
final Iterable<Target> deployed2DS = assignDistributionSet(dsA, deployResWithDsB.getDeployedTargets())
.getAssignedEntity();
final List<Target> deployed2DS = assignDistributionSet(dsA, deployResWithDsB.getDeployedTargets())
.getAssignedEntity().stream().map(Action::getTarget).collect(Collectors.toList());
actionRepository.findByDistributionSetId(pageRequest, dsA.getId()).getContent().get(1);
// get final updated version of targets
final List<Target> deployResWithDsBTargets = targetManagement.getByControllerID(deployResWithDsB
.getDeployedTargets().stream().map(Target::getControllerId).collect(Collectors.toList()));
assertThat(deployed2DS).as("deployed ds is wrong").containsAll(deployResWithDsBTargets);
assertThat(deployed2DS).as("deployed ds is wrong").usingElementComparator(controllerIdComparator())
.containsAll(deployResWithDsBTargets);
assertThat(deployed2DS).as("deployed ds is wrong").hasSameSizeAs(deployResWithDsBTargets);
for (final Target t_ : deployed2DS) {
@@ -892,10 +897,11 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet dsA = testdataFactory.createDistributionSet("a");
final DistributionSet dsB = testdataFactory.createDistributionSet("b");
List<Target> targs = Arrays.asList(testdataFactory.createTarget("target-id-A"));
List<Target> targs = Collections.singletonList(testdataFactory.createTarget("target-id-A"));
// doing the assignment
targs = assignDistributionSet(dsA, targs).getAssignedEntity();
targs = assignDistributionSet(dsA, targs).getAssignedEntity().stream().map(Action::getTarget)
.collect(Collectors.toList());
Target targ = targetManagement.getByControllerID(targs.iterator().next().getControllerId()).get();
// checking the revisions of the created entities
@@ -934,7 +940,8 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertEquals("wrong installed ds", dsA,
deploymentManagement.getInstalledDistributionSet(targ.getControllerId()).get());
targs = assignDistributionSet(dsB.getId(), "target-id-A").getAssignedEntity();
targs = assignDistributionSet(dsB.getId(), "target-id-A").getAssignedEntity().stream().map(Action::getTarget)
.collect(Collectors.toList());
targ = targs.iterator().next();
@@ -962,7 +969,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(dsA.getOptLockRevision()).as("lock revision is wrong")
.isEqualTo(distributionSetManagement.getWithDetails(dsA.getId()).get().getOptLockRevision());
assignDistributionSet(dsA, Arrays.asList(targ));
assignDistributionSet(dsA, Collections.singletonList(targ));
assertThat(dsA.getOptLockRevision()).as("lock revision is wrong")
.isEqualTo(distributionSetManagement.getWithDetails(dsA.getId()).get().getOptLockRevision());
@@ -978,8 +985,8 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final DistributionSetAssignmentResult assignDistributionSet = deploymentManagement.assignDistributionSet(
ds.getId(), ActionType.SOFT,
org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME,
Arrays.asList(target.getControllerId()));
final Long actionId = assignDistributionSet.getActionIds().get(0);
Collections.singletonList(target.getControllerId()));
final Long actionId = getFirstAssignedActionId(assignDistributionSet);
// verify preparation
Action findAction = deploymentManagement.findAction(actionId).get();
assertThat(findAction.getActionType()).as("action type is wrong").isEqualTo(ActionType.SOFT);
@@ -1002,8 +1009,8 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final DistributionSetAssignmentResult assignDistributionSet = deploymentManagement.assignDistributionSet(
ds.getId(), ActionType.FORCED,
org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME,
Arrays.asList(target.getControllerId()));
final Long actionId = assignDistributionSet.getActionIds().get(0);
Collections.singletonList(target.getControllerId()));
final Long actionId = getFirstAssignedActionId(assignDistributionSet);
// verify perparation
Action findAction = deploymentManagement.findAction(actionId).get();
assertThat(findAction.getActionType()).as("action type is wrong").isEqualTo(ActionType.FORCED);
@@ -1017,6 +1024,50 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(findAction.getActionType()).as("action type is wrong").isEqualTo(ActionType.FORCED);
}
@Test
@Description("Tests the computation of already assigned entities returned as a result of an assignment")
public void testAlreadyAssignedAndAssignedActionsInAssignmentResult(){
// create target1, distributionSet, assign ds to target1 and finish update (close all actions)
final Action action = prepareFinishedUpdate("target1", "ds", false);
final Target target2 = testdataFactory.createTarget("target2");
final Target target3 = testdataFactory.createTarget("target3");
// assign ds to target2, but don't finish update (actions should be still open)
assignDistributionSet(action.getDistributionSet().getId(), target2.getControllerId());
final DistributionSetAssignmentResult assignmentResult = deploymentManagement.assignDistributionSet(
action.getDistributionSet().getId(),
Arrays.asList(new TargetWithActionType(action.getTarget().getControllerId()),
new TargetWithActionType(target3.getControllerId())));
assertThat(assignmentResult).isNotNull();
assertThat(assignmentResult.getTotal()).as("Total count of assigned and already assigned targets").isEqualTo(2);
assertThat(assignmentResult.getAssigned()).as("Total count of assigned targets").isEqualTo(1);
assertThat(assignmentResult.getAlreadyAssigned()).as("Total count of already assigned targets").isEqualTo(1);
assertThat(assignmentResult.getAssignedEntity()).isNotEmpty();
assertThat(assignmentResult.getAssignedEntity()).allMatch(
a -> a.getTarget().equals(target3) && a.getDistributionSet().equals(action.getDistributionSet()));
assertThat(assignmentResult.getAssignedEntity())
.noneMatch(a -> a.getTarget().getControllerId().equals("target1"));
}
@Test
@Description("Verify that the DistributionSetAssignmentResult not contains already assigned targets.")
public void verifyDistributionSetAssignmentResultNotContainsAlreadyAssignedTargets() {
final DistributionSet dsToTargetAssigned = testdataFactory.createDistributionSet("ds-3");
// create assigned DS
final Target savedTarget = testdataFactory.createTarget();
DistributionSetAssignmentResult assignmentResult = assignDistributionSet(dsToTargetAssigned.getId(),
savedTarget.getControllerId());
assertThat(assignmentResult.getAssignedEntity()).hasSize(1);
assignmentResult = assignDistributionSet(dsToTargetAssigned.getId(), savedTarget.getControllerId());
assertThat(assignmentResult.getAssignedEntity()).hasSize(0);
assertThat(distributionSetRepository.findAll()).hasSize(1);
}
/**
* Helper methods that creates 2 lists of targets and a list of distribution
* sets.
@@ -1059,7 +1110,8 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
// assigning all DistributionSet to the Target in the list
// deployedTargets
for (final DistributionSet ds : dsList) {
deployedTargets = assignDistributionSet(ds, deployedTargets).getAssignedEntity();
deployedTargets = assignDistributionSet(ds, deployedTargets).getAssignedEntity().stream()
.map(Action::getTarget).collect(Collectors.toList());
}
return new DeploymentResult(deployedTargets, nakedTargets, dsList, deployedTargetPrefix, undeployedTargetPrefix,

View File

@@ -40,7 +40,6 @@ import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetMetadata;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult;
import org.eclipse.hawkbit.repository.model.DistributionSetFilter.DistributionSetFilterBuilder;
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
@@ -993,23 +992,6 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetManagement.findByCompleted(PAGE, true).getTotalElements()).isEqualTo(2);
}
@Test
@Description("Verify that the DistributionSetAssignmentResult not contains already assigned targets.")
public void verifyDistributionSetAssignmentResultNotContainsAlreadyAssignedTargets() {
final DistributionSet dsToTargetAssigned = testdataFactory.createDistributionSet("ds-3");
// create assigned DS
final Target savedTarget = testdataFactory.createTarget();
DistributionSetAssignmentResult assignmentResult = assignDistributionSet(dsToTargetAssigned.getId(),
savedTarget.getControllerId());
assertThat(assignmentResult.getAssignedEntity()).hasSize(1);
assignmentResult = assignDistributionSet(dsToTargetAssigned.getId(), savedTarget.getControllerId());
assertThat(assignmentResult.getAssignedEntity()).hasSize(0);
assertThat(distributionSetRepository.findAll()).hasSize(1);
}
@Test
@Description("Verify that the find all by ids contains the entities which are looking for")
@ExpectEvents({ @Expect(type = DistributionSetCreatedEvent.class, count = 12),

View File

@@ -104,7 +104,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
testdataFactory.createTarget(knownControllerId);
final DistributionSetAssignmentResult assignmentResult = deploymentManagement.assignDistributionSet(
knownDistributionSet.getId(), ActionType.FORCED, 0, Collections.singleton(knownControllerId));
final Long manuallyAssignedActionId = assignmentResult.getActionIds().get(0);
final Long manuallyAssignedActionId = getFirstAssignedActionId(assignmentResult);
// create rollout with the same distribution set already assigned
// start rollout
@@ -144,7 +144,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
testdataFactory.createTarget(knownControllerId);
final DistributionSetAssignmentResult assignmentResult = deploymentManagement.assignDistributionSet(
firstDistributionSet.getId(), ActionType.FORCED, 0, Collections.singleton(knownControllerId));
final Long manuallyAssignedActionId = assignmentResult.getActionIds().get(0);
final Long manuallyAssignedActionId = getFirstAssignedActionId(assignmentResult);
// create rollout with the same distribution set already assigned
// start rollout

View File

@@ -96,7 +96,7 @@ public class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
final String assignedB = targBs.iterator().next().getControllerId();
assignDistributionSet(setA.getId(), assignedB);
final String installedC = targCs.iterator().next().getControllerId();
final Long actionId = assignDistributionSet(installedSet.getId(), assignedC).getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(assignDistributionSet(installedSet.getId(), assignedC));
// add attributes to match against only attribute value or attribute
// value and name
@@ -578,8 +578,10 @@ public class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
final DistributionSet ds = testdataFactory.createDistributionSet("a");
targAssigned = Lists.newLinkedList(assignDistributionSet(ds, targAssigned).getAssignedEntity());
targInstalled = assignDistributionSet(ds, targInstalled).getAssignedEntity();
targAssigned = assignDistributionSet(ds, targAssigned).getAssignedEntity().stream().map(Action::getTarget)
.collect(Collectors.toList());
targInstalled = assignDistributionSet(ds, targInstalled).getAssignedEntity().stream().map(Action::getTarget)
.collect(Collectors.toList());
targInstalled = testdataFactory
.sendUpdateActionStatusToTargets(targInstalled, Status.FINISHED, Collections.singletonList("installed"))
.stream().map(Action::getTarget).collect(Collectors.toList());
@@ -598,7 +600,8 @@ public class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
expected.addAll(targAssigned);
expected.addAll(notAssigned);
assertThat(result.getContent()).containsExactly(expected.toArray(new Target[0]));
assertThat(result.getContent()).usingElementComparator(controllerIdComparator())
.containsExactly(expected.toArray(new Target[0]));
}
@@ -628,8 +631,10 @@ public class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
final DistributionSet ds = testdataFactory.createDistributionSet("a");
targAssigned = assignDistributionSet(ds, targAssigned).getAssignedEntity();
targInstalled = assignDistributionSet(ds, targInstalled).getAssignedEntity();
targAssigned = assignDistributionSet(ds, targAssigned).getAssignedEntity().stream().map(Action::getTarget)
.collect(Collectors.toList());
targInstalled = assignDistributionSet(ds, targInstalled).getAssignedEntity().stream().map(Action::getTarget)
.collect(Collectors.toList());
targInstalled = testdataFactory
.sendUpdateActionStatusToTargets(targInstalled, Status.FINISHED, Collections.singletonList("installed"))
.stream().map(Action::getTarget).collect(Collectors.toList());
@@ -651,7 +656,8 @@ public class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.filter(item -> lastTargetQueryAlwaysOverdue.equals(item.getLastTargetQuery()))
.collect(Collectors.toList()));
assertThat(result.getContent()).containsExactly(expected.toArray(new Target[0]));
assertThat(result.getContent()).usingElementComparator(controllerIdComparator())
.containsExactly(expected.toArray(new Target[0]));
}
@@ -701,8 +707,8 @@ public class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
List<Target> installedtargets = testdataFactory.createTargets(10, "assigned", "assigned");
// set on installed and assign another one
assignDistributionSet(installedSet, installedtargets).getActionIds().forEach(actionId -> controllerManagement
.addUpdateActionStatus(entityFactory.actionStatus().create(actionId).status(Status.FINISHED)));
assignDistributionSet(installedSet, installedtargets).getAssignedEntity().forEach(action -> controllerManagement
.addUpdateActionStatus(entityFactory.actionStatus().create(action.getId()).status(Status.FINISHED)));
assignDistributionSet(assignedSet, installedtargets);
// get final updated version of targets

View File

@@ -478,7 +478,7 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest {
final DistributionSetAssignmentResult result = assignDistributionSet(set.getId(), "4711");
controllerManagement.addUpdateActionStatus(
entityFactory.actionStatus().create(result.getActionIds().get(0)).status(Status.FINISHED));
entityFactory.actionStatus().create(getFirstAssignedActionId(result)).status(Status.FINISHED));
assignDistributionSet(set2.getId(), "4711");
target = targetManagement.getByControllerID("4711").get();

View File

@@ -59,7 +59,7 @@ public class AutoAssignCheckerTest extends AbstractJpaIntegrationTest {
testdataFactory.createTarget(knownControllerId);
final DistributionSetAssignmentResult assignmentResult = deploymentManagement.assignDistributionSet(
firstDistributionSet.getId(), ActionType.FORCED, 0, Collections.singleton(knownControllerId));
final Long manuallyAssignedActionId = assignmentResult.getActionIds().get(0);
final Long manuallyAssignedActionId = getFirstAssignedActionId(assignmentResult);
// target filter query that matches all targets
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement

View File

@@ -80,8 +80,8 @@ public class AutoActionCleanupTest extends AbstractJpaIntegrationTest {
final DistributionSet ds1 = testdataFactory.createDistributionSet("ds1");
final DistributionSet ds2 = testdataFactory.createDistributionSet("ds2");
final Long action1 = deploymentManagement.assignDistributionSet(ds1.getId(), ActionType.FORCED, 0,
Collections.singletonList(trg1.getControllerId())).getActionIds().get(0);
final Long action1 = getFirstAssignedActionId(deploymentManagement.assignDistributionSet(ds1.getId(),
ActionType.FORCED, 0, Collections.singletonList(trg1.getControllerId())));
deploymentManagement.assignDistributionSet(ds2.getId(), ActionType.FORCED, 0,
Collections.singletonList(trg2.getControllerId()));
@@ -109,12 +109,12 @@ public class AutoActionCleanupTest extends AbstractJpaIntegrationTest {
final DistributionSet ds1 = testdataFactory.createDistributionSet("ds1");
final DistributionSet ds2 = testdataFactory.createDistributionSet("ds2");
final Long action1 = deploymentManagement.assignDistributionSet(ds1.getId(), ActionType.FORCED, 0,
Collections.singletonList(trg1.getControllerId())).getActionIds().get(0);
final Long action2 = deploymentManagement.assignDistributionSet(ds2.getId(), ActionType.FORCED, 0,
Collections.singletonList(trg2.getControllerId())).getActionIds().get(0);
final Long action3 = deploymentManagement.assignDistributionSet(ds2.getId(), ActionType.FORCED, 0,
Collections.singletonList(trg3.getControllerId())).getActionIds().get(0);
final Long action1 = getFirstAssignedActionId(deploymentManagement.assignDistributionSet(ds1.getId(),
ActionType.FORCED, 0, Collections.singletonList(trg1.getControllerId())));
final Long action2 = getFirstAssignedActionId(deploymentManagement.assignDistributionSet(ds2.getId(),
ActionType.FORCED, 0, Collections.singletonList(trg2.getControllerId())));
final Long action3 = getFirstAssignedActionId(deploymentManagement.assignDistributionSet(ds2.getId(),
ActionType.FORCED, 0, Collections.singletonList(trg3.getControllerId())));
assertThat(actionRepository.count()).isEqualTo(3);
@@ -144,12 +144,12 @@ public class AutoActionCleanupTest extends AbstractJpaIntegrationTest {
final DistributionSet ds1 = testdataFactory.createDistributionSet("ds1");
final DistributionSet ds2 = testdataFactory.createDistributionSet("ds2");
final Long action1 = deploymentManagement.assignDistributionSet(ds1.getId(), ActionType.FORCED, 0,
Collections.singletonList(trg1.getControllerId())).getActionIds().get(0);
final Long action2 = deploymentManagement.assignDistributionSet(ds2.getId(), ActionType.FORCED, 0,
Collections.singletonList(trg2.getControllerId())).getActionIds().get(0);
final Long action3 = deploymentManagement.assignDistributionSet(ds2.getId(), ActionType.FORCED, 0,
Collections.singletonList(trg3.getControllerId())).getActionIds().get(0);
final Long action1 = getFirstAssignedActionId(deploymentManagement.assignDistributionSet(ds1.getId(),
ActionType.FORCED, 0, Collections.singletonList(trg1.getControllerId())));
final Long action2 = getFirstAssignedActionId(deploymentManagement.assignDistributionSet(ds2.getId(),
ActionType.FORCED, 0, Collections.singletonList(trg2.getControllerId())));
final Long action3 = getFirstAssignedActionId(deploymentManagement.assignDistributionSet(ds2.getId(),
ActionType.FORCED, 0, Collections.singletonList(trg3.getControllerId())));
assertThat(actionRepository.count()).isEqualTo(3);
@@ -181,12 +181,12 @@ public class AutoActionCleanupTest extends AbstractJpaIntegrationTest {
final DistributionSet ds1 = testdataFactory.createDistributionSet("ds1");
final DistributionSet ds2 = testdataFactory.createDistributionSet("ds2");
final Long action1 = deploymentManagement.assignDistributionSet(ds1.getId(), ActionType.FORCED, 0,
Collections.singletonList(trg1.getControllerId())).getActionIds().get(0);
final Long action2 = deploymentManagement.assignDistributionSet(ds2.getId(), ActionType.FORCED, 0,
Collections.singletonList(trg2.getControllerId())).getActionIds().get(0);
final Long action3 = deploymentManagement.assignDistributionSet(ds2.getId(), ActionType.FORCED, 0,
Collections.singletonList(trg3.getControllerId())).getActionIds().get(0);
final Long action1 = getFirstAssignedActionId(deploymentManagement.assignDistributionSet(ds1.getId(),
ActionType.FORCED, 0, Collections.singletonList(trg1.getControllerId())));
final Long action2 = getFirstAssignedActionId(deploymentManagement.assignDistributionSet(ds2.getId(),
ActionType.FORCED, 0, Collections.singletonList(trg2.getControllerId())));
final Long action3 = getFirstAssignedActionId(deploymentManagement.assignDistributionSet(ds2.getId(),
ActionType.FORCED, 0, Collections.singletonList(trg3.getControllerId())));
assertThat(actionRepository.count()).isEqualTo(3);

View File

@@ -17,6 +17,7 @@ import java.net.URI;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
@@ -321,8 +322,8 @@ public abstract class AbstractIntegrationTest {
final boolean isRequiredMigrationStep) {
final DistributionSet ds = testdataFactory.createDistributionSet(distributionSet, isRequiredMigrationStep);
Target savedTarget = testdataFactory.createTarget(controllerId);
savedTarget = assignDistributionSet(ds.getId(), savedTarget.getControllerId(), ActionType.FORCED)
.getAssignedEntity().iterator().next();
savedTarget = getFirstAssignedTarget(
assignDistributionSet(ds.getId(), savedTarget.getControllerId(), ActionType.FORCED));
Action savedAction = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
.getContent().get(0);
@@ -434,4 +435,21 @@ public abstract class AbstractIntegrationTest {
return randomStringBuilder.toString();
}
protected static Action getFirstAssignedAction(final DistributionSetAssignmentResult distributionSetAssignmentResult) {
return distributionSetAssignmentResult.getAssignedEntity().stream().findFirst()
.orElseThrow(() -> new IllegalStateException("expected one assigned action, found none"));
}
protected static Long getFirstAssignedActionId(final DistributionSetAssignmentResult distributionSetAssignmentResult) {
return getFirstAssignedAction(distributionSetAssignmentResult).getId();
}
protected static Target getFirstAssignedTarget(final DistributionSetAssignmentResult assignment) {
return getFirstAssignedAction(assignment).getTarget();
}
protected static Comparator<Target> controllerIdComparator() {
return (o1, o2) -> o1.getControllerId().equals(o2.getControllerId()) ? 0 : 1;
}
}

View File

@@ -52,8 +52,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
public void cancelActionCbor() throws Exception {
final DistributionSet ds = testdataFactory.createDistributionSet("");
testdataFactory.createTarget();
final Long actionId = assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActionIds()
.get(0);
final Long actionId = getFirstAssignedActionId(
assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID));
final Action cancelAction = deploymentManagement.cancelAction(actionId);
// check that we can get the cancel action as CBOR
@@ -80,7 +80,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final DistributionSet ds = testdataFactory.createDistributionSet("");
final Target savedTarget = testdataFactory.createTarget();
final Long actionId = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(
assignDistributionSet(ds.getId(), savedTarget.getControllerId()));
final Action cancelAction = deploymentManagement.cancelAction(actionId);
@@ -133,7 +134,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final DistributionSet ds = testdataFactory.createDistributionSet("");
final Target savedTarget = testdataFactory.createTarget();
final Long actionId = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(
assignDistributionSet(ds.getId(), savedTarget.getControllerId()));
long current = System.currentTimeMillis();
mvc.perform(get("/{tenant}/controller/v1/{controller}", tenantAware.getCurrentTenant(),
@@ -249,7 +251,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final Target savedTarget = testdataFactory.createTarget(targetid);
final List<Target> toAssign = new ArrayList<>();
toAssign.add(savedTarget);
final Long actionId = assignDistributionSet(ds, toAssign).getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(assignDistributionSet(ds, toAssign));
return deploymentManagement.cancelAction(actionId);
}
@@ -262,8 +264,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final Target savedTarget = testdataFactory.createTarget();
final Long actionId = assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActionIds()
.get(0);
final Long actionId = getFirstAssignedActionId(
assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID));
// cancel action manually
final Action cancelAction = deploymentManagement.cancelAction(actionId);
@@ -337,12 +339,12 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final Target savedTarget = testdataFactory.createTarget();
final Long actionId = assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActionIds()
.get(0);
final Long actionId2 = assignDistributionSet(ds2.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActionIds()
.get(0);
final Long actionId3 = assignDistributionSet(ds3.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActionIds()
.get(0);
final Long actionId = getFirstAssignedActionId(
assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID));
final Long actionId2 = getFirstAssignedActionId(
assignDistributionSet(ds2.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID));
final Long actionId3 = getFirstAssignedActionId(
assignDistributionSet(ds3.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID));
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3);
@@ -451,8 +453,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
testdataFactory.createTarget();
final DistributionSet ds = testdataFactory.createDistributionSet("");
final Long actionId = assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActionIds()
.get(0);
final Long actionId = getFirstAssignedActionId(
assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID));
final Action cancelAction = deploymentManagement.cancelAction(actionId);

View File

@@ -25,6 +25,7 @@ import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.commons.lang3.RandomUtils;
import org.assertj.core.api.Condition;
@@ -156,7 +157,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final List<Target> targetsAssignedToDs = deploymentManagement
.assignDistributionSet(ds.getId(), ActionType.FORCED, RepositoryModelConstants.NO_FORCE_TIME,
Collections.singletonList(savedTarget.getControllerId()))
.getAssignedEntity();
.getAssignedEntity().stream().map(Action::getTarget).collect(Collectors.toList());;
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
final Action action = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
@@ -207,9 +208,9 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final Target target = testdataFactory.createTarget(DEFAULT_CONTROLLER_ID);
final DistributionSet ds = testdataFactory.createDistributionSet("", true);
final Long actionId = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.TIMEFORCED,
System.currentTimeMillis() + 2_000, Collections.singletonList(target.getControllerId())).getActionIds()
.get(0);
final Long actionId = getFirstAssignedActionId(
deploymentManagement.assignDistributionSet(ds.getId(), ActionType.TIMEFORCED,
System.currentTimeMillis() + 2_000, Collections.singletonList(target.getControllerId())));
MvcResult mvcResult = performGet("/{tenant}/controller/v1/" + DEFAULT_CONTROLLER_ID, MediaTypes.HAL_JSON,
status().isOk(), tenantAware.getCurrentTenant()).andReturn();
@@ -258,7 +259,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final List<Target> saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.SOFT,
RepositoryModelConstants.NO_FORCE_TIME, Collections.singletonList(savedTarget.getControllerId()))
.getAssignedEntity();
.getAssignedEntity().stream().map(Action::getTarget).collect(Collectors.toList());
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
final Action action = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
@@ -318,7 +319,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final List<Target> saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.TIMEFORCED,
System.currentTimeMillis(), Collections.singletonList(savedTarget.getControllerId()))
.getAssignedEntity();
.getAssignedEntity().stream().map(Action::getTarget).collect(Collectors.toList());
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
final Action action = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
@@ -386,7 +387,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final List<Target> saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.DOWNLOAD_ONLY,
RepositoryModelConstants.NO_FORCE_TIME, Collections.singletonList(savedTarget.getControllerId()))
.getAssignedEntity();
.getAssignedEntity().stream().map(Action::getTarget).collect(Collectors.toList());
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
final Action action = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
@@ -528,7 +529,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final List<Target> toAssign = Collections.singletonList(target);
final DistributionSet savedSet = testdataFactory.createDistributionSet("");
final Long actionId = assignDistributionSet(savedSet, toAssign).getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(assignDistributionSet(savedSet, toAssign));
mvc.perform(MockMvcRequestBuilders.get(DEPLOYMENT_BASE + actionId, tenantAware.getCurrentTenant(),
DEFAULT_CONTROLLER_ID)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
mvc.perform(MockMvcRequestBuilders
@@ -591,9 +592,9 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true);
final DistributionSet ds3 = testdataFactory.createDistributionSet("3", true);
final Long actionId1 = assignDistributionSet(ds1.getId(), DEFAULT_CONTROLLER_ID).getActionIds().get(0);
final Long actionId2 = assignDistributionSet(ds2.getId(), DEFAULT_CONTROLLER_ID).getActionIds().get(0);
final Long actionId3 = assignDistributionSet(ds3.getId(), DEFAULT_CONTROLLER_ID).getActionIds().get(0);
final Long actionId1 = getFirstAssignedActionId(assignDistributionSet(ds1.getId(), DEFAULT_CONTROLLER_ID));
final Long actionId2 = getFirstAssignedActionId(assignDistributionSet(ds2.getId(), DEFAULT_CONTROLLER_ID));
final Long actionId3 = getFirstAssignedActionId(assignDistributionSet(ds3.getId(), DEFAULT_CONTROLLER_ID));
findTargetAndAssertUpdateStatus(Optional.of(ds3), TargetUpdateStatus.PENDING, 3, Optional.empty());
assertThat(targetManagement.findByUpdateStatus(PageRequest.of(0, 10), TargetUpdateStatus.UNKNOWN)).hasSize(2);
@@ -663,39 +664,39 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
@Description("Verifies that the controller can provided as much feedback entries as necessary as long as it is in the configured limits.")
public void rootRsSingleDeploymentActionFeedback() throws Exception {
final DistributionSet ds = testdataFactory.createDistributionSet("");
final Action action = assignDistributionSet(ds,
Collections.singletonList(testdataFactory.createTarget(DEFAULT_CONTROLLER_ID))).getActions().get(0);
final Long actionId = getFirstAssignedActionId(assignDistributionSet(ds,
Collections.singletonList(testdataFactory.createTarget(DEFAULT_CONTROLLER_ID))));
findTargetAndAssertUpdateStatus(Optional.of(ds), TargetUpdateStatus.PENDING, 1, Optional.empty());
// Now valid Feedback
for (int i = 0; i < 4; i++) {
postFeedback(MediaType.APPLICATION_JSON, DEFAULT_CONTROLLER_ID, action.getId(),
JsonBuilder.deploymentActionFeedback(action.getId().toString(), "proceeding"), status().isOk());
postFeedback(MediaType.APPLICATION_JSON, DEFAULT_CONTROLLER_ID, actionId,
JsonBuilder.deploymentActionFeedback(actionId.toString(), "proceeding"), status().isOk());
assertActionStatusCount(i + 2, i);
}
postFeedback(MediaType.APPLICATION_JSON, DEFAULT_CONTROLLER_ID, action.getId(),
JsonBuilder.deploymentActionFeedback(action.getId().toString(), "scheduled"), status().isOk());
postFeedback(MediaType.APPLICATION_JSON, DEFAULT_CONTROLLER_ID, actionId,
JsonBuilder.deploymentActionFeedback(actionId.toString(), "scheduled"), status().isOk());
assertActionStatusCount(6, 5);
postFeedback(MediaType.APPLICATION_JSON, DEFAULT_CONTROLLER_ID, action.getId(),
JsonBuilder.deploymentActionFeedback(action.getId().toString(), "resumed"), status().isOk());
postFeedback(MediaType.APPLICATION_JSON, DEFAULT_CONTROLLER_ID, actionId,
JsonBuilder.deploymentActionFeedback(actionId.toString(), "resumed"), status().isOk());
assertActionStatusCount(7, 6);
postFeedback(MediaType.APPLICATION_JSON, DEFAULT_CONTROLLER_ID, action.getId(),
JsonBuilder.deploymentActionFeedback(action.getId().toString(), "canceled"), status().isOk());
postFeedback(MediaType.APPLICATION_JSON, DEFAULT_CONTROLLER_ID, actionId,
JsonBuilder.deploymentActionFeedback(actionId.toString(), "canceled"), status().isOk());
assertStatusAndActiveActionsCount(TargetUpdateStatus.PENDING, 1);
assertActionStatusCount(8, 7, 0, 0, 1);
assertTargetCountByStatus(1, 0, 0);
postFeedback(MediaType.APPLICATION_JSON, DEFAULT_CONTROLLER_ID, action.getId(),
JsonBuilder.deploymentActionFeedback(action.getId().toString(), "rejected"), status().isOk());
postFeedback(MediaType.APPLICATION_JSON, DEFAULT_CONTROLLER_ID, actionId,
JsonBuilder.deploymentActionFeedback(actionId.toString(), "rejected"), status().isOk());
assertStatusAndActiveActionsCount(TargetUpdateStatus.PENDING, 1);
assertActionStatusCount(9, 6, 1, 0, 1);
postFeedback(MediaType.APPLICATION_JSON, DEFAULT_CONTROLLER_ID, action.getId(),
JsonBuilder.deploymentActionFeedback(action.getId().toString(), "closed"), status().isOk());
postFeedback(MediaType.APPLICATION_JSON, DEFAULT_CONTROLLER_ID, actionId,
JsonBuilder.deploymentActionFeedback(actionId.toString(), "closed"), status().isOk());
assertStatusAndActiveActionsCount(TargetUpdateStatus.IN_SYNC, 0);
assertActionStatusCount(10, 7, 1, 1, 1);
assertTargetCountByStatus(0, 0, 1);

View File

@@ -369,8 +369,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
public void tryToFinishAnUpdateProcessAfterItHasBeenFinished() throws Exception {
final DistributionSet ds = testdataFactory.createDistributionSet("");
Target savedTarget = testdataFactory.createTarget("911");
savedTarget = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getAssignedEntity().iterator()
.next();
savedTarget = getFirstAssignedTarget(assignDistributionSet(ds.getId(), savedTarget.getControllerId()));
final Action savedAction = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
.getContent().get(0);
sendDeploymentActionFeedback(savedTarget, savedAction, "proceeding", null).andDo(MockMvcResultPrinter.print())
@@ -413,7 +412,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
@Step
private void assertAttributesUpdateNotRequestedAfterFailedDeployment(Target target, final DistributionSet ds)
throws Exception {
target = assignDistributionSet(ds.getId(), target.getControllerId()).getAssignedEntity().iterator().next();
target = getFirstAssignedTarget(assignDistributionSet(ds.getId(), target.getControllerId()));
final Action action = deploymentManagement.findActiveActionsByTarget(PAGE, target.getControllerId())
.getContent().get(0);
sendDeploymentActionFeedback(target, action, "closed", "failure").andExpect(status().isOk());
@@ -423,7 +422,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
@Step
private void assertAttributesUpdateRequestedAfterSuccessfulDeployment(Target target, final DistributionSet ds)
throws Exception {
target = assignDistributionSet(ds.getId(), target.getControllerId()).getAssignedEntity().iterator().next();
target = getFirstAssignedTarget(assignDistributionSet(ds.getId(), target.getControllerId()));
final Action action = deploymentManagement.findActiveActionsByTarget(PAGE, target.getControllerId())
.getContent().get(0);
sendDeploymentActionFeedback(target, action, "closed", null).andExpect(status().isOk());
@@ -474,8 +473,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
public void testActionHistoryCount() throws Exception {
final DistributionSet ds = testdataFactory.createDistributionSet("");
Target savedTarget = testdataFactory.createTarget("911");
savedTarget = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getAssignedEntity().iterator()
.next();
savedTarget = getFirstAssignedTarget(assignDistributionSet(ds.getId(), savedTarget.getControllerId()));
final Action savedAction = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
.getContent().get(0);
@@ -510,8 +508,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
public void testActionHistoryZeroInput() throws Exception {
final DistributionSet ds = testdataFactory.createDistributionSet("");
Target savedTarget = testdataFactory.createTarget("911");
savedTarget = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getAssignedEntity().iterator()
.next();
savedTarget = getFirstAssignedTarget(assignDistributionSet(ds.getId(), savedTarget.getControllerId()));
final Action savedAction = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
.getContent().get(0);
@@ -542,8 +539,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
public void testActionHistoryNegativeInput() throws Exception {
final DistributionSet ds = testdataFactory.createDistributionSet("");
Target savedTarget = testdataFactory.createTarget("911");
savedTarget = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getAssignedEntity().iterator()
.next();
savedTarget = getFirstAssignedTarget(assignDistributionSet(ds.getId(), savedTarget.getControllerId()));
final Action savedAction = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
.getContent().get(0);
@@ -620,8 +616,8 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
public void downloadAndUpdateStatusBeforeMaintenanceWindowStartTime() throws Exception {
Target savedTarget = testdataFactory.createTarget("1911");
final DistributionSet ds = testdataFactory.createDistributionSet("");
savedTarget = assignDistributionSetWithMaintenanceWindow(ds.getId(), savedTarget.getControllerId(),
getTestSchedule(2), getTestDuration(1), getTestTimeZone()).getAssignedEntity().iterator().next();
savedTarget = getFirstAssignedTarget(assignDistributionSetWithMaintenanceWindow(ds.getId(),
savedTarget.getControllerId(), getTestSchedule(2), getTestDuration(1), getTestTimeZone()));
mvc.perform(get("/default-tenant/controller/v1/1911/")).andExpect(status().isOk());
@@ -640,8 +636,8 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
public void downloadAndUpdateStatusDuringMaintenanceWindow() throws Exception {
Target savedTarget = testdataFactory.createTarget("1911");
final DistributionSet ds = testdataFactory.createDistributionSet("");
savedTarget = assignDistributionSetWithMaintenanceWindow(ds.getId(), savedTarget.getControllerId(),
getTestSchedule(-5), getTestDuration(10), getTestTimeZone()).getAssignedEntity().iterator().next();
savedTarget = getFirstAssignedTarget(assignDistributionSetWithMaintenanceWindow(ds.getId(),
savedTarget.getControllerId(), getTestSchedule(-5), getTestDuration(10), getTestTimeZone()));
mvc.perform(get("/default-tenant/controller/v1/1911/")).andExpect(status().isOk());
@@ -662,12 +658,12 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
final Target target = testdataFactory.createTarget();
final DistributionSet ds1 = testdataFactory.createDistributionSet(UUID.randomUUID().toString());
final DistributionSet ds2 = testdataFactory.createDistributionSet(UUID.randomUUID().toString());
final Action action1 = assignDistributionSet(ds1, target).getActions().get(0);
final Action action2 = assignDistributionSet(ds2, target).getActions().get(0);
final Action action1 = getFirstAssignedAction(assignDistributionSet(ds1, target));
final Long action2Id = getFirstAssignedActionId(assignDistributionSet(ds2, target));
assertDeploymentActionIsExposedToTarget(target.getControllerId(), action1.getId());
sendDeploymentActionFeedback(target, action1, "closed", "success");
assertDeploymentActionIsExposedToTarget(target.getControllerId(), action2.getId());
assertDeploymentActionIsExposedToTarget(target.getControllerId(), action2Id);
}

View File

@@ -13,7 +13,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.hawkbit.repository.model.Action;
@@ -156,9 +156,9 @@ public class DosFilterTest extends AbstractDDiApiIntegrationTest {
private Long prepareDeploymentBase() {
final DistributionSet ds = testdataFactory.createDistributionSet("test");
final Target target = testdataFactory.createTarget("4711");
final List<Target> toAssign = Arrays.asList(target);
final List<Target> toAssign = Collections.singletonList(target);
final Iterable<Target> saved = assignDistributionSet(ds, toAssign).getAssignedEntity();
assignDistributionSet(ds, toAssign);
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, target.getControllerId())).hasSize(1);
final Action uaction = deploymentManagement.findActiveActionsByTarget(PAGE, target.getControllerId())

View File

@@ -0,0 +1,65 @@
/**
* Copyright (c) 2019 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.json.model.distributionset;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetRestApi;
import org.springframework.hateoas.ResourceSupport;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
/**
* Representation of an Action Id as a Json Object with link to the Action resource
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class MgmtActionId extends ResourceSupport {
private long actionId;
public MgmtActionId() {
}
/**
* Constructor
* @param actionId
* the actionId
* @param controllerId
* the controller Id
*/
public MgmtActionId(final String controllerId, final long actionId) {
this.actionId = actionId;
add(linkTo(methodOn(MgmtTargetRestApi.class).getAction(controllerId, actionId)).withSelfRel());
}
@JsonProperty("id")
public long getActionId() {
return actionId;
}
public void setActionId(final long actionId) {
this.actionId = actionId;
}
@Override
public boolean equals(final Object obj) {
return super.equals(obj) && this.getClass().isInstance(obj) && actionId == ((MgmtActionId) obj).getActionId();
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), actionId);
}
}

View File

@@ -8,9 +8,14 @@
*/
package org.eclipse.hawkbit.mgmt.json.model.distributionset;
import java.util.List;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.hateoas.ResourceSupport;
/**
* Response Body of Target for assignment operations.
@@ -20,25 +25,17 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
*/
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class MgmtTargetAssignmentResponseBody {
public class MgmtTargetAssignmentResponseBody extends ResourceSupport {
private int assigned;
private int alreadyAssigned;
private int total;
private List<MgmtActionId> assignedActions;
/**
* @return the assigned
* @return the count of assigned targets
*/
@JsonProperty("assigned")
public int getAssigned() {
return assigned;
}
/**
* @param assigned
* the assigned to set
*/
public void setAssigned(final int assigned) {
this.assigned = assigned;
return assignedActions == null ? 0 : assignedActions.size();
}
/**
@@ -59,15 +56,35 @@ public class MgmtTargetAssignmentResponseBody {
/**
* @return the total
*/
@JsonProperty("total")
public int getTotal() {
return total;
return getAssigned() + alreadyAssigned;
}
/**
* @param total
* the total to set
* @return the assignedActions
*/
public void setTotal(final int total) {
this.total = total;
public List<MgmtActionId> getAssignedActions() {
return assignedActions;
}
/**
* @param assignedActions
* the assigned actions to set
*/
public void setAssignedActions(final List<MgmtActionId> assignedActions) {
this.assignedActions = assignedActions;
}
@Override
public boolean equals(final Object obj) {
return super.equals(obj) && this.getClass().isInstance(obj)
&& ((MgmtTargetAssignmentResponseBody) obj).getAlreadyAssigned() == alreadyAssigned
&& Objects.equals(((MgmtTargetAssignmentResponseBody) obj).getAssignedActions(), assignedActions);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), alreadyAssigned, assignedActions);
}
}

View File

@@ -0,0 +1,79 @@
/**
* Copyright (c) 2019 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.json.model.distributionset;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import io.qameta.allure.Story;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Description;
@Story("Retrieve all open action ids")
@Description("Tests for the MgmtTargetAssignmentResponseBody")
public class MgmtTargetAssignmentResponseBodyTest {
private static final List<Long> ASSIGNED_ACTIONS = Arrays.asList(4L, 5L, 6L);
private static final int ALREADY_ASSIGNED_COUNT = 3;
private static final String CONTROLLER_ID = "target";
@Test
@Description("Tests that the ActionIds are serialized correctly in MgmtTargetAssignmentResponseBody")
public void testActionIdsSerialization() throws IOException {
final MgmtTargetAssignmentResponseBody responseBody = generateResponseBody();
final ObjectMapper objectMapper = new ObjectMapper();
final String responseBodyAsString = objectMapper.writeValueAsString(responseBody);
final JsonNode jsonNode = objectMapper.readTree(responseBodyAsString);
assertThat(jsonNode.has("assigned")).as("the assigned targets count").isTrue();
assertThat(jsonNode.get("assigned").isNumber()).as("the assigned targets count").isTrue();
assertThat(jsonNode.get("assigned").asLong()).as("the assigned targets count")
.isEqualTo(ASSIGNED_ACTIONS.size());
assertThat(jsonNode.has("alreadyAssigned")).as("the already assigned targets count").isTrue();
assertThat(jsonNode.get("alreadyAssigned").isNumber()).as("the already assigned targets count").isTrue();
assertThat(jsonNode.get("alreadyAssigned").asLong()).as("the already assigned targets count")
.isEqualTo(ALREADY_ASSIGNED_COUNT);
assertThat(jsonNode.has("total")).as("the total targets count").isTrue();
assertThat(jsonNode.get("total").isNumber()).as("the total targets count").isTrue();
assertThat(jsonNode.get("total").asLong()).as("the total targets count")
.isEqualTo(ALREADY_ASSIGNED_COUNT + ASSIGNED_ACTIONS.size());
assertThat(jsonNode.has("assignedActions")).as("The created actions in result of this assignment").isTrue();
assertThat(jsonNode.get("assignedActions").isArray()).as("The created actions in result of this assignment")
.isTrue();
assertThat(jsonNode.get("assignedActions").size()).as("The created actions in result of this assignment")
.isEqualTo(3);
assertThat(jsonNode.get("assignedActions").get(0).isObject())
.as("A created action in result of this assignment").isTrue();
assertThat(jsonNode.get("assignedActions").get(0).has("id")).as("A created action in result of this assignment")
.isTrue();
assertThat(jsonNode.get("assignedActions").get(0).get("id").isNumber())
.as("A created action in result of this assignment").isTrue();
assertThat(ASSIGNED_ACTIONS).as("The expected action ids")
.contains(jsonNode.get("assignedActions").get(0).get("id").asLong());
}
private static MgmtTargetAssignmentResponseBody generateResponseBody() {
MgmtTargetAssignmentResponseBody response = new MgmtTargetAssignmentResponseBody();
response.setAssignedActions(
ASSIGNED_ACTIONS.stream().map(id -> new MgmtActionId(CONTROLLER_ID, id)).collect(Collectors.toList()));
response.setAlreadyAssigned(ALREADY_ASSIGNED_COUNT);
return response;
}
}

View File

@@ -18,6 +18,7 @@ import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionId;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSetRequestBodyPost;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtTargetAssignmentResponseBody;
@@ -137,9 +138,9 @@ public final class MgmtDistributionSetMapper {
static MgmtTargetAssignmentResponseBody toResponse(final DistributionSetAssignmentResult dsAssignmentResult) {
final MgmtTargetAssignmentResponseBody result = new MgmtTargetAssignmentResponseBody();
result.setAssigned(dsAssignmentResult.getAssigned());
result.setAlreadyAssigned(dsAssignmentResult.getAlreadyAssigned());
result.setTotal(dsAssignmentResult.getTotal());
result.setAssignedActions(dsAssignmentResult.getAssignedEntity().stream()
.map(a -> new MgmtActionId(a.getTarget().getControllerId(), a.getId())).collect(Collectors.toList()));
return result;
}

View File

@@ -8,8 +8,8 @@
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -286,7 +286,8 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
if (offline) {
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponse(
deploymentManagement.offlineAssignedDistributionSet(dsId.getId(), Arrays.asList(targetId))));
deploymentManagement.offlineAssignedDistributionSet(dsId.getId(),
Collections.singletonList(targetId))));
}
findTargetWithExceptionIfNotFound(targetId);
@@ -294,7 +295,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
if (maintenanceWindow == null) {
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponse(this.deploymentManagement
.assignDistributionSet(dsId.getId(), Arrays.asList(new TargetWithActionType(targetId,
.assignDistributionSet(dsId.getId(), Collections.singletonList(new TargetWithActionType(targetId,
MgmtRestModelMapper.convertActionType(dsId.getType()), dsId.getForcetime())))));
}
@@ -306,7 +307,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
return ResponseEntity
.ok(MgmtDistributionSetMapper.toResponse(this.deploymentManagement.assignDistributionSet(dsId.getId(),
Arrays.asList(new TargetWithActionType(targetId,
Collections.singletonList(new TargetWithActionType(targetId,
MgmtRestModelMapper.convertActionType(dsId.getType()), dsId.getForcetime(),
cronSchedule, duration, timezone)))));

View File

@@ -1210,14 +1210,16 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
// Update
if (schedule == null) {
final List<Target> updatedTargets = assignDistributionSet(one, Arrays.asList(target)).getAssignedEntity();
final List<Target> updatedTargets = assignDistributionSet(one, Arrays.asList(target)).getAssignedEntity()
.stream().map(Action::getTarget).collect(Collectors.toList());
// 2nd update
// sleep 10ms to ensure that we can sort by reportedAt
Thread.sleep(10);
assignDistributionSet(two, updatedTargets);
} else {
final List<Target> updatedTargets = assignDistributionSetWithMaintenanceWindow(one.getId(),
target.getControllerId(), schedule, duration, timezone).getAssignedEntity();
target.getControllerId(), schedule, duration, timezone).getAssignedEntity().stream()
.map(Action::getTarget).collect(Collectors.toList());
// 2nd update
// sleep 10ms to ensure that we can sort by reportedAt
Thread.sleep(10);
@@ -1238,9 +1240,8 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
public void updateAction() throws Exception {
final Target target = testdataFactory.createTarget();
final DistributionSet set = testdataFactory.createDistributionSet();
final Long actionId = deploymentManagement
.assignDistributionSet(set.getId(), ActionType.SOFT, 0, Arrays.asList(target.getControllerId()))
.getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(deploymentManagement.assignDistributionSet(set.getId(),
ActionType.SOFT, 0, Collections.singletonList(target.getControllerId())));
assertThat(deploymentManagement.findAction(actionId).get().getActionType()).isEqualTo(ActionType.SOFT);
final String body = new JSONObject().put("forceType", "forced").toString();

View File

@@ -577,6 +577,9 @@ include::{snippets}/targets/post-assign-distribution-set-to-target/http-request.
=== Response (Status 200)
==== Response fields
include::{snippets}/targets/post-assign-distribution-set-to-target/response-fields.adoc[]
==== Response example
include::{snippets}/targets/post-assign-distribution-set-to-target/http-response.adoc[]

View File

@@ -137,9 +137,8 @@ public class RootControllerDocumentationTest extends AbstractApiRestDocumentatio
});
final Target target = targetManagement.create(entityFactory.target().create().controllerId(CONTROLLER_ID));
final Long actionId = deploymentManagement
.assignDistributionSet(set.getId(), Arrays.asList(target.getTargetWithActionType())).getActionIds()
.get(0);
final Long actionId = getFirstAssignedActionId(deploymentManagement.assignDistributionSet(set.getId(),
Arrays.asList(target.getTargetWithActionType())));
final Action cancelAction = deploymentManagement.cancelAction(actionId);
mockMvc.perform(
@@ -170,9 +169,8 @@ public class RootControllerDocumentationTest extends AbstractApiRestDocumentatio
final DistributionSet set = testdataFactory.createDistributionSet("one");
final Target target = targetManagement.create(entityFactory.target().create().controllerId(CONTROLLER_ID));
final Long actionId = deploymentManagement
.assignDistributionSet(set.getId(), Arrays.asList(target.getTargetWithActionType())).getActionIds()
.get(0);
final Long actionId = getFirstAssignedActionId(deploymentManagement.assignDistributionSet(set.getId(),
Arrays.asList(target.getTargetWithActionType())));
final Action cancelAction = deploymentManagement.cancelAction(actionId);
mockMvc.perform(post(
@@ -264,8 +262,8 @@ public class RootControllerDocumentationTest extends AbstractApiRestDocumentatio
.key("aMetadataKey").value("Metadata value as defined in software module").targetVisible(true));
final Target target = targetManagement.create(entityFactory.target().create().controllerId(CONTROLLER_ID));
final Long actionId = assignDistributionSetWithMaintenanceWindow(set.getId(), target.getControllerId(),
getTestSchedule(-5), getTestDuration(10), getTestTimeZone()).getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(assignDistributionSetWithMaintenanceWindow(set.getId(),
target.getControllerId(), getTestSchedule(-5), getTestDuration(10), getTestTimeZone()));
controllerManagement.addInformationalActionStatus(
entityFactory.actionStatus().create(actionId).message("Started download").status(Status.DOWNLOAD));
@@ -348,8 +346,8 @@ public class RootControllerDocumentationTest extends AbstractApiRestDocumentatio
final DistributionSet set = testdataFactory.createDistributionSet("one");
final Target target = targetManagement.create(entityFactory.target().create().controllerId(CONTROLLER_ID));
final Long actionId = assignDistributionSetWithMaintenanceWindow(set.getId(), target.getControllerId(),
getTestSchedule(2), getTestDuration(1), getTestTimeZone()).getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(assignDistributionSetWithMaintenanceWindow(set.getId(),
target.getControllerId(), getTestSchedule(2), getTestDuration(1), getTestTimeZone()));
mockMvc.perform(get(
DdiRestConstants.BASE_V1_REQUEST_MAPPING + "/{controllerId}/" + DdiRestConstants.DEPLOYMENT_BASE_ACTION
@@ -389,9 +387,8 @@ public class RootControllerDocumentationTest extends AbstractApiRestDocumentatio
final DistributionSet set = testdataFactory.createDistributionSet("one");
final Target target = targetManagement.create(entityFactory.target().create().controllerId(CONTROLLER_ID));
final Long actionId = deploymentManagement
.assignDistributionSet(set.getId(), Arrays.asList(target.getTargetWithActionType())).getActionIds()
.get(0);
final Long actionId = getFirstAssignedActionId(deploymentManagement.assignDistributionSet(set.getId(),
Arrays.asList(target.getTargetWithActionType())));
mockMvc.perform(post(DdiRestConstants.BASE_V1_REQUEST_MAPPING + "/{controllerId}/"
+ DdiRestConstants.DEPLOYMENT_BASE_ACTION + "/{actionId}/feedback", tenantAware.getCurrentTenant(),

View File

@@ -20,6 +20,7 @@ import static org.springframework.restdocs.snippet.Attributes.key;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.hawkbit.ddi.rest.resource.DdiApiConfiguration;
@@ -167,20 +168,23 @@ public abstract class AbstractApiRestDocumentation extends AbstractRestIntegrati
private List<Target> assignWithoutMaintenanceWindow(final DistributionSet distributionSet, final Target savedTarget,
final boolean timeforced) {
return timeforced ? assignDistributionSetTimeForced(distributionSet, savedTarget).getAssignedEntity()
final List<Action> actions = timeforced
? assignDistributionSetTimeForced(distributionSet, savedTarget).getAssignedEntity()
: assignDistributionSet(distributionSet, savedTarget).getAssignedEntity();
return actions.stream().map(Action::getTarget).collect(Collectors.toList());
}
private List<Target> assignWithMaintenanceWindow(final DistributionSet distributionSet, final Target savedTarget,
final boolean timeforced, final String maintenanceWindowSchedule, final String maintenanceWindowDuration,
final String maintenanceWindowTimeZone) {
return timeforced
final List<Action> actions = timeforced
? assignDistributionSetWithMaintenanceWindowTimeForced(distributionSet.getId(),
savedTarget.getControllerId(), maintenanceWindowSchedule, maintenanceWindowDuration,
maintenanceWindowTimeZone).getAssignedEntity()
: assignDistributionSetWithMaintenanceWindow(distributionSet.getId(), savedTarget.getControllerId(),
maintenanceWindowSchedule, maintenanceWindowDuration, maintenanceWindowTimeZone)
.getAssignedEntity();
return actions.stream().map(Action::getTarget).collect(Collectors.toList());
}
protected DistributionSet createDistributionSet() {

View File

@@ -211,4 +211,5 @@ public final class MgmtApiModelProperties {
public static final String CONFIG_GLOBAL = "true - if the current value is the global configuration value, false - if there is a tenant specific value configured.";
public static final String CONFIG_PARAM = "The name of the configuration parameter.";
public static final String DS_NEW_ASSIGNED_ACTIONS = "The newly created actions as a result of this assignment";
}

View File

@@ -23,9 +23,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
@@ -306,7 +308,8 @@ public class DistributionSetsDocumentationTest extends AbstractApiRestDocumentat
final DistributionSet set = testdataFactory.createUpdatedDistributionSet();
final List<Target> targets = assignDistributionSet(set,
testdataFactory.createTargets(5, "targetMisc", "Test targets for query")).getAssignedEntity();
testdataFactory.createTargets(5, "targetMisc", "Test targets for query")).getAssignedEntity().stream()
.map(Action::getTarget).collect(Collectors.toList());
testdataFactory.sendUpdateActionStatusToTargets(targets, Status.FINISHED, "some message");
mockMvc.perform(
@@ -396,6 +399,12 @@ public class DistributionSetsDocumentationTest extends AbstractApiRestDocumentat
fieldWithPath("assigned").description(MgmtApiModelProperties.DS_NEW_ASSIGNED_TARGETS),
fieldWithPath("alreadyAssigned").type(JsonFieldType.NUMBER)
.description(MgmtApiModelProperties.DS_ALREADY_ASSIGNED_TARGETS),
fieldWithPath("assignedActions").type(JsonFieldType.ARRAY)
.description(MgmtApiModelProperties.DS_NEW_ASSIGNED_ACTIONS),
fieldWithPath("assignedActions.[].id").type(JsonFieldType.NUMBER)
.description(MgmtApiModelProperties.ACTION_ID),
fieldWithPath("assignedActions.[]._links.self").type(JsonFieldType.OBJECT)
.description(MgmtApiModelProperties.LINK_TO_ACTION),
fieldWithPath("total").type(JsonFieldType.NUMBER)
.description(MgmtApiModelProperties.DS_TOTAL_ASSIGNED_TARGETS))));
}

View File

@@ -24,7 +24,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -395,9 +395,8 @@ public class TargetResourceDocumentationTest extends AbstractApiRestDocumentatio
public void switchActionToForced() throws Exception {
final Target target = testdataFactory.createTarget(targetId);
final DistributionSet set = testdataFactory.createDistributionSet();
final Long actionId = deploymentManagement
.assignDistributionSet(set.getId(), ActionType.SOFT, 0, Arrays.asList(target.getControllerId()))
.getActionIds().get(0);
final Long actionId = getFirstAssignedActionId(deploymentManagement.assignDistributionSet(set.getId(),
ActionType.SOFT, 0, Collections.singletonList(target.getControllerId())));
assertThat(deploymentManagement.findAction(actionId).get().getActionType()).isEqualTo(ActionType.SOFT);
final Map<String, Object> body = new HashMap<>();
@@ -490,8 +489,12 @@ public class TargetResourceDocumentationTest extends AbstractApiRestDocumentatio
@Test
@Description("Handles the POST request for assigning a distribution set to a specific target. Required Permission: READ_REPOSITORY and UPDATE_TARGET.")
public void postAssignDistributionSetToTarget() throws Exception {
testdataFactory.createTarget(targetId);
// create target and ds, and assign ds
testdataFactory.createTarget(targetId + "-old");
final DistributionSet set = testdataFactory.createDistributionSet("one");
assignDistributionSet(set.getId(), targetId + "-old");
testdataFactory.createTarget(targetId);
final long forceTime = System.currentTimeMillis();
final String body = new JSONObject().put("id", set.getId()).put("type", "timeforced")
@@ -502,7 +505,7 @@ public class TargetResourceDocumentationTest extends AbstractApiRestDocumentatio
mockMvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/"
+ MgmtRestConstants.TARGET_V1_ASSIGNED_DISTRIBUTION_SET, targetId).content(body)
.contentType(MediaType.APPLICATION_JSON_UTF8))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andDo(this.document.document(
pathParameters(parameterWithName("targetId").description(ApiModelPropertiesGeneric.ITEM_ID)),
@@ -524,6 +527,12 @@ public class TargetResourceDocumentationTest extends AbstractApiRestDocumentatio
fieldWithPath("assigned").description(MgmtApiModelProperties.DS_NEW_ASSIGNED_TARGETS),
fieldWithPath("alreadyAssigned").type(JsonFieldType.NUMBER)
.description(MgmtApiModelProperties.DS_ALREADY_ASSIGNED_TARGETS),
fieldWithPath("assignedActions").type(JsonFieldType.ARRAY)
.description(MgmtApiModelProperties.DS_NEW_ASSIGNED_ACTIONS),
fieldWithPath("assignedActions.[].id").type(JsonFieldType.NUMBER)
.description(MgmtApiModelProperties.ACTION_ID),
fieldWithPath("assignedActions.[]._links.self").type(JsonFieldType.OBJECT)
.description(MgmtApiModelProperties.LINK_TO_ACTION),
fieldWithPath("total").type(JsonFieldType.NUMBER)
.description(MgmtApiModelProperties.DS_TOTAL_ASSIGNED_TARGETS))));
}
@@ -630,7 +639,7 @@ public class TargetResourceDocumentationTest extends AbstractApiRestDocumentatio
final String knownValue = "knownValue";
final Target testTarget = testdataFactory.createTarget(targetId);
targetManagement.createMetaData(testTarget.getControllerId(),
Arrays.asList(entityFactory.generateTargetMetadata(knownKey, knownValue)));
Collections.singletonList(entityFactory.generateTargetMetadata(knownKey, knownValue)));
mockMvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/metadata/{metadatakey}",
testTarget.getControllerId(), knownKey)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -652,7 +661,7 @@ public class TargetResourceDocumentationTest extends AbstractApiRestDocumentatio
final Target testTarget = testdataFactory.createTarget(targetId);
targetManagement.createMetaData(testTarget.getControllerId(),
Arrays.asList(entityFactory.generateTargetMetadata(knownKey, knownValue)));
Collections.singletonList(entityFactory.generateTargetMetadata(knownKey, knownValue)));
final JSONObject jsonObject = new JSONObject().put("key", knownKey).put("value", updateValue);
@@ -679,7 +688,7 @@ public class TargetResourceDocumentationTest extends AbstractApiRestDocumentatio
final Target testTarget = testdataFactory.createTarget(targetId);
targetManagement.createMetaData(testTarget.getControllerId(),
Arrays.asList(entityFactory.generateTargetMetadata(knownKey, knownValue)));
Collections.singletonList(entityFactory.generateTargetMetadata(knownKey, knownValue)));
mockMvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/metadata/{key}",
testTarget.getControllerId(), knownKey)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())

View File

@@ -88,7 +88,6 @@ import org.vaadin.spring.events.EventBus.UIEventBus;
import org.vaadin.spring.events.EventScope;
import org.vaadin.spring.events.annotation.EventBusListenerMethod;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.vaadin.data.Container;
import com.vaadin.data.Item;
@@ -547,21 +546,19 @@ public class TargetTable extends AbstractTable<Target> {
* @return TagAssigmentResult with all meta data of the assignment outcome.
*/
public TargetTagAssignmentResult toggleTagAssignment(final Collection<Long> targetIds, final String targTagName) {
final List<String> controllerIds = targetManagement.get(targetIds).stream().map(Target::getControllerId)
.collect(Collectors.toList());
if (controllerIds.isEmpty()) {
final List<Target> targets = targetManagement.get(targetIds);
if (targets.isEmpty()) {
getNotification().displayWarning(getI18n().getMessage("targets.not.exists"));
return new TargetTagAssignmentResult(0, 0, 0, Lists.newArrayListWithCapacity(0),
Lists.newArrayListWithCapacity(0), null);
return new TargetTagAssignmentResult(0, Collections.emptyList(), Collections.emptyList(), null);
}
final Optional<TargetTag> tag = tagManagement.getByName(targTagName);
if (!tag.isPresent()) {
getNotification().displayWarning(getI18n().getMessage("targettag.not.exists", targTagName));
return new TargetTagAssignmentResult(0, 0, 0, Lists.newArrayListWithCapacity(0),
Lists.newArrayListWithCapacity(0), null);
return new TargetTagAssignmentResult(0, Collections.emptyList(), Collections.emptyList(), null);
}
final List<String> controllerIds = targets.stream().map(Target::getControllerId).collect(Collectors.toList());
final TargetTagAssignmentResult result = targetManagement.toggleTagAssignment(controllerIds, targTagName);
getNotification().displaySuccess(HawkbitCommonUtil.createAssignmentMessage(targTagName, result, getI18n()));

View File

@@ -14,7 +14,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.eclipse.hawkbit.repository.model.AssignmentResult;
import org.eclipse.hawkbit.repository.model.AbstractAssignmentResult;
import org.eclipse.hawkbit.repository.model.NamedEntity;
import org.eclipse.hawkbit.repository.model.PollStatus;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
@@ -294,7 +294,7 @@ public final class HawkbitCommonUtil {
* @return message
*/
public static String createAssignmentMessage(final String tagName,
final AssignmentResult<? extends NamedEntity> result, final VaadinMessageSource i18n) {
final AbstractAssignmentResult<? extends NamedEntity> result, final VaadinMessageSource i18n) {
final StringBuilder formMsg = new StringBuilder();
final int assignedCount = result.getAssigned();
final int alreadyAssignedCount = result.getAlreadyAssigned();