Remove unlimited collections from the repository API (#496)

* Started to get rid of unlimited collections

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Align API usage.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* fix compile issues.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix tests.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Remove comments

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Performance optimizations.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Remove dead code.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Allign method names

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Wait until the action update event is processed

Conflicts:
	hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageHandlerServiceIntegrationTest.java

Signed-off-by: SirWayne <dennis.melzer@bosch-si.com>

* Started new tag APIs

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Quotas into central interface. Tag tests added. Event names fixed.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Simplified consumer run for every tenant.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* remove unused fields.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Alligned beans.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Deprecated client methods for old resources.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix new foreach method.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix transaction for foreach.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Extended DS creating to handle larger volumes. Fix on Readme.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fixed simulator bug and cleaned up tests.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix in sorting.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Remove configuration processor.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix wrong usage of sanitize.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Missing brackets.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix README API compatability.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix misinterpretation of pessimistic locking exceptions.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix stability sentence.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Code cleanup.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fixed page calculation

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>
This commit is contained in:
Kai Zimmermann
2017-05-09 16:40:49 +02:00
committed by GitHub
parent aca87464bd
commit c18e9f515e
199 changed files with 3502 additions and 1607 deletions

View File

@@ -121,8 +121,8 @@ public final class MgmtDistributionSetMapper {
.getDistributionSetType(distributionSet.getType().getId())).withRel("type"));
response.add(linkTo(methodOn(MgmtDistributionSetRestApi.class).getMetadata(response.getDsId(),
Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET),
Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT), null, null))
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null))
.withRel("metadata"));
return response;

View File

@@ -31,8 +31,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -67,25 +67,20 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTargetSortParam(sortParam);
final Sort sorting = PagingUtility.sanitizeTagSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Slice<DistributionSetTag> findTargetsAll;
final Long countTargetsAll;
final Page<DistributionSetTag> findTargetsAll;
if (rsqlParam == null) {
findTargetsAll = this.tagManagement.findAllDistributionSetTags(pageable);
countTargetsAll = this.tagManagement.countTargetTags();
findTargetsAll = tagManagement.findAllDistributionSetTags(pageable);
} else {
final Page<DistributionSetTag> findTargetPage = this.tagManagement.findAllDistributionSetTags(rsqlParam,
pageable);
countTargetsAll = findTargetPage.getTotalElements();
findTargetsAll = findTargetPage;
findTargetsAll = tagManagement.findAllDistributionSetTags(rsqlParam, pageable);
}
final List<MgmtTag> rest = MgmtTagMapper.toResponseDistributionSetTag(findTargetsAll.getContent());
return new ResponseEntity<>(new PagedList<>(rest, countTargetsAll), HttpStatus.OK);
return new ResponseEntity<>(new PagedList<>(rest, findTargetsAll.getTotalElements()), HttpStatus.OK);
}
@Override
@@ -132,10 +127,36 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
@Override
public ResponseEntity<List<MgmtDistributionSet>> getAssignedDistributionSets(
@PathVariable("distributionsetTagId") final Long distributionsetTagId) {
final DistributionSetTag tag = findDistributionTagById(distributionsetTagId);
return new ResponseEntity<>(
MgmtDistributionSetMapper.toResponseDistributionSets(tag.getAssignedToDistributionSet()),
HttpStatus.OK);
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(distributionSetManagement
.findDistributionSetsByTag(new PageRequest(0, MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT),
distributionsetTagId)
.getContent()), HttpStatus.OK);
}
@Override
public ResponseEntity<PagedList<MgmtDistributionSet>> getAssignedDistributionSets(
@PathVariable("distributionsetTagId") final Long distributionsetTagId,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTagSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
Page<DistributionSet> findDistrAll;
if (rsqlParam == null) {
findDistrAll = distributionSetManagement.findDistributionSetsByTag(pageable, distributionsetTagId);
} else {
findDistrAll = distributionSetManagement.findDistributionSetsByTag(pageable, rsqlParam,
distributionsetTagId);
}
final List<MgmtDistributionSet> rest = MgmtDistributionSetMapper
.toResponseFromDsList(findDistrAll.getContent());
return new ResponseEntity<>(new PagedList<>(rest, findDistrAll.getTotalElements()), HttpStatus.OK);
}
@Override
@@ -173,17 +194,6 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(assignedDs), HttpStatus.OK);
}
@Override
public ResponseEntity<Void> unassignDistributionSets(
@PathVariable("distributionsetTagId") final Long distributionsetTagId) {
LOG.debug("Unassign all DS for ds tag {}", distributionsetTagId);
final List<DistributionSet> distributionSets = this.distributionSetManagement
.unAssignAllDistributionSetsByTag(distributionsetTagId);
LOG.debug("Unassigned ds {}", distributionSets.size());
return new ResponseEntity<>(HttpStatus.OK);
}
@Override
public ResponseEntity<Void> unassignDistributionSet(
@PathVariable("distributionsetTagId") final Long distributionsetTagId,
@@ -203,4 +213,24 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
return assignedDistributionSetRequestBodies.stream()
.map(MgmtAssignedDistributionSetRequestBody::getDistributionSetId).collect(Collectors.toList());
}
@Override
public ResponseEntity<MgmtDistributionSetTagAssigmentResult> toggleTagAssignmentUnpaged(
final Long distributionsetTagId,
final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies) {
return toggleTagAssignment(distributionsetTagId, assignedDSRequestBodies);
}
@Override
public ResponseEntity<List<MgmtDistributionSet>> assignDistributionSetsUnpaged(final Long distributionsetTagId,
final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies) {
return assignDistributionSets(distributionsetTagId, assignedDSRequestBodies);
}
@Override
public ResponseEntity<Void> unassignDistributionSetUnpaged(final Long distributionsetTagId,
final Long distributionsetId) {
return unassignDistributionSet(distributionsetTagId, distributionsetId);
}
}

View File

@@ -90,8 +90,8 @@ final class MgmtRolloutMapper {
body.add(linkTo(methodOn(MgmtRolloutRestApi.class).pause(rollout.getId())).withRel("pause"));
body.add(linkTo(methodOn(MgmtRolloutRestApi.class).resume(rollout.getId())).withRel("resume"));
body.add(linkTo(methodOn(MgmtRolloutRestApi.class).getRolloutGroups(rollout.getId(),
Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET),
Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT), null, null))
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null))
.withRel("groups"));
return body;
}

View File

@@ -115,8 +115,8 @@ public final class MgmtSoftwareModuleMapper {
.withRel(MgmtRestConstants.SOFTWAREMODULE_V1_TYPE));
response.add(linkTo(methodOn(MgmtSoftwareModuleResource.class).getMetadata(response.getModuleId(),
Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET),
Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT), null, null))
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null))
.withRel("metadata").expand(ArrayUtils.toArray()));
return response;
}

View File

@@ -19,6 +19,7 @@ import java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTag;
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTagRequestBodyPut;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTagRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetTagRestApi;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.builder.TagCreate;
@@ -61,8 +62,10 @@ final class MgmtTagMapper {
response.add(linkTo(methodOn(MgmtTargetTagRestApi.class).getTargetTag(targetTag.getId())).withSelfRel());
response.add(linkTo(methodOn(MgmtTargetTagRestApi.class).getAssignedTargets(targetTag.getId()))
.withRel("assignedTargets"));
response.add(linkTo(methodOn(MgmtTargetTagRestApi.class).getAssignedTargets(targetTag.getId(),
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null))
.withRel("assignedTargets"));
return response;
}
@@ -93,8 +96,9 @@ final class MgmtTagMapper {
linkTo(methodOn(MgmtDistributionSetTagRestApi.class).getDistributionSetTag(distributionSetTag.getId()))
.withSelfRel());
response.add(linkTo(
methodOn(MgmtDistributionSetTagRestApi.class).getAssignedDistributionSets(distributionSetTag.getId()))
response.add(linkTo(methodOn(MgmtDistributionSetTagRestApi.class).getAssignedDistributionSets(
distributionSetTag.getId(), MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null))
.withRel("assignedDistributionSets"));
return response;

View File

@@ -28,6 +28,7 @@ import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTargetRequestBody;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetRestApi;
import org.eclipse.hawkbit.repository.ActionFields;
import org.eclipse.hawkbit.repository.DeploymentManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.builder.TargetCreate;
import org.eclipse.hawkbit.repository.model.Action;
@@ -37,6 +38,7 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.rest.data.ResponseList;
import org.eclipse.hawkbit.rest.data.SortDirection;
import org.eclipse.hawkbit.util.IpUtil;
import org.springframework.data.domain.PageRequest;
/**
* A mapper which maps repository model to RESTful model representation and
@@ -161,12 +163,17 @@ public final class MgmtTargetMapper {
.address(targetRest.getAddress());
}
static List<MgmtActionStatus> toActionStatusRestResponse(final Collection<ActionStatus> actionStatus) {
static List<MgmtActionStatus> toActionStatusRestResponse(final Collection<ActionStatus> actionStatus,
final DeploymentManagement deploymentManagement) {
if (actionStatus == null) {
return Collections.emptyList();
}
return actionStatus.stream().map(MgmtTargetMapper::toResponse).collect(Collectors.toList());
return actionStatus.stream().map(status -> toResponse(status,
deploymentManagement.findMessagesByActionStatusId(
new PageRequest(0, MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT), status.getId())
.getContent()))
.collect(Collectors.toList());
}
static MgmtAction toResponse(final String targetId, final Action action, final boolean isActive) {
@@ -207,10 +214,10 @@ public final class MgmtTargetMapper {
return null;
}
private static MgmtActionStatus toResponse(final ActionStatus actionStatus) {
private static MgmtActionStatus toResponse(final ActionStatus actionStatus, final List<String> messages) {
final MgmtActionStatus result = new MgmtActionStatus();
result.setMessages(actionStatus.getMessages());
result.setMessages(messages);
result.setReportedAt(actionStatus.getCreatedAt());
result.setStatusId(actionStatus.getId());
result.setType(actionStatus.getStatus().name().toLowerCase());

View File

@@ -252,13 +252,12 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeActionStatusSortParam(sortParam);
final Page<ActionStatus> statusList = this.deploymentManagement.findActionStatusByActionWithMessages(
final Page<ActionStatus> statusList = this.deploymentManagement.findActionStatusByAction(
new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting), action.getId());
return new ResponseEntity<>(
new PagedList<>(MgmtTargetMapper.toActionStatusRestResponse(statusList.getContent()),
statusList.getTotalElements()),
HttpStatus.OK);
return new ResponseEntity<>(new PagedList<>(
MgmtTargetMapper.toActionStatusRestResponse(statusList.getContent(), deploymentManagement),
statusList.getTotalElements()), HttpStatus.OK);
}

View File

@@ -31,8 +31,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -67,24 +67,19 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTargetSortParam(sortParam);
final Sort sorting = PagingUtility.sanitizeTagSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Slice<TargetTag> findTargetsAll;
final Long countTargetsAll;
Page<TargetTag> findTargetsAll;
if (rsqlParam == null) {
findTargetsAll = this.tagManagement.findAllTargetTags(pageable);
countTargetsAll = this.tagManagement.countTargetTags();
} else {
final Page<TargetTag> findTargetPage = this.tagManagement.findAllTargetTags(rsqlParam, pageable);
countTargetsAll = findTargetPage.getTotalElements();
findTargetsAll = findTargetPage;
findTargetsAll = this.tagManagement.findAllTargetTags(rsqlParam, pageable);
}
final List<MgmtTag> rest = MgmtTagMapper.toResponse(findTargetsAll.getContent());
return new ResponseEntity<>(new PagedList<>(rest, countTargetsAll), HttpStatus.OK);
return new ResponseEntity<>(new PagedList<>(rest, findTargetsAll.getTotalElements()), HttpStatus.OK);
}
@Override
@@ -102,7 +97,7 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
}
@Override
public ResponseEntity<MgmtTag> updateTagretTag(@PathVariable("targetTagId") final Long targetTagId,
public ResponseEntity<MgmtTag> updateTargetTag(@PathVariable("targetTagId") final Long targetTagId,
@RequestBody final MgmtTagRequestBodyPut restTargetTagRest) {
LOG.debug("update {} target tag", restTargetTagRest);
@@ -127,8 +122,36 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
@Override
public ResponseEntity<List<MgmtTarget>> getAssignedTargets(@PathVariable("targetTagId") final Long targetTagId) {
final TargetTag targetTag = findTargetTagById(targetTagId);
return new ResponseEntity<>(MgmtTargetMapper.toResponse(targetTag.getAssignedToTargets()), HttpStatus.OK);
return new ResponseEntity<>(MgmtTargetMapper.toResponse(targetManagement
.findTargetsByTag(new PageRequest(0, MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT), targetTagId)
.getContent()), HttpStatus.OK);
}
@Override
public ResponseEntity<PagedList<MgmtTarget>> getAssignedTargets(@PathVariable("targetTagId") final Long targetTagId,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTargetSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
Page<Target> findTargetsAll;
if (rsqlParam == null) {
findTargetsAll = targetManagement.findTargetsByTag(pageable, targetTagId);
} else {
findTargetsAll = targetManagement.findTargetsByTag(pageable, rsqlParam, targetTagId);
}
final Long countTargetsAll = findTargetsAll.getTotalElements();
final List<MgmtTarget> rest = MgmtTargetMapper.toResponse(findTargetsAll.getContent());
return new ResponseEntity<>(new PagedList<>(rest, countTargetsAll), HttpStatus.OK);
}
@Override
@@ -156,14 +179,6 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
return new ResponseEntity<>(MgmtTargetMapper.toResponse(assignedTarget), HttpStatus.OK);
}
@Override
public ResponseEntity<Void> unassignTargets(@PathVariable("targetTagId") final Long targetTagId) {
LOG.debug("Unassign all Targets for target tag {}", targetTagId);
this.targetManagement.unAssignAllTargetsByTag(targetTagId);
return new ResponseEntity<>(HttpStatus.OK);
}
@Override
public ResponseEntity<Void> unassignTarget(@PathVariable("targetTagId") final Long targetTagId,
@PathVariable("controllerId") final String controllerId) {
@@ -183,4 +198,21 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
.collect(Collectors.toList());
}
@Override
public ResponseEntity<MgmtTargetTagAssigmentResult> toggleTagAssignmentUnpaged(final Long targetTagId,
final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) {
return toggleTagAssignment(targetTagId, assignedTargetRequestBodies);
}
@Override
public ResponseEntity<List<MgmtTarget>> assignTargetsUnpaged(final Long targetTagId,
final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) {
return assignTargets(targetTagId, assignedTargetRequestBodies);
}
@Override
public ResponseEntity<Void> unassignTargetUnpaged(final Long targetTagId, final String controllerId) {
return unassignTarget(targetTagId, controllerId);
}
}

View File

@@ -19,6 +19,7 @@ import org.eclipse.hawkbit.repository.RolloutGroupFields;
import org.eclipse.hawkbit.repository.SoftwareModuleFields;
import org.eclipse.hawkbit.repository.SoftwareModuleMetadataFields;
import org.eclipse.hawkbit.repository.SoftwareModuleTypeFields;
import org.eclipse.hawkbit.repository.TagFields;
import org.eclipse.hawkbit.repository.TargetFields;
import org.eclipse.hawkbit.repository.TargetFilterQueryFields;
import org.eclipse.hawkbit.rest.util.SortUtility;
@@ -38,14 +39,14 @@ public final class PagingUtility {
static int sanitizeOffsetParam(final int offset) {
if (offset < 0) {
return Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET);
return MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE;
}
return offset;
}
static int sanitizePageLimitParam(final int pageLimit) {
if (pageLimit < 1) {
return Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT);
return MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE;
} else if (pageLimit > MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT) {
return MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT;
}
@@ -55,15 +56,23 @@ public final class PagingUtility {
static Sort sanitizeTargetSortParam(final String sortParam) {
if (sortParam == null) {
// default
return new Sort(Direction.ASC, TargetFields.NAME.getFieldName());
return new Sort(Direction.ASC, TargetFields.CONTROLLERID.getFieldName());
}
return new Sort(SortUtility.parse(TargetFields.class, sortParam));
}
static Sort sanitizeTagSortParam(final String sortParam) {
if (sortParam == null) {
// default
return new Sort(Direction.ASC, TagFields.ID.getFieldName());
}
return new Sort(SortUtility.parse(TagFields.class, sortParam));
}
static Sort sanitizeTargetFilterQuerySortParam(final String sortParam) {
if (sortParam == null) {
// default
return new Sort(Direction.ASC, TargetFilterQueryFields.NAME.getFieldName());
return new Sort(Direction.ASC, TargetFilterQueryFields.ID.getFieldName());
}
return new Sort(SortUtility.parse(TargetFilterQueryFields.class, sortParam));
}
@@ -71,7 +80,7 @@ public final class PagingUtility {
static Sort sanitizeSoftwareModuleSortParam(final String sortParam) {
if (sortParam == null) {
// default
return new Sort(Direction.ASC, SoftwareModuleFields.NAME.getFieldName());
return new Sort(Direction.ASC, SoftwareModuleFields.ID.getFieldName());
}
return new Sort(SortUtility.parse(SoftwareModuleFields.class, sortParam));
}
@@ -79,7 +88,7 @@ public final class PagingUtility {
static Sort sanitizeSoftwareModuleTypeSortParam(final String sortParam) {
if (sortParam == null) {
// default
return new Sort(Direction.ASC, SoftwareModuleTypeFields.NAME.getFieldName());
return new Sort(Direction.ASC, SoftwareModuleTypeFields.ID.getFieldName());
}
return new Sort(SortUtility.parse(SoftwareModuleTypeFields.class, sortParam));
}
@@ -87,7 +96,7 @@ public final class PagingUtility {
static Sort sanitizeDistributionSetSortParam(final String sortParam) {
if (sortParam == null) {
// default
return new Sort(Direction.ASC, DistributionSetFields.NAME.getFieldName());
return new Sort(Direction.ASC, DistributionSetFields.ID.getFieldName());
}
return new Sort(SortUtility.parse(DistributionSetFields.class, sortParam));
}
@@ -95,7 +104,7 @@ public final class PagingUtility {
static Sort sanitizeDistributionSetTypeSortParam(final String sortParam) {
if (sortParam == null) {
// default
return new Sort(Direction.ASC, DistributionSetTypeFields.NAME.getFieldName());
return new Sort(Direction.ASC, DistributionSetTypeFields.ID.getFieldName());
}
return new Sort(SortUtility.parse(DistributionSetTypeFields.class, sortParam));
}
@@ -137,7 +146,7 @@ public final class PagingUtility {
static Sort sanitizeRolloutSortParam(final String sortParam) {
if (sortParam == null) {
// default
return new Sort(Direction.ASC, RolloutFields.NAME.getFieldName());
return new Sort(Direction.ASC, RolloutFields.ID.getFieldName());
}
return new Sort(SortUtility.parse(RolloutFields.class, sortParam));
}
@@ -145,7 +154,7 @@ public final class PagingUtility {
static Sort sanitizeRolloutGroupSortParam(final String sortParam) {
if (sortParam == null) {
// default
return new Sort(Direction.ASC, RolloutGroupFields.NAME.getFieldName());
return new Sort(Direction.ASC, RolloutGroupFields.ID.getFieldName());
}
return new Sort(SortUtility.parse(RolloutGroupFields.class, sortParam));
}

View File

@@ -8,10 +8,186 @@
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import org.eclipse.hawkbit.repository.model.BaseEntity;
import org.eclipse.hawkbit.repository.model.NamedEntity;
import org.eclipse.hawkbit.repository.model.NamedVersionedEntity;
import org.eclipse.hawkbit.repository.model.Tag;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.web.servlet.ResultMatcher;
@SpringApplicationConfiguration(classes = { MgmtApiConfiguration.class })
public abstract class AbstractManagementApiIntegrationTest extends AbstractRestIntegrationTest {
protected static ResultMatcher applyBaseEntityMatcherOnArrayResult(final BaseEntity entity,
final String arrayElement) throws Exception {
return mvcResult -> {
jsonPath("$." + arrayElement + ".[?(@.id==" + entity.getId() + ")].createdBy",
contains(entity.getCreatedBy())).match(mvcResult);
jsonPath("$." + arrayElement + ".[?(@.id==" + entity.getId() + ")].createdAt",
contains(entity.getCreatedAt())).match(mvcResult);
jsonPath("$." + arrayElement + ".[?(@.id==" + entity.getId() + ")].lastModifiedBy",
contains(entity.getLastModifiedBy())).match(mvcResult);
jsonPath("$." + arrayElement + ".[?(@.id==" + entity.getId() + ")].lastModifiedAt",
contains(entity.getLastModifiedAt())).match(mvcResult);
};
}
protected static ResultMatcher applyTargetEntityMatcherOnArrayResult(final Target entity, final String arrayElement)
throws Exception {
return mvcResult -> {
jsonPath("$." + arrayElement + ".[?(@.controllerId==" + entity.getControllerId() + ")].createdBy",
contains(entity.getCreatedBy())).match(mvcResult);
jsonPath("$." + arrayElement + ".[?(@.controllerId==" + entity.getControllerId() + ")].createdAt",
contains(entity.getCreatedAt())).match(mvcResult);
jsonPath("$." + arrayElement + ".[?(@.controllerId==" + entity.getControllerId() + ")].lastModifiedBy",
contains(entity.getLastModifiedBy())).match(mvcResult);
jsonPath("$." + arrayElement + ".[?(@.controllerId==" + entity.getControllerId() + ")].lastModifiedAt",
contains(entity.getLastModifiedAt())).match(mvcResult);
};
}
protected static ResultMatcher applyBaseEntityMatcherOnPagedResult(final BaseEntity entity) throws Exception {
return applyBaseEntityMatcherOnArrayResult(entity, "content");
}
protected static ResultMatcher applyNamedEntityMatcherOnPagedResult(final NamedEntity entity) throws Exception {
return mvcResult -> {
applyBaseEntityMatcherOnPagedResult(entity).match(mvcResult);
jsonPath("$.content.[?(@.id==" + entity.getId() + ")].name", contains(entity.getName())).match(mvcResult);
jsonPath("$.content.[?(@.id==" + entity.getId() + ")].description", contains(entity.getDescription()))
.match(mvcResult);
};
}
protected static ResultMatcher applyNamedVersionedEntityMatcherOnPagedResult(final NamedVersionedEntity entity)
throws Exception {
return mvcResult -> {
applyNamedEntityMatcherOnPagedResult(entity).match(mvcResult);
jsonPath("$.content.[?(@.id==" + entity.getId() + ")].version", contains(entity.getVersion()))
.match(mvcResult);
};
}
protected static ResultMatcher applyTagMatcherOnPagedResult(final Tag entity) throws Exception {
return mvcResult -> {
applyNamedEntityMatcherOnPagedResult(entity).match(mvcResult);
jsonPath("$.content.[?(@.id==" + entity.getId() + ")].colour", contains(entity.getColour()))
.match(mvcResult);
};
}
protected static ResultMatcher applySelfLinkMatcherOnPagedResult(final BaseEntity entity, final String link)
throws Exception {
return mvcResult -> {
jsonPath("$.content.[?(@.id==" + entity.getId() + ")]._links.self.href", contains(link)).match(mvcResult);
};
}
protected static ResultMatcher applyBaseEntityMatcherOnArrayResult(final BaseEntity entity) throws Exception {
return mvcResult -> {
jsonPath("$.[?(@.id==" + entity.getId() + ")].createdBy", contains(entity.getCreatedBy())).match(mvcResult);
jsonPath("$.[?(@.id==" + entity.getId() + ")].createdAt", contains(entity.getCreatedAt())).match(mvcResult);
jsonPath("$.[?(@.id==" + entity.getId() + ")].lastModifiedBy", contains(entity.getLastModifiedBy()))
.match(mvcResult);
jsonPath("$.[?(@.id==" + entity.getId() + ")].lastModifiedAt", contains(entity.getLastModifiedAt()))
.match(mvcResult);
};
}
protected static ResultMatcher applyTargetEntityMatcherOnArrayResult(final Target entity) throws Exception {
return mvcResult -> {
jsonPath("$.[?(@.controllerId==" + entity.getControllerId() + ")].createdBy",
contains(entity.getCreatedBy())).match(mvcResult);
jsonPath("$.[?(@.controllerId==" + entity.getControllerId() + ")].createdAt",
contains(entity.getCreatedAt())).match(mvcResult);
jsonPath("$.[?(@.controllerId==" + entity.getControllerId() + ")].lastModifiedBy",
contains(entity.getLastModifiedBy())).match(mvcResult);
jsonPath("$.[?(@.controllerId==" + entity.getControllerId() + ")].lastModifiedAt",
contains(entity.getLastModifiedAt())).match(mvcResult);
};
}
protected static ResultMatcher applyNamedEntityMatcherOnArrayResult(final NamedEntity entity) throws Exception {
return mvcResult -> {
applyBaseEntityMatcherOnPagedResult(entity);
jsonPath("$.[?(@.id==" + entity.getId() + ")].name", contains(entity.getName())).match(mvcResult);
jsonPath("$.[?(@.id==" + entity.getId() + ")].description", contains(entity.getDescription()))
.match(mvcResult);
};
}
protected static ResultMatcher applyNamedVersionedEntityMatcherOnArrayResult(final NamedVersionedEntity entity)
throws Exception {
return mvcResult -> {
applyNamedEntityMatcherOnPagedResult(entity);
jsonPath("$.[?(@.id==" + entity.getId() + ")].version", contains(entity.getVersion())).match(mvcResult);
};
}
protected static ResultMatcher applyTagMatcherOnArrayResult(final Tag entity) throws Exception {
return mvcResult -> {
applyNamedEntityMatcherOnPagedResult(entity);
jsonPath("$.[?(@.id==" + entity.getId() + ")].colour", contains(entity.getColour())).match(mvcResult);
};
}
protected static ResultMatcher applySelfLinkMatcherOnArrayResult(final BaseEntity entity, final String link)
throws Exception {
return mvcResult -> {
jsonPath("$.[?(@.id==" + entity.getId() + ")]._links.self.href", contains(link)).match(mvcResult);
};
}
protected static ResultMatcher applyBaseEntityMatcherOnSingleResult(final BaseEntity entity) throws Exception {
return mvcResult -> {
jsonPath("createdBy", equalTo(entity.getCreatedBy())).match(mvcResult);
jsonPath("createdAt", equalTo(entity.getCreatedAt())).match(mvcResult);
jsonPath("lastModifiedBy", equalTo(entity.getLastModifiedBy())).match(mvcResult);
jsonPath("lastModifiedAt", equalTo(entity.getLastModifiedAt())).match(mvcResult);
};
}
protected static ResultMatcher applyNamedEntityMatcherOnSingleResult(final NamedEntity entity) throws Exception {
return mvcResult -> {
applyBaseEntityMatcherOnSingleResult(entity);
jsonPath("name", equalTo(entity.getName())).match(mvcResult);
jsonPath("description", equalTo(entity.getDescription())).match(mvcResult);
};
}
protected static ResultMatcher applyNamedVersionedEntityMatcherOnSingleResult(final NamedVersionedEntity entity)
throws Exception {
return mvcResult -> {
applyNamedEntityMatcherOnSingleResult(entity);
jsonPath("version", equalTo(entity.getVersion())).match(mvcResult);
};
}
protected static ResultMatcher applyTagMatcherOnSingleResult(final Tag entity) throws Exception {
return mvcResult -> {
applyNamedEntityMatcherOnSingleResult(entity);
jsonPath("colour", equalTo(entity.getColour())).match(mvcResult);
};
}
protected static ResultMatcher applySelfLinkMatcherOnSingleResult(final String link) throws Exception {
return mvcResult -> {
jsonPath("_links.self.href", equalTo(link)).match(mvcResult);
};
}
}

View File

@@ -169,14 +169,11 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
// create Software Modules
final List<Long> smIDs = Lists.newArrayList(testdataFactory.createSoftwareModuleOs().getId(),
testdataFactory.createSoftwareModuleApp().getId());
final JSONArray list = new JSONArray();
for (final Long smID : smIDs) {
list.put(new JSONObject().put("id", Long.valueOf(smID)));
}
// post assignment
mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")
.contentType(MediaType.APPLICATION_JSON).content(list.toString())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
.contentType(MediaType.APPLICATION_JSON).content(JsonBuilder.ids(smIDs)))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// Test if size is 3
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -228,7 +225,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(jsonPath("$.alreadyAssigned", equalTo(1)))
.andExpect(jsonPath("$.total", equalTo(knownTargetIds.length)));
assertThat(targetManagement.findTargetByAssignedDistributionSet(createdDs.getId(), pageReq).getContent())
assertThat(targetManagement.findTargetByAssignedDistributionSet(createdDs.getId(), PAGE).getContent())
.as("Five targets in repository have DS assigned").hasSize(5);
}
@@ -417,7 +414,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@Description("Ensures that multiple DS requested are listed with expected payload.")
public void getDistributionSets() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0);
DistributionSet set = testdataFactory.createDistributionSet("one");
@@ -427,7 +424,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
// load also lazy stuff
set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).get();
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(1);
// perform request
@@ -491,7 +488,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Ensures that multipe DS posted to API are created in the repository.")
public void createDistributionSets() throws Exception {
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0);
final SoftwareModule ah = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_APP);
@@ -510,11 +507,11 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
final MvcResult mvcResult = executeMgmtTargetPost(one, two, three);
one = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
.findDistributionSetsAll("name==one", pageReq, false).getContent().get(0).getId()).get();
.findDistributionSetsAll("name==one", PAGE, false).getContent().get(0).getId()).get();
two = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
.findDistributionSetsAll("name==two", pageReq, false).getContent().get(0).getId()).get();
.findDistributionSetsAll("name==two", PAGE, false).getContent().get(0).getId()).get();
three = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
.findDistributionSetsAll("name==three", pageReq, false).getContent().get(0).getId()).get();
.findDistributionSetsAll("name==three", PAGE, false).getContent().get(0).getId()).get();
assertThat(
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
@@ -545,7 +542,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.isEqualTo(String.valueOf(three.getId()));
// check in database
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(3);
assertThat(one.isRequiredMigrationStep()).isEqualTo(false);
assertThat(two.isRequiredMigrationStep()).isEqualTo(false);
@@ -610,12 +607,12 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@Description("Ensures that DS deletion request to API is reflected by the repository.")
public void deleteUnassignedistributionSet() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0);
final DistributionSet set = testdataFactory.createDistributionSet("one");
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(1);
// perform request
@@ -623,7 +620,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(status().isOk());
// check repository content
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.isEmpty();
assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(0);
}
@@ -639,14 +636,14 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@Description("Ensures that assigned DS deletion request to API is reflected by the repository by means of deleted flag set.")
public void deleteAssignedDistributionSet() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0);
final DistributionSet set = testdataFactory.createDistributionSet("one");
testdataFactory.createTarget("test");
assignDistributionSet(set.getId(), "test");
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(1);
// perform request
@@ -654,9 +651,9 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(status().isOk());
// check repository content
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, true, true))
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, true, true))
.hasSize(1);
}
@@ -665,7 +662,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
public void updateDistributionSet() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0);
final DistributionSet set = testdataFactory.createDistributionSet("one");
@@ -689,7 +686,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
public void updateRequiredMigrationStepFailsIfDistributionSetisInUse() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0);
final DistributionSet set = testdataFactory.createDistributionSet("one");

View File

@@ -0,0 +1,328 @@
/**
* Copyright (c) 2015 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.rest.resource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
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.List;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.event.remote.DistributionSetTagDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetUpdatedEvent;
import org.eclipse.hawkbit.repository.model.BaseEntity;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.Tag;
import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.json.JSONException;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.ResultActions;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
@Features("Component Tests - Management API")
@Stories("Distribution Set Tag Resource")
public class MgmtDistributionSetTagResourceTest extends AbstractManagementApiIntegrationTest {
private static final String DISTRIBUTIONSETTAGS_ROOT = "http://localhost"
+ MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/";
@Test
@Description("Verfies that a paged result list of DS tags reflects the content on the repository side.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 2) })
public void getDistributionSetTags() throws Exception {
final List<DistributionSetTag> tags = testdataFactory.createDistributionSetTags(2);
final DistributionSetTag assigned = tags.get(0);
final DistributionSetTag unassigned = tags.get(1);
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(applyBaseEntityMatcherOnPagedResult(assigned))
.andExpect(applyBaseEntityMatcherOnPagedResult(unassigned))
.andExpect(applySelfLinkMatcherOnPagedResult(assigned, DISTRIBUTIONSETTAGS_ROOT + assigned.getId()))
.andExpect(applySelfLinkMatcherOnPagedResult(unassigned, DISTRIBUTIONSETTAGS_ROOT + unassigned.getId()))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(2)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(2)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(2)))
.andExpect(jsonPath(
"$.content.[?(@.id==" + assigned.getId() + ")]._links.assignedDistributionSets.href",
contains(DISTRIBUTIONSETTAGS_ROOT + assigned.getId() + "/assigned?offset=0&limit=50{&sort,q}")))
.andExpect(
jsonPath("$.content.[?(@.id==" + unassigned.getId() + ")]._links.assignedDistributionSets.href",
contains(DISTRIBUTIONSETTAGS_ROOT + unassigned.getId()
+ "/assigned?offset=0&limit=50{&sort,q}")));
}
@Test
@Description("Verfies that a single result of a DS tag reflects the content on the repository side.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 2) })
public void getDistributionSetTag() throws Exception {
final List<DistributionSetTag> tags = testdataFactory.createDistributionSetTags(2);
final DistributionSetTag assigned = tags.get(0);
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + assigned.getId())
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(applyTagMatcherOnSingleResult(assigned))
.andExpect(applySelfLinkMatcherOnSingleResult(DISTRIBUTIONSETTAGS_ROOT + assigned.getId()))
.andExpect(jsonPath("_links.assignedDistributionSets.href",
equalTo(DISTRIBUTIONSETTAGS_ROOT + assigned.getId() + "/assigned?offset=0&limit=50{&sort,q}")));
}
@Test
@Description("Verifies that created DS tags are stored in the repository as send to the API.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 2) })
public void createDistributionSetTags() throws JSONException, Exception {
final Tag tagOne = entityFactory.tag().create().colour("testcol1").description("its a test1").name("thetest1")
.build();
final Tag tagTwo = entityFactory.tag().create().colour("testcol2").description("its a test2").name("thetest2")
.build();
final ResultActions result = mvc
.perform(post(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING)
.content(JsonBuilder.tags(Arrays.asList(tagOne, tagTwo)))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
final Tag createdOne = tagManagement.findAllDistributionSetTags("name==thetest1", PAGE).getContent().get(0);
assertThat(createdOne.getName()).isEqualTo(tagOne.getName());
assertThat(createdOne.getDescription()).isEqualTo(tagOne.getDescription());
assertThat(createdOne.getColour()).isEqualTo(tagOne.getColour());
final Tag createdTwo = tagManagement.findAllDistributionSetTags("name==thetest2", PAGE).getContent().get(0);
assertThat(createdTwo.getName()).isEqualTo(tagTwo.getName());
assertThat(createdTwo.getDescription()).isEqualTo(tagTwo.getDescription());
assertThat(createdTwo.getColour()).isEqualTo(tagTwo.getColour());
result.andExpect(applyTagMatcherOnArrayResult(createdOne)).andExpect(applyTagMatcherOnArrayResult(createdTwo));
}
@Test
@Description("Verifies that an updated DS tag is stored in the repository as send to the API.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetTagUpdatedEvent.class, count = 1) })
public void updateDistributionSetTag() throws Exception {
final List<DistributionSetTag> tags = testdataFactory.createDistributionSetTags(1);
final DistributionSetTag original = tags.get(0);
final Tag update = entityFactory.tag().create().name("updatedName").colour("updatedCol")
.description("updatedDesc").build();
final ResultActions result = mvc
.perform(put(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + original.getId())
.content(JsonBuilder.tag(update)).contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
final Tag updated = tagManagement.findAllDistributionSetTags("name==updatedName", PAGE).getContent().get(0);
assertThat(updated.getName()).isEqualTo(update.getName());
assertThat(updated.getDescription()).isEqualTo(update.getDescription());
assertThat(updated.getColour()).isEqualTo(update.getColour());
result.andExpect(applyTagMatcherOnArrayResult(updated)).andExpect(applyTagMatcherOnArrayResult(updated));
}
@Test
@Description("Verfies that the delete call is reflected by the repository.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetTagDeletedEvent.class, count = 1) })
public void deleteDistributionSetTag() throws Exception {
final List<DistributionSetTag> tags = testdataFactory.createDistributionSetTags(1);
final DistributionSetTag original = tags.get(0);
mvc.perform(delete(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + original.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(tagManagement.findDistributionSetTagById(original.getId())).isNotPresent();
}
@Test
@Description("Ensures that assigned DS to tag in repository are listed with proper paging results.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 5),
@Expect(type = DistributionSetUpdatedEvent.class, count = 5) })
public void getAssignedDistributionSets() throws Exception {
final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0);
final int setsAssigned = 5;
final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned);
distributionSetManagement.toggleTagAssignment(sets.stream().map(BaseEntity::getId).collect(Collectors.toList()),
tag.getName());
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(setsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(setsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(setsAssigned)));
}
@Test
@Description("Ensures that assigned DS to tag in repository are listed with proper paging results with paging limit parameter.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 5),
@Expect(type = DistributionSetUpdatedEvent.class, count = 5) })
public void getAssignedDistributionSetsWithPagingLimitRequestParameter() throws Exception {
final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0);
final int setsAssigned = 5;
final int limitSize = 1;
final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned);
distributionSetManagement.toggleTagAssignment(sets.stream().map(BaseEntity::getId).collect(Collectors.toList()),
tag.getName());
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(setsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize)));
}
@Test
@Description("Ensures that assigned DS to tag in repository are listed with proper paging results with paging limit and offset parameter.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 5),
@Expect(type = DistributionSetUpdatedEvent.class, count = 5) })
public void getAssignedDistributionSetsWithPagingLimitAndOffsetRequestParameter() throws Exception {
final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0);
final int setsAssigned = 5;
final int offsetParam = 2;
final int expectedSize = setsAssigned - offsetParam;
final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned);
distributionSetManagement.toggleTagAssignment(sets.stream().map(BaseEntity::getId).collect(Collectors.toList()),
tag.getName());
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(setsAssigned)))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(setsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize)));
}
@Test
@Description("Verfies that tag assignments done through toggle API command are correctly assigned or unassigned.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 2),
@Expect(type = DistributionSetUpdatedEvent.class, count = 4) })
public void toggleTagAssignment() throws Exception {
final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0);
final int setsAssigned = 2;
final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned);
// 2 DistributionSetUpdateEvent
ResultActions result = toggle(tag, sets);
List<DistributionSet> updated = distributionSetManagement.findDistributionSetsByTag(PAGE, tag.getId())
.getContent();
assertThat(updated.stream().map(DistributionSet::getId).collect(Collectors.toList()))
.containsAll(sets.stream().map(DistributionSet::getId).collect(Collectors.toList()));
result.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(0), "assignedDistributionSets"))
.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(1), "assignedDistributionSets"));
// 2 DistributionSetUpdateEvent
result = toggle(tag, sets);
updated = distributionSetManagement.findDistributionSetsAll(PAGE, false).getContent();
result.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(0), "unassignedDistributionSets"))
.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(1), "unassignedDistributionSets"));
assertThat(distributionSetManagement.findDistributionSetsByTag(PAGE, tag.getId())).isEmpty();
}
private ResultActions toggle(final DistributionSetTag tag, final List<DistributionSet> sets) throws Exception {
return mvc
.perform(post(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId()
+ "/assigned/toggleTagAssignment").content(
JsonBuilder.ids(sets.stream().map(DistributionSet::getId).collect(Collectors.toList())))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
}
@Test
@Description("Verfies that tag assignments done through tag API command are correctly stored in the repository.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 2),
@Expect(type = DistributionSetUpdatedEvent.class, count = 2) })
public void assignDistributionSets() throws Exception {
final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0);
final int setsAssigned = 2;
final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned);
final ResultActions result = mvc
.perform(
post(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.content(JsonBuilder
.ids(sets.stream().map(DistributionSet::getId).collect(Collectors.toList())))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
final List<DistributionSet> updated = distributionSetManagement.findDistributionSetsByTag(PAGE, tag.getId())
.getContent();
assertThat(updated.stream().map(DistributionSet::getId).collect(Collectors.toList()))
.containsAll(sets.stream().map(DistributionSet::getId).collect(Collectors.toList()));
result.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(0)))
.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(1)));
}
@Test
@Description("Verfies that tag unassignments done through tag API command are correctly stored in the repository.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 2),
@Expect(type = DistributionSetUpdatedEvent.class, count = 3) })
public void unassignDistributionSet() throws Exception {
final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0);
final int setsAssigned = 2;
final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned);
final DistributionSet assigned = sets.get(0);
final DistributionSet unassigned = sets.get(1);
distributionSetManagement.toggleTagAssignment(sets.stream().map(BaseEntity::getId).collect(Collectors.toList()),
tag.getName());
mvc.perform(delete(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned/"
+ unassigned.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
final List<DistributionSet> updated = distributionSetManagement.findDistributionSetsByTag(PAGE, tag.getId())
.getContent();
assertThat(updated.stream().map(DistributionSet::getId).collect(Collectors.toList()))
.containsOnly(assigned.getId());
}
}

View File

@@ -71,7 +71,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
@Before
public void assertPreparationOfRepo() {
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("no softwaremodule should be founded")
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("no softwaremodule should be founded")
.hasSize(0);
}
@@ -182,7 +182,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
@Test
@Description("Verfies that the system does not accept empty artifact uploads. Expected response: BAD REQUEST")
public void emptyUploadArtifact() throws Exception {
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0);
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
@@ -313,7 +313,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
assertTrue("Response has wrong response content",
Arrays.equals(result2.getResponse().getContentAsByteArray(), random));
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremodule size is wrong").hasSize(1);
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("Softwaremodule size is wrong").hasSize(1);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(2);
}
@@ -551,7 +551,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")]._links.self.href",
contains("http://localhost/rest/v1/softwaremodules/" + app.getId())));
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremodule size is wrong").hasSize(2);
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("Softwaremodule size is wrong").hasSize(2);
}
@Test
@@ -562,7 +562,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
testdataFactory.createSoftwareModuleOs("2");
final SoftwareModule app2 = testdataFactory.createSoftwareModuleApp("2");
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(4);
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(4);
// only by name, only one exists per name
mvc.perform(get("/rest/v1/softwaremodules?q=name==" + os1.getName()).accept(MediaType.APPLICATION_JSON))
@@ -652,7 +652,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(jsonPath("$._links.artifacts.href",
equalTo("http://localhost/rest/v1/softwaremodules/" + os.getId() + "/artifacts")));
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremodule size is wrong").hasSize(1);
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("Softwaremodule size is wrong").hasSize(1);
}
@Test
@@ -707,14 +707,14 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.toString()).as("Response contains invalid artifacts href")
.isEqualTo("http://localhost/rest/v1/softwaremodules/" + appCreated.getId() + "/artifacts");
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Wrong softwaremodule size").hasSize(2);
assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType.getId()).getContent().get(0).getName())
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("Wrong softwaremodule size").hasSize(2);
assertThat(softwareManagement.findSoftwareModulesByType(PAGE, osType.getId()).getContent().get(0).getName())
.as("Softwaremoudle name is wrong").isEqualTo(os.getName());
assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType.getId()).getContent().get(0)
assertThat(softwareManagement.findSoftwareModulesByType(PAGE, osType.getId()).getContent().get(0)
.getCreatedBy()).as("Softwaremoudle created by is wrong").isEqualTo("uploadTester");
assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType.getId()).getContent().get(0)
assertThat(softwareManagement.findSoftwareModulesByType(PAGE, osType.getId()).getContent().get(0)
.getCreatedAt()).as("Softwaremoudle created at is wrong").isGreaterThanOrEqualTo(current);
assertThat(softwareManagement.findSoftwareModulesByType(pageReq, appType.getId()).getContent().get(0).getName())
assertThat(softwareManagement.findSoftwareModulesByType(PAGE, appType.getId()).getContent().get(0).getName())
.as("Softwaremoudle name is wrong").isEqualTo(ah.getName());
}
@@ -728,13 +728,13 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
artifactManagement.createArtifact(new ByteArrayInputStream(random), sm.getId(), "file1", false);
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremoudle size is wrong").hasSize(1);
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("Softwaremoudle size is wrong").hasSize(1);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
mvc.perform(delete("/rest/v1/softwaremodules/{smId}", sm.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
assertThat(softwareManagement.findSoftwareModulesAll(pageReq))
assertThat(softwareManagement.findSoftwareModulesAll(PAGE))
.as("After delete no softwarmodule should be available").isEmpty();
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0);
}
@@ -749,7 +749,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
artifactManagement.createArtifact(new ByteArrayInputStream(random),
ds1.findFirstModuleByType(appType).get().getId(), "file1", false);
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(3);
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(3);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(appType).get().getId()))
@@ -760,7 +760,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// all 3 are now marked as deleted
assertThat(softwareManagement.findSoftwareModulesAll(pageReq).getNumber())
assertThat(softwareManagement.findSoftwareModulesAll(PAGE).getNumber())
.as("After delete no softwarmodule should be available").isEqualTo(0);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
}
@@ -779,7 +779,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
artifactManagement.createArtifact(new ByteArrayInputStream(random), sm.getId(), "file2", false);
// check repo before delete
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(1);
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(1);
assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts()).hasSize(2);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(2);
@@ -789,7 +789,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// check that only one artifact is still alive and still assigned
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("After the sm should be marked as deleted")
assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("After the sm should be marked as deleted")
.hasSize(1);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts())

View File

@@ -110,9 +110,10 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
entityFactory.actionStatus().create(actions.get(0).getId()).status(Status.FINISHED).message("test"));
final PageRequest pageRequest = new PageRequest(0, 1000, Direction.ASC, ActionFields.ID.getFieldName());
final ActionStatus status = deploymentManagement.findActionsByTarget(knownTargetId, pageRequest).getContent()
.get(0).getActionStatus().stream().sorted((e1, e2) -> Long.compare(e2.getId(), e1.getId()))
.collect(Collectors.toList()).get(0);
final Action action = deploymentManagement.findActionsByTarget(knownTargetId, pageRequest).getContent().get(0);
final ActionStatus status = deploymentManagement.findActionStatusByAction(PAGE, action.getId()).getContent()
.stream().sorted((e1, e2) -> Long.compare(e2.getId(), e1.getId())).collect(Collectors.toList()).get(0);
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/"
+ MgmtRestConstants.TARGET_V1_ACTIONS + "/" + actions.get(0).getId() + "/status")
@@ -224,12 +225,12 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
// test - cancel the active action
mvc.perform(
delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}",
tA.getControllerId(), deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq)
tA.getControllerId(), deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE)
.getContent().get(0).getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNoContent());
final Action action = deploymentManagement.findAction(
deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq).getContent().get(0).getId())
deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE).getContent().get(0).getId())
.get();
// still active because in "canceling" state and waiting for controller
// feedback
@@ -250,10 +251,10 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
// cancel the active action
deploymentManagement.cancelAction(
deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq).getContent().get(0).getId());
deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE).getContent().get(0).getId());
// find the current active action
final List<Action> cancelActions = deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq)
final List<Action> cancelActions = deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE)
.getContent().stream().filter(Action::isCancelingOrCanceled).collect(Collectors.toList());
assertThat(cancelActions).hasSize(1);
@@ -271,10 +272,10 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
// cancel the active action
deploymentManagement.cancelAction(
deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq).getContent().get(0).getId());
deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE).getContent().get(0).getId());
// find the current active action
final List<Action> cancelActions = deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq)
final List<Action> cancelActions = deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE)
.getContent().stream().filter(Action::isCancelingOrCanceled).collect(Collectors.toList());
assertThat(cancelActions).hasSize(1);
assertThat(cancelActions.get(0).isCancelingOrCanceled()).isTrue();
@@ -294,7 +295,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
// test - cancel an cancel action returns forbidden
mvc.perform(
delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}?force=true",
tA.getControllerId(), deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq)
tA.getControllerId(), deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE)
.getContent().get(0).getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
}
@@ -876,8 +877,9 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
final String knownTargetId = "targetId";
final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0);
// retrieve list in default descending order for actionstaus entries
final List<ActionStatus> actionStatus = action.getActionStatus().stream()
.sorted((e1, e2) -> Long.compare(e2.getId(), e1.getId())).collect(Collectors.toList());
final List<ActionStatus> actionStatus = deploymentManagement.findActionStatusByAction(PAGE, action.getId())
.getContent().stream().sorted((e1, e2) -> Long.compare(e2.getId(), e1.getId()))
.collect(Collectors.toList());
// sort is default descending order, latest status first
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/"
@@ -902,8 +904,9 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
public void getMultipleActionStatusSortedByReportedAt() throws Exception {
final String knownTargetId = "targetId";
final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0);
final List<ActionStatus> actionStatus = action.getActionStatus().stream()
.sorted((e1, e2) -> Long.compare(e1.getId(), e2.getId())).collect(Collectors.toList());
final List<ActionStatus> actionStatus = deploymentManagement.findActionStatusByAction(PAGE, action.getId())
.getContent().stream().sorted((e1, e2) -> Long.compare(e1.getId(), e2.getId()))
.collect(Collectors.toList());
// descending order
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/"
@@ -948,8 +951,9 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
final String knownTargetId = "targetId";
final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0);
final List<ActionStatus> actionStatus = action.getActionStatus().stream()
.sorted((e1, e2) -> Long.compare(e1.getId(), e2.getId())).collect(Collectors.toList());
final List<ActionStatus> actionStatus = deploymentManagement.findActionStatusByAction(PAGE, action.getId())
.getContent().stream().sorted((e1, e2) -> Long.compare(e1.getId(), e2.getId()))
.collect(Collectors.toList());
// Page 1
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/"
@@ -1054,7 +1058,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
assignDistributionSet(two, updatedTargets);
// two updates, one cancellation
final List<Action> actions = deploymentManagement.findActionsByTarget(target.getControllerId(), pageReq)
final List<Action> actions = deploymentManagement.findActionsByTarget(target.getControllerId(), PAGE)
.getContent();
assertThat(actions).hasSize(2);
@@ -1118,7 +1122,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
.andExpect(status().isOk());
final List<Action> findActiveActionsByTarget = deploymentManagement
.findActiveActionsByTarget(target.getControllerId());
.findActiveActionsByTarget(PAGE, target.getControllerId()).getContent();
assertThat(findActiveActionsByTarget).hasSize(1);
assertThat(findActiveActionsByTarget.get(0).getActionType()).isEqualTo(ActionType.TIMEFORCED);
assertThat(findActiveActionsByTarget.get(0).getForcedTime()).isEqualTo(forceTime);
@@ -1298,7 +1302,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
// assign a distribution set so we get an active update action
assignDistributionSet(dsA, Lists.newArrayList(tA));
// verify active action
final Slice<Action> actionsByTarget = deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq);
final Slice<Action> actionsByTarget = deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE);
assertThat(actionsByTarget.getContent()).hasSize(1);
return targetManagement.findTargetByControllerID(tA.getControllerId()).get();
}

View File

@@ -0,0 +1,318 @@
/**
* Copyright (c) 2015 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.rest.resource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
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.List;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.event.remote.TargetTagDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetTagCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetTagUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetUpdatedEvent;
import org.eclipse.hawkbit.repository.model.Tag;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetTag;
import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.ResultActions;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
/**
* Spring MVC Tests against the MgmtTargetTagResource.
*
*/
@Features("Component Tests - Management API")
@Stories("Target Tag Resource")
public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationTest {
private static final String TARGETTAGS_ROOT = "http://localhost" + MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING
+ "/";
@Test
@Description("Verfies that a paged result list of target tags reflects the content on the repository side.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 2) })
public void getTargetTags() throws Exception {
final List<TargetTag> tags = testdataFactory.createTargetTags(2, "");
final TargetTag assigned = tags.get(0);
final TargetTag unassigned = tags.get(1);
mvc.perform(get(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(applyTagMatcherOnPagedResult(assigned)).andExpect(applyTagMatcherOnPagedResult(unassigned))
.andExpect(applySelfLinkMatcherOnPagedResult(assigned, TARGETTAGS_ROOT + assigned.getId()))
.andExpect(applySelfLinkMatcherOnPagedResult(unassigned, TARGETTAGS_ROOT + unassigned.getId()))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(2)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(2)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(2)))
.andExpect(jsonPath("$.content.[?(@.id==" + assigned.getId() + ")]._links.assignedTargets.href",
contains(TARGETTAGS_ROOT + assigned.getId() + "/assigned?offset=0&limit=50{&sort,q}")))
.andExpect(jsonPath("$.content.[?(@.id==" + unassigned.getId() + ")]._links.assignedTargets.href",
contains(TARGETTAGS_ROOT + unassigned.getId() + "/assigned?offset=0&limit=50{&sort,q}")));
}
@Test
@Description("Verfies that a single result of a target tag reflects the content on the repository side.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 2) })
public void getTargetTag() throws Exception {
final List<TargetTag> tags = testdataFactory.createTargetTags(2, "");
final TargetTag assigned = tags.get(0);
mvc.perform(get(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + assigned.getId())
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(applyTagMatcherOnSingleResult(assigned))
.andExpect(applySelfLinkMatcherOnSingleResult(TARGETTAGS_ROOT + assigned.getId()))
.andExpect(jsonPath("_links.assignedTargets.href",
equalTo(TARGETTAGS_ROOT + assigned.getId() + "/assigned?offset=0&limit=50{&sort,q}")));
}
@Test
@Description("Verifies that created target tags are stored in the repository as send to the API.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 2) })
public void createTargetTags() throws Exception {
final Tag tagOne = entityFactory.tag().create().colour("testcol1").description("its a test1").name("thetest1")
.build();
final Tag tagTwo = entityFactory.tag().create().colour("testcol2").description("its a test2").name("thetest2")
.build();
final ResultActions result = mvc
.perform(post(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING)
.content(JsonBuilder.tags(Arrays.asList(tagOne, tagTwo)))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
final Tag createdOne = tagManagement.findAllTargetTags("name==thetest1", PAGE).getContent().get(0);
assertThat(createdOne.getName()).isEqualTo(tagOne.getName());
assertThat(createdOne.getDescription()).isEqualTo(tagOne.getDescription());
assertThat(createdOne.getColour()).isEqualTo(tagOne.getColour());
final Tag createdTwo = tagManagement.findAllTargetTags("name==thetest2", PAGE).getContent().get(0);
assertThat(createdTwo.getName()).isEqualTo(tagTwo.getName());
assertThat(createdTwo.getDescription()).isEqualTo(tagTwo.getDescription());
assertThat(createdTwo.getColour()).isEqualTo(tagTwo.getColour());
result.andExpect(applyTagMatcherOnArrayResult(createdOne)).andExpect(applyTagMatcherOnArrayResult(createdTwo));
}
@Test
@Description("Verifies that an updated target tag is stored in the repository as send to the API.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetTagUpdatedEvent.class, count = 1) })
public void updateTargetTag() throws Exception {
final List<TargetTag> tags = testdataFactory.createTargetTags(1, "");
final TargetTag original = tags.get(0);
final Tag update = entityFactory.tag().create().name("updatedName").colour("updatedCol")
.description("updatedDesc").build();
final ResultActions result = mvc
.perform(put(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + original.getId())
.content(JsonBuilder.tag(update)).contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
final Tag updated = tagManagement.findAllTargetTags("name==updatedName", PAGE).getContent().get(0);
assertThat(updated.getName()).isEqualTo(update.getName());
assertThat(updated.getDescription()).isEqualTo(update.getDescription());
assertThat(updated.getColour()).isEqualTo(update.getColour());
result.andExpect(applyTagMatcherOnArrayResult(updated)).andExpect(applyTagMatcherOnArrayResult(updated));
}
@Test
@Description("Verfies that the delete call is reflected by the repository.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetTagDeletedEvent.class, count = 1) })
public void deleteTargetTag() throws Exception {
final List<TargetTag> tags = testdataFactory.createTargetTags(1, "");
final TargetTag original = tags.get(0);
mvc.perform(delete(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + original.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(tagManagement.findTargetTagById(original.getId())).isNotPresent();
}
@Test
@Description("Ensures that assigned targets to tag in repository are listed with proper paging results.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 5), @Expect(type = TargetUpdatedEvent.class, count = 5) })
public void getAssignedTargets() throws Exception {
final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0);
final int targetsAssigned = 5;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
targetManagement.toggleTagAssignment(targets.stream().map(Target::getControllerId).collect(Collectors.toList()),
tag.getName());
mvc.perform(get(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(targetsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(targetsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(targetsAssigned)));
}
@Test
@Description("Ensures that assigned DS to tag in repository are listed with proper paging results with paging limit parameter.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 5), @Expect(type = TargetUpdatedEvent.class, count = 5) })
public void getAssignedTargetsWithPagingLimitRequestParameter() throws Exception {
final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0);
final int targetsAssigned = 5;
final int limitSize = 1;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
targetManagement.toggleTagAssignment(targets.stream().map(Target::getControllerId).collect(Collectors.toList()),
tag.getName());
mvc.perform(get(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(targetsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize)));
}
@Test
@Description("Ensures that assigned targets to tag in repository are listed with proper paging results with paging limit and offset parameter.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 5), @Expect(type = TargetUpdatedEvent.class, count = 5) })
public void getAssignedTargetsWithPagingLimitAndOffsetRequestParameter() throws Exception {
final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0);
final int targetsAssigned = 5;
final int offsetParam = 2;
final int expectedSize = targetsAssigned - offsetParam;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
targetManagement.toggleTagAssignment(targets.stream().map(Target::getControllerId).collect(Collectors.toList()),
tag.getName());
mvc.perform(get(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(targetsAssigned)))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(targetsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize)));
}
@Test
@Description("verfies that tag assignments done through toggle API command are correctly assigned or unassigned.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 2), @Expect(type = TargetUpdatedEvent.class, count = 4) })
public void toggleTagAssignment() throws Exception {
final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0);
final int targetsAssigned = 2;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
ResultActions result = toggle(tag, targets);
List<Target> updated = targetManagement.findTargetsByTag(PAGE, tag.getId()).getContent();
assertThat(updated.stream().map(Target::getControllerId).collect(Collectors.toList()))
.containsAll(targets.stream().map(Target::getControllerId).collect(Collectors.toList()));
result.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(0), "assignedTargets"))
.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(1), "assignedTargets"));
result = toggle(tag, targets);
updated = targetManagement.findTargetsAll(PAGE).getContent();
result.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(0), "unassignedTargets"))
.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(1), "unassignedTargets"));
assertThat(targetManagement.findTargetsByTag(PAGE, tag.getId())).isEmpty();
}
private ResultActions toggle(final TargetTag tag, final List<Target> targets) throws Exception {
return mvc
.perform(post(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId()
+ "/assigned/toggleTagAssignment")
.content(JsonBuilder.controllerIds(
targets.stream().map(Target::getControllerId).collect(Collectors.toList())))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
}
@Test
@Description("Verfies that tag assignments done through tag API command are correctly stored in the repository.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 2), @Expect(type = TargetUpdatedEvent.class, count = 2) })
public void assignTargets() throws Exception {
final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0);
final int targetsAssigned = 2;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
final ResultActions result = mvc
.perform(post(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.content(JsonBuilder.controllerIds(
targets.stream().map(Target::getControllerId).collect(Collectors.toList())))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
final List<Target> updated = targetManagement.findTargetsByTag(PAGE, tag.getId()).getContent();
assertThat(updated.stream().map(Target::getControllerId).collect(Collectors.toList()))
.containsAll(targets.stream().map(Target::getControllerId).collect(Collectors.toList()));
result.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(0)))
.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(1)));
}
@Test
@Description("Verfies that tag unassignments done through tag API command are correctly stored in the repository.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 2), @Expect(type = TargetUpdatedEvent.class, count = 3) })
public void unassignTarget() throws Exception {
final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0);
final int targetsAssigned = 2;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
final Target assigned = targets.get(0);
final Target unassigned = targets.get(1);
targetManagement.toggleTagAssignment(targets.stream().map(Target::getControllerId).collect(Collectors.toList()),
tag.getName());
mvc.perform(delete(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned/"
+ unassigned.getControllerId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
final List<Target> updated = targetManagement.findTargetsByTag(PAGE, tag.getId()).getContent();
assertThat(updated.stream().map(Target::getControllerId).collect(Collectors.toList()))
.containsOnly(assigned.getControllerId());
}
}