Rename and split rest resources ddi, mgmt and system
Signed-off-by: SirWayne <dennis.melzer@bosch-si.com>
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* 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.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.stereotype.Controller;
|
||||
|
||||
/**
|
||||
* Annotation to enable {@link ComponentScan} in the resource package to setup
|
||||
* all {@link Controller} annotated classes and setup the REST-Resources for the
|
||||
* Management API.
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Target(ElementType.TYPE)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Configuration
|
||||
@ComponentScan
|
||||
public @interface EnableMgmtApi {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
/**
|
||||
* 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.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
|
||||
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.MetadataRest;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSetRequestBodyPost;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtTargetAssignmentResponseBody;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetRestApi;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTypeRestApi;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetAssignmentResult;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetManagement;
|
||||
import org.eclipse.hawkbit.repository.SoftwareManagement;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetType;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
|
||||
/**
|
||||
* A mapper which maps repository model to RESTful model representation and
|
||||
* back.
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
public final class MgmtDistributionSetMapper {
|
||||
private MgmtDistributionSetMapper() {
|
||||
// Utility class
|
||||
}
|
||||
|
||||
private static SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId,
|
||||
final SoftwareManagement softwareManagement) {
|
||||
final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId);
|
||||
if (module == null) {
|
||||
throw new EntityNotFoundException("SoftwareModule with Id {" + softwareModuleId + "} does not exist");
|
||||
}
|
||||
|
||||
return module;
|
||||
}
|
||||
|
||||
private static DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(
|
||||
final String distributionSetTypekey, final DistributionSetManagement distributionSetManagement) {
|
||||
|
||||
final DistributionSetType module = distributionSetManagement
|
||||
.findDistributionSetTypeByKey(distributionSetTypekey);
|
||||
if (module == null) {
|
||||
throw new EntityNotFoundException(
|
||||
"DistributionSetType with key {" + distributionSetTypekey + "} does not exist");
|
||||
}
|
||||
return module;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link MgmtDistributionSetRequestBodyPost}s to {@link DistributionSet}s.
|
||||
*
|
||||
* @param sets
|
||||
* to convert
|
||||
* @param softwareManagement
|
||||
* to use for conversion
|
||||
* @return converted list of {@link DistributionSet}s
|
||||
*/
|
||||
static List<DistributionSet> dsFromRequest(final Iterable<MgmtDistributionSetRequestBodyPost> sets,
|
||||
final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement) {
|
||||
|
||||
final List<DistributionSet> mappedList = new ArrayList<>();
|
||||
for (final MgmtDistributionSetRequestBodyPost dsRest : sets) {
|
||||
mappedList.add(fromRequest(dsRest, softwareManagement, distributionSetManagement));
|
||||
}
|
||||
return mappedList;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link MgmtDistributionSetRequestBodyPost} to {@link DistributionSet}.
|
||||
*
|
||||
* @param dsRest
|
||||
* to convert
|
||||
* @param softwareManagement
|
||||
* to use for conversion
|
||||
* @return converted {@link DistributionSet}
|
||||
*/
|
||||
static DistributionSet fromRequest(final MgmtDistributionSetRequestBodyPost dsRest,
|
||||
final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement) {
|
||||
|
||||
final DistributionSet result = new DistributionSet();
|
||||
result.setDescription(dsRest.getDescription());
|
||||
result.setName(dsRest.getName());
|
||||
result.setType(findDistributionSetTypeWithExceptionIfNotFound(dsRest.getType(), distributionSetManagement));
|
||||
|
||||
result.setRequiredMigrationStep(dsRest.isRequiredMigrationStep());
|
||||
result.setVersion(dsRest.getVersion());
|
||||
|
||||
if (dsRest.getOs() != null) {
|
||||
result.addModule(findSoftwareModuleWithExceptionIfNotFound(dsRest.getOs().getId(), softwareManagement));
|
||||
}
|
||||
|
||||
if (dsRest.getApplication() != null) {
|
||||
result.addModule(
|
||||
findSoftwareModuleWithExceptionIfNotFound(dsRest.getApplication().getId(), softwareManagement));
|
||||
}
|
||||
|
||||
if (dsRest.getRuntime() != null) {
|
||||
result.addModule(
|
||||
findSoftwareModuleWithExceptionIfNotFound(dsRest.getRuntime().getId(), softwareManagement));
|
||||
}
|
||||
|
||||
if (dsRest.getModules() != null) {
|
||||
dsRest.getModules().forEach(module -> result
|
||||
.addModule(findSoftwareModuleWithExceptionIfNotFound(module.getId(), softwareManagement)));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* From {@link MetadataRest} to {@link DistributionSetMetadata}.
|
||||
*
|
||||
* @param ds
|
||||
* @param metadata
|
||||
* @return
|
||||
*/
|
||||
static List<DistributionSetMetadata> fromRequestDsMetadata(final DistributionSet ds,
|
||||
final List<MetadataRest> metadata) {
|
||||
final List<DistributionSetMetadata> mappedList = new ArrayList<>(metadata.size());
|
||||
for (final MetadataRest metadataRest : metadata) {
|
||||
if (metadataRest.getKey() == null) {
|
||||
throw new IllegalArgumentException("the key of the metadata must be present");
|
||||
}
|
||||
mappedList.add(new DistributionSetMetadata(metadataRest.getKey(), ds, metadataRest.getValue()));
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a response for distribution set.
|
||||
*
|
||||
* @param distributionSet
|
||||
* the ds set
|
||||
* @return the response
|
||||
*/
|
||||
public static MgmtDistributionSet toResponse(final DistributionSet distributionSet) {
|
||||
if (distributionSet == null) {
|
||||
return null;
|
||||
}
|
||||
final MgmtDistributionSet response = new MgmtDistributionSet();
|
||||
MgmtRestModelMapper.mapNamedToNamed(response, distributionSet);
|
||||
|
||||
response.setDsId(distributionSet.getId());
|
||||
response.setVersion(distributionSet.getVersion());
|
||||
response.setComplete(distributionSet.isComplete());
|
||||
response.setType(distributionSet.getType().getKey());
|
||||
|
||||
distributionSet.getModules()
|
||||
.forEach(module -> response.getModules().add(MgmtSoftwareModuleMapper.toResponse(module)));
|
||||
|
||||
response.setRequiredMigrationStep(distributionSet.isRequiredMigrationStep());
|
||||
|
||||
response.add(
|
||||
linkTo(methodOn(MgmtDistributionSetRestApi.class).getDistributionSet(response.getDsId())).withRel("self"));
|
||||
|
||||
response.add(linkTo(
|
||||
methodOn(MgmtDistributionSetTypeRestApi.class).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))
|
||||
.withRel("metadata"));
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
static MgmtTargetAssignmentResponseBody toResponse(final DistributionSetAssignmentResult dsAssignmentResult) {
|
||||
final MgmtTargetAssignmentResponseBody result = new MgmtTargetAssignmentResponseBody();
|
||||
result.setAssigned(dsAssignmentResult.getAssigned());
|
||||
result.setAlreadyAssigned(dsAssignmentResult.getAlreadyAssigned());
|
||||
result.setTotal(dsAssignmentResult.getTotal());
|
||||
return result;
|
||||
}
|
||||
|
||||
static List<MgmtDistributionSet> toResponseDistributionSets(final Iterable<DistributionSet> sets) {
|
||||
final List<MgmtDistributionSet> response = new ArrayList<>();
|
||||
if (sets != null) {
|
||||
|
||||
for (final DistributionSet set : sets) {
|
||||
response.add(toResponse(set));
|
||||
}
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
static MetadataRest toResponseDsMetadata(final DistributionSetMetadata metadata) {
|
||||
final MetadataRest metadataRest = new MetadataRest();
|
||||
metadataRest.setKey(metadata.getId().getKey());
|
||||
metadataRest.setValue(metadata.getValue());
|
||||
return metadataRest;
|
||||
}
|
||||
|
||||
static List<MetadataRest> toResponseDsMetadata(final List<DistributionSetMetadata> metadata) {
|
||||
|
||||
final List<MetadataRest> mappedList = new ArrayList<>(metadata.size());
|
||||
for (final DistributionSetMetadata distributionSetMetadata : metadata) {
|
||||
mappedList.add(toResponseDsMetadata(distributionSetMetadata));
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
|
||||
static List<MgmtDistributionSet> toResponseFromDsList(final List<DistributionSet> sets) {
|
||||
final List<MgmtDistributionSet> mappedList = new ArrayList<>();
|
||||
if (sets != null) {
|
||||
for (final DistributionSet set : sets) {
|
||||
final MgmtDistributionSet response = toResponse(set);
|
||||
|
||||
mappedList.add(response);
|
||||
}
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
/**
|
||||
* 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 java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.MetadataRest;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.PagedList;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSetRequestBodyPost;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSetRequestBodyPut;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtTargetAssignmentRequestBody;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtTargetAssignmentResponseBody;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModule;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleAssigment;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetRestApi;
|
||||
import org.eclipse.hawkbit.repository.DeploymentManagement;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetAssignmentResult;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetFields;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetManagement;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetMetadataFields;
|
||||
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
|
||||
import org.eclipse.hawkbit.repository.SoftwareManagement;
|
||||
import org.eclipse.hawkbit.repository.SystemManagement;
|
||||
import org.eclipse.hawkbit.repository.TargetFields;
|
||||
import org.eclipse.hawkbit.repository.TargetManagement;
|
||||
import org.eclipse.hawkbit.repository.TargetWithActionType;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
|
||||
import org.eclipse.hawkbit.repository.model.DsMetadataCompositeKey;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
|
||||
import org.eclipse.hawkbit.tenancy.TenantAware;
|
||||
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.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* REST Resource handling for {@link DistributionSet} CRUD operations.
|
||||
*/
|
||||
@RestController
|
||||
public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(MgmtDistributionSetResource.class);
|
||||
|
||||
@Autowired
|
||||
private SoftwareManagement softwareManagement;
|
||||
|
||||
@Autowired
|
||||
private TargetManagement targetManagement;
|
||||
|
||||
@Autowired
|
||||
private DeploymentManagement deployManagament;
|
||||
|
||||
@Autowired
|
||||
private SystemManagement systemManagement;
|
||||
|
||||
@Autowired
|
||||
private TenantAware currentTenant;
|
||||
|
||||
@Autowired
|
||||
private DistributionSetManagement distributionSetManagement;
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MgmtDistributionSet>> getDistributionSets(final int pagingOffsetParam,
|
||||
final int pagingLimitParam, final String sortParam, final String rsqlParam) {
|
||||
|
||||
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
|
||||
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
|
||||
final Sort sorting = PagingUtility.sanitizeDistributionSetSortParam(sortParam);
|
||||
|
||||
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
|
||||
final Page<DistributionSet> findDsPage;
|
||||
if (rsqlParam != null) {
|
||||
findDsPage = this.distributionSetManagement.findDistributionSetsAll(
|
||||
RSQLUtility.parse(rsqlParam, DistributionSetFields.class), pageable, false);
|
||||
} else {
|
||||
findDsPage = this.distributionSetManagement.findDistributionSetsAll(pageable, false, null);
|
||||
}
|
||||
|
||||
final List<MgmtDistributionSet> rest = MgmtDistributionSetMapper.toResponseFromDsList(findDsPage.getContent());
|
||||
return new ResponseEntity<>(new PagedList<>(rest, findDsPage.getTotalElements()), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtDistributionSet> getDistributionSet(final Long distributionSetId) {
|
||||
final DistributionSet foundDs = findDistributionSetWithExceptionIfNotFound(distributionSetId);
|
||||
|
||||
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponse(foundDs), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MgmtDistributionSet>> createDistributionSets(
|
||||
final List<MgmtDistributionSetRequestBodyPost> sets) {
|
||||
|
||||
LOG.debug("creating {} distribution sets", sets.size());
|
||||
// set default Ds type if ds type is null
|
||||
sets.stream().filter(ds -> ds.getType() == null).forEach(ds -> ds.setType(this.systemManagement
|
||||
.getTenantMetadata(this.currentTenant.getCurrentTenant()).getDefaultDsType().getKey()));
|
||||
|
||||
final Iterable<DistributionSet> createdDSets = this.distributionSetManagement.createDistributionSets(
|
||||
MgmtDistributionSetMapper.dsFromRequest(sets, this.softwareManagement, this.distributionSetManagement));
|
||||
|
||||
LOG.debug("{} distribution sets created, return status {}", sets.size(), HttpStatus.CREATED);
|
||||
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(createdDSets),
|
||||
HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> deleteDistributionSet(final Long distributionSetId) {
|
||||
final DistributionSet set = findDistributionSetWithExceptionIfNotFound(distributionSetId);
|
||||
|
||||
this.distributionSetManagement.deleteDistributionSet(set);
|
||||
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtDistributionSet> updateDistributionSet(final Long distributionSetId,
|
||||
final MgmtDistributionSetRequestBodyPut toUpdate) {
|
||||
final DistributionSet set = findDistributionSetWithExceptionIfNotFound(distributionSetId);
|
||||
|
||||
if (toUpdate.getDescription() != null) {
|
||||
set.setDescription(toUpdate.getDescription());
|
||||
}
|
||||
|
||||
if (toUpdate.getName() != null) {
|
||||
set.setName(toUpdate.getName());
|
||||
}
|
||||
|
||||
if (toUpdate.getVersion() != null) {
|
||||
set.setVersion(toUpdate.getVersion());
|
||||
}
|
||||
return new ResponseEntity<>(
|
||||
MgmtDistributionSetMapper.toResponse(this.distributionSetManagement.updateDistributionSet(set)),
|
||||
HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MgmtTarget>> getAssignedTargets(final Long distributionSetId,
|
||||
final int pagingOffsetParam, final int pagingLimitParam, final String sortParam, final String rsqlParam) {
|
||||
|
||||
// check if distribution set exists otherwise throw exception
|
||||
// immediately
|
||||
findDistributionSetWithExceptionIfNotFound(distributionSetId);
|
||||
|
||||
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);
|
||||
final Page<Target> targetsAssignedDS;
|
||||
if (rsqlParam != null) {
|
||||
targetsAssignedDS = this.targetManagement.findTargetByAssignedDistributionSet(distributionSetId,
|
||||
RSQLUtility.parse(rsqlParam, TargetFields.class), pageable);
|
||||
} else {
|
||||
targetsAssignedDS = this.targetManagement.findTargetByAssignedDistributionSet(distributionSetId, pageable);
|
||||
}
|
||||
|
||||
return new ResponseEntity<>(new PagedList<>(MgmtTargetMapper.toResponse(targetsAssignedDS.getContent()),
|
||||
targetsAssignedDS.getTotalElements()), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MgmtTarget>> getInstalledTargets(final Long distributionSetId,
|
||||
final int pagingOffsetParam, final int pagingLimitParam, final String sortParam, final String rsqlParam) {
|
||||
// check if distribution set exists otherwise throw exception
|
||||
// immediately
|
||||
findDistributionSetWithExceptionIfNotFound(distributionSetId);
|
||||
|
||||
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);
|
||||
final Page<Target> targetsInstalledDS;
|
||||
if (rsqlParam != null) {
|
||||
targetsInstalledDS = this.targetManagement.findTargetByInstalledDistributionSet(distributionSetId,
|
||||
RSQLUtility.parse(rsqlParam, TargetFields.class), pageable);
|
||||
} else {
|
||||
targetsInstalledDS = this.targetManagement.findTargetByInstalledDistributionSet(distributionSetId,
|
||||
pageable);
|
||||
}
|
||||
|
||||
return new ResponseEntity<>(
|
||||
new PagedList<MgmtTarget>(MgmtTargetMapper.toResponse(targetsInstalledDS.getContent()),
|
||||
targetsInstalledDS.getTotalElements()),
|
||||
HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtTargetAssignmentResponseBody> createAssignedTarget(final Long distributionSetId,
|
||||
final List<MgmtTargetAssignmentRequestBody> targetIds) {
|
||||
|
||||
final DistributionSetAssignmentResult assignDistributionSet = this.deployManagament.assignDistributionSet(
|
||||
distributionSetId,
|
||||
targetIds.stream()
|
||||
.map(t -> new TargetWithActionType(t.getId(),
|
||||
MgmtRestModelMapper.convertActionType(t.getType()), t.getForcetime()))
|
||||
.collect(Collectors.toList()));
|
||||
|
||||
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponse(assignDistributionSet), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MetadataRest>> getMetadata(final Long distributionSetId,
|
||||
final int pagingOffsetParam, final int pagingLimitParam, final String sortParam, final String rsqlParam) {
|
||||
|
||||
// check if distribution set exists otherwise throw exception
|
||||
// immediately
|
||||
findDistributionSetWithExceptionIfNotFound(distributionSetId);
|
||||
|
||||
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
|
||||
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
|
||||
final Sort sorting = PagingUtility.sanitizeDistributionSetMetadataSortParam(sortParam);
|
||||
|
||||
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
|
||||
final Page<DistributionSetMetadata> metaDataPage;
|
||||
|
||||
if (rsqlParam != null) {
|
||||
metaDataPage = this.distributionSetManagement.findDistributionSetMetadataByDistributionSetId(
|
||||
distributionSetId, RSQLUtility.parse(rsqlParam, DistributionSetMetadataFields.class), pageable);
|
||||
} else {
|
||||
metaDataPage = this.distributionSetManagement
|
||||
.findDistributionSetMetadataByDistributionSetId(distributionSetId, pageable);
|
||||
}
|
||||
|
||||
return new ResponseEntity<>(
|
||||
new PagedList<>(MgmtDistributionSetMapper.toResponseDsMetadata(metaDataPage.getContent()),
|
||||
metaDataPage.getTotalElements()),
|
||||
HttpStatus.OK);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MetadataRest> getMetadataValue(final Long distributionSetId, final String metadataKey) {
|
||||
// check if distribution set exists otherwise throw exception
|
||||
// immediately
|
||||
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId);
|
||||
final DistributionSetMetadata findOne = this.distributionSetManagement
|
||||
.findOne(new DsMetadataCompositeKey(ds, metadataKey));
|
||||
return ResponseEntity.<MetadataRest> ok(MgmtDistributionSetMapper.toResponseDsMetadata(findOne));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MetadataRest> updateMetadata(final Long distributionSetId, final String metadataKey,
|
||||
final MetadataRest metadata) {
|
||||
// check if distribution set exists otherwise throw exception
|
||||
// immediately
|
||||
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId);
|
||||
final DistributionSetMetadata updated = this.distributionSetManagement
|
||||
.updateDistributionSetMetadata(new DistributionSetMetadata(metadataKey, ds, metadata.getValue()));
|
||||
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDsMetadata(updated));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> deleteMetadata(final Long distributionSetId, final String metadataKey) {
|
||||
// check if distribution set exists otherwise throw exception
|
||||
// immediately
|
||||
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId);
|
||||
this.distributionSetManagement.deleteDistributionSetMetadata(new DsMetadataCompositeKey(ds, metadataKey));
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MetadataRest>> createMetadata(final Long distributionSetId,
|
||||
final List<MetadataRest> metadataRest) {
|
||||
// check if distribution set exists otherwise throw exception
|
||||
// immediately
|
||||
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId);
|
||||
|
||||
final List<DistributionSetMetadata> created = this.distributionSetManagement
|
||||
.createDistributionSetMetadata(MgmtDistributionSetMapper.fromRequestDsMetadata(ds, metadataRest));
|
||||
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDsMetadata(created), HttpStatus.CREATED);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> assignSoftwareModules(final Long distributionSetId,
|
||||
final List<MgmtSoftwareModuleAssigment> softwareModuleIDs) {
|
||||
// check if distribution set exists otherwise throw exception
|
||||
// immediately
|
||||
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId);
|
||||
|
||||
final Set<SoftwareModule> softwareModuleToBeAssigned = new HashSet<>();
|
||||
for (final MgmtSoftwareModuleAssigment sm : softwareModuleIDs) {
|
||||
final SoftwareModule softwareModule = this.softwareManagement.findSoftwareModuleById(sm.getId());
|
||||
if (softwareModule != null) {
|
||||
softwareModuleToBeAssigned.add(softwareModule);
|
||||
} else {
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
// Add Softwaremodules to DisSet only if all of them were found
|
||||
this.distributionSetManagement.assignSoftwareModules(ds, softwareModuleToBeAssigned);
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> deleteAssignSoftwareModules(final Long distributionSetId, final Long softwareModuleId) {
|
||||
// check if distribution set and software module exist otherwise throw
|
||||
// exception immediately
|
||||
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId);
|
||||
final SoftwareModule sm = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId);
|
||||
this.distributionSetManagement.unassignSoftwareModule(ds, sm);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MgmtSoftwareModule>> getAssignedSoftwareModules(final Long distributionSetId,
|
||||
final int pagingOffsetParam, final int pagingLimitParam, final String sortParam) {
|
||||
// check if distribution set exists otherwise throw exception
|
||||
// immediately
|
||||
final DistributionSet foundDs = findDistributionSetWithExceptionIfNotFound(distributionSetId);
|
||||
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
|
||||
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
|
||||
final Sort sorting = PagingUtility.sanitizeSoftwareModuleSortParam(sortParam);
|
||||
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
|
||||
final Page<SoftwareModule> softwaremodules = this.softwareManagement.findSoftwareModuleByAssignedTo(pageable,
|
||||
foundDs);
|
||||
return new ResponseEntity<>(new PagedList<>(MgmtSoftwareModuleMapper.toResponse(softwaremodules.getContent()),
|
||||
softwaremodules.getTotalElements()), HttpStatus.OK);
|
||||
}
|
||||
|
||||
private DistributionSet findDistributionSetWithExceptionIfNotFound(final Long distributionSetId) {
|
||||
final DistributionSet set = this.distributionSetManagement.findDistributionSetById(distributionSetId);
|
||||
if (set == null) {
|
||||
throw new EntityNotFoundException("DistributionSet with Id {" + distributionSetId + "} does not exist");
|
||||
}
|
||||
|
||||
return set;
|
||||
}
|
||||
|
||||
private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId) {
|
||||
final SoftwareModule sm = this.softwareManagement.findSoftwareModuleById(softwareModuleId);
|
||||
if (sm == null) {
|
||||
throw new EntityNotFoundException("SoftwareModule with Id {" + softwareModuleId + "} does not exist");
|
||||
}
|
||||
return sm;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
/**
|
||||
* 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 java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.PagedList;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtAssignedDistributionSetRequestBody;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtDistributionSetTagAssigmentResult;
|
||||
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.repository.DistributionSetManagement;
|
||||
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
|
||||
import org.eclipse.hawkbit.repository.TagFields;
|
||||
import org.eclipse.hawkbit.repository.TagManagement;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult;
|
||||
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
|
||||
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.Pageable;
|
||||
import org.springframework.data.domain.Slice;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* REST Resource handling for {@link DistributionSetTag} CRUD operations.
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRestApi {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(MgmtDistributionSetTagResource.class);
|
||||
|
||||
@Autowired
|
||||
private TagManagement tagManagement;
|
||||
|
||||
@Autowired
|
||||
private DistributionSetManagement distributionSetManagement;
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MgmtTag>> getDistributionSetTags(final int pagingOffsetParam,
|
||||
final int pagingLimitParam, final String sortParam, 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);
|
||||
final Slice<DistributionSetTag> findTargetsAll;
|
||||
final Long countTargetsAll;
|
||||
if (rsqlParam == null) {
|
||||
findTargetsAll = this.tagManagement.findAllDistributionSetTags(pageable);
|
||||
countTargetsAll = this.tagManagement.countTargetTags();
|
||||
|
||||
} else {
|
||||
final Page<DistributionSetTag> findTargetPage = this.tagManagement
|
||||
.findAllDistributionSetTags(RSQLUtility.parse(rsqlParam, TagFields.class), pageable);
|
||||
countTargetsAll = findTargetPage.getTotalElements();
|
||||
findTargetsAll = findTargetPage;
|
||||
|
||||
}
|
||||
|
||||
final List<MgmtTag> rest = MgmtTagMapper.toResponseDistributionSetTag(findTargetsAll.getContent());
|
||||
return new ResponseEntity<>(new PagedList<>(rest, countTargetsAll), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtTag> getDistributionSetTag(final Long distributionsetTagId) {
|
||||
final DistributionSetTag tag = findDistributionTagById(distributionsetTagId);
|
||||
return new ResponseEntity<>(MgmtTagMapper.toResponse(tag), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MgmtTag>> createDistributionSetTags(final List<MgmtTagRequestBodyPut> tags) {
|
||||
LOG.debug("creating {} ds tags", tags.size());
|
||||
|
||||
final List<DistributionSetTag> createdTags = this.tagManagement
|
||||
.createDistributionSetTags(MgmtTagMapper.mapDistributionSetTagFromRequest(tags));
|
||||
|
||||
return new ResponseEntity<>(MgmtTagMapper.toResponseDistributionSetTag(createdTags), HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtTag> updateDistributionSetTag(final Long distributionsetTagId,
|
||||
final MgmtTagRequestBodyPut restDSTagRest) {
|
||||
LOG.debug("update {} ds tag", restDSTagRest);
|
||||
|
||||
final DistributionSetTag distributionSetTag = findDistributionTagById(distributionsetTagId);
|
||||
MgmtTagMapper.updateTag(restDSTagRest, distributionSetTag);
|
||||
final DistributionSetTag updateDistributionSetTag = this.tagManagement
|
||||
.updateDistributionSetTag(distributionSetTag);
|
||||
|
||||
LOG.debug("ds tag updated");
|
||||
|
||||
return new ResponseEntity<>(MgmtTagMapper.toResponse(updateDistributionSetTag), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> deleteDistributionSetTag(final Long distributionsetTagId) {
|
||||
LOG.debug("Delete {} distribution set tag", distributionsetTagId);
|
||||
final DistributionSetTag tag = findDistributionTagById(distributionsetTagId);
|
||||
|
||||
this.tagManagement.deleteDistributionSetTag(tag.getName());
|
||||
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MgmtDistributionSet>> getAssignedDistributionSets(final Long distributionsetTagId) {
|
||||
final DistributionSetTag tag = findDistributionTagById(distributionsetTagId);
|
||||
return new ResponseEntity<>(
|
||||
MgmtDistributionSetMapper.toResponseDistributionSets(tag.getAssignedToDistributionSet()), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtDistributionSetTagAssigmentResult> toggleTagAssignment(final Long distributionsetTagId,
|
||||
final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies) {
|
||||
LOG.debug("Toggle distribution set assignment {} for ds tag {}", assignedDSRequestBodies.size(),
|
||||
distributionsetTagId);
|
||||
|
||||
final DistributionSetTag tag = findDistributionTagById(distributionsetTagId);
|
||||
|
||||
final DistributionSetTagAssignmentResult assigmentResult = this.distributionSetManagement
|
||||
.toggleTagAssignment(findDistributionSetIds(assignedDSRequestBodies), tag.getName());
|
||||
|
||||
final MgmtDistributionSetTagAssigmentResult tagAssigmentResultRest = new MgmtDistributionSetTagAssigmentResult();
|
||||
tagAssigmentResultRest.setAssignedDistributionSets(
|
||||
MgmtDistributionSetMapper.toResponseDistributionSets(assigmentResult.getAssignedEntity()));
|
||||
tagAssigmentResultRest.setUnassignedDistributionSets(
|
||||
MgmtDistributionSetMapper.toResponseDistributionSets(assigmentResult.getUnassignedEntity()));
|
||||
|
||||
LOG.debug("Toggled assignedDS {} and unassignedDS{}", assigmentResult.getAssigned(),
|
||||
assigmentResult.getUnassigned());
|
||||
|
||||
return new ResponseEntity<>(tagAssigmentResultRest, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MgmtDistributionSet>> assignDistributionSets(final Long distributionsetTagId,
|
||||
final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies) {
|
||||
LOG.debug("Assign DistributionSet {} for ds tag {}", assignedDSRequestBodies.size(), distributionsetTagId);
|
||||
final DistributionSetTag tag = findDistributionTagById(distributionsetTagId);
|
||||
|
||||
final List<DistributionSet> assignedDs = this.distributionSetManagement
|
||||
.assignTag(findDistributionSetIds(assignedDSRequestBodies), tag);
|
||||
LOG.debug("Assignd DistributionSet {}", assignedDs.size());
|
||||
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(assignedDs), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> unassignDistributionSets(final Long distributionsetTagId) {
|
||||
LOG.debug("Unassign all DS for ds tag {}", distributionsetTagId);
|
||||
final DistributionSetTag tag = findDistributionTagById(distributionsetTagId);
|
||||
if (tag.getAssignedToDistributionSet() == null) {
|
||||
LOG.debug("No assigned ds founded");
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
final List<DistributionSet> distributionSets = this.distributionSetManagement
|
||||
.unAssignAllDistributionSetsByTag(tag);
|
||||
LOG.debug("Unassigned ds {}", distributionSets.size());
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> unassignDistributionSet(final Long distributionsetTagId, final Long distributionsetId) {
|
||||
LOG.debug("Unassign ds {} for ds tag {}", distributionsetId, distributionsetTagId);
|
||||
final DistributionSetTag tag = findDistributionTagById(distributionsetTagId);
|
||||
this.distributionSetManagement.unAssignTag(distributionsetId, tag);
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
private DistributionSetTag findDistributionTagById(final Long distributionsetTagId) {
|
||||
final DistributionSetTag tag = this.tagManagement.findDistributionSetTagById(distributionsetTagId);
|
||||
if (tag == null) {
|
||||
throw new EntityNotFoundException("Distribution Tag with Id {" + distributionsetTagId + "} does not exist");
|
||||
}
|
||||
return tag;
|
||||
}
|
||||
|
||||
private List<Long> findDistributionSetIds(
|
||||
final List<MgmtAssignedDistributionSetRequestBody> assignedDistributionSetRequestBodies) {
|
||||
return assignedDistributionSetRequestBodies.stream().map(request -> request.getDistributionSetId())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* 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.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
|
||||
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRest;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTypeRestApi;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
|
||||
import org.eclipse.hawkbit.repository.SoftwareManagement;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetType;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
|
||||
|
||||
/**
|
||||
* A mapper which maps repository model to RESTful model representation and
|
||||
* back.
|
||||
*
|
||||
*/
|
||||
final class MgmtDistributionSetTypeMapper {
|
||||
|
||||
// private constructor, utility class
|
||||
private MgmtDistributionSetTypeMapper() {
|
||||
|
||||
}
|
||||
|
||||
static List<DistributionSetType> smFromRequest(final SoftwareManagement softwareManagement,
|
||||
final Iterable<MgmtDistributionSetTypeRequestBodyPost> smTypesRest) {
|
||||
final List<DistributionSetType> mappedList = new ArrayList<>();
|
||||
|
||||
for (final MgmtDistributionSetTypeRequestBodyPost smRest : smTypesRest) {
|
||||
mappedList.add(fromRequest(softwareManagement, smRest));
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
|
||||
static DistributionSetType fromRequest(final SoftwareManagement softwareManagement,
|
||||
final MgmtDistributionSetTypeRequestBodyPost smsRest) {
|
||||
|
||||
final DistributionSetType result = new DistributionSetType(smsRest.getKey(), smsRest.getName(),
|
||||
smsRest.getDescription());
|
||||
|
||||
// Add mandatory
|
||||
smsRest.getMandatorymodules().stream().map(mand -> {
|
||||
final SoftwareModuleType smType = softwareManagement.findSoftwareModuleTypeById(mand.getId());
|
||||
|
||||
if (smType == null) {
|
||||
throw new EntityNotFoundException("SoftwareModuleType with ID " + mand.getId() + " not found");
|
||||
}
|
||||
|
||||
return smType;
|
||||
}).forEach(result::addMandatoryModuleType);
|
||||
|
||||
// Add optional
|
||||
smsRest.getOptionalmodules().stream().map(opt -> {
|
||||
final SoftwareModuleType smType = softwareManagement.findSoftwareModuleTypeById(opt.getId());
|
||||
|
||||
if (smType == null) {
|
||||
throw new EntityNotFoundException("SoftwareModuleType with ID " + opt.getId() + " not found");
|
||||
}
|
||||
|
||||
return smType;
|
||||
}).forEach(result::addOptionalModuleType);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static List<MgmtDistributionSetTypeRest> toTypesResponse(final List<DistributionSetType> types) {
|
||||
final List<MgmtDistributionSetTypeRest> response = new ArrayList<>();
|
||||
for (final DistributionSetType dsType : types) {
|
||||
response.add(toResponse(dsType));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
static List<MgmtDistributionSetTypeRest> toListResponse(final List<DistributionSetType> types) {
|
||||
final List<MgmtDistributionSetTypeRest> response = new ArrayList<>();
|
||||
for (final DistributionSetType dsType : types) {
|
||||
response.add(toResponse(dsType));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
static MgmtDistributionSetTypeRest toResponse(final DistributionSetType type) {
|
||||
final MgmtDistributionSetTypeRest result = new MgmtDistributionSetTypeRest();
|
||||
|
||||
MgmtRestModelMapper.mapNamedToNamed(result, type);
|
||||
result.setKey(type.getKey());
|
||||
result.setModuleId(type.getId());
|
||||
|
||||
result.add(linkTo(methodOn(MgmtDistributionSetTypeRestApi.class).getDistributionSetType(result.getModuleId()))
|
||||
.withRel("self"));
|
||||
|
||||
result.add(linkTo(methodOn(MgmtDistributionSetTypeRestApi.class).getMandatoryModules(result.getModuleId()))
|
||||
.withRel(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_MANDATORY_MODULES));
|
||||
|
||||
result.add(linkTo(methodOn(MgmtDistributionSetTypeRestApi.class).getOptionalModules(result.getModuleId()))
|
||||
.withRel(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_OPTIONAL_MODULES));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
/**
|
||||
* 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 java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.MgmtId;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.PagedList;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPut;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRest;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleType;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTypeRestApi;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetManagement;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetTypeFields;
|
||||
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
|
||||
import org.eclipse.hawkbit.repository.SoftwareManagement;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
|
||||
import org.eclipse.hawkbit.repository.model.Artifact;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetType;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
|
||||
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
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;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* REST Resource handling for {@link SoftwareModule} and related
|
||||
* {@link Artifact} CRUD operations.
|
||||
*
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeRestApi {
|
||||
|
||||
@Autowired
|
||||
private SoftwareManagement softwareManagement;
|
||||
|
||||
@Autowired
|
||||
private DistributionSetManagement distributionSetManagement;
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MgmtDistributionSetTypeRest>> getDistributionSetTypes(
|
||||
@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.sanitizeDistributionSetTypeSortParam(sortParam);
|
||||
|
||||
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
|
||||
|
||||
final Slice<DistributionSetType> findModuleTypessAll;
|
||||
Long countModulesAll;
|
||||
if (rsqlParam != null) {
|
||||
findModuleTypessAll = distributionSetManagement.findDistributionSetTypesByPredicate(
|
||||
RSQLUtility.parse(rsqlParam, DistributionSetTypeFields.class), pageable);
|
||||
countModulesAll = ((Page<DistributionSetType>) findModuleTypessAll).getTotalElements();
|
||||
} else {
|
||||
findModuleTypessAll = distributionSetManagement.findDistributionSetTypesAll(pageable);
|
||||
countModulesAll = distributionSetManagement.countDistributionSetTypesAll();
|
||||
}
|
||||
|
||||
final List<MgmtDistributionSetTypeRest> rest = MgmtDistributionSetTypeMapper
|
||||
.toListResponse(findModuleTypessAll.getContent());
|
||||
return new ResponseEntity<>(new PagedList<>(rest, countModulesAll), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtDistributionSetTypeRest> getDistributionSetType(
|
||||
@PathVariable final Long distributionSetTypeId) {
|
||||
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
|
||||
|
||||
return new ResponseEntity<>(MgmtDistributionSetTypeMapper.toResponse(foundType), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> deleteDistributionSetType(@PathVariable final Long distributionSetTypeId) {
|
||||
final DistributionSetType module = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
|
||||
|
||||
distributionSetManagement.deleteDistributionSetType(module);
|
||||
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtDistributionSetTypeRest> updateDistributionSetType(
|
||||
@PathVariable final Long distributionSetTypeId,
|
||||
@RequestBody final MgmtDistributionSetTypeRequestBodyPut restDistributionSetType) {
|
||||
final DistributionSetType type = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
|
||||
|
||||
// only description can be modified
|
||||
if (restDistributionSetType.getDescription() != null) {
|
||||
type.setDescription(restDistributionSetType.getDescription());
|
||||
}
|
||||
|
||||
final DistributionSetType updatedDistributionSetType = distributionSetManagement
|
||||
.updateDistributionSetType(type);
|
||||
|
||||
return new ResponseEntity<>(MgmtDistributionSetTypeMapper.toResponse(updatedDistributionSetType), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MgmtDistributionSetTypeRest>> createDistributionSetTypes(
|
||||
@RequestBody final List<MgmtDistributionSetTypeRequestBodyPost> distributionSetTypes) {
|
||||
|
||||
final List<DistributionSetType> createdSoftwareModules = distributionSetManagement.createDistributionSetTypes(
|
||||
MgmtDistributionSetTypeMapper.smFromRequest(softwareManagement, distributionSetTypes));
|
||||
|
||||
return new ResponseEntity<>(MgmtDistributionSetTypeMapper.toTypesResponse(createdSoftwareModules),
|
||||
HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final Long distributionSetTypeId) {
|
||||
final DistributionSetType module = distributionSetManagement.findDistributionSetTypeById(distributionSetTypeId);
|
||||
if (module == null) {
|
||||
throw new EntityNotFoundException(
|
||||
"DistributionSetType with Id {" + distributionSetTypeId + "} does not exist");
|
||||
}
|
||||
return module;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MgmtSoftwareModuleType>> getMandatoryModules(
|
||||
@PathVariable final Long distributionSetTypeId) {
|
||||
|
||||
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
|
||||
return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toListResponse(foundType.getMandatoryModuleTypes()),
|
||||
HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtSoftwareModuleType> getMandatoryModule(@PathVariable final Long distributionSetTypeId,
|
||||
@PathVariable final Long softwareModuleTypeId) {
|
||||
|
||||
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
|
||||
|
||||
final SoftwareModuleType foundSmType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
|
||||
|
||||
if (!foundType.containsMandatoryModuleType(foundSmType)) {
|
||||
throw new EntityNotFoundException(
|
||||
"Software module with given ID is not part of this distribution set type!");
|
||||
}
|
||||
|
||||
return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toResponse(foundSmType), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtSoftwareModuleType> getOptionalModule(@PathVariable final Long distributionSetTypeId,
|
||||
@PathVariable final Long softwareModuleTypeId) {
|
||||
|
||||
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
|
||||
|
||||
final SoftwareModuleType foundSmType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
|
||||
|
||||
if (!foundType.containsOptionalModuleType(foundSmType)) {
|
||||
throw new EntityNotFoundException(
|
||||
"Software module with given ID is not part of this distribution set type!");
|
||||
}
|
||||
|
||||
return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toResponse(foundSmType), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MgmtSoftwareModuleType>> getOptionalModules(
|
||||
@PathVariable final Long distributionSetTypeId) {
|
||||
|
||||
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
|
||||
|
||||
return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toListResponse(foundType.getOptionalModuleTypes()),
|
||||
HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> removeMandatoryModule(@PathVariable final Long distributionSetTypeId,
|
||||
@PathVariable final Long softwareModuleTypeId) {
|
||||
|
||||
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
|
||||
|
||||
final SoftwareModuleType foundSmType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
|
||||
|
||||
if (!foundType.containsMandatoryModuleType(foundSmType)) {
|
||||
throw new EntityNotFoundException(
|
||||
"Software module with given ID is not mandatory part of this distribution set type!");
|
||||
}
|
||||
|
||||
foundType.removeModuleType(softwareModuleTypeId);
|
||||
|
||||
distributionSetManagement.updateDistributionSetType(foundType);
|
||||
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> removeOptionalModule(@PathVariable final Long distributionSetTypeId,
|
||||
@PathVariable final Long softwareModuleTypeId) {
|
||||
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
|
||||
|
||||
final SoftwareModuleType foundSmType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
|
||||
|
||||
if (!foundType.containsOptionalModuleType(foundSmType)) {
|
||||
throw new EntityNotFoundException(
|
||||
"Software module with given ID is not optional part of this distribution set type!");
|
||||
}
|
||||
|
||||
foundType.removeModuleType(softwareModuleTypeId);
|
||||
|
||||
distributionSetManagement.updateDistributionSetType(foundType);
|
||||
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> addMandatoryModule(@PathVariable final Long distributionSetTypeId,
|
||||
@RequestBody final MgmtId smtId) {
|
||||
|
||||
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
|
||||
|
||||
final SoftwareModuleType smType = findSoftwareModuleTypeWithExceptionIfNotFound(smtId.getId());
|
||||
|
||||
foundType.addMandatoryModuleType(smType);
|
||||
|
||||
distributionSetManagement.updateDistributionSetType(foundType);
|
||||
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> addOptionalModule(@PathVariable final Long distributionSetTypeId,
|
||||
@RequestBody final MgmtId smtId) {
|
||||
|
||||
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
|
||||
|
||||
final SoftwareModuleType smType = findSoftwareModuleTypeWithExceptionIfNotFound(smtId.getId());
|
||||
|
||||
foundType.addOptionalModuleType(smType);
|
||||
|
||||
distributionSetManagement.updateDistributionSetType(foundType);
|
||||
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
|
||||
}
|
||||
|
||||
private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) {
|
||||
final SoftwareModuleType module = softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId);
|
||||
if (module == null) {
|
||||
throw new EntityNotFoundException(
|
||||
"SoftwareModuleType with Id {" + softwareModuleTypeId + "} does not exist");
|
||||
}
|
||||
return module;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* 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 javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDownloadArtifactRestApi;
|
||||
import org.eclipse.hawkbit.repository.ArtifactManagement;
|
||||
import org.eclipse.hawkbit.repository.SoftwareManagement;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
|
||||
import org.eclipse.hawkbit.repository.model.LocalArtifact;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.rest.util.RestResourceConversionHelper;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
public class MgmtDownloadArtifactResource implements MgmtDownloadArtifactRestApi {
|
||||
|
||||
@Autowired
|
||||
private SoftwareManagement softwareManagement;
|
||||
|
||||
@Autowired
|
||||
private ArtifactManagement artifactManagement;
|
||||
|
||||
/**
|
||||
* Handles the GET request for downloading an artifact.
|
||||
*
|
||||
* @param softwareModuleId
|
||||
* of the parent SoftwareModule
|
||||
* @param artifactId
|
||||
* of the related LocalArtifact
|
||||
* @param servletResponse
|
||||
* of the servlet
|
||||
* @param request
|
||||
* of the client
|
||||
*
|
||||
* @return responseEntity with status ok if successful
|
||||
*/
|
||||
@Override
|
||||
@ResponseBody
|
||||
public ResponseEntity<Void> downloadArtifact(final Long softwareModuleId, final Long artifactId,
|
||||
final HttpServletResponse servletResponse, final HttpServletRequest request) {
|
||||
final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, artifactId);
|
||||
|
||||
if (null == module || !module.getLocalArtifact(artifactId).isPresent()) {
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
final LocalArtifact artifact = module.getLocalArtifact(artifactId).get();
|
||||
final DbArtifact file = artifactManagement.loadLocalArtifactBinary(artifact);
|
||||
|
||||
final String ifMatch = request.getHeader("If-Match");
|
||||
if (ifMatch != null && !RestResourceConversionHelper.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) {
|
||||
return new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED);
|
||||
}
|
||||
|
||||
return RestResourceConversionHelper.writeFileResponse(artifact, servletResponse, request, file);
|
||||
|
||||
}
|
||||
|
||||
private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId,
|
||||
final Long artifactId) {
|
||||
final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId);
|
||||
if (module == null) {
|
||||
throw new EntityNotFoundException("SoftwareModule with Id {" + softwareModuleId + "} does not exist");
|
||||
} else if (artifactId != null && !module.getLocalArtifact(artifactId).isPresent()) {
|
||||
throw new EntityNotFoundException("Artifact with Id {" + artifactId + "} does not exist");
|
||||
}
|
||||
return module;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* 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 java.io.IOException;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.eclipse.hawkbit.artifact.repository.ArtifactRepository;
|
||||
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
|
||||
import org.eclipse.hawkbit.cache.CacheConstants;
|
||||
import org.eclipse.hawkbit.cache.DownloadArtifactCache;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDownloadRestApi;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.Cache.ValueWrapper;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* A resource for download artifacts.
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
public class MgmtDownloadResource implements MgmtDownloadRestApi {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(MgmtDownloadResource.class);
|
||||
|
||||
@Autowired
|
||||
private ArtifactRepository artifactRepository;
|
||||
|
||||
@Autowired
|
||||
@Qualifier(CacheConstants.DOWNLOAD_ID_CACHE)
|
||||
private Cache cache;
|
||||
|
||||
/**
|
||||
* Handles the GET request for downloading an artifact.
|
||||
*
|
||||
* @param downloadId
|
||||
* the generated download id
|
||||
* @param response
|
||||
* of the servlet
|
||||
* @return {@link ResponseEntity} with status {@link HttpStatus#OK} if
|
||||
* successful
|
||||
*/
|
||||
@Override
|
||||
public ResponseEntity<Void> downloadArtifactByDownloadId(final String downloadId,
|
||||
final HttpServletResponse response) {
|
||||
try {
|
||||
final ValueWrapper cacheWrapper = cache.get(downloadId);
|
||||
if (cacheWrapper == null) {
|
||||
LOGGER.warn("Download Id {} could not be found", downloadId);
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
final DownloadArtifactCache artifactCache = (DownloadArtifactCache) cacheWrapper.get();
|
||||
DbArtifact artifact = null;
|
||||
switch (artifactCache.getDownloadType()) {
|
||||
case BY_SHA1:
|
||||
artifact = artifactRepository.getArtifactBySha1(artifactCache.getId());
|
||||
break;
|
||||
|
||||
default:
|
||||
LOGGER.warn("Download Type {} not supported", artifactCache.getDownloadType());
|
||||
break;
|
||||
}
|
||||
|
||||
if (artifact == null) {
|
||||
LOGGER.warn("Artifact with cached id {} and download type {} could not be found.",
|
||||
artifactCache.getId(), artifactCache.getDownloadType());
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
try {
|
||||
IOUtils.copy(artifact.getFileInputStream(), response.getOutputStream());
|
||||
} catch (final IOException e) {
|
||||
LOGGER.error("Cannot copy streams", e);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
} finally {
|
||||
cache.evict(downloadId);
|
||||
}
|
||||
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* 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 org.eclipse.hawkbit.mgmt.json.model.MgmtBaseEntity;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.MgmtNamedEntity;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionType;
|
||||
import org.eclipse.hawkbit.repository.model.Action.ActionType;
|
||||
import org.eclipse.hawkbit.repository.model.NamedEntity;
|
||||
import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity;
|
||||
|
||||
/**
|
||||
* A mapper which maps repository model to RESTful model representation and
|
||||
* back.
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
final class MgmtRestModelMapper {
|
||||
|
||||
// private constructor, utility class
|
||||
private MgmtRestModelMapper() {
|
||||
|
||||
}
|
||||
|
||||
static void mapBaseToBase(final MgmtBaseEntity response, final TenantAwareBaseEntity base) {
|
||||
response.setCreatedBy(base.getCreatedBy());
|
||||
response.setLastModifiedBy(base.getLastModifiedBy());
|
||||
if (base.getCreatedAt() != null) {
|
||||
response.setCreatedAt(base.getCreatedAt());
|
||||
}
|
||||
if (base.getLastModifiedAt() != null) {
|
||||
response.setLastModifiedAt(base.getLastModifiedAt());
|
||||
}
|
||||
}
|
||||
|
||||
static void mapNamedToNamed(final MgmtNamedEntity response, final NamedEntity base) {
|
||||
mapBaseToBase(response, base);
|
||||
|
||||
response.setName(base.getName());
|
||||
response.setDescription(base.getDescription());
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a action rest type to a action repository type.
|
||||
*
|
||||
* @param actionTypeRest
|
||||
* the rest type
|
||||
* @return <null> or the action repository type
|
||||
*/
|
||||
/**
|
||||
* Convert a action rest type to a action repository type.
|
||||
*
|
||||
* @param actionTypeRest
|
||||
* the rest type
|
||||
* @return <null> or the action repository type
|
||||
*/
|
||||
public static ActionType convertActionType(final MgmtActionType actionTypeRest) {
|
||||
if (actionTypeRest == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (actionTypeRest) {
|
||||
case SOFT:
|
||||
return ActionType.SOFT;
|
||||
case FORCED:
|
||||
return ActionType.FORCED;
|
||||
case TIMEFORCED:
|
||||
return ActionType.TIMEFORCED;
|
||||
default:
|
||||
throw new IllegalStateException("Action Type is not supported");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* 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.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
|
||||
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutCondition.Condition;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutErrorAction.ErrorAction;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutResponseBody;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutRestRequestBody;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutSuccessAction.SuccessAction;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.rolloutgroup.MgmtRolloutGroupResponseBody;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRolloutRestApi;
|
||||
import org.eclipse.hawkbit.repository.model.Action.ActionType;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.Rollout;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorAction;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorCondition;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessAction;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessCondition;
|
||||
import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus;
|
||||
|
||||
/**
|
||||
* A mapper which maps repository model to RESTful model representation and
|
||||
* back.
|
||||
*
|
||||
*
|
||||
*/
|
||||
final class MgmtRolloutMapper {
|
||||
|
||||
private static final String NOT_SUPPORTED = " is not supported";
|
||||
|
||||
private MgmtRolloutMapper() {
|
||||
// Utility class
|
||||
}
|
||||
|
||||
static List<MgmtRolloutResponseBody> toResponseRollout(final List<Rollout> rollouts) {
|
||||
final List<MgmtRolloutResponseBody> result = new ArrayList<>(rollouts.size());
|
||||
rollouts.forEach(r -> result.add(toResponseRollout(r)));
|
||||
return result;
|
||||
}
|
||||
|
||||
static MgmtRolloutResponseBody toResponseRollout(final Rollout rollout) {
|
||||
final MgmtRolloutResponseBody body = new MgmtRolloutResponseBody();
|
||||
body.setCreatedAt(rollout.getCreatedAt());
|
||||
body.setCreatedBy(rollout.getCreatedBy());
|
||||
body.setDescription(rollout.getDescription());
|
||||
body.setLastModifiedAt(rollout.getLastModifiedAt());
|
||||
body.setLastModifiedBy(rollout.getLastModifiedBy());
|
||||
body.setName(rollout.getName());
|
||||
body.setRolloutId(rollout.getId());
|
||||
body.setTargetFilterQuery(rollout.getTargetFilterQuery());
|
||||
body.setDistributionSetId(rollout.getDistributionSet().getId());
|
||||
body.setStatus(rollout.getStatus().toString().toLowerCase());
|
||||
body.setTotalTargets(rollout.getTotalTargets());
|
||||
|
||||
for (final TotalTargetCountStatus.Status status : TotalTargetCountStatus.Status.values()) {
|
||||
body.getTotalTargetsPerStatus().put(status.name().toLowerCase(),
|
||||
rollout.getTotalTargetCountStatus().getTotalTargetCountByStatus(status));
|
||||
}
|
||||
|
||||
body.add(linkTo(methodOn(MgmtRolloutRestApi.class).getRollout(rollout.getId())).withRel("self"));
|
||||
body.add(linkTo(methodOn(MgmtRolloutRestApi.class).start(rollout.getId(), false)).withRel("start"));
|
||||
body.add(linkTo(methodOn(MgmtRolloutRestApi.class).start(rollout.getId(), true)).withRel("startAsync"));
|
||||
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))
|
||||
.withRel("groups"));
|
||||
return body;
|
||||
}
|
||||
|
||||
static Rollout fromRequest(final MgmtRolloutRestRequestBody restRequest, final DistributionSet distributionSet,
|
||||
final String filterQuery) {
|
||||
final Rollout rollout = new Rollout();
|
||||
rollout.setName(restRequest.getName());
|
||||
rollout.setDescription(restRequest.getDescription());
|
||||
rollout.setDistributionSet(distributionSet);
|
||||
rollout.setTargetFilterQuery(filterQuery);
|
||||
final ActionType convertActionType = MgmtRestModelMapper.convertActionType(restRequest.getType());
|
||||
if (convertActionType != null) {
|
||||
rollout.setActionType(convertActionType);
|
||||
}
|
||||
if (restRequest.getForcetime() != null) {
|
||||
rollout.setForcedTime(restRequest.getForcetime());
|
||||
|
||||
}
|
||||
return rollout;
|
||||
}
|
||||
|
||||
static List<MgmtRolloutGroupResponseBody> toResponseRolloutGroup(final List<RolloutGroup> rollouts) {
|
||||
final List<MgmtRolloutGroupResponseBody> result = new ArrayList<>(rollouts.size());
|
||||
rollouts.forEach(r -> result.add(toResponseRolloutGroup(r)));
|
||||
return result;
|
||||
}
|
||||
|
||||
static MgmtRolloutGroupResponseBody toResponseRolloutGroup(final RolloutGroup rolloutGroup) {
|
||||
final MgmtRolloutGroupResponseBody body = new MgmtRolloutGroupResponseBody();
|
||||
body.setCreatedAt(rolloutGroup.getCreatedAt());
|
||||
body.setCreatedBy(rolloutGroup.getCreatedBy());
|
||||
body.setDescription(rolloutGroup.getDescription());
|
||||
body.setLastModifiedAt(rolloutGroup.getLastModifiedAt());
|
||||
body.setLastModifiedBy(rolloutGroup.getLastModifiedBy());
|
||||
body.setName(rolloutGroup.getName());
|
||||
body.setRolloutGroupId(rolloutGroup.getId());
|
||||
body.setStatus(rolloutGroup.getStatus().toString().toLowerCase());
|
||||
body.add(linkTo(methodOn(MgmtRolloutRestApi.class).getRolloutGroup(rolloutGroup.getRollout().getId(),
|
||||
rolloutGroup.getId())).withRel("self"));
|
||||
return body;
|
||||
}
|
||||
|
||||
static RolloutGroupErrorCondition mapErrorCondition(final Condition condition) {
|
||||
if (Condition.THRESHOLD.equals(condition)) {
|
||||
return RolloutGroupErrorCondition.THRESHOLD;
|
||||
}
|
||||
throw new IllegalArgumentException(createIllegalArgumentLiteral(condition));
|
||||
}
|
||||
|
||||
static RolloutGroupSuccessCondition mapFinishCondition(final Condition condition) {
|
||||
if (Condition.THRESHOLD.equals(condition)) {
|
||||
return RolloutGroupSuccessCondition.THRESHOLD;
|
||||
}
|
||||
throw new IllegalArgumentException(createIllegalArgumentLiteral(condition));
|
||||
}
|
||||
|
||||
static Condition map(final RolloutGroupSuccessCondition rolloutCondition) {
|
||||
if (RolloutGroupSuccessCondition.THRESHOLD.equals(rolloutCondition)) {
|
||||
return Condition.THRESHOLD;
|
||||
}
|
||||
throw new IllegalArgumentException("Rollout group condition " + rolloutCondition + NOT_SUPPORTED);
|
||||
}
|
||||
|
||||
static RolloutGroupErrorAction map(final ErrorAction action) {
|
||||
if (ErrorAction.PAUSE.equals(action)) {
|
||||
return RolloutGroupErrorAction.PAUSE;
|
||||
}
|
||||
throw new IllegalArgumentException("Error Action " + action + NOT_SUPPORTED);
|
||||
}
|
||||
|
||||
static RolloutGroupSuccessAction map(final SuccessAction action) {
|
||||
if (SuccessAction.NEXTGROUP.equals(action)) {
|
||||
return RolloutGroupSuccessAction.NEXTGROUP;
|
||||
}
|
||||
throw new IllegalArgumentException("Success Action " + action + NOT_SUPPORTED);
|
||||
}
|
||||
|
||||
private static String createIllegalArgumentLiteral(final Condition condition) {
|
||||
return "Condition " + condition + NOT_SUPPORTED;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
/**
|
||||
* 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 java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.PagedList;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutResponseBody;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutRestRequestBody;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.rolloutgroup.MgmtRolloutGroupResponseBody;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRolloutRestApi;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetManagement;
|
||||
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
|
||||
import org.eclipse.hawkbit.repository.RolloutFields;
|
||||
import org.eclipse.hawkbit.repository.RolloutGroupFields;
|
||||
import org.eclipse.hawkbit.repository.RolloutGroupManagement;
|
||||
import org.eclipse.hawkbit.repository.RolloutManagement;
|
||||
import org.eclipse.hawkbit.repository.TargetFields;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.Rollout;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupConditions;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorAction;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorCondition;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessAction;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessCondition;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* REST Resource handling rollout CRUD operations.
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
public class MgmtRolloutResource implements MgmtRolloutRestApi {
|
||||
|
||||
private static final String DOES_NOT_EXIST = "} does not exist";
|
||||
|
||||
@Autowired
|
||||
private RolloutManagement rolloutManagement;
|
||||
|
||||
@Autowired
|
||||
private RolloutGroupManagement rolloutGroupManagement;
|
||||
|
||||
@Autowired
|
||||
private DistributionSetManagement distributionSetManagement;
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MgmtRolloutResponseBody>> getRollouts(final int pagingOffsetParam,
|
||||
final int pagingLimitParam, final String sortParam, final String rsqlParam) {
|
||||
|
||||
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
|
||||
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
|
||||
final Sort sorting = PagingUtility.sanitizeRolloutSortParam(sortParam);
|
||||
|
||||
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
|
||||
|
||||
final Page<Rollout> findModulesAll;
|
||||
if (rsqlParam != null) {
|
||||
findModulesAll = this.rolloutManagement
|
||||
.findAllWithDetailedStatusByPredicate(RSQLUtility.parse(rsqlParam, RolloutFields.class), pageable);
|
||||
} else {
|
||||
findModulesAll = this.rolloutManagement.findAll(pageable);
|
||||
}
|
||||
|
||||
final List<MgmtRolloutResponseBody> rest = MgmtRolloutMapper.toResponseRollout(findModulesAll.getContent());
|
||||
return new ResponseEntity<>(new PagedList<>(rest, findModulesAll.getTotalElements()), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtRolloutResponseBody> getRollout(final Long rolloutId) {
|
||||
final Rollout findRolloutById = findRolloutOrThrowException(rolloutId);
|
||||
return new ResponseEntity<>(MgmtRolloutMapper.toResponseRollout(findRolloutById), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtRolloutResponseBody> create(@RequestBody final MgmtRolloutRestRequestBody rolloutRequestBody) {
|
||||
|
||||
// first check the given RSQL query if it's well formed, otherwise and
|
||||
// exception is thrown
|
||||
RSQLUtility.parse(rolloutRequestBody.getTargetFilterQuery(), TargetFields.class);
|
||||
|
||||
final DistributionSet distributionSet = findDistributionSetOrThrowException(rolloutRequestBody);
|
||||
|
||||
// success condition
|
||||
RolloutGroupSuccessCondition successCondition = null;
|
||||
String successConditionExpr = null;
|
||||
// success action
|
||||
RolloutGroupSuccessAction successAction = null;
|
||||
String successActionExpr = null;
|
||||
// error condition
|
||||
RolloutGroupErrorCondition errorCondition = null;
|
||||
// error action
|
||||
String errorConditionExpr = null;
|
||||
RolloutGroupErrorAction errorAction = null;
|
||||
String errorActionExpr = null;
|
||||
if (rolloutRequestBody.getSuccessCondition() != null) {
|
||||
successCondition = MgmtRolloutMapper
|
||||
.mapFinishCondition(rolloutRequestBody.getSuccessCondition().getCondition());
|
||||
successConditionExpr = rolloutRequestBody.getSuccessCondition().getExpression();
|
||||
}
|
||||
if (rolloutRequestBody.getSuccessAction() != null) {
|
||||
successAction = MgmtRolloutMapper.map(rolloutRequestBody.getSuccessAction().getAction());
|
||||
successActionExpr = rolloutRequestBody.getSuccessAction().getExpression();
|
||||
}
|
||||
if (rolloutRequestBody.getErrorCondition() != null) {
|
||||
errorCondition = MgmtRolloutMapper.mapErrorCondition(rolloutRequestBody.getErrorCondition().getCondition());
|
||||
errorConditionExpr = rolloutRequestBody.getErrorCondition().getExpression();
|
||||
}
|
||||
if (rolloutRequestBody.getErrorAction() != null) {
|
||||
errorAction = MgmtRolloutMapper.map(rolloutRequestBody.getErrorAction().getAction());
|
||||
errorActionExpr = rolloutRequestBody.getErrorAction().getExpression();
|
||||
}
|
||||
|
||||
final RolloutGroupConditions rolloutGroupConditions = new RolloutGroup.RolloutGroupConditionBuilder()
|
||||
.successCondition(successCondition, successConditionExpr)
|
||||
.successAction(successAction, successActionExpr).errorCondition(errorCondition, errorConditionExpr)
|
||||
.errorAction(errorAction, errorActionExpr).build();
|
||||
final Rollout rollout = this.rolloutManagement.createRollout(
|
||||
MgmtRolloutMapper.fromRequest(rolloutRequestBody, distributionSet,
|
||||
rolloutRequestBody.getTargetFilterQuery()),
|
||||
rolloutRequestBody.getAmountGroups(), rolloutGroupConditions);
|
||||
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(MgmtRolloutMapper.toResponseRollout(rollout));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> start(final Long rolloutId, final boolean startAsync) {
|
||||
final Rollout rollout = findRolloutOrThrowException(rolloutId);
|
||||
if (startAsync) {
|
||||
this.rolloutManagement.startRolloutAsync(rollout);
|
||||
} else {
|
||||
this.rolloutManagement.startRollout(rollout);
|
||||
}
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> pause(final Long rolloutId) {
|
||||
final Rollout rollout = findRolloutOrThrowException(rolloutId);
|
||||
this.rolloutManagement.pauseRollout(rollout);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> resume(final Long rolloutId) {
|
||||
final Rollout rollout = findRolloutOrThrowException(rolloutId);
|
||||
this.rolloutManagement.resumeRollout(rollout);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MgmtRolloutGroupResponseBody>> getRolloutGroups(final Long rolloutId,
|
||||
final int pagingOffsetParam, final int pagingLimitParam, final String sortParam, final String rsqlParam) {
|
||||
final Rollout rollout = findRolloutOrThrowException(rolloutId);
|
||||
|
||||
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
|
||||
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
|
||||
final Sort sorting = PagingUtility.sanitizeRolloutGroupSortParam(sortParam);
|
||||
|
||||
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
|
||||
|
||||
final Page<RolloutGroup> findRolloutGroupsAll;
|
||||
if (rsqlParam != null) {
|
||||
findRolloutGroupsAll = this.rolloutGroupManagement.findRolloutGroupsByPredicate(rollout,
|
||||
RSQLUtility.parse(rsqlParam, RolloutGroupFields.class), pageable);
|
||||
} else {
|
||||
findRolloutGroupsAll = this.rolloutGroupManagement.findRolloutGroupsByRolloutId(rolloutId, pageable);
|
||||
}
|
||||
|
||||
final List<MgmtRolloutGroupResponseBody> rest = MgmtRolloutMapper
|
||||
.toResponseRolloutGroup(findRolloutGroupsAll.getContent());
|
||||
return new ResponseEntity<>(new PagedList<>(rest, findRolloutGroupsAll.getTotalElements()), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtRolloutGroupResponseBody> getRolloutGroup(final Long rolloutId, final Long groupId) {
|
||||
findRolloutOrThrowException(rolloutId);
|
||||
final RolloutGroup rolloutGroup = findRolloutGroupOrThrowException(groupId);
|
||||
return ResponseEntity.ok(MgmtRolloutMapper.toResponseRolloutGroup(rolloutGroup));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MgmtTarget>> getRolloutGroupTargets(final Long rolloutId, final Long groupId,
|
||||
final int pagingOffsetParam, final int pagingLimitParam, final String sortParam, final String rsqlParam) {
|
||||
findRolloutOrThrowException(rolloutId);
|
||||
final RolloutGroup rolloutGroup = findRolloutGroupOrThrowException(groupId);
|
||||
|
||||
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);
|
||||
|
||||
final Page<Target> rolloutGroupTargets;
|
||||
if (rsqlParam != null) {
|
||||
final Specification<Target> rsqlSpecification = RSQLUtility.parse(rsqlParam, TargetFields.class);
|
||||
rolloutGroupTargets = this.rolloutGroupManagement.findRolloutGroupTargets(rolloutGroup, rsqlSpecification,
|
||||
pageable);
|
||||
} else {
|
||||
final Page<Target> pageTargets = this.rolloutGroupManagement.findRolloutGroupTargets(rolloutGroup,
|
||||
pageable);
|
||||
rolloutGroupTargets = pageTargets;
|
||||
}
|
||||
final List<MgmtTarget> rest = MgmtTargetMapper.toResponse(rolloutGroupTargets.getContent());
|
||||
return new ResponseEntity<>(new PagedList<MgmtTarget>(rest, rolloutGroupTargets.getTotalElements()),
|
||||
HttpStatus.OK);
|
||||
}
|
||||
|
||||
private Rollout findRolloutOrThrowException(final Long rolloutId) {
|
||||
final Rollout rollout = this.rolloutManagement.findRolloutWithDetailedStatus(rolloutId);
|
||||
if (rollout == null) {
|
||||
throw new EntityNotFoundException("Rollout with Id {" + rolloutId + DOES_NOT_EXIST);
|
||||
}
|
||||
return rollout;
|
||||
}
|
||||
|
||||
private RolloutGroup findRolloutGroupOrThrowException(final Long rolloutGroupId) {
|
||||
final RolloutGroup rolloutGroup = this.rolloutGroupManagement.findRolloutGroupById(rolloutGroupId);
|
||||
if (rolloutGroup == null) {
|
||||
throw new EntityNotFoundException("Group with Id {" + rolloutGroupId + DOES_NOT_EXIST);
|
||||
}
|
||||
return rolloutGroup;
|
||||
}
|
||||
|
||||
private DistributionSet findDistributionSetOrThrowException(final MgmtRolloutRestRequestBody rolloutRequestBody) {
|
||||
final DistributionSet ds = this.distributionSetManagement
|
||||
.findDistributionSetById(rolloutRequestBody.getDistributionSetId());
|
||||
if (ds == null) {
|
||||
throw new EntityNotFoundException(
|
||||
"DistributionSet with Id {" + rolloutRequestBody.getDistributionSetId() + DOES_NOT_EXIST);
|
||||
}
|
||||
return ds;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* 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.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
|
||||
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.MetadataRest;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifactHash;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModule;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleRequestBodyPost;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleRestAPI;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi;
|
||||
import org.eclipse.hawkbit.repository.SoftwareManagement;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
|
||||
import org.eclipse.hawkbit.repository.model.Artifact;
|
||||
import org.eclipse.hawkbit.repository.model.LocalArtifact;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
|
||||
|
||||
/**
|
||||
* A mapper which maps repository model to RESTful model representation and
|
||||
* back.
|
||||
*
|
||||
*/
|
||||
public final class MgmtSoftwareModuleMapper {
|
||||
private MgmtSoftwareModuleMapper() {
|
||||
// Utility class
|
||||
}
|
||||
|
||||
private static SoftwareModuleType getSoftwareModuleTypeFromKeyString(final String type,
|
||||
final SoftwareManagement softwareManagement) {
|
||||
|
||||
final SoftwareModuleType smType = softwareManagement.findSoftwareModuleTypeByKey(type.trim());
|
||||
|
||||
if (smType == null) {
|
||||
throw new EntityNotFoundException(type.trim());
|
||||
}
|
||||
|
||||
return smType;
|
||||
}
|
||||
|
||||
static SoftwareModule fromRequest(final MgmtSoftwareModuleRequestBodyPost smsRest,
|
||||
final SoftwareManagement softwareManagement) {
|
||||
return new SoftwareModule(getSoftwareModuleTypeFromKeyString(smsRest.getType(), softwareManagement),
|
||||
smsRest.getName(), smsRest.getVersion(), smsRest.getDescription(), smsRest.getVendor());
|
||||
}
|
||||
|
||||
static List<SoftwareModuleMetadata> fromRequestSwMetadata(final SoftwareModule sw,
|
||||
final List<MetadataRest> metadata) {
|
||||
final List<SoftwareModuleMetadata> mappedList = new ArrayList<>(metadata.size());
|
||||
for (final MetadataRest metadataRest : metadata) {
|
||||
if (metadataRest.getKey() == null) {
|
||||
throw new IllegalArgumentException("the key of the metadata must be present");
|
||||
}
|
||||
mappedList.add(new SoftwareModuleMetadata(metadataRest.getKey(), sw, metadataRest.getValue()));
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
|
||||
static List<SoftwareModule> smFromRequest(final Iterable<MgmtSoftwareModuleRequestBodyPost> smsRest,
|
||||
final SoftwareManagement softwareManagement) {
|
||||
final List<SoftwareModule> mappedList = new ArrayList<>();
|
||||
for (final MgmtSoftwareModuleRequestBodyPost smRest : smsRest) {
|
||||
mappedList.add(fromRequest(smRest, softwareManagement));
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create response for sw modules.
|
||||
*
|
||||
* @param baseSoftareModules
|
||||
* the modules
|
||||
* @return the response
|
||||
*/
|
||||
public static List<MgmtSoftwareModule> toResponse(final List<SoftwareModule> baseSoftareModules) {
|
||||
final List<MgmtSoftwareModule> mappedList = new ArrayList<>();
|
||||
if (baseSoftareModules != null) {
|
||||
for (final SoftwareModule target : baseSoftareModules) {
|
||||
final MgmtSoftwareModule response = toResponse(target);
|
||||
|
||||
mappedList.add(response);
|
||||
}
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
|
||||
static List<MgmtSoftwareModule> toResponseSoftwareModules(final Iterable<SoftwareModule> softwareModules) {
|
||||
final List<MgmtSoftwareModule> response = new ArrayList<>();
|
||||
for (final SoftwareModule softwareModule : softwareModules) {
|
||||
response.add(toResponse(softwareModule));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
static List<MetadataRest> toResponseSwMetadata(final List<SoftwareModuleMetadata> metadata) {
|
||||
final List<MetadataRest> mappedList = new ArrayList<>(metadata.size());
|
||||
for (final SoftwareModuleMetadata distributionSetMetadata : metadata) {
|
||||
mappedList.add(toResponseSwMetadata(distributionSetMetadata));
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
|
||||
static MetadataRest toResponseSwMetadata(final SoftwareModuleMetadata metadata) {
|
||||
final MetadataRest metadataRest = new MetadataRest();
|
||||
metadataRest.setKey(metadata.getId().getKey());
|
||||
metadataRest.setValue(metadata.getValue());
|
||||
return metadataRest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create response for one sw module.
|
||||
*
|
||||
* @param baseSofwareModule
|
||||
* the sw module
|
||||
* @return the response
|
||||
*/
|
||||
public static MgmtSoftwareModule toResponse(final SoftwareModule baseSofwareModule) {
|
||||
if (baseSofwareModule == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final MgmtSoftwareModule response = new MgmtSoftwareModule();
|
||||
MgmtRestModelMapper.mapNamedToNamed(response, baseSofwareModule);
|
||||
response.setModuleId(baseSofwareModule.getId());
|
||||
response.setVersion(baseSofwareModule.getVersion());
|
||||
response.setType(baseSofwareModule.getType().getKey());
|
||||
response.setVendor(baseSofwareModule.getVendor());
|
||||
|
||||
response.add(linkTo(methodOn(MgmtSoftwareModuleRestAPI.class).getArtifacts(response.getModuleId()))
|
||||
.withRel(MgmtRestConstants.SOFTWAREMODULE_V1_ARTIFACT));
|
||||
response.add(linkTo(methodOn(MgmtSoftwareModuleRestAPI.class).getSoftwareModule(response.getModuleId()))
|
||||
.withRel("self"));
|
||||
|
||||
response.add(linkTo(
|
||||
methodOn(MgmtSoftwareModuleTypeRestApi.class).getSoftwareModuleType(baseSofwareModule.getType().getId()))
|
||||
.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))
|
||||
.withRel("metadata"));
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param artifact
|
||||
* @return
|
||||
*/
|
||||
static MgmtArtifact toResponse(final Artifact artifact) {
|
||||
final MgmtArtifact.ArtifactType type = artifact instanceof LocalArtifact ? MgmtArtifact.ArtifactType.LOCAL
|
||||
: MgmtArtifact.ArtifactType.EXTERNAL;
|
||||
|
||||
final MgmtArtifact artifactRest = new MgmtArtifact();
|
||||
artifactRest.setType(type);
|
||||
artifactRest.setArtifactId(artifact.getId());
|
||||
artifactRest.setSize(artifact.getSize());
|
||||
artifactRest.setHashes(new MgmtArtifactHash(artifact.getSha1Hash(), artifact.getMd5Hash()));
|
||||
|
||||
if (artifact instanceof LocalArtifact) {
|
||||
artifactRest.setProvidedFilename(((LocalArtifact) artifact).getFilename());
|
||||
}
|
||||
|
||||
MgmtRestModelMapper.mapBaseToBase(artifactRest, artifact);
|
||||
|
||||
artifactRest.add(linkTo(methodOn(MgmtSoftwareModuleRestAPI.class).getArtifact(artifact.getSoftwareModule().getId(),
|
||||
artifact.getId())).withRel("self"));
|
||||
|
||||
if (artifact instanceof LocalArtifact) {
|
||||
artifactRest.add(linkTo(methodOn(MgmtDownloadArtifactResource.class)
|
||||
.downloadArtifact(artifact.getSoftwareModule().getId(), artifact.getId(), null, null))
|
||||
.withRel("download"));
|
||||
}
|
||||
|
||||
return artifactRest;
|
||||
}
|
||||
|
||||
static List<MgmtArtifact> artifactsToResponse(final List<Artifact> artifacts) {
|
||||
final List<MgmtArtifact> mappedList = new ArrayList<>();
|
||||
|
||||
if (artifacts != null) {
|
||||
for (final Artifact artifact : artifacts) {
|
||||
final MgmtArtifact response = toResponse(artifact);
|
||||
mappedList.add(response);
|
||||
}
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
/**
|
||||
* 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 java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.MetadataRest;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.PagedList;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModule;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleRequestBodyPost;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleRequestBodyPut;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleRestAPI;
|
||||
import org.eclipse.hawkbit.repository.ArtifactManagement;
|
||||
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
|
||||
import org.eclipse.hawkbit.repository.SoftwareManagement;
|
||||
import org.eclipse.hawkbit.repository.SoftwareModuleFields;
|
||||
import org.eclipse.hawkbit.repository.SoftwareModuleMetadataFields;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
|
||||
import org.eclipse.hawkbit.repository.model.Artifact;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata;
|
||||
import org.eclipse.hawkbit.repository.model.SwMetadataCompositeKey;
|
||||
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
|
||||
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.Pageable;
|
||||
import org.springframework.data.domain.Slice;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
/**
|
||||
* REST Resource handling for {@link SoftwareModule} and related
|
||||
* {@link Artifact} CRUD operations.
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestAPI {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(MgmtSoftwareModuleResource.class);
|
||||
|
||||
@Autowired
|
||||
private ArtifactManagement artifactManagement;
|
||||
|
||||
@Autowired
|
||||
private SoftwareManagement softwareManagement;
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtArtifact> uploadArtifact(@PathVariable final Long softwareModuleId,
|
||||
@RequestParam("file") final MultipartFile file,
|
||||
@RequestParam(value = "filename", required = false) final String optionalFileName,
|
||||
@RequestParam(value = "md5sum", required = false) final String md5Sum,
|
||||
@RequestParam(value = "sha1sum", required = false) final String sha1Sum) {
|
||||
|
||||
Artifact result;
|
||||
if (!file.isEmpty()) {
|
||||
String fileName = optionalFileName;
|
||||
|
||||
if (null == fileName) {
|
||||
fileName = file.getOriginalFilename();
|
||||
}
|
||||
|
||||
try {
|
||||
result = artifactManagement.createLocalArtifact(file.getInputStream(), softwareModuleId, fileName,
|
||||
md5Sum == null ? null : md5Sum.toLowerCase(), sha1Sum == null ? null : sha1Sum.toLowerCase(),
|
||||
false, file.getContentType());
|
||||
} catch (final IOException e) {
|
||||
LOG.error("Failed to store artifact", e);
|
||||
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
} else {
|
||||
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponse(result), HttpStatus.CREATED);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MgmtArtifact>> getArtifacts(@PathVariable final Long softwareModuleId) {
|
||||
final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
|
||||
|
||||
return new ResponseEntity<>(MgmtSoftwareModuleMapper.artifactsToResponse(module.getArtifacts()), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtArtifact> getArtifact(@PathVariable final Long softwareModuleId,
|
||||
@PathVariable final Long artifactId) {
|
||||
final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, artifactId);
|
||||
|
||||
return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponse(module.getLocalArtifact(artifactId).get()),
|
||||
HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> deleteArtifact(@PathVariable final Long softwareModuleId,
|
||||
@PathVariable final Long artifactId) {
|
||||
findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, artifactId);
|
||||
|
||||
artifactManagement.deleteLocalArtifact(artifactId);
|
||||
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MgmtSoftwareModule>> getSoftwareModules(
|
||||
@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.sanitizeSoftwareModuleSortParam(sortParam);
|
||||
|
||||
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
|
||||
|
||||
final Slice<SoftwareModule> findModulesAll;
|
||||
Long countModulesAll;
|
||||
if (rsqlParam != null) {
|
||||
findModulesAll = softwareManagement
|
||||
.findSoftwareModulesByPredicate(RSQLUtility.parse(rsqlParam, SoftwareModuleFields.class), pageable);
|
||||
countModulesAll = ((Page<SoftwareModule>) findModulesAll).getTotalElements();
|
||||
} else {
|
||||
findModulesAll = softwareManagement.findSoftwareModulesAll(pageable);
|
||||
countModulesAll = softwareManagement.countSoftwareModulesAll();
|
||||
}
|
||||
|
||||
final List<MgmtSoftwareModule> rest = MgmtSoftwareModuleMapper.toResponse(findModulesAll.getContent());
|
||||
return new ResponseEntity<>(new PagedList<>(rest, countModulesAll), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtSoftwareModule> getSoftwareModule(@PathVariable final Long softwareModuleId) {
|
||||
final SoftwareModule findBaseSoftareModule = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
|
||||
|
||||
return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponse(findBaseSoftareModule), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MgmtSoftwareModule>> createSoftwareModules(
|
||||
@RequestBody final List<MgmtSoftwareModuleRequestBodyPost> softwareModules) {
|
||||
LOG.debug("creating {} softwareModules", softwareModules.size());
|
||||
final Iterable<SoftwareModule> createdSoftwareModules = softwareManagement
|
||||
.createSoftwareModule(MgmtSoftwareModuleMapper.smFromRequest(softwareModules, softwareManagement));
|
||||
LOG.debug("{} softwareModules created, return status {}", softwareModules.size(), HttpStatus.CREATED);
|
||||
|
||||
return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponseSoftwareModules(createdSoftwareModules),
|
||||
HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtSoftwareModule> updateSoftwareModule(@PathVariable final Long softwareModuleId,
|
||||
@RequestBody final MgmtSoftwareModuleRequestBodyPut restSoftwareModule) {
|
||||
final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
|
||||
|
||||
// only description and vendor can be modified
|
||||
if (restSoftwareModule.getDescription() != null) {
|
||||
module.setDescription(restSoftwareModule.getDescription());
|
||||
}
|
||||
if (restSoftwareModule.getVendor() != null) {
|
||||
module.setVendor(restSoftwareModule.getVendor());
|
||||
}
|
||||
|
||||
final SoftwareModule updateSoftwareModule = softwareManagement.updateSoftwareModule(module);
|
||||
return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponse(updateSoftwareModule), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> deleteSoftwareModule(@PathVariable final Long softwareModuleId) {
|
||||
final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
|
||||
|
||||
softwareManagement.deleteSoftwareModule(module);
|
||||
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MetadataRest>> getMetadata(@PathVariable final Long softwareModuleId,
|
||||
@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) {
|
||||
|
||||
// check if software module exists otherwise throw exception immediately
|
||||
findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
|
||||
|
||||
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
|
||||
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
|
||||
final Sort sorting = PagingUtility.sanitizeSoftwareModuleMetadataSortParam(sortParam);
|
||||
|
||||
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
|
||||
final Page<SoftwareModuleMetadata> metaDataPage;
|
||||
|
||||
if (rsqlParam != null) {
|
||||
metaDataPage = softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(softwareModuleId,
|
||||
RSQLUtility.parse(rsqlParam, SoftwareModuleMetadataFields.class), pageable);
|
||||
} else {
|
||||
metaDataPage = softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(softwareModuleId, pageable);
|
||||
}
|
||||
|
||||
return new ResponseEntity<>(
|
||||
new PagedList<>(MgmtSoftwareModuleMapper.toResponseSwMetadata(metaDataPage.getContent()),
|
||||
metaDataPage.getTotalElements()),
|
||||
HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MetadataRest> getMetadataValue(@PathVariable final Long softwareModuleId,
|
||||
@PathVariable final String metadataKey) {
|
||||
// check if distribution set exists otherwise throw exception
|
||||
// immediately
|
||||
final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
|
||||
final SoftwareModuleMetadata findOne = softwareManagement.findSoftwareModuleMetadata(new SwMetadataCompositeKey(sw, metadataKey));
|
||||
return ResponseEntity.<MetadataRest> ok(MgmtSoftwareModuleMapper.toResponseSwMetadata(findOne));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MetadataRest> updateMetadata(@PathVariable final Long softwareModuleId,
|
||||
@PathVariable final String metadataKey, @RequestBody final MetadataRest metadata) {
|
||||
// check if software module exists otherwise throw exception immediately
|
||||
final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
|
||||
final SoftwareModuleMetadata updated = softwareManagement
|
||||
.updateSoftwareModuleMetadata(new SoftwareModuleMetadata(metadataKey, sw, metadata.getValue()));
|
||||
return ResponseEntity.ok(MgmtSoftwareModuleMapper.toResponseSwMetadata(updated));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> deleteMetadata(@PathVariable final Long softwareModuleId,
|
||||
@PathVariable final String metadataKey) {
|
||||
// check if software module exists otherwise throw exception immediately
|
||||
final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
|
||||
softwareManagement.deleteSoftwareModuleMetadata(new SwMetadataCompositeKey(sw, metadataKey));
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MetadataRest>> createMetadata(@PathVariable final Long softwareModuleId,
|
||||
@RequestBody final List<MetadataRest> metadataRest) {
|
||||
// check if software module exists otherwise throw exception immediately
|
||||
final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
|
||||
|
||||
final List<SoftwareModuleMetadata> created = softwareManagement
|
||||
.createSoftwareModuleMetadata(MgmtSoftwareModuleMapper.fromRequestSwMetadata(sw, metadataRest));
|
||||
|
||||
return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponseSwMetadata(created), HttpStatus.CREATED);
|
||||
|
||||
}
|
||||
|
||||
private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId,
|
||||
final Long artifactId) {
|
||||
final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId);
|
||||
if (module == null) {
|
||||
throw new EntityNotFoundException("SoftwareModule with Id {" + softwareModuleId + "} does not exist");
|
||||
} else if (artifactId != null && !module.getLocalArtifact(artifactId).isPresent()) {
|
||||
throw new EntityNotFoundException("Artifact with Id {" + artifactId + "} does not exist");
|
||||
}
|
||||
return module;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* 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.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
|
||||
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleType;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPost;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
|
||||
|
||||
/**
|
||||
* A mapper which maps repository model to RESTful model representation and
|
||||
* back.
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
final class MgmtSoftwareModuleTypeMapper {
|
||||
|
||||
// private constructor, utility class
|
||||
private MgmtSoftwareModuleTypeMapper() {
|
||||
|
||||
}
|
||||
|
||||
static List<SoftwareModuleType> smFromRequest(final Iterable<MgmtSoftwareModuleTypeRequestBodyPost> smTypesRest) {
|
||||
final List<SoftwareModuleType> mappedList = new ArrayList<>();
|
||||
|
||||
for (final MgmtSoftwareModuleTypeRequestBodyPost smRest : smTypesRest) {
|
||||
mappedList.add(fromRequest(smRest));
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
|
||||
static SoftwareModuleType fromRequest(final MgmtSoftwareModuleTypeRequestBodyPost smsRest) {
|
||||
return new SoftwareModuleType(smsRest.getKey(), smsRest.getName(), smsRest.getDescription(),
|
||||
smsRest.getMaxAssignments());
|
||||
}
|
||||
|
||||
static List<MgmtSoftwareModuleType> toTypesResponse(final List<SoftwareModuleType> types) {
|
||||
final List<MgmtSoftwareModuleType> response = new ArrayList<>();
|
||||
for (final SoftwareModuleType softwareModule : types) {
|
||||
response.add(toResponse(softwareModule));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
static List<MgmtSoftwareModuleType> toListResponse(final Collection<SoftwareModuleType> types) {
|
||||
final List<MgmtSoftwareModuleType> response = new ArrayList<>();
|
||||
for (final SoftwareModuleType softwareModule : types) {
|
||||
response.add(toResponse(softwareModule));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
static MgmtSoftwareModuleType toResponse(final SoftwareModuleType type) {
|
||||
final MgmtSoftwareModuleType result = new MgmtSoftwareModuleType();
|
||||
|
||||
MgmtRestModelMapper.mapNamedToNamed(result, type);
|
||||
result.setKey(type.getKey());
|
||||
result.setMaxAssignments(type.getMaxAssignments());
|
||||
result.setModuleId(type.getId());
|
||||
|
||||
result.add(linkTo(methodOn(MgmtSoftwareModuleTypeRestApi.class).getSoftwareModuleType(result.getModuleId()))
|
||||
.withRel("self"));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* 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 java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.PagedList;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleType;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPost;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPut;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi;
|
||||
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
|
||||
import org.eclipse.hawkbit.repository.SoftwareManagement;
|
||||
import org.eclipse.hawkbit.repository.SoftwareModuleTypeFields;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
|
||||
import org.eclipse.hawkbit.repository.model.Artifact;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
|
||||
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
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;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* REST Resource handling for {@link SoftwareModule} and related
|
||||
* {@link Artifact} CRUD operations.
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRestApi {
|
||||
@Autowired
|
||||
private SoftwareManagement softwareManagement;
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MgmtSoftwareModuleType>> getTypes(final int pagingOffsetParam,
|
||||
final int pagingLimitParam, final String sortParam, final String rsqlParam) {
|
||||
|
||||
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
|
||||
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
|
||||
final Sort sorting = PagingUtility.sanitizeSoftwareModuleTypeSortParam(sortParam);
|
||||
|
||||
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
|
||||
|
||||
final Slice<SoftwareModuleType> findModuleTypessAll;
|
||||
Long countModulesAll;
|
||||
if (rsqlParam != null) {
|
||||
findModuleTypessAll = this.softwareManagement.findSoftwareModuleTypesByPredicate(
|
||||
RSQLUtility.parse(rsqlParam, SoftwareModuleTypeFields.class), pageable);
|
||||
countModulesAll = ((Page<SoftwareModuleType>) findModuleTypessAll).getTotalElements();
|
||||
} else {
|
||||
findModuleTypessAll = this.softwareManagement.findSoftwareModuleTypesAll(pageable);
|
||||
countModulesAll = this.softwareManagement.countSoftwareModuleTypesAll();
|
||||
}
|
||||
|
||||
final List<MgmtSoftwareModuleType> rest = MgmtSoftwareModuleTypeMapper
|
||||
.toListResponse(findModuleTypessAll.getContent());
|
||||
return new ResponseEntity<>(new PagedList<>(rest, countModulesAll), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtSoftwareModuleType> getSoftwareModuleType(final Long softwareModuleTypeId) {
|
||||
final SoftwareModuleType foundType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
|
||||
|
||||
return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toResponse(foundType), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> deleteSoftwareModuleType(final Long softwareModuleTypeId) {
|
||||
final SoftwareModuleType module = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
|
||||
|
||||
this.softwareManagement.deleteSoftwareModuleType(module);
|
||||
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtSoftwareModuleType> updateSoftwareModuleType(final Long softwareModuleTypeId,
|
||||
final MgmtSoftwareModuleTypeRequestBodyPut restSoftwareModuleType) {
|
||||
final SoftwareModuleType type = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
|
||||
|
||||
// only description can be modified
|
||||
if (restSoftwareModuleType.getDescription() != null) {
|
||||
type.setDescription(restSoftwareModuleType.getDescription());
|
||||
}
|
||||
|
||||
final SoftwareModuleType updatedSoftwareModuleType = this.softwareManagement.updateSoftwareModuleType(type);
|
||||
return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toResponse(updatedSoftwareModuleType), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MgmtSoftwareModuleType>> createSoftwareModuleTypes(
|
||||
final List<MgmtSoftwareModuleTypeRequestBodyPost> softwareModuleTypes) {
|
||||
|
||||
final List<SoftwareModuleType> createdSoftwareModules = this.softwareManagement
|
||||
.createSoftwareModuleType(MgmtSoftwareModuleTypeMapper.smFromRequest(softwareModuleTypes));
|
||||
|
||||
return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toTypesResponse(createdSoftwareModules),
|
||||
HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) {
|
||||
final SoftwareModuleType module = this.softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId);
|
||||
if (module == null) {
|
||||
throw new EntityNotFoundException(
|
||||
"SoftwareModuleType with Id {" + softwareModuleTypeId + "} does not exist");
|
||||
}
|
||||
return module;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* 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.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
|
||||
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
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.MgmtTargetTagRestApi;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
|
||||
import org.eclipse.hawkbit.repository.model.Tag;
|
||||
import org.eclipse.hawkbit.repository.model.TargetTag;
|
||||
|
||||
/**
|
||||
* A mapper which maps repository model to RESTful model representation and
|
||||
* back.
|
||||
*
|
||||
*/
|
||||
final class MgmtTagMapper {
|
||||
private MgmtTagMapper() {
|
||||
// Utility class
|
||||
}
|
||||
|
||||
static List<MgmtTag> toResponse(final List<TargetTag> targetTags) {
|
||||
final List<MgmtTag> tagsRest = new ArrayList<>();
|
||||
if (targetTags == null) {
|
||||
return tagsRest;
|
||||
}
|
||||
|
||||
for (final TargetTag target : targetTags) {
|
||||
final MgmtTag response = toResponse(target);
|
||||
|
||||
tagsRest.add(response);
|
||||
}
|
||||
return tagsRest;
|
||||
}
|
||||
|
||||
static MgmtTag toResponse(final TargetTag targetTag) {
|
||||
final MgmtTag response = new MgmtTag();
|
||||
if (targetTag == null) {
|
||||
return response;
|
||||
}
|
||||
|
||||
mapTag(response, targetTag);
|
||||
|
||||
response.add(linkTo(methodOn(MgmtTargetTagRestApi.class).getTargetTag(targetTag.getId())).withRel("self"));
|
||||
|
||||
response.add(linkTo(methodOn(MgmtTargetTagRestApi.class).getAssignedTargets(targetTag.getId()))
|
||||
.withRel("assignedTargets"));
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
static List<MgmtTag> toResponseDistributionSetTag(final List<DistributionSetTag> distributionSetTags) {
|
||||
final List<MgmtTag> tagsRest = new ArrayList<>();
|
||||
if (distributionSetTags == null) {
|
||||
return tagsRest;
|
||||
}
|
||||
|
||||
for (final DistributionSetTag distributionSetTag : distributionSetTags) {
|
||||
final MgmtTag response = toResponse(distributionSetTag);
|
||||
|
||||
tagsRest.add(response);
|
||||
}
|
||||
return tagsRest;
|
||||
}
|
||||
|
||||
static MgmtTag toResponse(final DistributionSetTag distributionSetTag) {
|
||||
final MgmtTag response = new MgmtTag();
|
||||
if (distributionSetTag == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
mapTag(response, distributionSetTag);
|
||||
|
||||
response.add(linkTo(methodOn(MgmtDistributionSetTagRestApi.class).getDistributionSetTag(distributionSetTag.getId()))
|
||||
.withRel("self"));
|
||||
|
||||
response.add(linkTo(
|
||||
methodOn(MgmtDistributionSetTagRestApi.class).getAssignedDistributionSets(distributionSetTag.getId()))
|
||||
.withRel("assignedDistributionSets"));
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
static List<TargetTag> mapTargeTagFromRequest(final Iterable<MgmtTagRequestBodyPut> tags) {
|
||||
final List<TargetTag> mappedList = new ArrayList<>();
|
||||
for (final MgmtTagRequestBodyPut targetTagRest : tags) {
|
||||
mappedList.add(
|
||||
new TargetTag(targetTagRest.getName(), targetTagRest.getDescription(), targetTagRest.getColour()));
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
|
||||
static List<DistributionSetTag> mapDistributionSetTagFromRequest(final Iterable<MgmtTagRequestBodyPut> tags) {
|
||||
final List<DistributionSetTag> mappedList = new ArrayList<>();
|
||||
for (final MgmtTagRequestBodyPut targetTagRest : tags) {
|
||||
mappedList.add(new DistributionSetTag(targetTagRest.getName(), targetTagRest.getDescription(),
|
||||
targetTagRest.getColour()));
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
|
||||
private static void mapTag(final MgmtTag response, final Tag tag) {
|
||||
MgmtRestModelMapper.mapNamedToNamed(response, tag);
|
||||
response.setTagId(tag.getId());
|
||||
response.setColour(tag.getColour());
|
||||
}
|
||||
|
||||
static void updateTag(final MgmtTagRequestBodyPut response, final Tag tag) {
|
||||
if (response.getDescription() != null) {
|
||||
tag.setDescription(response.getDescription());
|
||||
}
|
||||
|
||||
if (response.getColour() != null) {
|
||||
tag.setColour(response.getColour());
|
||||
}
|
||||
|
||||
if (response.getName() != null) {
|
||||
tag.setName(response.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
/**
|
||||
* 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.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
|
||||
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.MgmtPollStatus;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.action.MgmtAction;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.action.MgmtActionStatus;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget;
|
||||
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.model.Action;
|
||||
import org.eclipse.hawkbit.repository.model.ActionStatus;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.repository.model.TargetInfo.PollStatus;
|
||||
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
|
||||
import org.eclipse.hawkbit.rest.data.SortDirection;
|
||||
|
||||
/**
|
||||
* A mapper which maps repository model to RESTful model representation and
|
||||
* back.
|
||||
*
|
||||
*/
|
||||
public final class MgmtTargetMapper {
|
||||
|
||||
private MgmtTargetMapper() {
|
||||
// Utility class
|
||||
}
|
||||
|
||||
/**
|
||||
* Add links to a target response.
|
||||
*
|
||||
* @param response
|
||||
* the target response
|
||||
*/
|
||||
public static void addTargetLinks(final MgmtTarget response) {
|
||||
response.add(linkTo(methodOn(MgmtTargetRestApi.class).getAssignedDistributionSet(response.getControllerId()))
|
||||
.withRel(MgmtRestConstants.TARGET_V1_ASSIGNED_DISTRIBUTION_SET));
|
||||
response.add(linkTo(methodOn(MgmtTargetRestApi.class).getInstalledDistributionSet(response.getControllerId()))
|
||||
.withRel(MgmtRestConstants.TARGET_V1_INSTALLED_DISTRIBUTION_SET));
|
||||
response.add(linkTo(methodOn(MgmtTargetRestApi.class).getAttributes(response.getControllerId()))
|
||||
.withRel(MgmtRestConstants.TARGET_V1_ATTRIBUTES));
|
||||
response.add(linkTo(methodOn(MgmtTargetRestApi.class).getActionHistory(response.getControllerId(), 0,
|
||||
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE,
|
||||
ActionFields.ID.getFieldName() + ":" + SortDirection.DESC, null))
|
||||
.withRel(MgmtRestConstants.TARGET_V1_ACTIONS));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the poll status to a target response.
|
||||
*
|
||||
* @param target
|
||||
* the target
|
||||
* @param targetRest
|
||||
* the response
|
||||
*/
|
||||
public static void addPollStatus(final Target target, final MgmtTarget targetRest) {
|
||||
final PollStatus pollStatus = target.getTargetInfo().getPollStatus();
|
||||
if (pollStatus != null) {
|
||||
final MgmtPollStatus pollStatusRest = new MgmtPollStatus();
|
||||
pollStatusRest.setLastRequestAt(
|
||||
Date.from(pollStatus.getLastPollDate().atZone(ZoneId.systemDefault()).toInstant()).getTime());
|
||||
pollStatusRest.setNextExpectedRequestAt(
|
||||
Date.from(pollStatus.getNextPollDate().atZone(ZoneId.systemDefault()).toInstant()).getTime());
|
||||
pollStatusRest.setOverdue(pollStatus.isOverdue());
|
||||
targetRest.setPollStatus(pollStatusRest);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a response which includes links and pollstatus for all targets.
|
||||
*
|
||||
* @param targets
|
||||
* the targets
|
||||
* @return the response
|
||||
*/
|
||||
public static List<MgmtTarget> toResponseWithLinksAndPollStatus(final Iterable<Target> targets) {
|
||||
final List<MgmtTarget> mappedList = new ArrayList<>();
|
||||
if (targets != null) {
|
||||
for (final Target target : targets) {
|
||||
final MgmtTarget response = toResponse(target);
|
||||
addPollStatus(target, response);
|
||||
addTargetLinks(response);
|
||||
mappedList.add(response);
|
||||
}
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a response for targets.
|
||||
*
|
||||
* @param targets
|
||||
* list of targets
|
||||
* @return the response
|
||||
*/
|
||||
public static List<MgmtTarget> toResponse(final Iterable<Target> targets) {
|
||||
final List<MgmtTarget> mappedList = new ArrayList<>();
|
||||
if (targets != null) {
|
||||
for (final Target target : targets) {
|
||||
final MgmtTarget response = toResponse(target);
|
||||
mappedList.add(response);
|
||||
}
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a response for target.
|
||||
*
|
||||
* @param target
|
||||
* the target
|
||||
* @return the response
|
||||
*/
|
||||
public static MgmtTarget toResponse(final Target target) {
|
||||
if (target == null) {
|
||||
return null;
|
||||
}
|
||||
final MgmtTarget targetRest = new MgmtTarget();
|
||||
targetRest.setControllerId(target.getControllerId());
|
||||
targetRest.setDescription(target.getDescription());
|
||||
targetRest.setName(target.getName());
|
||||
targetRest.setUpdateStatus(getUpdateStatusName(target.getTargetInfo().getUpdateStatus()));
|
||||
|
||||
final URI address = target.getTargetInfo().getAddress();
|
||||
if (address != null) {
|
||||
targetRest.setIpAddress(address.getHost());
|
||||
targetRest.setAddress(address.toString());
|
||||
}
|
||||
|
||||
targetRest.setCreatedBy(target.getCreatedBy());
|
||||
targetRest.setLastModifiedBy(target.getLastModifiedBy());
|
||||
|
||||
targetRest.setCreatedAt(target.getCreatedAt());
|
||||
targetRest.setLastModifiedAt(target.getLastModifiedAt());
|
||||
|
||||
targetRest.setSecurityToken(target.getSecurityToken());
|
||||
|
||||
// last target query is the last controller request date
|
||||
final Long lastTargetQuery = target.getTargetInfo().getLastTargetQuery();
|
||||
final Long installationDate = target.getTargetInfo().getInstallationDate();
|
||||
|
||||
if (lastTargetQuery != null) {
|
||||
targetRest.setLastControllerRequestAt(lastTargetQuery);
|
||||
}
|
||||
if (installationDate != null) {
|
||||
targetRest.setInstalledAt(installationDate);
|
||||
}
|
||||
|
||||
targetRest.add(linkTo(methodOn(MgmtTargetRestApi.class).getTarget(target.getControllerId())).withRel("self"));
|
||||
|
||||
return targetRest;
|
||||
}
|
||||
|
||||
static List<Target> fromRequest(final Iterable<MgmtTargetRequestBody> targetsRest) {
|
||||
final List<Target> mappedList = new ArrayList<>();
|
||||
for (final MgmtTargetRequestBody targetRest : targetsRest) {
|
||||
mappedList.add(fromRequest(targetRest));
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
|
||||
static Target fromRequest(final MgmtTargetRequestBody targetRest) {
|
||||
final Target target = new Target(targetRest.getControllerId());
|
||||
target.setDescription(targetRest.getDescription());
|
||||
target.setName(targetRest.getName());
|
||||
return target;
|
||||
}
|
||||
|
||||
static List<MgmtActionStatus> toActionStatusRestResponse(final List<ActionStatus> actionStatus) {
|
||||
final List<MgmtActionStatus> mappedList = new ArrayList<>();
|
||||
|
||||
if (actionStatus != null) {
|
||||
for (final ActionStatus status : actionStatus) {
|
||||
final MgmtActionStatus response = toResponse(status);
|
||||
mappedList.add(response);
|
||||
}
|
||||
}
|
||||
|
||||
return mappedList;
|
||||
}
|
||||
|
||||
static MgmtAction toResponse(final String targetId, final Action action, final boolean isActive) {
|
||||
final MgmtAction result = new MgmtAction();
|
||||
|
||||
result.setActionId(action.getId());
|
||||
result.setType(getType(action));
|
||||
|
||||
if (isActive) {
|
||||
result.setStatus(MgmtAction.ACTION_PENDING);
|
||||
} else {
|
||||
result.setStatus(MgmtAction.ACTION_FINISHED);
|
||||
}
|
||||
|
||||
MgmtRestModelMapper.mapBaseToBase(result, action);
|
||||
|
||||
result.add(linkTo(methodOn(MgmtTargetRestApi.class).getAction(targetId, action.getId())).withRel("self"));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static List<MgmtAction> toResponse(final String targetId, final List<Action> actions) {
|
||||
final List<MgmtAction> mappedList = new ArrayList<>();
|
||||
|
||||
for (final Action action : actions) {
|
||||
final MgmtAction response = toResponse(targetId, action, action.isActive());
|
||||
mappedList.add(response);
|
||||
}
|
||||
return mappedList;
|
||||
}
|
||||
|
||||
private static String getNameOfActionStatusType(final Action.Status type) {
|
||||
String result;
|
||||
|
||||
switch (type) {
|
||||
case CANCELED:
|
||||
result = MgmtActionStatus.AS_CANCELED;
|
||||
break;
|
||||
case ERROR:
|
||||
result = MgmtActionStatus.AS_ERROR;
|
||||
break;
|
||||
case FINISHED:
|
||||
result = MgmtActionStatus.AS_FINISHED;
|
||||
break;
|
||||
case RETRIEVED:
|
||||
result = MgmtActionStatus.AS_RETRIEVED;
|
||||
break;
|
||||
case RUNNING:
|
||||
result = MgmtActionStatus.AS_RUNNING;
|
||||
break;
|
||||
case WARNING:
|
||||
result = MgmtActionStatus.AS_WARNING;
|
||||
break;
|
||||
default:
|
||||
return type.name().toLowerCase();
|
||||
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
private static String getType(final Action action) {
|
||||
if (!action.isCancelingOrCanceled()) {
|
||||
return MgmtAction.ACTION_UPDATE;
|
||||
} else if (action.isCancelingOrCanceled()) {
|
||||
return MgmtAction.ACTION_CANCEL;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String getUpdateStatusName(final TargetUpdateStatus updatestatus) {
|
||||
String result;
|
||||
|
||||
switch (updatestatus) {
|
||||
case ERROR:
|
||||
result = "error";
|
||||
break;
|
||||
case IN_SYNC:
|
||||
result = "in_sync";
|
||||
break;
|
||||
case PENDING:
|
||||
result = "pending";
|
||||
break;
|
||||
case REGISTERED:
|
||||
result = "registered";
|
||||
break;
|
||||
case UNKNOWN:
|
||||
result = "unknown";
|
||||
break;
|
||||
default:
|
||||
return updatestatus.name().toLowerCase();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static MgmtActionStatus toResponse(final ActionStatus actionStatus) {
|
||||
final MgmtActionStatus result = new MgmtActionStatus();
|
||||
|
||||
result.setMessages(actionStatus.getMessages());
|
||||
result.setReportedAt(actionStatus.getCreatedAt());
|
||||
result.setStatusId(actionStatus.getId());
|
||||
result.setType(getNameOfActionStatusType(actionStatus.getStatus()));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
/**
|
||||
* 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.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
|
||||
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.PagedList;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.action.MgmtAction;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.action.MgmtActionStatus;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.target.MgmtDistributionSetAssigment;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTargetAttributes;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTargetRequestBody;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetRestApi;
|
||||
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.ActionStatusFields;
|
||||
import org.eclipse.hawkbit.repository.DeploymentManagement;
|
||||
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
|
||||
import org.eclipse.hawkbit.repository.TargetFields;
|
||||
import org.eclipse.hawkbit.repository.TargetManagement;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
|
||||
import org.eclipse.hawkbit.repository.model.Action;
|
||||
import org.eclipse.hawkbit.repository.model.Action.ActionType;
|
||||
import org.eclipse.hawkbit.repository.model.ActionStatus;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
|
||||
import org.eclipse.hawkbit.rest.data.SortDirection;
|
||||
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.Pageable;
|
||||
import org.springframework.data.domain.Slice;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* REST Resource handling target CRUD operations.
|
||||
*/
|
||||
@RestController
|
||||
public class MgmtTargetResource implements MgmtTargetRestApi {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(MgmtTargetResource.class);
|
||||
|
||||
@Autowired
|
||||
private TargetManagement targetManagement;
|
||||
|
||||
@Autowired
|
||||
private DeploymentManagement deploymentManagement;
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtTarget> getTarget(final String targetId) {
|
||||
final Target findTarget = findTargetWithExceptionIfNotFound(targetId);
|
||||
// to single response include poll status
|
||||
final MgmtTarget response = MgmtTargetMapper.toResponse(findTarget);
|
||||
MgmtTargetMapper.addPollStatus(findTarget, response);
|
||||
MgmtTargetMapper.addTargetLinks(response);
|
||||
|
||||
return new ResponseEntity<>(response, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MgmtTarget>> getTargets(final int pagingOffsetParam, final int pagingLimitParam,
|
||||
final String sortParam, 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);
|
||||
final Slice<Target> findTargetsAll;
|
||||
final Long countTargetsAll;
|
||||
if (rsqlParam != null) {
|
||||
final Page<Target> findTargetPage = this.targetManagement
|
||||
.findTargetsAll(RSQLUtility.parse(rsqlParam, TargetFields.class), pageable);
|
||||
countTargetsAll = findTargetPage.getTotalElements();
|
||||
findTargetsAll = findTargetPage;
|
||||
} else {
|
||||
findTargetsAll = this.targetManagement.findTargetsAll(pageable);
|
||||
countTargetsAll = this.targetManagement.countTargetsAll();
|
||||
}
|
||||
|
||||
final List<MgmtTarget> rest = MgmtTargetMapper.toResponse(findTargetsAll.getContent());
|
||||
return new ResponseEntity<>(new PagedList<MgmtTarget>(rest, countTargetsAll), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MgmtTarget>> createTargets(final List<MgmtTargetRequestBody> targets) {
|
||||
LOG.debug("creating {} targets", targets.size());
|
||||
final Iterable<Target> createdTargets = this.targetManagement
|
||||
.createTargets(MgmtTargetMapper.fromRequest(targets));
|
||||
LOG.debug("{} targets created, return status {}", targets.size(), HttpStatus.CREATED);
|
||||
return new ResponseEntity<>(MgmtTargetMapper.toResponse(createdTargets), HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtTarget> updateTarget(final String targetId, final MgmtTargetRequestBody targetRest) {
|
||||
final Target existingTarget = findTargetWithExceptionIfNotFound(targetId);
|
||||
LOG.debug("updating target {}", existingTarget.getId());
|
||||
if (targetRest.getDescription() != null) {
|
||||
existingTarget.setDescription(targetRest.getDescription());
|
||||
}
|
||||
if (targetRest.getName() != null) {
|
||||
existingTarget.setName(targetRest.getName());
|
||||
}
|
||||
final Target updateTarget = this.targetManagement.updateTarget(existingTarget);
|
||||
|
||||
return new ResponseEntity<>(MgmtTargetMapper.toResponse(updateTarget), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> deleteTarget(final String targetId) {
|
||||
final Target target = findTargetWithExceptionIfNotFound(targetId);
|
||||
this.targetManagement.deleteTargets(target.getId());
|
||||
LOG.debug("{} target deleted, return status {}", targetId, HttpStatus.OK);
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtTargetAttributes> getAttributes(final String targetId) {
|
||||
final Target foundTarget = findTargetWithExceptionIfNotFound(targetId);
|
||||
final Map<String, String> controllerAttributes = foundTarget.getTargetInfo().getControllerAttributes();
|
||||
if (controllerAttributes.isEmpty()) {
|
||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
final MgmtTargetAttributes result = new MgmtTargetAttributes();
|
||||
result.putAll(controllerAttributes);
|
||||
|
||||
return new ResponseEntity<>(result, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MgmtAction>> getActionHistory(final String targetId, final int pagingOffsetParam,
|
||||
final int pagingLimitParam, final String sortParam, final String rsqlParam) {
|
||||
|
||||
final Target foundTarget = findTargetWithExceptionIfNotFound(targetId);
|
||||
|
||||
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
|
||||
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
|
||||
final Sort sorting = PagingUtility.sanitizeActionSortParam(sortParam);
|
||||
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
|
||||
|
||||
final Slice<Action> activeActions;
|
||||
final Long totalActionCount;
|
||||
if (rsqlParam != null) {
|
||||
final Specification<Action> parse = RSQLUtility.parse(rsqlParam, ActionFields.class);
|
||||
activeActions = this.deploymentManagement.findActionsByTarget(parse, foundTarget, pageable);
|
||||
totalActionCount = this.deploymentManagement.countActionsByTarget(parse, foundTarget);
|
||||
} else {
|
||||
activeActions = this.deploymentManagement.findActionsByTarget(foundTarget, pageable);
|
||||
totalActionCount = this.deploymentManagement.countActionsByTarget(foundTarget);
|
||||
}
|
||||
|
||||
return new ResponseEntity<>(
|
||||
new PagedList<>(MgmtTargetMapper.toResponse(targetId, activeActions.getContent()), totalActionCount),
|
||||
HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtAction> getAction(final String targetId, final Long actionId) {
|
||||
final Target target = findTargetWithExceptionIfNotFound(targetId);
|
||||
|
||||
final Action action = findActionWithExceptionIfNotFound(actionId);
|
||||
if (!action.getTarget().getId().equals(target.getId())) {
|
||||
LOG.warn("given action ({}) is not assigned to given target ({}).", action.getId(), target.getId());
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
final MgmtAction result = MgmtTargetMapper.toResponse(targetId, action, action.isActive());
|
||||
|
||||
if (!action.isCancelingOrCanceled()) {
|
||||
result.add(linkTo(
|
||||
methodOn(MgmtDistributionSetRestApi.class).getDistributionSet(action.getDistributionSet().getId()))
|
||||
.withRel("distributionset"));
|
||||
} else if (action.isCancelingOrCanceled()) {
|
||||
result.add(linkTo(methodOn(MgmtTargetRestApi.class).getAction(targetId, action.getId()))
|
||||
.withRel(MgmtRestConstants.TARGET_V1_CANCELED_ACTION));
|
||||
}
|
||||
|
||||
result.add(linkTo(methodOn(MgmtTargetRestApi.class).getActionStatusList(targetId, action.getId(), 0,
|
||||
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE,
|
||||
ActionStatusFields.ID.getFieldName() + ":" + SortDirection.DESC))
|
||||
.withRel(MgmtRestConstants.TARGET_V1_ACTION_STATUS));
|
||||
|
||||
return new ResponseEntity<>(result, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> cancelAction(final String targetId, final Long actionId,
|
||||
@RequestParam(required = false, defaultValue = "false") final boolean force) {
|
||||
final Target target = findTargetWithExceptionIfNotFound(targetId);
|
||||
final Action action = findActionWithExceptionIfNotFound(actionId);
|
||||
|
||||
if (force) {
|
||||
this.deploymentManagement.forceQuitAction(action);
|
||||
} else {
|
||||
this.deploymentManagement.cancelAction(action, target);
|
||||
}
|
||||
// both functions will throw an exception, when action is in wrong
|
||||
// state, which is mapped by MgmtResponseExceptionHandler.
|
||||
|
||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MgmtActionStatus>> getActionStatusList(final String targetId, final Long actionId,
|
||||
final int pagingOffsetParam, final int pagingLimitParam, final String sortParam) {
|
||||
|
||||
final Target target = findTargetWithExceptionIfNotFound(targetId);
|
||||
|
||||
final Action action = findActionWithExceptionIfNotFound(actionId);
|
||||
if (!action.getTarget().getId().equals(target.getId())) {
|
||||
LOG.warn("given action ({}) is not assigned to given target ({}).", action.getId(), target.getId());
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
|
||||
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
|
||||
final Sort sorting = PagingUtility.sanitizeActionStatusSortParam(sortParam);
|
||||
|
||||
final Page<ActionStatus> statusList = this.deploymentManagement.findActionStatusByAction(
|
||||
new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting), action, true);
|
||||
|
||||
return new ResponseEntity<>(
|
||||
new PagedList<>(MgmtTargetMapper.toActionStatusRestResponse(statusList.getContent()),
|
||||
statusList.getTotalElements()),
|
||||
HttpStatus.OK);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtDistributionSet> getAssignedDistributionSet(final String targetId) {
|
||||
final Target findTarget = findTargetWithExceptionIfNotFound(targetId);
|
||||
final MgmtDistributionSet distributionSetRest = MgmtDistributionSetMapper
|
||||
.toResponse(findTarget.getAssignedDistributionSet());
|
||||
final HttpStatus retStatus;
|
||||
if (distributionSetRest == null) {
|
||||
retStatus = HttpStatus.NO_CONTENT;
|
||||
} else {
|
||||
retStatus = HttpStatus.OK;
|
||||
}
|
||||
return new ResponseEntity<>(distributionSetRest, retStatus);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> postAssignedDistributionSet(final String targetId,
|
||||
final MgmtDistributionSetAssigment dsId) {
|
||||
|
||||
findTargetWithExceptionIfNotFound(targetId);
|
||||
final ActionType type = (dsId.getType() != null) ? MgmtRestModelMapper.convertActionType(dsId.getType())
|
||||
: ActionType.FORCED;
|
||||
final Iterator<Target> changed = this.deploymentManagement
|
||||
.assignDistributionSet(dsId.getId(), type, dsId.getForcetime(), targetId).getAssignedEntity()
|
||||
.iterator();
|
||||
if (changed.hasNext()) {
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
LOG.error("Target update (ds {} assigment to target {}) failed! Returnd target list is empty.", dsId.getId(),
|
||||
targetId);
|
||||
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtDistributionSet> getInstalledDistributionSet(final String targetId) {
|
||||
final Target findTarget = findTargetWithExceptionIfNotFound(targetId);
|
||||
final MgmtDistributionSet distributionSetRest = MgmtDistributionSetMapper
|
||||
.toResponse(findTarget.getTargetInfo().getInstalledDistributionSet());
|
||||
final HttpStatus retStatus;
|
||||
if (distributionSetRest == null) {
|
||||
retStatus = HttpStatus.NO_CONTENT;
|
||||
} else {
|
||||
retStatus = HttpStatus.OK;
|
||||
}
|
||||
return new ResponseEntity<>(distributionSetRest, retStatus);
|
||||
}
|
||||
|
||||
private Target findTargetWithExceptionIfNotFound(final String targetId) {
|
||||
final Target findTarget = this.targetManagement.findTargetByControllerID(targetId);
|
||||
if (findTarget == null) {
|
||||
throw new EntityNotFoundException("Target with Id {" + targetId + "} does not exist");
|
||||
}
|
||||
return findTarget;
|
||||
}
|
||||
|
||||
private Action findActionWithExceptionIfNotFound(final Long actionId) {
|
||||
final Action findAction = this.deploymentManagement.findAction(actionId);
|
||||
if (findAction == null) {
|
||||
throw new EntityNotFoundException("Action with Id {" + actionId + "} does not exist");
|
||||
}
|
||||
return findAction;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* 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 java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.PagedList;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtAssignedTargetRequestBody;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTag;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTagRequestBodyPut;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTargetTagAssigmentResult;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetTagRestApi;
|
||||
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
|
||||
import org.eclipse.hawkbit.repository.TagFields;
|
||||
import org.eclipse.hawkbit.repository.TagManagement;
|
||||
import org.eclipse.hawkbit.repository.TargetManagement;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.repository.model.TargetTag;
|
||||
import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult;
|
||||
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
|
||||
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.Pageable;
|
||||
import org.springframework.data.domain.Slice;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* REST Resource handling for {@link Tag} CRUD operations.
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(MgmtTargetTagResource.class);
|
||||
|
||||
@Autowired
|
||||
private TagManagement tagManagement;
|
||||
|
||||
@Autowired
|
||||
private TargetManagement targetManagement;
|
||||
|
||||
@Override
|
||||
public ResponseEntity<PagedList<MgmtTag>> getTargetTags(final int pagingOffsetParam, final int pagingLimitParam,
|
||||
final String sortParam, 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);
|
||||
final Slice<TargetTag> findTargetsAll;
|
||||
final Long countTargetsAll;
|
||||
if (rsqlParam == null) {
|
||||
findTargetsAll = this.tagManagement.findAllTargetTags(pageable);
|
||||
countTargetsAll = this.tagManagement.countTargetTags();
|
||||
|
||||
} else {
|
||||
final Page<TargetTag> findTargetPage = this.tagManagement
|
||||
.findAllTargetTags(RSQLUtility.parse(rsqlParam, TagFields.class), pageable);
|
||||
countTargetsAll = findTargetPage.getTotalElements();
|
||||
findTargetsAll = findTargetPage;
|
||||
|
||||
}
|
||||
|
||||
final List<MgmtTag> rest = MgmtTagMapper.toResponse(findTargetsAll.getContent());
|
||||
return new ResponseEntity<>(new PagedList<>(rest, countTargetsAll), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtTag> getTargetTag(final Long targetTagId) {
|
||||
final TargetTag tag = findTargetTagById(targetTagId);
|
||||
return new ResponseEntity<>(MgmtTagMapper.toResponse(tag), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MgmtTag>> createTargetTags(@RequestBody final List<MgmtTagRequestBodyPut> tags) {
|
||||
LOG.debug("creating {} target tags", tags.size());
|
||||
final List<TargetTag> createdTargetTags = this.tagManagement
|
||||
.createTargetTags(MgmtTagMapper.mapTargeTagFromRequest(tags));
|
||||
return new ResponseEntity<>(MgmtTagMapper.toResponse(createdTargetTags), HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtTag> updateTagretTag(final Long targetTagId, final MgmtTagRequestBodyPut restTargetTagRest) {
|
||||
LOG.debug("update {} target tag", restTargetTagRest);
|
||||
|
||||
final TargetTag targetTag = findTargetTagById(targetTagId);
|
||||
MgmtTagMapper.updateTag(restTargetTagRest, targetTag);
|
||||
final TargetTag updateTargetTag = this.tagManagement.updateTargetTag(targetTag);
|
||||
|
||||
LOG.debug("target tag updated");
|
||||
|
||||
return new ResponseEntity<>(MgmtTagMapper.toResponse(updateTargetTag), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> deleteTargetTag(final Long targetTagId) {
|
||||
LOG.debug("Delete {} target tag", targetTagId);
|
||||
final TargetTag targetTag = findTargetTagById(targetTagId);
|
||||
|
||||
this.tagManagement.deleteTargetTag(targetTag.getName());
|
||||
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MgmtTarget>> getAssignedTargets(final Long targetTagId) {
|
||||
final TargetTag targetTag = findTargetTagById(targetTagId);
|
||||
return new ResponseEntity<>(MgmtTargetMapper.toResponseWithLinksAndPollStatus(targetTag.getAssignedToTargets()),
|
||||
HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<MgmtTargetTagAssigmentResult> toggleTagAssignment(final Long targetTagId,
|
||||
final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) {
|
||||
LOG.debug("Toggle Target assignment {} for target tag {}", assignedTargetRequestBodies.size(), targetTagId);
|
||||
|
||||
final TargetTag targetTag = findTargetTagById(targetTagId);
|
||||
final TargetTagAssignmentResult assigmentResult = this.targetManagement
|
||||
.toggleTagAssignment(findTargetControllerIds(assignedTargetRequestBodies), targetTag.getName());
|
||||
|
||||
final MgmtTargetTagAssigmentResult tagAssigmentResultRest = new MgmtTargetTagAssigmentResult();
|
||||
tagAssigmentResultRest.setAssignedTargets(MgmtTargetMapper.toResponse(assigmentResult.getAssignedEntity()));
|
||||
tagAssigmentResultRest.setUnassignedTargets(MgmtTargetMapper.toResponse(assigmentResult.getUnassignedEntity()));
|
||||
return new ResponseEntity<>(tagAssigmentResultRest, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<List<MgmtTarget>> assignTargets(final Long targetTagId,
|
||||
final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) {
|
||||
LOG.debug("Assign Targets {} for target tag {}", assignedTargetRequestBodies.size(), targetTagId);
|
||||
final TargetTag targetTag = findTargetTagById(targetTagId);
|
||||
final List<Target> assignedTarget = this.targetManagement
|
||||
.assignTag(findTargetControllerIds(assignedTargetRequestBodies), targetTag);
|
||||
return new ResponseEntity<>(MgmtTargetMapper.toResponseWithLinksAndPollStatus(assignedTarget), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> unassignTargets(final Long targetTagId) {
|
||||
LOG.debug("Unassign all Targets for target tag {}", targetTagId);
|
||||
final TargetTag targetTag = findTargetTagById(targetTagId);
|
||||
if (targetTag.getAssignedToTargets() == null) {
|
||||
LOG.debug("No assigned targets found");
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
this.targetManagement.unAssignAllTargetsByTag(targetTag);
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<Void> unassignTarget(final Long targetTagId, final String controllerId) {
|
||||
LOG.debug("Unassign target {} for target tag {}", controllerId, targetTagId);
|
||||
final TargetTag targetTag = findTargetTagById(targetTagId);
|
||||
this.targetManagement.unAssignTag(controllerId, targetTag);
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
private TargetTag findTargetTagById(final Long targetTagId) {
|
||||
final TargetTag tag = this.tagManagement.findTargetTagById(targetTagId);
|
||||
if (tag == null) {
|
||||
throw new EntityNotFoundException("Target Tag with Id {" + targetTagId + "} does not exist");
|
||||
}
|
||||
return tag;
|
||||
}
|
||||
|
||||
private List<String> findTargetControllerIds(final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) {
|
||||
return assignedTargetRequestBodies.stream().map(request -> request.getControllerId())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* 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 org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
|
||||
import org.eclipse.hawkbit.repository.ActionFields;
|
||||
import org.eclipse.hawkbit.repository.ActionStatusFields;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetFields;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetMetadataFields;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetTypeFields;
|
||||
import org.eclipse.hawkbit.repository.RolloutFields;
|
||||
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.TargetFields;
|
||||
import org.eclipse.hawkbit.rest.util.SortUtility;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
|
||||
/**
|
||||
* Utility class for for paged body generation.
|
||||
*
|
||||
*/
|
||||
public final class PagingUtility {
|
||||
/*
|
||||
* utility constructor private.
|
||||
*/
|
||||
private PagingUtility() {
|
||||
}
|
||||
|
||||
static int sanitizeOffsetParam(final int offset) {
|
||||
if (offset < 0) {
|
||||
return Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET);
|
||||
}
|
||||
return offset;
|
||||
}
|
||||
|
||||
static int sanitizePageLimitParam(final int pageLimit) {
|
||||
if (pageLimit < 1) {
|
||||
return Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT);
|
||||
} else if (pageLimit > MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT) {
|
||||
return MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT;
|
||||
}
|
||||
return pageLimit;
|
||||
}
|
||||
|
||||
static Sort sanitizeTargetSortParam(final String sortParam) {
|
||||
if (sortParam == null) {
|
||||
// default
|
||||
return new Sort(Direction.ASC, TargetFields.NAME.getFieldName());
|
||||
}
|
||||
return new Sort(SortUtility.parse(TargetFields.class, sortParam));
|
||||
}
|
||||
|
||||
static Sort sanitizeSoftwareModuleSortParam(final String sortParam) {
|
||||
if (sortParam == null) {
|
||||
// default
|
||||
return new Sort(Direction.ASC, SoftwareModuleFields.NAME.getFieldName());
|
||||
}
|
||||
return new Sort(SortUtility.parse(SoftwareModuleFields.class, sortParam));
|
||||
}
|
||||
|
||||
static Sort sanitizeSoftwareModuleTypeSortParam(final String sortParam) {
|
||||
if (sortParam == null) {
|
||||
// default
|
||||
return new Sort(Direction.ASC, SoftwareModuleTypeFields.NAME.getFieldName());
|
||||
}
|
||||
return new Sort(SortUtility.parse(SoftwareModuleTypeFields.class, sortParam));
|
||||
}
|
||||
|
||||
static Sort sanitizeDistributionSetSortParam(final String sortParam) {
|
||||
if (sortParam == null) {
|
||||
// default
|
||||
return new Sort(Direction.ASC, DistributionSetFields.NAME.getFieldName());
|
||||
}
|
||||
return new Sort(SortUtility.parse(DistributionSetFields.class, sortParam));
|
||||
}
|
||||
|
||||
static Sort sanitizeDistributionSetTypeSortParam(final String sortParam) {
|
||||
if (sortParam == null) {
|
||||
// default
|
||||
return new Sort(Direction.ASC, DistributionSetTypeFields.NAME.getFieldName());
|
||||
}
|
||||
return new Sort(SortUtility.parse(DistributionSetTypeFields.class, sortParam));
|
||||
}
|
||||
|
||||
static Sort sanitizeActionSortParam(final String sortParam) {
|
||||
if (sortParam == null) {
|
||||
// default sort is DESC in case of action to match behavior
|
||||
// of management UI (last entry on top)
|
||||
return new Sort(Direction.DESC, ActionFields.ID.getFieldName());
|
||||
}
|
||||
return new Sort(SortUtility.parse(ActionFields.class, sortParam));
|
||||
}
|
||||
|
||||
static Sort sanitizeActionStatusSortParam(final String sortParam) {
|
||||
if (sortParam == null) {
|
||||
// default sort is DESC in case of action status to match behavior
|
||||
// of management UI (last entry on top)
|
||||
return new Sort(Direction.DESC, ActionStatusFields.ID.getFieldName());
|
||||
}
|
||||
return new Sort(SortUtility.parse(ActionStatusFields.class, sortParam));
|
||||
}
|
||||
|
||||
static Sort sanitizeDistributionSetMetadataSortParam(final String sortParam) {
|
||||
if (sortParam == null) {
|
||||
// default
|
||||
return new Sort(Direction.ASC, DistributionSetMetadataFields.KEY.getFieldName());
|
||||
}
|
||||
return new Sort(SortUtility.parse(DistributionSetMetadataFields.class, sortParam));
|
||||
}
|
||||
|
||||
static Sort sanitizeSoftwareModuleMetadataSortParam(final String sortParam) {
|
||||
if (sortParam == null) {
|
||||
// default
|
||||
return new Sort(Direction.ASC, SoftwareModuleMetadataFields.KEY.getFieldName());
|
||||
}
|
||||
return new Sort(SortUtility.parse(SoftwareModuleMetadataFields.class, sortParam));
|
||||
}
|
||||
|
||||
static Sort sanitizeRolloutSortParam(final String sortParam) {
|
||||
if (sortParam == null) {
|
||||
// default
|
||||
return new Sort(Direction.ASC, RolloutFields.NAME.getFieldName());
|
||||
}
|
||||
return new Sort(SortUtility.parse(RolloutFields.class, sortParam));
|
||||
}
|
||||
|
||||
static Sort sanitizeRolloutGroupSortParam(final String sortParam) {
|
||||
if (sortParam == null) {
|
||||
// default
|
||||
return new Sort(Direction.ASC, RolloutGroupFields.NAME.getFieldName());
|
||||
}
|
||||
return new Sort(SortUtility.parse(RolloutGroupFields.class, sortParam));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
/**
|
||||
* 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 java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetType;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupConditions;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
/**
|
||||
* Builder class for building certain json strings.
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
public abstract class JsonBuilder {
|
||||
|
||||
public static String softwareModules(final List<SoftwareModule> modules) throws JSONException {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append("[");
|
||||
int i = 0;
|
||||
for (final SoftwareModule module : modules) {
|
||||
try {
|
||||
builder.append(new JSONObject().put("name", module.getName())
|
||||
.put("description", module.getDescription()).put("type", module.getType().getKey())
|
||||
.put("id", Long.MAX_VALUE).put("vendor", module.getVendor())
|
||||
.put("version", module.getVersion()).put("createdAt", "0").put("updatedAt", "0")
|
||||
.put("createdBy", "fghdfkjghdfkjh").put("updatedBy", "fghdfkjghdfkjh").toString());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (++i < modules.size()) {
|
||||
builder.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
builder.append("]");
|
||||
|
||||
return builder.toString();
|
||||
|
||||
}
|
||||
|
||||
public static String softwareModulesCreatableFieldsOnly(final List<SoftwareModule> modules) throws JSONException {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append("[");
|
||||
int i = 0;
|
||||
for (final SoftwareModule module : modules) {
|
||||
try {
|
||||
builder.append(new JSONObject().put("name", module.getName())
|
||||
.put("description", module.getDescription()).put("type", module.getType().getKey())
|
||||
.put("vendor", module.getVendor()).put("version", module.getVersion()).toString());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (++i < modules.size()) {
|
||||
builder.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
builder.append("]");
|
||||
|
||||
return builder.toString();
|
||||
|
||||
}
|
||||
|
||||
public static String softwareModuleUpdatableFieldsOnly(final SoftwareModule module) throws JSONException {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append(new JSONObject().put("description", module.getDescription()).put("vendor", module.getVendor())
|
||||
.toString());
|
||||
|
||||
return builder.toString();
|
||||
|
||||
}
|
||||
|
||||
public static String softwareModuleTypes(final List<SoftwareModuleType> types) throws JSONException {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append("[");
|
||||
int i = 0;
|
||||
for (final SoftwareModuleType module : types) {
|
||||
try {
|
||||
builder.append(new JSONObject().put("name", module.getName())
|
||||
.put("description", module.getDescription()).put("id", Long.MAX_VALUE)
|
||||
.put("key", module.getKey()).put("maxAssignments", module.getMaxAssignments())
|
||||
.put("createdAt", "0").put("updatedAt", "0").put("createdBy", "fghdfkjghdfkjh")
|
||||
.put("updatedBy", "fghdfkjghdfkjh").toString());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (++i < types.size()) {
|
||||
builder.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
builder.append("]");
|
||||
|
||||
return builder.toString();
|
||||
|
||||
}
|
||||
|
||||
public static String softwareModuleTypesCreatableFieldsOnly(final List<SoftwareModuleType> types)
|
||||
throws JSONException {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append("[");
|
||||
int i = 0;
|
||||
for (final SoftwareModuleType module : types) {
|
||||
try {
|
||||
builder.append(new JSONObject().put("name", module.getName())
|
||||
.put("description", module.getDescription()).put("key", module.getKey())
|
||||
.put("maxAssignments", module.getMaxAssignments()).toString());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (++i < types.size()) {
|
||||
builder.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
builder.append("]");
|
||||
|
||||
return builder.toString();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* builds a json string for the feedback for the execution "proceeding".
|
||||
*
|
||||
* @param id
|
||||
* of the Action feedback refers to
|
||||
* @return the built string
|
||||
* @throws JSONException
|
||||
*/
|
||||
public static String deploymentActionInProgressFeedback(final String id) throws JSONException {
|
||||
return deploymentActionFeedback(id, "proceeding");
|
||||
}
|
||||
|
||||
/**
|
||||
* builds a certain json string for a action feedback.
|
||||
*
|
||||
* @param id
|
||||
* of the action the feedback refers to
|
||||
* @param execution
|
||||
* see ExecutionStatus
|
||||
* @return the build json string
|
||||
* @throws JSONException
|
||||
*/
|
||||
public static String deploymentActionFeedback(final String id, final String execution) throws JSONException {
|
||||
return deploymentActionFeedback(id, execution, "none", RandomStringUtils.randomAscii(1000));
|
||||
|
||||
}
|
||||
|
||||
public static String deploymentActionFeedback(final String id, final String execution, final String message)
|
||||
throws JSONException {
|
||||
return deploymentActionFeedback(id, execution, "none", message);
|
||||
|
||||
}
|
||||
|
||||
public static String deploymentActionFeedback(final String id, final String execution, final String finished,
|
||||
final String message) throws JSONException {
|
||||
final List<String> messages = new ArrayList<String>();
|
||||
messages.add(message);
|
||||
|
||||
return new JSONObject()
|
||||
.put("id", id)
|
||||
.put("time", "20140511T121314")
|
||||
.put("status",
|
||||
new JSONObject()
|
||||
.put("execution", execution)
|
||||
.put("result",
|
||||
new JSONObject().put("finished", finished).put("progress",
|
||||
new JSONObject().put("cnt", 2).put("of", 5))).put("details", messages))
|
||||
.toString();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param types
|
||||
* @return
|
||||
*/
|
||||
public static String distributionSetTypes(final List<DistributionSetType> types) {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append("[");
|
||||
int i = 0;
|
||||
for (final DistributionSetType module : types) {
|
||||
|
||||
try {
|
||||
|
||||
final JSONArray osmTypes = new JSONArray();
|
||||
module.getOptionalModuleTypes().forEach(smt -> osmTypes.put(new JSONObject().put("id", smt.getId())));
|
||||
|
||||
final JSONArray msmTypes = new JSONArray();
|
||||
module.getMandatoryModuleTypes().forEach(smt -> msmTypes.put(new JSONObject().put("id", smt.getId())));
|
||||
|
||||
builder.append(new JSONObject().put("name", module.getName())
|
||||
.put("description", module.getDescription()).put("id", Long.MAX_VALUE)
|
||||
.put("key", module.getKey()).put("createdAt", "0").put("updatedAt", "0")
|
||||
.put("createdBy", "fghdfkjghdfkjh").put("optionalmodules", osmTypes)
|
||||
.put("mandatorymodules", msmTypes).put("updatedBy", "fghdfkjghdfkjh").toString());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (++i < types.size()) {
|
||||
builder.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
builder.append("]");
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public static String distributionSetTypesCreateValidFieldsOnly(final List<DistributionSetType> types) {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append("[");
|
||||
int i = 0;
|
||||
for (final DistributionSetType module : types) {
|
||||
|
||||
try {
|
||||
|
||||
final JSONArray osmTypes = new JSONArray();
|
||||
module.getOptionalModuleTypes().forEach(smt -> osmTypes.put(new JSONObject().put("id", smt.getId())));
|
||||
|
||||
final JSONArray msmTypes = new JSONArray();
|
||||
module.getMandatoryModuleTypes().forEach(smt -> msmTypes.put(new JSONObject().put("id", smt.getId())));
|
||||
|
||||
builder.append(new JSONObject().put("name", module.getName())
|
||||
.put("description", module.getDescription()).put("key", module.getKey())
|
||||
.put("optionalmodules", osmTypes).put("mandatorymodules", msmTypes).toString());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (++i < types.size()) {
|
||||
builder.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
builder.append("]");
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public static String distributionSets(final List<DistributionSet> sets) throws JSONException {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append("[");
|
||||
int i = 0;
|
||||
for (final DistributionSet set : sets) {
|
||||
try {
|
||||
builder.append(distributionSet(set));
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (++i < sets.size()) {
|
||||
builder.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
builder.append("]");
|
||||
|
||||
return builder.toString();
|
||||
|
||||
}
|
||||
|
||||
public static String distributionSetsCreateValidFieldsOnly(final List<DistributionSet> sets) throws JSONException {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append("[");
|
||||
int i = 0;
|
||||
for (final DistributionSet set : sets) {
|
||||
try {
|
||||
builder.append(distributionSetCreateValidFieldsOnly(set));
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (++i < sets.size()) {
|
||||
builder.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
builder.append("]");
|
||||
|
||||
return builder.toString();
|
||||
|
||||
}
|
||||
|
||||
public static String distributionSetCreateValidFieldsOnly(final DistributionSet set) throws JSONException {
|
||||
|
||||
final List<JSONObject> modules = set.getModules().stream().map(module -> {
|
||||
try {
|
||||
return new JSONObject().put("id", module.getId());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}).collect(Collectors.toList());
|
||||
|
||||
return new JSONObject().put("name", set.getName()).put("description", set.getDescription())
|
||||
.put("type", set.getType() == null ? null : set.getType().getKey()).put("version", set.getVersion())
|
||||
.put("requiredMigrationStep", set.isRequiredMigrationStep()).put("modules", modules).toString();
|
||||
|
||||
}
|
||||
|
||||
public static String distributionSetUpdateValidFieldsOnly(final DistributionSet set) throws JSONException {
|
||||
|
||||
final List<JSONObject> modules = set.getModules().stream().map(module -> {
|
||||
try {
|
||||
return new JSONObject().put("id", module.getId());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}).collect(Collectors.toList());
|
||||
|
||||
return new JSONObject().put("name", set.getName()).put("description", set.getDescription())
|
||||
.put("version", set.getVersion()).toString();
|
||||
|
||||
}
|
||||
|
||||
public static String distributionSet(final DistributionSet set) throws JSONException {
|
||||
|
||||
final List<JSONObject> modules = set.getModules().stream().map(module -> {
|
||||
try {
|
||||
return new JSONObject().put("id", module.getId());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}).collect(Collectors.toList());
|
||||
|
||||
return new JSONObject().put("name", set.getName()).put("description", set.getDescription())
|
||||
.put("type", set.getType() == null ? null : set.getType().getKey()).put("id", Long.MAX_VALUE)
|
||||
.put("version", set.getVersion()).put("createdAt", "0").put("updatedAt", "0")
|
||||
.put("createdBy", "fghdfkjghdfkjh").put("updatedBy", "fghdfkjghdfkjh")
|
||||
.put("requiredMigrationStep", set.isRequiredMigrationStep()).put("modules", modules).toString();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param targets
|
||||
* @return
|
||||
*/
|
||||
public static String targets(final List<Target> targets) {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append("[");
|
||||
int i = 0;
|
||||
for (final Target target : targets) {
|
||||
try {
|
||||
builder.append(new JSONObject().put("controllerId", target.getControllerId())
|
||||
.put("description", target.getDescription()).put("name", target.getName())
|
||||
.put("createdAt", "0").put("updatedAt", "0").put("createdBy", "fghdfkjghdfkjh")
|
||||
.put("updatedBy", "fghdfkjghdfkjh").toString());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (++i < targets.size()) {
|
||||
builder.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
builder.append("]");
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public static String rollout(final String name, final String description, final int groupSize,
|
||||
final long distributionSetId, final String targetFilterQuery, final RolloutGroupConditions conditions) {
|
||||
final JSONObject json = new JSONObject();
|
||||
json.put("name", name);
|
||||
json.put("description", description);
|
||||
json.put("amountGroups", groupSize);
|
||||
json.put("distributionSetId", distributionSetId);
|
||||
json.put("targetFilterQuery", targetFilterQuery);
|
||||
|
||||
if (conditions != null) {
|
||||
final JSONObject successCondition = new JSONObject();
|
||||
json.put("successCondition", successCondition);
|
||||
successCondition.put("condition", conditions.getSuccessCondition().toString());
|
||||
successCondition.put("expression", conditions.getSuccessConditionExp().toString());
|
||||
|
||||
final JSONObject successAction = new JSONObject();
|
||||
json.put("successAction", successAction);
|
||||
successAction.put("action", conditions.getSuccessAction().toString());
|
||||
successAction.put("expression", conditions.getSuccessActionExp().toString());
|
||||
|
||||
final JSONObject errorCondition = new JSONObject();
|
||||
json.put("errorCondition", errorCondition);
|
||||
errorCondition.put("condition", conditions.getErrorCondition().toString());
|
||||
errorCondition.put("expression", conditions.getErrorConditionExp().toString());
|
||||
|
||||
final JSONObject errorAction = new JSONObject();
|
||||
json.put("errorAction", errorAction);
|
||||
errorAction.put("action", conditions.getErrorAction().toString());
|
||||
errorAction.put("expression", conditions.getErrorActionExp().toString());
|
||||
}
|
||||
|
||||
return json.toString();
|
||||
}
|
||||
|
||||
public static String cancelActionFeedback(final String id, final String execution) throws JSONException {
|
||||
return cancelActionFeedback(id, execution, RandomStringUtils.randomAscii(1000));
|
||||
|
||||
}
|
||||
|
||||
public static String cancelActionFeedback(final String id, final String execution, final String message)
|
||||
throws JSONException {
|
||||
final List<String> messages = new ArrayList<String>();
|
||||
messages.add(message);
|
||||
return new JSONObject()
|
||||
.put("id", id)
|
||||
.put("time", "20140511T121314")
|
||||
.put("status",
|
||||
new JSONObject().put("execution", execution)
|
||||
.put("result", new JSONObject().put("finished", "success")).put("details", messages))
|
||||
.toString();
|
||||
|
||||
}
|
||||
|
||||
public static String configData(final String id, final Map<String, String> attributes, final String execution)
|
||||
throws JSONException {
|
||||
return new JSONObject()
|
||||
.put("id", id)
|
||||
.put("time", "20140511T121314")
|
||||
.put("status",
|
||||
new JSONObject().put("execution", execution)
|
||||
.put("result", new JSONObject().put("finished", "success"))
|
||||
.put("details", new ArrayList<String>())).put("data", attributes).toString();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,920 @@
|
||||
/**
|
||||
* 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.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.Assert.fail;
|
||||
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.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.WithUser;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
|
||||
import org.eclipse.hawkbit.repository.ActionRepository;
|
||||
import org.eclipse.hawkbit.repository.ControllerManagement;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetManagement;
|
||||
import org.eclipse.hawkbit.repository.SoftwareManagement;
|
||||
import org.eclipse.hawkbit.repository.TargetManagement;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
|
||||
import org.eclipse.hawkbit.repository.model.Action;
|
||||
import org.eclipse.hawkbit.repository.model.Action.Status;
|
||||
import org.eclipse.hawkbit.repository.model.ActionStatus;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
|
||||
import org.eclipse.hawkbit.repository.model.DsMetadataCompositeKey;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.annotation.Description;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
@Features("Component Tests - Management API")
|
||||
@Stories("Distribution Set Resource")
|
||||
public class MgmtDistributionSetResourceTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("This test verifies the call of all Software Modules that are assiged to a Distribution Set through the RESTful API.")
|
||||
public void getSoftwaremodules() throws Exception {
|
||||
// Create DistributionSet with three software modules
|
||||
final DistributionSet set = TestDataUtil.generateDistributionSet("SMTest", softwareManagement,
|
||||
distributionSetManagement);
|
||||
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.size", equalTo(set.getModules().size())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("This test verifies the deletion of a assigned Software Module of a Distribution Set can not be achieved when that Distribution Set has been assigned or installed to a target.")
|
||||
public void deleteFailureWhenDistributionSetInUse() throws Exception {
|
||||
|
||||
// create DisSet
|
||||
final DistributionSet disSet = TestDataUtil.generateDistributionSetWithNoSoftwareModules("Eris", "560a",
|
||||
distributionSetManagement);
|
||||
final List<Long> smIDs = new ArrayList<Long>();
|
||||
SoftwareModule sm = new SoftwareModule(osType, "Dysnomia ", "15,772", null, null);
|
||||
sm = softwareManagement.createSoftwareModule(sm);
|
||||
smIDs.add(sm.getId());
|
||||
final JSONArray smList = new JSONArray();
|
||||
for (final Long smID : smIDs) {
|
||||
smList.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(smList.toString())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// create targets and assign DisSet to target
|
||||
final String[] knownTargetIds = new String[] { "1", "2" };
|
||||
final JSONArray list = new JSONArray();
|
||||
for (final String targetId : knownTargetIds) {
|
||||
targetManagement.createTarget(new Target(targetId));
|
||||
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
|
||||
}
|
||||
deploymentManagement.assignDistributionSet(disSet.getId(), knownTargetIds[0]);
|
||||
mvc.perform(
|
||||
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(list.toString()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.assigned", equalTo(knownTargetIds.length - 1)))
|
||||
.andExpect(jsonPath("$.alreadyAssigned", equalTo(1)))
|
||||
.andExpect(jsonPath("$.total", equalTo(knownTargetIds.length)));
|
||||
|
||||
// try to delete the Software Module from DistSet that has been assigned
|
||||
// to the target.
|
||||
mvc.perform(delete(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM/"
|
||||
+ smIDs.get(0)).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isLocked())
|
||||
.andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entitiylocked")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("This test verifies that the assignment of a Software Module to a Distribution Set can not be achieved when that Distribution Set has been assigned or installed to a target.")
|
||||
public void assignmentFailureWhenAssigningToUsedDistributionSet() throws Exception {
|
||||
|
||||
// create DisSet
|
||||
final DistributionSet disSet = TestDataUtil.generateDistributionSetWithNoSoftwareModules("Mars", "686,980",
|
||||
distributionSetManagement);
|
||||
final List<Long> smIDs = new ArrayList<>();
|
||||
SoftwareModule sm = new SoftwareModule(osType, "Phobos", "0,3189", null, null);
|
||||
sm = softwareManagement.createSoftwareModule(sm);
|
||||
smIDs.add(sm.getId());
|
||||
final JSONArray smList = new JSONArray();
|
||||
for (final Long smID : smIDs) {
|
||||
smList.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(smList.toString())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// create Targets
|
||||
final String[] knownTargetIds = new String[] { "1", "2" };
|
||||
final JSONArray list = new JSONArray();
|
||||
for (final String targetId : knownTargetIds) {
|
||||
targetManagement.createTarget(new Target(targetId));
|
||||
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
|
||||
}
|
||||
// assign DisSet to target and test assignment
|
||||
deploymentManagement.assignDistributionSet(disSet.getId(), knownTargetIds[0]);
|
||||
mvc.perform(
|
||||
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(list.toString()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.assigned", equalTo(knownTargetIds.length - 1)))
|
||||
.andExpect(jsonPath("$.alreadyAssigned", equalTo(1)))
|
||||
.andExpect(jsonPath("$.total", equalTo(knownTargetIds.length)));
|
||||
|
||||
// Create another SM and post assignment
|
||||
final List<Long> smID2s = new ArrayList<Long>();
|
||||
SoftwareModule sm2 = new SoftwareModule(appType, "Deimos", "1,262", null, null);
|
||||
sm2 = softwareManagement.createSoftwareModule(sm2);
|
||||
smID2s.add(sm2.getId());
|
||||
final JSONArray smList2 = new JSONArray();
|
||||
for (final Long smID : smID2s) {
|
||||
smList2.put(new JSONObject().put("id", Long.valueOf(smID)));
|
||||
}
|
||||
|
||||
mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(smList2.toString()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isLocked())
|
||||
.andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entitiylocked")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("This test verifies the assignment of Software Modules to a Distribution Set through the RESTful API.")
|
||||
public void assignSoftwaremoduleToDistributionSet() throws Exception {
|
||||
|
||||
// create DisSet
|
||||
final DistributionSet disSet = TestDataUtil.generateDistributionSetWithNoSoftwareModules("Jupiter", "398,88",
|
||||
distributionSetManagement);
|
||||
// Test if size is 0
|
||||
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.size", equalTo(disSet.getModules().size())));
|
||||
// create Software Modules
|
||||
final List<Long> smIDs = new ArrayList<Long>();
|
||||
SoftwareModule sm = new SoftwareModule(osType, "Europa", "3,551", null, null);
|
||||
sm = softwareManagement.createSoftwareModule(sm);
|
||||
smIDs.add(sm.getId());
|
||||
SoftwareModule sm2 = new SoftwareModule(appType, "Ganymed", "7,155", null, null);
|
||||
sm2 = softwareManagement.createSoftwareModule(sm2);
|
||||
smIDs.add(sm2.getId());
|
||||
SoftwareModule sm3 = new SoftwareModule(runtimeType, "Kallisto", "16,689", null, null);
|
||||
sm3 = softwareManagement.createSoftwareModule(sm3);
|
||||
smIDs.add(sm3.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());
|
||||
// Test if size is 3
|
||||
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.size", equalTo(smIDs.size())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("This test verifies the removal of Software Modules of a Distribution Set through the RESTful API.")
|
||||
public void unassignSoftwaremoduleFromDistributionSet() throws Exception {
|
||||
|
||||
// Create DistributionSet with three software modules
|
||||
final DistributionSet set = TestDataUtil.generateDistributionSet("Venus", softwareManagement,
|
||||
distributionSetManagement);
|
||||
int amountOfSM = set.getModules().size();
|
||||
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.size", equalTo(amountOfSM)));
|
||||
// test the removal of all software modules one by one
|
||||
for (final Iterator<SoftwareModule> iter = set.getModules().iterator(); iter.hasNext();) {
|
||||
final Long smId = iter.next().getId();
|
||||
mvc.perform(delete(
|
||||
MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM/" + smId))
|
||||
.andExpect(status().isOk());
|
||||
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.size", equalTo(--amountOfSM)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that multi target assignment through API is reflected by the repository.")
|
||||
public void assignMultipleTargetsToDistributionSet() throws Exception {
|
||||
// prepare distribution set
|
||||
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
|
||||
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
|
||||
// prepare targets
|
||||
final String[] knownTargetIds = new String[] { "1", "2", "3", "4", "5" };
|
||||
final JSONArray list = new JSONArray();
|
||||
for (final String targetId : knownTargetIds) {
|
||||
targetManagement.createTarget(new Target(targetId));
|
||||
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
|
||||
}
|
||||
// assign already one target to DS
|
||||
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetIds[0]);
|
||||
|
||||
mvc.perform(post(
|
||||
MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(list.toString()))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.assigned", equalTo(knownTargetIds.length - 1)))
|
||||
.andExpect(jsonPath("$.alreadyAssigned", equalTo(1)))
|
||||
.andExpect(jsonPath("$.total", equalTo(knownTargetIds.length)));
|
||||
|
||||
assertThat(targetManagement.findTargetByAssignedDistributionSet(createdDs.getId(), pageReq).getContent())
|
||||
.as("Five targets in repository have DS assigned").hasSize(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that assigned targets of DS are returned as reflected by the repository.")
|
||||
public void getAssignedTargetsOfDistributionSet() throws Exception {
|
||||
// prepare distribution set
|
||||
final String knownTargetId = "knownTargetId1";
|
||||
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
|
||||
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
|
||||
targetManagement.createTarget(new Target(knownTargetId));
|
||||
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetId);
|
||||
|
||||
mvc.perform(get(
|
||||
MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(1)))
|
||||
.andExpect(jsonPath("$.content[0].controllerId", equalTo(knownTargetId)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that assigned targets of DS are returned as persisted in the repository.")
|
||||
public void getAssignedTargetsOfDistributionSetIsEmpty() throws Exception {
|
||||
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
|
||||
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
|
||||
mvc.perform(get(
|
||||
MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(0)))
|
||||
.andExpect(jsonPath("$.total", equalTo(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that installed targets of DS are returned as persisted in the repository.")
|
||||
public void getInstalledTargetsOfDistributionSet() throws Exception {
|
||||
// prepare distribution set
|
||||
final String knownTargetId = "knownTargetId1";
|
||||
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
|
||||
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
|
||||
final Target createTarget = targetManagement.createTarget(new Target(knownTargetId));
|
||||
// create some dummy targets which are not assigned or installed
|
||||
targetManagement.createTarget(new Target("dummy1"));
|
||||
targetManagement.createTarget(new Target("dummy2"));
|
||||
// assign knownTargetId to distribution set
|
||||
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetId);
|
||||
// make it in install state
|
||||
sendUpdateActionStatusToTargets(controllerManagament, targetManagement, actionRepository, createdDs,
|
||||
Lists.newArrayList(createTarget), Status.FINISHED, "some message");
|
||||
|
||||
mvc.perform(get(
|
||||
MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/installedTargets"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(1)))
|
||||
.andExpect(jsonPath("$.content[0].controllerId", equalTo(knownTargetId)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that DS in repository are listed with proper paging properties.")
|
||||
public void getDistributionSetsWithoutAddtionalRequestParameters() throws Exception {
|
||||
final int sets = 5;
|
||||
createDistributionSetsAlphabetical(sets);
|
||||
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(sets)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(sets)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(sets)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that DS in repository are listed with proper paging results with paging limit parameter.")
|
||||
public void getDistributionSetsWithPagingLimitRequestParameter() throws Exception {
|
||||
final int sets = 5;
|
||||
final int limitSize = 1;
|
||||
createDistributionSetsAlphabetical(sets);
|
||||
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING)
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(sets)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that DS in repository are listed with proper paging results with paging limit and offset parameter.")
|
||||
public void getDistributionSetsWithPagingLimitAndOffsetRequestParameter() throws Exception {
|
||||
final int sets = 5;
|
||||
final int offsetParam = 2;
|
||||
final int expectedSize = sets - offsetParam;
|
||||
createDistributionSetsAlphabetical(sets);
|
||||
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING)
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(sets)))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(sets)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Ensures that multiple DS requested are listed with expected payload.")
|
||||
public void getDistributionSets() throws Exception {
|
||||
// prepare test data
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
|
||||
|
||||
DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
set.setRequiredMigrationStep(set.isRequiredMigrationStep());
|
||||
set = distributionSetManagement.updateDistributionSet(set);
|
||||
|
||||
set.setVersion("anotherVersion");
|
||||
set = distributionSetManagement.updateDistributionSet(set);
|
||||
|
||||
// load also lazy stuff
|
||||
set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId());
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
|
||||
|
||||
// perform request
|
||||
mvc.perform(get("/rest/v1/distributionsets").accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content.[0]._links.self.href",
|
||||
equalTo("http://localhost/rest/v1/distributionsets/" + set.getId())))
|
||||
.andExpect(jsonPath("$content.[0].id", equalTo(set.getId().intValue())))
|
||||
.andExpect(jsonPath("$content.[0].name", equalTo(set.getName())))
|
||||
.andExpect(jsonPath("$content.[0].requiredMigrationStep", equalTo(set.isRequiredMigrationStep())))
|
||||
.andExpect(jsonPath("$content.[0].description", equalTo(set.getDescription())))
|
||||
.andExpect(jsonPath("$content.[0].type", equalTo(set.getType().getKey())))
|
||||
.andExpect(jsonPath("$content.[0].createdBy", equalTo(set.getCreatedBy())))
|
||||
.andExpect(jsonPath("$content.[0].createdAt", equalTo(set.getCreatedAt())))
|
||||
.andExpect(jsonPath("$content.[0].complete", equalTo(Boolean.TRUE)))
|
||||
.andExpect(jsonPath("$content.[0].lastModifiedBy", equalTo(set.getLastModifiedBy())))
|
||||
.andExpect(jsonPath("$content.[0].lastModifiedAt", equalTo(set.getLastModifiedAt())))
|
||||
.andExpect(jsonPath("$content.[0].version", equalTo(set.getVersion())))
|
||||
.andExpect(jsonPath("$content.[0].modules.[?(@.type==" + runtimeType.getKey() + ")][0].id",
|
||||
equalTo(set.findFirstModuleByType(runtimeType).getId().intValue())))
|
||||
.andExpect(jsonPath("$content.[0].modules.[?(@.type==" + appType.getKey() + ")][0].id",
|
||||
equalTo(set.findFirstModuleByType(appType).getId().intValue())))
|
||||
.andExpect(jsonPath("$content.[0].modules.[?(@.type==" + osType.getKey() + ")][0].id",
|
||||
equalTo(set.findFirstModuleByType(osType).getId().intValue())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Ensures that single DS requested by ID is listed with expected payload.")
|
||||
public void getDistributionSet() throws Exception {
|
||||
final DistributionSet set = createTestDistributionSet(softwareManagement, distributionSetManagement);
|
||||
|
||||
// perform request
|
||||
mvc.perform(get("/rest/v1/distributionsets/{dsId}", set.getId()).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$_links.self.href",
|
||||
equalTo("http://localhost/rest/v1/distributionsets/" + set.getId())))
|
||||
.andExpect(jsonPath("$id", equalTo(set.getId().intValue())))
|
||||
.andExpect(jsonPath("$name", equalTo(set.getName())))
|
||||
.andExpect(jsonPath("$type", equalTo(set.getType().getKey())))
|
||||
.andExpect(jsonPath("$description", equalTo(set.getDescription())))
|
||||
.andExpect(jsonPath("$requiredMigrationStep", equalTo(set.isRequiredMigrationStep())))
|
||||
.andExpect(jsonPath("$createdBy", equalTo(set.getCreatedBy())))
|
||||
.andExpect(jsonPath("$complete", equalTo(Boolean.TRUE)))
|
||||
.andExpect(jsonPath("$createdAt", equalTo(set.getCreatedAt())))
|
||||
.andExpect(jsonPath("$lastModifiedBy", equalTo(set.getLastModifiedBy())))
|
||||
.andExpect(jsonPath("$lastModifiedAt", equalTo(set.getLastModifiedAt())))
|
||||
.andExpect(jsonPath("$version", equalTo(set.getVersion())))
|
||||
.andExpect(jsonPath("$modules.[?(@.type==" + runtimeType.getKey() + ")][0].id",
|
||||
equalTo(set.findFirstModuleByType(runtimeType).getId().intValue())))
|
||||
.andExpect(jsonPath("$modules.[?(@.type==" + appType.getKey() + ")][0].id",
|
||||
equalTo(set.findFirstModuleByType(appType).getId().intValue())))
|
||||
.andExpect(jsonPath("$modules.[?(@.type==" + osType.getKey() + ")][0].id",
|
||||
equalTo(set.findFirstModuleByType(osType).getId().intValue())));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Ensures that multipe DS posted to API are created in the repository.")
|
||||
public void createDistributionSets() throws JSONException, Exception {
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
|
||||
|
||||
final SoftwareModule ah = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, ""));
|
||||
final SoftwareModule jvm = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, ""));
|
||||
final SoftwareModule os = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(osType, "poky", "3.0.2", null, ""));
|
||||
|
||||
DistributionSet one = TestDataUtil.buildDistributionSet("one", "one", standardDsType, os, jvm, ah);
|
||||
DistributionSet two = TestDataUtil.buildDistributionSet("two", "two", standardDsType, os, jvm, ah);
|
||||
DistributionSet three = TestDataUtil.buildDistributionSet("three", "three", standardDsType, os, jvm, ah);
|
||||
three.setRequiredMigrationStep(true);
|
||||
|
||||
final List<DistributionSet> sets = new ArrayList<>();
|
||||
sets.add(one);
|
||||
sets.add(two);
|
||||
sets.add(three);
|
||||
|
||||
final long current = System.currentTimeMillis();
|
||||
|
||||
final MvcResult mvcResult = mvc
|
||||
.perform(post("/rest/v1/distributionsets/").content(JsonBuilder.distributionSets(sets))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("[0]name", equalTo(one.getName())))
|
||||
.andExpect(jsonPath("[0]description", equalTo(one.getDescription())))
|
||||
.andExpect(jsonPath("[0]type", equalTo(standardDsType.getKey())))
|
||||
.andExpect(jsonPath("[0]createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[0]version", equalTo(one.getVersion())))
|
||||
.andExpect(jsonPath("[0]complete", equalTo(Boolean.TRUE)))
|
||||
.andExpect(jsonPath("[0]requiredMigrationStep", equalTo(one.isRequiredMigrationStep())))
|
||||
.andExpect(jsonPath("[0].modules.[?(@.type==" + runtimeType.getKey() + ")][0].id",
|
||||
equalTo(one.findFirstModuleByType(runtimeType).getId().intValue())))
|
||||
.andExpect(jsonPath("[0].modules.[?(@.type==" + appType.getKey() + ")][0].id",
|
||||
equalTo(one.findFirstModuleByType(appType).getId().intValue())))
|
||||
.andExpect(jsonPath("[0].modules.[?(@.type==" + osType.getKey() + ")][0].id",
|
||||
equalTo(one.findFirstModuleByType(osType).getId().intValue())))
|
||||
.andExpect(jsonPath("[1]name", equalTo(two.getName())))
|
||||
.andExpect(jsonPath("[1]description", equalTo(two.getDescription())))
|
||||
.andExpect(jsonPath("[1]complete", equalTo(Boolean.TRUE)))
|
||||
.andExpect(jsonPath("[1]type", equalTo(standardDsType.getKey())))
|
||||
.andExpect(jsonPath("[1]createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[1]version", equalTo(two.getVersion())))
|
||||
.andExpect(jsonPath("[1].modules.[?(@.type==" + runtimeType.getKey() + ")][0].id",
|
||||
equalTo(two.findFirstModuleByType(runtimeType).getId().intValue())))
|
||||
.andExpect(jsonPath("[1].modules.[?(@.type==" + appType.getKey() + ")][0].id",
|
||||
equalTo(two.findFirstModuleByType(appType).getId().intValue())))
|
||||
.andExpect(jsonPath("[1].modules.[?(@.type==" + osType.getKey() + ")][0].id",
|
||||
equalTo(two.findFirstModuleByType(osType).getId().intValue())))
|
||||
.andExpect(jsonPath("[1]requiredMigrationStep", equalTo(two.isRequiredMigrationStep())))
|
||||
.andExpect(jsonPath("[2]name", equalTo(three.getName())))
|
||||
.andExpect(jsonPath("[2]description", equalTo(three.getDescription())))
|
||||
.andExpect(jsonPath("[2]complete", equalTo(Boolean.TRUE)))
|
||||
.andExpect(jsonPath("[2]type", equalTo(standardDsType.getKey())))
|
||||
.andExpect(jsonPath("[2]createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[2]version", equalTo(three.getVersion())))
|
||||
.andExpect(jsonPath("[2].modules.[?(@.type==" + runtimeType.getKey() + ")][0].id",
|
||||
equalTo(three.findFirstModuleByType(runtimeType).getId().intValue())))
|
||||
.andExpect(jsonPath("[2].modules.[?(@.type==" + appType.getKey() + ")][0].id",
|
||||
equalTo(three.findFirstModuleByType(appType).getId().intValue())))
|
||||
.andExpect(jsonPath("[2].modules.[?(@.type==" + osType.getKey() + ")][0].id",
|
||||
equalTo(three.findFirstModuleByType(osType).getId().intValue())))
|
||||
.andExpect(jsonPath("[2]requiredMigrationStep", equalTo(three.isRequiredMigrationStep()))).andReturn();
|
||||
|
||||
one = distributionSetManagement.findDistributionSetByIdWithDetails(
|
||||
distributionSetManagement.findDistributionSetByNameAndVersion("one", "one").getId());
|
||||
two = distributionSetManagement.findDistributionSetByIdWithDetails(
|
||||
distributionSetManagement.findDistributionSetByNameAndVersion("two", "two").getId());
|
||||
three = distributionSetManagement.findDistributionSetByIdWithDetails(
|
||||
distributionSetManagement.findDistributionSetByNameAndVersion("three", "three").getId());
|
||||
|
||||
assertThat(
|
||||
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsets/" + one.getId());
|
||||
assertThat(
|
||||
JsonPath.compile("[0]_links.type.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + one.getType().getId());
|
||||
|
||||
assertThat(JsonPath.compile("[0]id").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo(String.valueOf(one.getId()));
|
||||
assertThat(
|
||||
JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsets/" + two.getId());
|
||||
assertThat(
|
||||
JsonPath.compile("[1]_links.type.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + two.getType().getId());
|
||||
|
||||
assertThat(JsonPath.compile("[1]id").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo(String.valueOf(two.getId()));
|
||||
assertThat(
|
||||
JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsets/" + three.getId());
|
||||
assertThat(
|
||||
JsonPath.compile("[2]_links.type.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + three.getType().getId());
|
||||
|
||||
assertThat(JsonPath.compile("[2]id").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo(String.valueOf(three.getId()));
|
||||
|
||||
// check in database
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(3);
|
||||
assertThat(one.isRequiredMigrationStep()).isEqualTo(false);
|
||||
assertThat(two.isRequiredMigrationStep()).isEqualTo(false);
|
||||
assertThat(three.isRequiredMigrationStep()).isEqualTo(true);
|
||||
|
||||
assertThat(one.getCreatedAt()).isGreaterThanOrEqualTo(current);
|
||||
assertThat(two.getCreatedAt()).isGreaterThanOrEqualTo(current);
|
||||
assertThat(three.getCreatedAt()).isGreaterThanOrEqualTo(current);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that DS deletion request to API is reflected by the repository.")
|
||||
public void deleteUnassignedistributionSet() throws Exception {
|
||||
// prepare test data
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
|
||||
|
||||
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
|
||||
|
||||
// perform request
|
||||
mvc.perform(delete("/rest/v1/distributionsets/{smId}", set.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// check repository content
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).isEmpty();
|
||||
assertThat(distributionSetRepository.findAll()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@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.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
|
||||
|
||||
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
targetManagement.createTarget(new Target("test"));
|
||||
deploymentManagement.assignDistributionSet(set.getId(), "test");
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
|
||||
|
||||
// perform request
|
||||
mvc.perform(delete("/rest/v1/distributionsets/{smId}", set.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// check repository content
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, true, true)).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that DS property update request to API is reflected by the repository.")
|
||||
public void updateDistributionSet() throws Exception {
|
||||
|
||||
// prepare test data
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
|
||||
|
||||
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
|
||||
|
||||
final DistributionSet update = new DistributionSet();
|
||||
update.setVersion("anotherVersion");
|
||||
update.setName(null);
|
||||
update.setType(standardDsType);
|
||||
|
||||
mvc.perform(put("/rest/v1/distributionsets/{dsId}", set.getId()).content(JsonBuilder.distributionSet(update))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true).getContent().get(0)
|
||||
.getVersion()).isEqualTo("anotherVersion");
|
||||
assertThat(
|
||||
distributionSetManagement.findDistributionSetsAll(pageReq, false, true).getContent().get(0).getName())
|
||||
.isEqualTo(set.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the server reacts properly to invalid requests (URI, Media Type, Methods) with correct reponses.")
|
||||
public void invalidRequestsOnDistributionSetsResource() throws Exception {
|
||||
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
final List<DistributionSet> sets = new ArrayList<>();
|
||||
sets.add(set);
|
||||
|
||||
// SM does not exist
|
||||
mvc.perform(get("/rest/v1/distributionsets/12345678")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsets/12345678")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
// bad request - no content
|
||||
mvc.perform(post("/rest/v1/distributionsets").contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
|
||||
|
||||
// bad request - bad content
|
||||
mvc.perform(post("/rest/v1/distributionsets").content("sdfjsdlkjfskdjf".getBytes())
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
// unsupported media type
|
||||
mvc.perform(post("/rest/v1/distributionsets").content(JsonBuilder.distributionSets(sets))
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isUnsupportedMediaType());
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(post("/rest/v1/distributionsets/{smId}", set.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(put("/rest/v1/distributionsets")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsets")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the metadata creation through API is reflected by the repository.")
|
||||
public void createMetadata() throws Exception {
|
||||
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
final String knownKey1 = "knownKey1";
|
||||
final String knownKey2 = "knownKey2";
|
||||
|
||||
final String knownValue1 = "knownValue1";
|
||||
final String knownValue2 = "knownValue2";
|
||||
|
||||
final JSONArray jsonArray = new JSONArray();
|
||||
jsonArray.put(new JSONObject().put("key", knownKey1).put("value", knownValue1));
|
||||
jsonArray.put(new JSONObject().put("key", knownKey2).put("value", knownValue2));
|
||||
|
||||
mvc.perform(post("/rest/v1/distributionsets/{dsId}/metadata", testDS.getId())
|
||||
.contentType(MediaType.APPLICATION_JSON).content(jsonArray.toString()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("[0]key", equalTo(knownKey1))).andExpect(jsonPath("[0]value", equalTo(knownValue1)))
|
||||
.andExpect(jsonPath("[1]key", equalTo(knownKey2)))
|
||||
.andExpect(jsonPath("[1]value", equalTo(knownValue2)));
|
||||
|
||||
final DistributionSetMetadata metaKey1 = distributionSetManagement
|
||||
.findOne(new DsMetadataCompositeKey(testDS, knownKey1));
|
||||
final DistributionSetMetadata metaKey2 = distributionSetManagement
|
||||
.findOne(new DsMetadataCompositeKey(testDS, knownKey2));
|
||||
|
||||
assertThat(metaKey1.getValue()).isEqualTo(knownValue1);
|
||||
assertThat(metaKey2.getValue()).isEqualTo(knownValue2);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a metadata update through API is reflected by the repository.")
|
||||
public void updateMetadata() throws Exception {
|
||||
// prepare and create metadata for update
|
||||
final String knownKey = "knownKey";
|
||||
final String knownValue = "knownValue";
|
||||
final String updateValue = "valueForUpdate";
|
||||
|
||||
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
distributionSetManagement
|
||||
.createDistributionSetMetadata(new DistributionSetMetadata(knownKey, testDS, knownValue));
|
||||
|
||||
final JSONObject jsonObject = new JSONObject().put("key", knownKey).put("value", updateValue);
|
||||
|
||||
mvc.perform(put("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey)
|
||||
.contentType(MediaType.APPLICATION_JSON).content(jsonObject.toString()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue)));
|
||||
|
||||
final DistributionSetMetadata assertDS = distributionSetManagement
|
||||
.findOne(new DsMetadataCompositeKey(testDS, knownKey));
|
||||
assertThat(assertDS.getValue()).isEqualTo(updateValue);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a metadata entry deletion through API is reflected by the repository.")
|
||||
public void deleteMetadata() throws Exception {
|
||||
// prepare and create metadata for deletion
|
||||
final String knownKey = "knownKey";
|
||||
final String knownValue = "knownValue";
|
||||
|
||||
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
distributionSetManagement
|
||||
.createDistributionSetMetadata(new DistributionSetMetadata(knownKey, testDS, knownValue));
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
try {
|
||||
distributionSetManagement.findOne(new DsMetadataCompositeKey(testDS, knownKey));
|
||||
fail("expected EntityNotFoundException but didn't throw");
|
||||
} catch (final EntityNotFoundException e) {
|
||||
// ok as expected
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a metadata entry selection through API reflectes the repository content.")
|
||||
public void getSingleMetadata() throws Exception {
|
||||
// prepare and create metadata
|
||||
final String knownKey = "knownKey";
|
||||
final String knownValue = "knownValue";
|
||||
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
distributionSetManagement
|
||||
.createDistributionSetMetadata(new DistributionSetMetadata(knownKey, testDS, knownValue));
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(knownValue)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a metadata entry paged list selection through API reflectes the repository content.")
|
||||
public void getPagedListofMetadata() throws Exception {
|
||||
|
||||
final int totalMetadata = 10;
|
||||
final int limitParam = 5;
|
||||
final String offsetParam = "0";
|
||||
final String knownKeyPrefix = "knownKey";
|
||||
final String knownValuePrefix = "knownValue";
|
||||
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
for (int index = 0; index < totalMetadata; index++) {
|
||||
distributionSetManagement.createDistributionSetMetadata(new DistributionSetMetadata(knownKeyPrefix + index,
|
||||
distributionSetManagement.findDistributionSetById(testDS.getId()), knownValuePrefix + index));
|
||||
}
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata?offset=" + offsetParam + "&limit=" + limitParam,
|
||||
testDS.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("size", equalTo(limitParam))).andExpect(jsonPath("total", equalTo(totalMetadata)))
|
||||
.andExpect(jsonPath("content[0].key", equalTo("knownKey0")))
|
||||
.andExpect(jsonPath("content[0].value", equalTo("knownValue0")));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a DS search with query parameters returns the expected result.")
|
||||
public void searchDistributionSetRsql() throws Exception {
|
||||
final String dsSuffix = "test";
|
||||
final int amount = 10;
|
||||
TestDataUtil.generateDistributionSets(dsSuffix, amount, softwareManagement, distributionSetManagement);
|
||||
TestDataUtil.generateDistributionSet("DS1test", softwareManagement, distributionSetManagement);
|
||||
TestDataUtil.generateDistributionSet("DS2test", softwareManagement, distributionSetManagement);
|
||||
|
||||
final String rsqlFindLikeDs1OrDs2 = "name==DS1test,name==DS2test";
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsets?q=" + rsqlFindLikeDs1OrDs2)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(2)))
|
||||
.andExpect(jsonPath("total", equalTo(2))).andExpect(jsonPath("content[0].name", equalTo("DS1test")))
|
||||
.andExpect(jsonPath("content[1].name", equalTo("DS2test")));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a DS search with complete==true parameter returns only DS that are actually completely filled with mandatory modules.")
|
||||
public void filterDistributionSetComplete() throws Exception {
|
||||
final int amount = 10;
|
||||
TestDataUtil.generateDistributionSets(amount, softwareManagement, distributionSetManagement);
|
||||
distributionSetManagement.createDistributionSet(new DistributionSet("incomplete", "2", "incomplete",
|
||||
distributionSetManagement.findDistributionSetTypeByKey("ecl_os"), null));
|
||||
|
||||
final String rsqlFindLikeDs1OrDs2 = "complete==" + Boolean.TRUE;
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsets?q=" + rsqlFindLikeDs1OrDs2)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(10)))
|
||||
.andExpect(jsonPath("total", equalTo(10)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a DS assigned target search with controllerId==1 parameter returns only the target with the given ID.")
|
||||
public void searchDistributionSetAssignedTargetsRsql() throws Exception {
|
||||
// prepare distribution set
|
||||
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
|
||||
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
|
||||
// prepare targets
|
||||
final String[] knownTargetIds = new String[] { "1", "2", "3", "4", "5" };
|
||||
final JSONArray list = new JSONArray();
|
||||
for (final String targetId : knownTargetIds) {
|
||||
targetManagement.createTarget(new Target(targetId));
|
||||
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
|
||||
}
|
||||
|
||||
// assign already one target to DS
|
||||
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetIds[0]);
|
||||
|
||||
final String rsqlFindTargetId1 = "controllerId==1";
|
||||
|
||||
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId()
|
||||
+ "/assignedTargets?q=" + rsqlFindTargetId1).contentType(MediaType.APPLICATION_JSON)
|
||||
.content(list.toString()))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("total", equalTo(1)))
|
||||
.andExpect(jsonPath("size", equalTo(1))).andExpect(jsonPath("content[0].controllerId", equalTo("1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a DS metadata filtered query with value==knownValue1 parameter returns only the metadata entries with that value.")
|
||||
public void searchDistributionSetMetadataRsql() throws Exception {
|
||||
final int totalMetadata = 10;
|
||||
final String knownKeyPrefix = "knownKey";
|
||||
final String knownValuePrefix = "knownValue";
|
||||
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
for (int index = 0; index < totalMetadata; index++) {
|
||||
distributionSetManagement.createDistributionSetMetadata(new DistributionSetMetadata(knownKeyPrefix + index,
|
||||
distributionSetManagement.findDistributionSetById(testDS.getId()), knownValuePrefix + index));
|
||||
}
|
||||
|
||||
final String rsqlSearchValue1 = "value==knownValue1";
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata?q=" + rsqlSearchValue1, testDS.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(1)))
|
||||
.andExpect(jsonPath("total", equalTo(1))).andExpect(jsonPath("content[0].key", equalTo("knownKey1")))
|
||||
.andExpect(jsonPath("content[0].value", equalTo("knownValue1")));
|
||||
}
|
||||
|
||||
private Set<DistributionSet> createDistributionSetsAlphabetical(final int amount) {
|
||||
char character = 'a';
|
||||
final Set<DistributionSet> created = new HashSet<>();
|
||||
for (int index = 0; index < amount; index++) {
|
||||
final String str = String.valueOf(character);
|
||||
created.add(TestDataUtil.generateDistributionSet(str, softwareManagement, distributionSetManagement));
|
||||
character++;
|
||||
}
|
||||
return created;
|
||||
}
|
||||
|
||||
public static List<Target> sendUpdateActionStatusToTargets(final ControllerManagement controllerManagament,
|
||||
final TargetManagement targetManagement, final ActionRepository actionRepository, final DistributionSet dsA,
|
||||
final Iterable<Target> targs, final Status status, final String... msgs) {
|
||||
final List<Target> result = new ArrayList<Target>();
|
||||
for (final Target t : targs) {
|
||||
final List<Action> findByTarget = actionRepository.findByTarget(t);
|
||||
for (final Action action : findByTarget) {
|
||||
result.add(sendUpdateActionStatusToTarget(controllerManagament, targetManagement, status, action, t,
|
||||
msgs));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Target sendUpdateActionStatusToTarget(final ControllerManagement controllerManagament,
|
||||
final TargetManagement targetManagement, final Status status, final Action updActA, final Target t,
|
||||
final String... msgs) {
|
||||
updActA.setStatus(status);
|
||||
|
||||
final ActionStatus statusMessages = new ActionStatus();
|
||||
statusMessages.setAction(updActA);
|
||||
statusMessages.setOccurredAt(System.currentTimeMillis());
|
||||
statusMessages.setStatus(status);
|
||||
for (final String msg : msgs) {
|
||||
statusMessages.addMessage(msg);
|
||||
}
|
||||
controllerManagament.addUpdateActionStatus(statusMessages, updActA);
|
||||
return targetManagement.findTargetByControllerID(t.getControllerId());
|
||||
}
|
||||
|
||||
public static DistributionSet createTestDistributionSet(final SoftwareManagement softwareManagement,
|
||||
final DistributionSetManagement distributionSetManagement) {
|
||||
|
||||
DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
set.setVersion("anotherVersion");
|
||||
set = distributionSetManagement.updateDistributionSet(set);
|
||||
|
||||
set.getModules().forEach(module -> {
|
||||
module.setDescription("updated description");
|
||||
softwareManagement.updateSoftwareModule(module);
|
||||
});
|
||||
|
||||
// load also lazy stuff
|
||||
set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId());
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
|
||||
return set;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,585 @@
|
||||
/**
|
||||
* 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.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
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.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.WithUser;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetType;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
/**
|
||||
* Test for {@link MgmtDistributionSetTypeResource}.
|
||||
*
|
||||
*/
|
||||
@Features("Component Tests - Management API")
|
||||
@Stories("Distribution Set Type Resource")
|
||||
public class MgmtDistributionSetTypeResourceTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests.")
|
||||
public void getDistributionSetTypes() throws Exception {
|
||||
|
||||
DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
testType.setDescription("Desc1234");
|
||||
testType = distributionSetManagement.updateDistributionSetType(testType);
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes").accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + standardDsType.getKey() + ")][0].name",
|
||||
equalTo(standardDsType.getName())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + standardDsType.getKey() + ")][0].description",
|
||||
equalTo(standardDsType.getDescription())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + standardDsType.getKey() + ")][0].key",
|
||||
equalTo(standardDsType.getKey())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].id", equalTo(testType.getId().intValue())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].description", equalTo("Desc1234")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].createdAt", equalTo(testType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].lastModifiedBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].lastModifiedAt",
|
||||
equalTo(testType.getLastModifiedAt())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].key", equalTo("test123")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0]._links.self.href",
|
||||
equalTo("http://localhost/rest/v1/distributionsettypes/" + testType.getId())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0]._links.mandatorymodules.href",
|
||||
equalTo("http://localhost/rest/v1/distributionsettypes/" + testType.getId()
|
||||
+ "/mandatorymoduletypes")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0]._links.optionalmodules.href", equalTo(
|
||||
"http://localhost/rest/v1/distributionsettypes/" + testType.getId() + "/optionalmoduletypes")))
|
||||
.andExpect(jsonPath("$total", equalTo(4)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with sorting by KEY.")
|
||||
public void getDistributionSetTypesSortedByKey() throws Exception {
|
||||
|
||||
DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("zzzzz", "TestName123", "Desc123"));
|
||||
testType.setDescription("Desc1234");
|
||||
testType = distributionSetManagement.updateDistributionSetType(testType);
|
||||
|
||||
// descending
|
||||
mvc.perform(get("/rest/v1/distributionsettypes").accept(MediaType.APPLICATION_JSON)
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "KEY:DESC")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content.[0].id", equalTo(testType.getId().intValue())))
|
||||
.andExpect(jsonPath("$content.[0].name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("$content.[0].description", equalTo("Desc1234")))
|
||||
.andExpect(jsonPath("$content.[0].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[0].createdAt", equalTo(testType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$content.[0].lastModifiedBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[0].lastModifiedAt", equalTo(testType.getLastModifiedAt())))
|
||||
.andExpect(jsonPath("$content.[0].key", equalTo("zzzzz"))).andExpect(jsonPath("$total", equalTo(4)));
|
||||
|
||||
// ascending
|
||||
mvc.perform(get("/rest/v1/distributionsettypes").accept(MediaType.APPLICATION_JSON)
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "KEY:ASC")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content.[3].id", equalTo(testType.getId().intValue())))
|
||||
.andExpect(jsonPath("$content.[3].name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("$content.[3].description", equalTo("Desc1234")))
|
||||
.andExpect(jsonPath("$content.[3].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[3].createdAt", equalTo(testType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$content.[3].lastModifiedBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[3].lastModifiedAt", equalTo(testType.getLastModifiedAt())))
|
||||
.andExpect(jsonPath("$content.[3].key", equalTo("zzzzz"))).andExpect(jsonPath("$total", equalTo(4)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes POST requests.")
|
||||
public void createDistributionSetTypes() throws JSONException, Exception {
|
||||
|
||||
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(3);
|
||||
|
||||
final List<DistributionSetType> types = new ArrayList<>();
|
||||
types.add(new DistributionSetType("test1", "TestName1", "Desc1").addMandatoryModuleType(osType)
|
||||
.addOptionalModuleType(runtimeType));
|
||||
types.add(new DistributionSetType("test2", "TestName2", "Desc2").addOptionalModuleType(osType)
|
||||
.addOptionalModuleType(runtimeType).addOptionalModuleType(appType));
|
||||
types.add(new DistributionSetType("test3", "TestName3", "Desc3").addMandatoryModuleType(osType)
|
||||
.addMandatoryModuleType(runtimeType));
|
||||
|
||||
final MvcResult mvcResult = mvc
|
||||
.perform(post("/rest/v1/distributionsettypes/").content(JsonBuilder.distributionSetTypes(types))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("[0].name", equalTo("TestName1"))).andExpect(jsonPath("[0].key", equalTo("test1")))
|
||||
.andExpect(jsonPath("[0].description", equalTo("Desc1")))
|
||||
.andExpect(jsonPath("[0].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[1].name", equalTo("TestName2"))).andExpect(jsonPath("[1].key", equalTo("test2")))
|
||||
.andExpect(jsonPath("[1].description", equalTo("Desc2")))
|
||||
.andExpect(jsonPath("[1].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[2].name", equalTo("TestName3"))).andExpect(jsonPath("[2].key", equalTo("test3")))
|
||||
.andExpect(jsonPath("[2].description", equalTo("Desc3")))
|
||||
.andExpect(jsonPath("[2].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[2].createdAt", not(equalTo(0)))).andReturn();
|
||||
|
||||
final DistributionSetType created1 = distributionSetManagement.findDistributionSetTypeByKey("test1");
|
||||
final DistributionSetType created2 = distributionSetManagement.findDistributionSetTypeByKey("test2");
|
||||
final DistributionSetType created3 = distributionSetManagement.findDistributionSetTypeByKey("test3");
|
||||
|
||||
assertThat(created1.getMandatoryModuleTypes()).containsOnly(osType);
|
||||
assertThat(created1.getOptionalModuleTypes()).containsOnly(runtimeType);
|
||||
assertThat(created2.getOptionalModuleTypes()).containsOnly(osType, runtimeType, appType);
|
||||
assertThat(created3.getMandatoryModuleTypes()).containsOnly(osType, runtimeType);
|
||||
|
||||
assertThat(
|
||||
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + created1.getId());
|
||||
assertThat(
|
||||
JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + created2.getId());
|
||||
assertThat(
|
||||
JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + created3.getId());
|
||||
|
||||
assertThat(JsonPath.compile("[0]_links.mandatorymodules.href")
|
||||
.read(mvcResult.getResponse().getContentAsString()).toString()).isEqualTo(
|
||||
"http://localhost/rest/v1/distributionsettypes/" + created1.getId() + "/mandatorymoduletypes");
|
||||
assertThat(JsonPath.compile("[1]_links.mandatorymodules.href")
|
||||
.read(mvcResult.getResponse().getContentAsString()).toString()).isEqualTo(
|
||||
"http://localhost/rest/v1/distributionsettypes/" + created2.getId() + "/mandatorymoduletypes");
|
||||
assertThat(JsonPath.compile("[2]_links.mandatorymodules.href")
|
||||
.read(mvcResult.getResponse().getContentAsString()).toString()).isEqualTo(
|
||||
"http://localhost/rest/v1/distributionsettypes/" + created3.getId() + "/mandatorymoduletypes");
|
||||
|
||||
assertThat(JsonPath.compile("[0]_links.optionalmodules.href").read(mvcResult.getResponse().getContentAsString())
|
||||
.toString()).isEqualTo(
|
||||
"http://localhost/rest/v1/distributionsettypes/" + created1.getId() + "/optionalmoduletypes");
|
||||
assertThat(JsonPath.compile("[1]_links.optionalmodules.href").read(mvcResult.getResponse().getContentAsString())
|
||||
.toString()).isEqualTo(
|
||||
"http://localhost/rest/v1/distributionsettypes/" + created2.getId() + "/optionalmoduletypes");
|
||||
assertThat(JsonPath.compile("[2]_links.optionalmodules.href").read(mvcResult.getResponse().getContentAsString())
|
||||
.toString()).isEqualTo(
|
||||
"http://localhost/rest/v1/distributionsettypes/" + created3.getId() + "/optionalmoduletypes");
|
||||
|
||||
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(6);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes POST requests.")
|
||||
public void addMandatoryModuleToDistributionSetType() throws JSONException, Exception {
|
||||
DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
|
||||
mvc.perform(post("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId())
|
||||
.content("{\"id\":" + osType.getId() + "}").contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
|
||||
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(2);
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
assertThat(testType.getOptionalModuleTypes()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes POST requests.")
|
||||
public void addOptionalModuleToDistributionSetType() throws JSONException, Exception {
|
||||
DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
|
||||
mvc.perform(post("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId())
|
||||
.content("{\"id\":" + osType.getId() + "}").contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
|
||||
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(2);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(osType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).isEmpty();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes GET requests.")
|
||||
public void getMandatoryModulesOfDistributionSetType() throws JSONException, Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
|
||||
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId())
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("[0].name", equalTo(osType.getName())))
|
||||
.andExpect(jsonPath("[0].description", equalTo(osType.getDescription())))
|
||||
.andExpect(jsonPath("[0].maxAssignments", equalTo(1))).andExpect(jsonPath("[0].key", equalTo("os")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes GET requests.")
|
||||
public void getOptionalModulesOfDistributionSetType() throws JSONException, Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
|
||||
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId())
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("[0].name", equalTo(appType.getName())))
|
||||
.andExpect(jsonPath("[0].description", equalTo(appType.getDescription())))
|
||||
.andExpect(jsonPath("[0].maxAssignments", equalTo(1)))
|
||||
.andExpect(jsonPath("[0].key", equalTo("application")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} GET requests.")
|
||||
public void getMandatoryModuleOfDistributionSetType() throws JSONException, Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
|
||||
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(),
|
||||
osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$id", equalTo(osType.getId().intValue())))
|
||||
.andExpect(jsonPath("$name", equalTo(osType.getName())))
|
||||
.andExpect(jsonPath("$description", equalTo(osType.getDescription())))
|
||||
.andExpect(jsonPath("$createdBy", equalTo(osType.getCreatedBy())))
|
||||
.andExpect(jsonPath("$createdAt", equalTo(osType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$lastModifiedBy", equalTo(osType.getLastModifiedBy())))
|
||||
.andExpect(jsonPath("$lastModifiedAt", equalTo(osType.getLastModifiedAt())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} GET requests.")
|
||||
public void getOptionalModuleOfDistributionSetType() throws JSONException, Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
|
||||
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(),
|
||||
appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$id", equalTo(appType.getId().intValue())))
|
||||
.andExpect(jsonPath("$name", equalTo(appType.getName())))
|
||||
.andExpect(jsonPath("$description", equalTo(appType.getDescription())))
|
||||
.andExpect(jsonPath("$createdBy", equalTo(appType.getCreatedBy())))
|
||||
.andExpect(jsonPath("$createdAt", equalTo(appType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$lastModifiedBy", equalTo(appType.getLastModifiedBy())))
|
||||
.andExpect(jsonPath("$lastModifiedAt", equalTo(appType.getLastModifiedAt())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} DELETE requests.")
|
||||
public void removeMandatoryModuleToDistributionSetType() throws JSONException, Exception {
|
||||
DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
|
||||
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(),
|
||||
osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
|
||||
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(2);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} DELETE requests.")
|
||||
public void removeOptionalModuleToDistributionSetType() throws JSONException, Exception {
|
||||
DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
|
||||
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(),
|
||||
appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
|
||||
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(2);
|
||||
assertThat(testType.getOptionalModuleTypes()).isEmpty();
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} GET requests.")
|
||||
public void getDistributionSetType() throws Exception {
|
||||
|
||||
DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
testType.setDescription("Desc1234");
|
||||
testType = distributionSetManagement.updateDistributionSetType(testType);
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/{dstId}", testType.getId()).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("$description", equalTo("Desc1234")))
|
||||
.andExpect(jsonPath("$createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$createdAt", equalTo(testType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$lastModifiedBy", equalTo("uploadTester")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (hard delete scenario).")
|
||||
public void deleteDistributionSetTypeUnused() throws Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
|
||||
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(4);
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsettypes/{dsId}", testType.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (soft delete scenario).")
|
||||
public void deleteDistributionSetTypeUsed() throws Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
distributionSetManagement
|
||||
.createDistributionSet(new DistributionSet("sdfsd", "dsfsdf", "sdfsdf", testType, null));
|
||||
|
||||
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(4);
|
||||
assertThat(distributionSetTypeRepository.count()).isEqualTo(4);
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsettypes/{smId}", testType.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
assertThat(distributionSetTypeRepository.count()).isEqualTo(4);
|
||||
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} PUT requests.")
|
||||
public void updateDistributionSetTypeOnlyDescriptionAndNameUntouched() throws Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
|
||||
final String body = new JSONObject().put("id", testType.getId()).put("description", "foobardesc")
|
||||
.put("name", "nameShouldNotBeChanged").toString();
|
||||
|
||||
mvc.perform(put("/rest/v1/distributionsettypes/{smId}", testType.getId()).content(body)
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$id", equalTo(testType.getId().intValue())))
|
||||
.andExpect(jsonPath("$description", equalTo("foobardesc")))
|
||||
.andExpect(jsonPath("$name", equalTo("TestName123"))).andReturn();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with paging.")
|
||||
public void getDistributionSetTypesWithoutAddtionalRequestParameters() throws Exception {
|
||||
final int types = 3;
|
||||
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(types)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(types)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with paging.")
|
||||
public void getDistributionSetTypesWithPagingLimitRequestParameter() throws Exception {
|
||||
final int types = 3;
|
||||
final int limitSize = 1;
|
||||
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING)
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with paging.")
|
||||
public void getDistributionSetTypesWithPagingLimitAndOffsetRequestParameter() throws Exception {
|
||||
final int types = 3;
|
||||
final int offsetParam = 2;
|
||||
final int expectedSize = types - offsetParam;
|
||||
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING)
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(types)))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the server is behaving as expected on invalid requests (wrong media type, wrong ID etc.).")
|
||||
public void invalidRequestsOnDistributionSetTypesResource() throws Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
|
||||
final SoftwareModuleType testSmType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
|
||||
final List<DistributionSetType> types = new ArrayList<>();
|
||||
types.add(testType);
|
||||
|
||||
// DST does not exist
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/12345678")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/12345678/mandatorymoduletypes"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/12345678/optionalmoduletypes"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsettypes/12345678")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
// Module types incorrect
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/mandatorymoduletypes"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/mandatorymoduletypes/565765656"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/optionalmoduletypes/565765656"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
mvc.perform(get(
|
||||
"/rest/v1/distributionsettypes/" + standardDsType.getId() + "/mandatorymoduletypes/" + osType.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/mandatorymoduletypes/"
|
||||
+ testSmType.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
mvc.perform(get(
|
||||
"/rest/v1/distributionsettypes/" + standardDsType.getId() + "/optionalmoduletypes/" + osType.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
mvc.perform(get(
|
||||
"/rest/v1/distributionsettypes/" + standardDsType.getId() + "/optionalmoduletypes/" + appType.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/optionalmoduletypes/"
|
||||
+ testSmType.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
// Modules types at creation time invalid
|
||||
|
||||
final DistributionSetType testNewType = new DistributionSetType("test123", "TestName123", "Desc123");
|
||||
testNewType.addMandatoryModuleType(new SoftwareModuleType("foo", "bar", "test", Integer.MAX_VALUE));
|
||||
|
||||
mvc.perform(post("/rest/v1/distributionsettypes")
|
||||
.content(JsonBuilder.distributionSetTypes(Lists.newArrayList(testNewType)))
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isUnsupportedMediaType());
|
||||
|
||||
// bad request - no content
|
||||
mvc.perform(post("/rest/v1/distributionsettypes").contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
|
||||
|
||||
// bad request - bad content
|
||||
mvc.perform(post("/rest/v1/distributionsettypes").content("sdfjsdlkjfskdjf".getBytes())
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(put("/rest/v1/distributionsettypes")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsettypes")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(put("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/mandatorymoduletypes"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
mvc.perform(put(
|
||||
"/rest/v1/distributionsettypes/" + standardDsType.getId() + "/optionalmoduletypes/" + osType.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Search erquest of software module types.")
|
||||
public void searchDistributionSetTypeRsql() throws Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
final DistributionSetType testType2 = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test1234", "TestName1234", "Desc123"));
|
||||
|
||||
final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234";
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes?q=" + rsqlFindLikeDs1OrDs2)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(2)))
|
||||
.andExpect(jsonPath("total", equalTo(2))).andExpect(jsonPath("content[0].name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("content[1].name", equalTo("TestName1234")));
|
||||
}
|
||||
|
||||
private void createSoftwareModulesAlphabetical(final int amount) {
|
||||
char character = 'a';
|
||||
for (int index = 0; index < amount; index++) {
|
||||
final String str = String.valueOf(character);
|
||||
final SoftwareModule softwareModule = new SoftwareModule(osType, str, str, str, str);
|
||||
|
||||
softwareManagement.createSoftwareModule(softwareModule);
|
||||
character++;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* 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.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.cache.CacheConstants;
|
||||
import org.eclipse.hawkbit.cache.DownloadArtifactCache;
|
||||
import org.eclipse.hawkbit.cache.DownloadType;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
|
||||
import org.eclipse.hawkbit.repository.model.Artifact;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.context.annotation.Description;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
@Features("Component Tests - Management API")
|
||||
@Stories("Download Resource")
|
||||
public class MgmtDownloadResourceTest extends AbstractIntegrationTestWithMongoDB {
|
||||
|
||||
@Autowired
|
||||
@Qualifier(CacheConstants.DOWNLOAD_ID_CACHE)
|
||||
private Cache downloadIdCache;
|
||||
|
||||
private final String downloadIdSha1 = "downloadIdSha1";
|
||||
|
||||
private final String downloadIdNotAvailable = "downloadIdNotAvailable";
|
||||
|
||||
@Before
|
||||
public void setupCache() {
|
||||
|
||||
final DistributionSet distributionSet = TestDataUtil.generateDistributionSet("Test", softwareManagement,
|
||||
distributionSetManagement);
|
||||
final SoftwareModule softwareModule = distributionSet.getModules().stream().findFirst().get();
|
||||
final Artifact artifact = TestDataUtil.generateArtifacts(artifactManagement, softwareModule.getId()).stream()
|
||||
.findFirst().get();
|
||||
|
||||
downloadIdCache.put(downloadIdSha1, new DownloadArtifactCache(DownloadType.BY_SHA1, artifact.getSha1Hash()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("This test verifies the call of download artifact without a valid download id fails.")
|
||||
public void testNoDownloadIdAvailable() throws Exception {
|
||||
mvc.perform(
|
||||
get(MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE + MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING,
|
||||
downloadIdNotAvailable))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("This test verifies the call of download artifact works and the download id will be removed.")
|
||||
public void testDownload() throws Exception {
|
||||
mvc.perform(
|
||||
get(MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE + MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING,
|
||||
downloadIdSha1))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
// because cache is empty
|
||||
mvc.perform(
|
||||
get(MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE + MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING,
|
||||
downloadIdSha1))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,597 @@
|
||||
/**
|
||||
* 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.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
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.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.List;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.WithUser;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
|
||||
import org.eclipse.hawkbit.mgmt.rest.resource.MgmtRolloutResource;
|
||||
import org.eclipse.hawkbit.repository.RolloutGroupManagement;
|
||||
import org.eclipse.hawkbit.repository.RolloutManagement;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.Rollout;
|
||||
import org.eclipse.hawkbit.repository.model.Rollout.RolloutStatus;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupConditionBuilder;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessCondition;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Description;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
import org.springframework.http.MediaType;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
/**
|
||||
* Tests for covering the {@link MgmtRolloutResource}.
|
||||
*/
|
||||
@Features("Component Tests - Management API")
|
||||
@Stories("Rollout Resource")
|
||||
public class MgmtRolloutResourceTest extends AbstractIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private RolloutManagement rolloutManagement;
|
||||
|
||||
@Autowired
|
||||
private RolloutGroupManagement rolloutGroupManagement;
|
||||
|
||||
@Test
|
||||
@Description("Testing that creating rollout with wrong body returns bad request")
|
||||
public void createRolloutWithInvalidBodyReturnsBadRequest() throws Exception {
|
||||
mvc.perform(post("/rest/v1/rollouts").content("invalid body").contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("errorCode", equalTo("hawkbit.server.error.rest.body.notReadable")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that creating rollout with insufficient permission returns forbidden")
|
||||
@WithUser(allSpPermissions = true, removeFromAllPermission = "ROLLOUT_MANAGEMENT")
|
||||
public void createRolloutWithInsufficientPermissionReturnsForbidden() throws Exception {
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
mvc.perform(post("/rest/v1/rollouts")
|
||||
.content(JsonBuilder.rollout("name", "desc", 10, dsA.getId(), "name==test", null))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().is(403)).andReturn();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that creating rollout with not exisiting distribution set returns not found")
|
||||
public void createRolloutWithNotExistingDistributionSetReturnsNotFound() throws Exception {
|
||||
mvc.perform(post("/rest/v1/rollouts").content(JsonBuilder.rollout("name", "desc", 10, 1234, "name==test", null))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()).andReturn();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that creating rollout with not valid formed target filter query returns bad request")
|
||||
public void createRolloutWithNotWellFormedFilterReturnsBadRequest() throws Exception {
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
mvc.perform(post("/rest/v1/rollouts")
|
||||
.content(JsonBuilder.rollout("name", "desc", 10, dsA.getId(), "name=test", null))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("errorCode", equalTo("hawkbit.server.error.rest.param.rsqlParamSyntax")))
|
||||
.andReturn();
|
||||
}
|
||||
|
||||
@Description("Ensures that the repository refuses to create rollout without a defined target filter set.")
|
||||
public void missingTargetFilterQueryInRollout() throws Exception {
|
||||
|
||||
final String targetFilterQuery = null;
|
||||
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
mvc.perform(post("/rest/v1/rollouts")
|
||||
.content(JsonBuilder.rollout("rollout1", "desc", 10, dsA.getId(), targetFilterQuery, null))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("errorCode", equalTo("hawkbit.server.error.rest.param.rsqlParamSyntax")))
|
||||
.andReturn();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that rollout can be created")
|
||||
public void createRollout() throws Exception {
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
postRollout("rollout1", 10, dsA.getId(), "name==target1");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing the empty list is returned if no rollout exists")
|
||||
public void noRolloutReturnsEmptyList() throws Exception {
|
||||
mvc.perform(get("/rest/v1/rollouts")).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content", hasSize(0))).andExpect(jsonPath("$total", equalTo(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that rollout paged list contains rollouts")
|
||||
public void rolloutPagedListContainsAllRollouts() throws Exception {
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
// setup - create 2 rollouts
|
||||
postRollout("rollout1", 10, dsA.getId(), "name==target1");
|
||||
postRollout("rollout2", 5, dsA.getId(), "name==target2");
|
||||
|
||||
mvc.perform(get("/rest/v1/rollouts")).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content", hasSize(2))).andExpect(jsonPath("$total", equalTo(2)))
|
||||
.andExpect(jsonPath("content[0].name", equalTo("rollout1")))
|
||||
.andExpect(jsonPath("content[0].status", equalTo("ready")))
|
||||
.andExpect(jsonPath("content[0].targetFilterQuery", equalTo("name==target1")))
|
||||
.andExpect(jsonPath("content[0].distributionSetId", equalTo(dsA.getId().intValue())))
|
||||
.andExpect(jsonPath("content[1].name", equalTo("rollout2")))
|
||||
.andExpect(jsonPath("content[1].status", equalTo("ready")))
|
||||
.andExpect(jsonPath("content[1].targetFilterQuery", equalTo("name==target2")))
|
||||
.andExpect(jsonPath("content[1].distributionSetId", equalTo(dsA.getId().intValue())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that rollout paged list is limited by the query param limit")
|
||||
public void rolloutPagedListIsLimitedToQueryParam() throws Exception {
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
// setup - create 2 rollouts
|
||||
postRollout("rollout1", 10, dsA.getId(), "name==target1");
|
||||
postRollout("rollout2", 5, dsA.getId(), "name==target2");
|
||||
|
||||
mvc.perform(get("/rest/v1/rollouts?limit=1")).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content", hasSize(1))).andExpect(jsonPath("$total", equalTo(2)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that rollout paged list is limited by the query param limit")
|
||||
public void retrieveRolloutGroupsForSpecificRollout() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 20;
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
// retrieve rollout groups from created rollout
|
||||
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups", rollout.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content", hasSize(4))).andExpect(jsonPath("$total", equalTo(4)))
|
||||
.andExpect(jsonPath("$content[0].status", equalTo("ready")))
|
||||
.andExpect(jsonPath("$content[1].status", equalTo("ready")))
|
||||
.andExpect(jsonPath("$content[2].status", equalTo("ready")))
|
||||
.andExpect(jsonPath("$content[3].status", equalTo("ready")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that starting the rollout switches the state to running")
|
||||
public void startingRolloutSwitchesIntoRunningState() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 20;
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
// starting rollout
|
||||
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/start", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// check rollout is in running state
|
||||
mvc.perform(get("/rest/v1/rollouts/{rolloutId}", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("id", equalTo(rollout.getId().intValue())))
|
||||
.andExpect(jsonPath("status", equalTo("running")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that pausing the rollout switches the state to paused")
|
||||
public void pausingRolloutSwitchesIntoPausedState() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 20;
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
// starting rollout
|
||||
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/start", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// pausing rollout
|
||||
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/pause", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// check rollout is in running state
|
||||
mvc.perform(get("/rest/v1/rollouts/{rolloutId}", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("id", equalTo(rollout.getId().intValue())))
|
||||
.andExpect(jsonPath("status", equalTo("paused")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that resuming the rollout switches the state to running")
|
||||
public void resumingRolloutSwitchesIntoRunningState() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 20;
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
// starting rollout
|
||||
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/start", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// pausing rollout
|
||||
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/pause", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// resume rollout
|
||||
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/resume", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// check rollout is in running state
|
||||
mvc.perform(get("/rest/v1/rollouts/{rolloutId}", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("id", equalTo(rollout.getId().intValue())))
|
||||
.andExpect(jsonPath("status", equalTo("running")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that an already started rollout cannot be started again and returns bad request")
|
||||
public void startingAlreadyStartedRolloutReturnsBadRequest() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 20;
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
// starting rollout
|
||||
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/start", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// starting rollout - already started should lead into bad request
|
||||
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/start", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("errorCode", equalTo("hawkbit.server.error.rollout.illegalstate")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that resuming a rollout which is not started leads to bad request")
|
||||
public void resumingNotStartedRolloutReturnsBadRequest() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 20;
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
// resume not yet started rollout
|
||||
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/resume", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("errorCode", equalTo("hawkbit.server.error.rollout.illegalstate")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that starting rollout the first rollout group is in running state")
|
||||
public void startingRolloutFirstRolloutGroupIsInRunningState() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 10;
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rollout1", 2, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
// starting rollout
|
||||
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/start", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// retrieve rollout groups from created rollout - 2 groups exists
|
||||
// (amountTargets / groupSize = 2)
|
||||
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups?sort=ID:ASC", rollout.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content", hasSize(2))).andExpect(jsonPath("$total", equalTo(2)))
|
||||
.andExpect(jsonPath("$content[0].status", equalTo("running")))
|
||||
.andExpect(jsonPath("$content[1].status", equalTo("scheduled")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that a single rollout group can be retrieved")
|
||||
public void retrieveSingleRolloutGroup() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 10;
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
final RolloutGroup firstGroup = rolloutGroupManagement
|
||||
.findRolloutGroupsByRolloutId(rollout.getId(), new PageRequest(0, 1, Direction.ASC, "id")).getContent()
|
||||
.get(0);
|
||||
|
||||
// retrieve single rollout group with known ID
|
||||
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups/{groupId}", rollout.getId(), firstGroup.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("id", equalTo(firstGroup.getId().intValue())))
|
||||
.andExpect(jsonPath("status", equalTo("ready"))).andExpect(jsonPath("name", notNullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that the targets of rollout group can be retrieved")
|
||||
public void retrieveTargetsFromRolloutGroup() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 10;
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rollout1", 2, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
final RolloutGroup firstGroup = rolloutGroupManagement
|
||||
.findRolloutGroupsByRolloutId(rollout.getId(), new PageRequest(0, 1, Direction.ASC, "id")).getContent()
|
||||
.get(0);
|
||||
|
||||
// retrieve targets from the first rollout group with known ID
|
||||
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups/{groupId}/targets", rollout.getId(),
|
||||
firstGroup.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content", hasSize(5))).andExpect(jsonPath("$total", equalTo(5)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that the targets of rollout group can be retrieved with rsql query param")
|
||||
public void retrieveTargetsFromRolloutGroupWithQuery() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 10;
|
||||
final List<Target> targets = targetManagement
|
||||
.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rollout1", 2, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
final RolloutGroup firstGroup = rolloutGroupManagement
|
||||
.findRolloutGroupsByRolloutId(rollout.getId(), new PageRequest(0, 1, Direction.ASC, "id")).getContent()
|
||||
.get(0);
|
||||
|
||||
// retrieve targets from the first rollout group with known ID
|
||||
mvc.perform(
|
||||
get("/rest/v1/rollouts/{rolloutId}/deploygroups/{groupId}/targets", rollout.getId(), firstGroup.getId())
|
||||
.param("q", "controllerId==" + targets.get(0).getControllerId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content", hasSize(1))).andExpect(jsonPath("$total", equalTo(1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that the targets of rollout group can be retrieved after the rollout has been started")
|
||||
public void retrieveTargetsFromRolloutGroupAfterRolloutIsStarted() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 10;
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rollout1", 2, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
rolloutManagement.startRollout(rollout);
|
||||
|
||||
final RolloutGroup firstGroup = rolloutGroupManagement
|
||||
.findRolloutGroupsByRolloutId(rollout.getId(), new PageRequest(0, 1, Direction.ASC, "id")).getContent()
|
||||
.get(0);
|
||||
|
||||
// retrieve targets from the first rollout group with known ID
|
||||
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups/{groupId}/targets", rollout.getId(),
|
||||
firstGroup.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content", hasSize(5))).andExpect(jsonPath("$total", equalTo(5)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Start the rollout in async mode")
|
||||
public void startingRolloutSwitchesIntoRunningStateAsync() throws Exception {
|
||||
|
||||
final int amountTargets = 1000;
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
// starting rollout
|
||||
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/start", rollout.getId())
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_ASYNC, "true")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// check if running
|
||||
assertThat(doWithTimeout(() -> getRollout(rollout.getId()), result -> success(result), 60_000, 100))
|
||||
.isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that rollout paged list with rsql parameter")
|
||||
public void getRolloutWithRSQLParam() throws Exception {
|
||||
|
||||
final int amountTargetsRollout1 = 25;
|
||||
final int amountTargetsRollout2 = 25;
|
||||
final int amountTargetsRollout3 = 25;
|
||||
final int amountTargetsOther = 25;
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargetsRollout1, "rollout1", "rollout1"));
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargetsRollout2, "rollout2", "rollout2"));
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargetsRollout3, "rollout3", "rollout3"));
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargetsOther, "other1", "other1"));
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
createRollout("rollout1", 5, dsA.getId(), "controllerId==rollout1*");
|
||||
final Rollout rollout2 = createRollout("rollout2", 5, dsA.getId(), "controllerId==rollout2*");
|
||||
createRollout("rollout3", 5, dsA.getId(), "controllerId==rollout3*");
|
||||
createRollout("other1", 5, dsA.getId(), "controllerId==other1*");
|
||||
|
||||
mvc.perform(get("/rest/v1/rollouts").param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==*2"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content", hasSize(1))).andExpect(jsonPath("$total", equalTo(1)))
|
||||
.andExpect(jsonPath("$content[0].name", equalTo(rollout2.getName())));
|
||||
|
||||
mvc.perform(get("/rest/v1/rollouts").param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==rollout*"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content", hasSize(3))).andExpect(jsonPath("$total", equalTo(3)));
|
||||
|
||||
mvc.perform(get("/rest/v1/rollouts").param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==*1"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content", hasSize(2))).andExpect(jsonPath("$total", equalTo(2)));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that rolloutgroup paged list with rsql parameter")
|
||||
public void retrieveRolloutGroupsForSpecificRolloutWithRSQLParam() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 20;
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
// retrieve rollout groups from created rollout
|
||||
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups", rollout.getId())
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==group-1")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content", hasSize(1))).andExpect(jsonPath("$total", equalTo(1)))
|
||||
.andExpect(jsonPath("$content[0].name", equalTo("group-1")));
|
||||
|
||||
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups", rollout.getId())
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==group*")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content", hasSize(4))).andExpect(jsonPath("$total", equalTo(4)));
|
||||
|
||||
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups", rollout.getId())
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==group-1,name==group-2"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content", hasSize(2))).andExpect(jsonPath("$total", equalTo(2)));
|
||||
|
||||
}
|
||||
|
||||
protected <T> T doWithTimeout(final Callable<T> callable, final SuccessCondition<T> successCondition,
|
||||
final long timeout, final long pollInterval) throws Exception // NOPMD
|
||||
{
|
||||
|
||||
if (pollInterval < 0) {
|
||||
throw new IllegalArgumentException("pollInterval must non negative");
|
||||
}
|
||||
|
||||
long duration = 0;
|
||||
Exception exception = null;
|
||||
T returnValue = null;
|
||||
while (untilTimeoutReached(timeout, duration)) {
|
||||
try {
|
||||
returnValue = callable.call();
|
||||
// clear exception
|
||||
exception = null;
|
||||
} catch (final Exception ex) {
|
||||
exception = ex;
|
||||
}
|
||||
Thread.sleep(pollInterval);
|
||||
duration += pollInterval > 0 ? pollInterval : 1;
|
||||
if (exception == null && successCondition.success(returnValue)) {
|
||||
return returnValue;
|
||||
} else {
|
||||
returnValue = null;
|
||||
}
|
||||
}
|
||||
if (exception != null) {
|
||||
throw exception;
|
||||
}
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
protected boolean untilTimeoutReached(final long timeout, final long duration) {
|
||||
return duration <= timeout || timeout < 0;
|
||||
}
|
||||
|
||||
private void postRollout(final String name, final int groupSize, final long distributionSetId,
|
||||
final String targetFilterQuery) throws Exception {
|
||||
mvc.perform(post("/rest/v1/rollouts")
|
||||
.content(JsonBuilder.rollout(name, "desc", groupSize, distributionSetId, targetFilterQuery, null))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated()).andReturn();
|
||||
}
|
||||
|
||||
private Rollout createRollout(final String name, final int amountGroups, final long distributionSetId,
|
||||
final String targetFilterQuery) {
|
||||
final Rollout rollout = new Rollout();
|
||||
rollout.setDistributionSet(distributionSetManagement.findDistributionSetById(distributionSetId));
|
||||
rollout.setName(name);
|
||||
rollout.setTargetFilterQuery(targetFilterQuery);
|
||||
return rolloutManagement.createRollout(rollout, amountGroups, new RolloutGroupConditionBuilder()
|
||||
.successCondition(RolloutGroupSuccessCondition.THRESHOLD, "100").build());
|
||||
}
|
||||
|
||||
protected boolean success(final Rollout result) {
|
||||
if (null != result && result.getStatus() == RolloutStatus.RUNNING) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public Rollout getRollout(final Long rolloutId) throws Exception {
|
||||
return rolloutManagement.findRolloutById(rolloutId);
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,357 @@
|
||||
/**
|
||||
* 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.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
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.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.WithUser;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
/**
|
||||
* Test for {@link MgmtSoftwareModuleTypeResource}.
|
||||
*
|
||||
*/
|
||||
@Features("Component Tests - Management API")
|
||||
@Stories("Software Module Type Resource")
|
||||
public class MgmtSoftwareModuleTypeResourceTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests.")
|
||||
public void getSoftwareModuleTypes() throws Exception {
|
||||
SoftwareModuleType testType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
testType.setDescription("Desc1234");
|
||||
testType = softwareManagement.updateSoftwareModuleType(testType);
|
||||
|
||||
mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + osType.getKey() + ")][0].name", equalTo(osType.getName())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + osType.getKey() + ")][0].description",
|
||||
equalTo(osType.getDescription())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + osType.getKey() + ")][0].maxAssignments", equalTo(1)))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + osType.getKey() + ")][0].key", equalTo("os")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + runtimeType.getKey() + ")][0].name",
|
||||
equalTo(runtimeType.getName())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + runtimeType.getKey() + ")][0].description",
|
||||
equalTo(runtimeType.getDescription())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + runtimeType.getKey() + ")][0].maxAssignments", equalTo(1)))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + runtimeType.getKey() + ")][0].key", equalTo("runtime")))
|
||||
.andExpect(
|
||||
jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].name", equalTo(appType.getName())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].description",
|
||||
equalTo(appType.getDescription())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].maxAssignments", equalTo(1)))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].key", equalTo("application")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].id", equalTo(testType.getId().intValue())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].description", equalTo("Desc1234")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].createdAt", equalTo(testType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].lastModifiedBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].lastModifiedAt",
|
||||
equalTo(testType.getLastModifiedAt())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].maxAssignments", equalTo(5)))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].key", equalTo("test123")))
|
||||
.andExpect(jsonPath("$total", equalTo(4)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with sorting by MAXASSIGNMENTS field.")
|
||||
public void getSoftwareModuleTypesSortedByMaxAssignments() throws Exception {
|
||||
SoftwareModuleType testType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
testType.setDescription("Desc1234");
|
||||
testType = softwareManagement.updateSoftwareModuleType(testType);
|
||||
|
||||
// descending
|
||||
mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON)
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "MAXASSIGNMENTS:DESC"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content.[0].id", equalTo(testType.getId().intValue())))
|
||||
.andExpect(jsonPath("$content.[0].name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("$content.[0].description", equalTo("Desc1234")))
|
||||
.andExpect(jsonPath("$content.[0].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[0].createdAt", equalTo(testType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$content.[0].lastModifiedBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[0].lastModifiedAt", equalTo(testType.getLastModifiedAt())))
|
||||
.andExpect(jsonPath("$content.[0].maxAssignments", equalTo(5)))
|
||||
.andExpect(jsonPath("$content.[0].key", equalTo("test123"))).andExpect(jsonPath("$total", equalTo(4)));
|
||||
|
||||
// ascending
|
||||
mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON)
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "MAXASSIGNMENTS:ASC"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content.[3].id", equalTo(testType.getId().intValue())))
|
||||
.andExpect(jsonPath("$content.[3].name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("$content.[3].description", equalTo("Desc1234")))
|
||||
.andExpect(jsonPath("$content.[3].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[3].createdAt", equalTo(testType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$content.[3].lastModifiedBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[3].lastModifiedAt", equalTo(testType.getLastModifiedAt())))
|
||||
.andExpect(jsonPath("$content.[3].maxAssignments", equalTo(5)))
|
||||
.andExpect(jsonPath("$content.[3].key", equalTo("test123"))).andExpect(jsonPath("$total", equalTo(4)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes POST requests.")
|
||||
public void createSoftwareModuleTypes() throws JSONException, Exception {
|
||||
|
||||
final List<SoftwareModuleType> types = new ArrayList<>();
|
||||
types.add(new SoftwareModuleType("test1", "TestName1", "Desc1", 1));
|
||||
types.add(new SoftwareModuleType("test2", "TestName2", "Desc2", 2));
|
||||
types.add(new SoftwareModuleType("test3", "TestName3", "Desc3", 3));
|
||||
|
||||
final MvcResult mvcResult = mvc
|
||||
.perform(post("/rest/v1/softwaremoduletypes/").content(JsonBuilder.softwareModuleTypes(types))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("[0].name", equalTo("TestName1"))).andExpect(jsonPath("[0].key", equalTo("test1")))
|
||||
.andExpect(jsonPath("[0].description", equalTo("Desc1")))
|
||||
.andExpect(jsonPath("[0].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[0].maxAssignments", equalTo(1)))
|
||||
.andExpect(jsonPath("[1].name", equalTo("TestName2"))).andExpect(jsonPath("[1].key", equalTo("test2")))
|
||||
.andExpect(jsonPath("[1].description", equalTo("Desc2")))
|
||||
.andExpect(jsonPath("[1].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[1].maxAssignments", equalTo(2)))
|
||||
.andExpect(jsonPath("[2].name", equalTo("TestName3"))).andExpect(jsonPath("[2].key", equalTo("test3")))
|
||||
.andExpect(jsonPath("[2].description", equalTo("Desc3")))
|
||||
.andExpect(jsonPath("[2].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[2].createdAt", not(equalTo(0))))
|
||||
.andExpect(jsonPath("[2].maxAssignments", equalTo(3))).andReturn();
|
||||
|
||||
final SoftwareModuleType created1 = softwareManagement.findSoftwareModuleTypeByKey("test1");
|
||||
final SoftwareModuleType created2 = softwareManagement.findSoftwareModuleTypeByKey("test2");
|
||||
final SoftwareModuleType created3 = softwareManagement.findSoftwareModuleTypeByKey("test3");
|
||||
|
||||
assertThat(
|
||||
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created1.getId());
|
||||
assertThat(
|
||||
JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created2.getId());
|
||||
assertThat(
|
||||
JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created3.getId());
|
||||
|
||||
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(6);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} GET requests.")
|
||||
public void getSoftwareModuleType() throws Exception {
|
||||
SoftwareModuleType testType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
testType.setDescription("Desc1234");
|
||||
testType = softwareManagement.updateSoftwareModuleType(testType);
|
||||
|
||||
mvc.perform(get("/rest/v1/softwaremoduletypes/{smtId}", testType.getId()).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("$description", equalTo("Desc1234")))
|
||||
.andExpect(jsonPath("$maxAssignments", equalTo(5)))
|
||||
.andExpect(jsonPath("$createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$createdAt", equalTo(testType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$lastModifiedBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$lastModifiedAt", equalTo(testType.getLastModifiedAt())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (hard delete scenario).")
|
||||
public void deleteSoftwareModuleTypeUnused() throws Exception {
|
||||
final SoftwareModuleType testType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
|
||||
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4);
|
||||
|
||||
mvc.perform(delete("/rest/v1/softwaremoduletypes/{smId}", testType.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (soft delete scenario).")
|
||||
public void deleteSoftwareModuleTypeUsed() throws Exception {
|
||||
final SoftwareModuleType testType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(testType, "name", "version", "description", "vendor"));
|
||||
|
||||
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4);
|
||||
assertThat(softwareModuleTypeRepository.count()).isEqualTo(4);
|
||||
|
||||
mvc.perform(delete("/rest/v1/softwaremoduletypes/{smId}", testType.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
assertThat(softwareModuleTypeRepository.count()).isEqualTo(4);
|
||||
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} PUT requests.")
|
||||
public void updateSoftwareModuleTypeOnlyDescriptionAndNameUntouched() throws Exception {
|
||||
final SoftwareModuleType testType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
|
||||
final String body = new JSONObject().put("id", testType.getId()).put("description", "foobardesc")
|
||||
.put("name", "nameShouldNotBeChanged").toString();
|
||||
|
||||
mvc.perform(put("/rest/v1/softwaremoduletypes/{smId}", testType.getId()).content(body)
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$id", equalTo(testType.getId().intValue())))
|
||||
.andExpect(jsonPath("$description", equalTo("foobardesc")))
|
||||
.andExpect(jsonPath("$name", equalTo("TestName123"))).andReturn();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with paging.")
|
||||
public void getSoftwareModuleTypesWithoutAddtionalRequestParameters() throws Exception {
|
||||
final int types = 3;
|
||||
mvc.perform(get(MgmtRestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(types)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(types)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with paging.")
|
||||
public void getSoftwareModuleTypesWithPagingLimitRequestParameter() throws Exception {
|
||||
final int types = 3;
|
||||
final int limitSize = 1;
|
||||
mvc.perform(get(MgmtRestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING)
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with paging.")
|
||||
public void getSoftwareModuleTypesWithPagingLimitAndOffsetRequestParameter() throws Exception {
|
||||
final int types = 3;
|
||||
final int offsetParam = 2;
|
||||
final int expectedSize = types - offsetParam;
|
||||
mvc.perform(get(MgmtRestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING)
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(types)))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the server is behaving as expected on invalid requests (wrong media type, wrong ID etc.).")
|
||||
public void invalidRequestsOnSoftwaremoduleTypesResource() throws Exception {
|
||||
final SoftwareModuleType testType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
|
||||
final List<SoftwareModuleType> types = new ArrayList<>();
|
||||
types.add(testType);
|
||||
|
||||
// SM does not exist
|
||||
mvc.perform(get("/rest/v1/softwaremoduletypes/12345678")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
mvc.perform(delete("/rest/v1/softwaremoduletypes/12345678")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
// bad request - no content
|
||||
mvc.perform(post("/rest/v1/softwaremoduletypes").contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
|
||||
|
||||
// bad request - bad content
|
||||
mvc.perform(post("/rest/v1/softwaremoduletypes").content("sdfjsdlkjfskdjf".getBytes())
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
// unsupported media type
|
||||
mvc.perform(post("/rest/v1/softwaremoduletypes").content(JsonBuilder.softwareModuleTypes(types))
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isUnsupportedMediaType());
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(put("/rest/v1/softwaremoduletypes")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/rest/v1/softwaremoduletypes")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Search erquest of software module types.")
|
||||
public void searchSoftwareModuleTypeRsql() throws Exception {
|
||||
final SoftwareModuleType testType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
final SoftwareModuleType testType2 = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test1234", "TestName1234", "Desc123", 5));
|
||||
|
||||
final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234";
|
||||
|
||||
mvc.perform(get("/rest/v1/softwaremoduletypes?q=" + rsqlFindLikeDs1OrDs2)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(2)))
|
||||
.andExpect(jsonPath("total", equalTo(2))).andExpect(jsonPath("content[0].name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("content[1].name", equalTo("TestName1234")));
|
||||
|
||||
}
|
||||
|
||||
private void createSoftwareModulesAlphabetical(final int amount) {
|
||||
char character = 'a';
|
||||
for (int index = 0; index < amount; index++) {
|
||||
final String str = String.valueOf(character);
|
||||
final SoftwareModule softwareModule = new SoftwareModule(osType, str, str, str, str);
|
||||
|
||||
softwareManagement.createSoftwareModule(softwareModule);
|
||||
character++;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* 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 org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.test.web.servlet.ResultHandler;
|
||||
import org.springframework.test.web.servlet.result.PrintingResultHandler;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
public abstract class MockMvcResultPrinter {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(MockMvcResultPrinter.class);
|
||||
|
||||
private MockMvcResultPrinter() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Print {@link MvcResult} details to the "standard" output stream.
|
||||
*/
|
||||
public static ResultHandler print() {
|
||||
return new ConsolePrintingResultHandler();
|
||||
}
|
||||
|
||||
/**
|
||||
* An {@link PrintingResultHandler} that writes to the "standard" output
|
||||
* stream
|
||||
*/
|
||||
private static class ConsolePrintingResultHandler extends PrintingResultHandler {
|
||||
|
||||
public ConsolePrintingResultHandler() {
|
||||
super(new ResultValuePrinter() {
|
||||
|
||||
@Override
|
||||
public void printHeading(final String heading) {
|
||||
LOG.debug(String.format("%20s:", heading));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void printValue(final String label, Object value) {
|
||||
if (value != null && value.getClass().isArray()) {
|
||||
value = CollectionUtils.arrayToList(value);
|
||||
}
|
||||
LOG.debug(String.format("%20s = %s", label, value));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* 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 java.io.IOException;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.PagedList;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact;
|
||||
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* Utility additions for the REST API tests.
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
public final class ResourceUtility {
|
||||
private static final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
static ExceptionInfo convertException(final String jsonExceptionResponse)
|
||||
throws JsonParseException, JsonMappingException, IOException {
|
||||
return mapper.readValue(jsonExceptionResponse, ExceptionInfo.class);
|
||||
}
|
||||
|
||||
static MgmtArtifact convertArtifactResponse(final String jsonResponse)
|
||||
throws JsonParseException, JsonMappingException, IOException {
|
||||
return mapper.readValue(jsonResponse, MgmtArtifact.class);
|
||||
|
||||
}
|
||||
|
||||
static <T> PagedList<T> mapResponse(final Class<T> clazz, final String responseBody)
|
||||
throws JsonParseException, JsonMappingException, IOException {
|
||||
return mapper.readValue(responseBody, PagedList.class);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* 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.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.exception.SpServerError;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
/**
|
||||
* Tests {@link MgmtSoftwareModuleResource} in case of missing MongoDB
|
||||
* connection.
|
||||
*
|
||||
*/
|
||||
@Features("Component Tests - Management API")
|
||||
@Stories("Download Resource")
|
||||
public class SMRessourceMisingMongoDbConnectionTest extends AbstractIntegrationTest {
|
||||
|
||||
@BeforeClass
|
||||
public static void initialize() {
|
||||
// set property to mongoPort which does not start any mongoDB of
|
||||
// parallel test execution
|
||||
System.setProperty("spring.data.mongodb.port", "1020");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the correct error code is returned in case MongoDB unavailable.")
|
||||
public void missingMongoDbConnectionResultsInErrorAtUpload() throws Exception {
|
||||
|
||||
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
|
||||
assertThat(artifactRepository.findAll()).hasSize(0);
|
||||
SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1",
|
||||
"version 1", null, null);
|
||||
sm = softwareManagement.createSoftwareModule(sm);
|
||||
assertThat(artifactRepository.findAll()).hasSize(0);
|
||||
|
||||
// create test file
|
||||
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
|
||||
final MockMultipartFile file = new MockMultipartFile("file", "origFilename", null, random);
|
||||
|
||||
// upload
|
||||
final MvcResult mvcResult = mvc
|
||||
.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isInternalServerError()).andReturn();
|
||||
|
||||
// check error result
|
||||
final ExceptionInfo exceptionInfo = ResourceUtility
|
||||
.convertException(mvcResult.getResponse().getContentAsString());
|
||||
assertThat(exceptionInfo.getErrorCode()).isEqualTo(SpServerError.SP_ARTIFACT_UPLOAD_FAILED.getKey());
|
||||
assertThat(exceptionInfo.getMessage()).isEqualTo(SpServerError.SP_ARTIFACT_UPLOAD_FAILED.getMessage());
|
||||
|
||||
// ensure that the JPA transaction was rolled back
|
||||
assertThat(artifactRepository.findAll()).hasSize(0);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* 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;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Dennis Melzer
|
||||
*
|
||||
* @param <T>
|
||||
*/
|
||||
public interface SuccessCondition<T> {
|
||||
|
||||
/**
|
||||
*
|
||||
* @param result
|
||||
* @return
|
||||
*/
|
||||
boolean success(final T result);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
#
|
||||
# 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
|
||||
#
|
||||
|
||||
# used if IM profile is disabled
|
||||
security.ignored=true
|
||||
|
||||
# IM required for integration tests
|
||||
spring.profiles.active=im,suiteembedded,artifactrepository,redis
|
||||
|
||||
server.port=12222
|
||||
|
||||
spring.data.mongodb.uri=mongodb://localhost/spArtifactRepository${random.value}
|
||||
spring.data.mongodb.port=28017
|
||||
|
||||
|
||||
# supported: H2, MYSQL
|
||||
hawkbit.server.database=H2
|
||||
hawkbit.server.database.env=TEST
|
||||
spring.main.show_banner=false
|
||||
|
||||
hawkbit.server.ddi.security.authentication.header=true
|
||||
|
||||
hawkbit.server.artifact.repo.upload.maxFileSize=5MB
|
||||
|
||||
hawkbit.server.security.dos.maxStatusEntriesPerAction=100
|
||||
|
||||
hawkbit.server.security.dos.maxAttributeEntriesPerTarget=10
|
||||
|
||||
spring.jpa.database=${hawkbit.server.database}
|
||||
#spring.jpa.show-sql=true
|
||||
|
||||
|
||||
flyway.sqlMigrationSuffix=${spring.jpa.database}.sql
|
||||
|
||||
# effective DB setting
|
||||
spring.datasource.url=${${hawkbit.server.database}.spring.datasource.url}
|
||||
spring.datasource.driverClassName=${${hawkbit.server.database}.spring.datasource.driverClassName}
|
||||
spring.datasource.username=${${hawkbit.server.database}.spring.datasource.username}
|
||||
spring.datasource.password=${${hawkbit.server.database}.spring.datasource.password}
|
||||
|
||||
# H2
|
||||
##;AUTOCOMMIT=ON
|
||||
H2.spring.datasource.url=jdbc:h2:mem:sp-db;DB_CLOSE_ON_EXIT=FALSE
|
||||
#H2.spring.datasource.url=jdbc:h2:./db/sp-db;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE;MVCC=TRUE
|
||||
H2.spring.datasource.driverClassName=org.h2.Driver
|
||||
H2.spring.datasource.username=sa
|
||||
H2.spring.datasource.password=sa
|
||||
|
||||
# MYSQL
|
||||
MYSQL.spring.datasource.url=jdbc:mysql://localhost:3306/sp_test
|
||||
MYSQL.spring.datasource.driverClassName=org.mariadb.jdbc.Driver
|
||||
MYSQL.spring.datasource.username=root
|
||||
MYSQL.spring.datasource.password=
|
||||
|
||||
# SP Controller configuration
|
||||
hawkbit.controller.pollingTime=00:01:00
|
||||
hawkbit.controller.pollingOverdueTime=00:01:00
|
||||
26
hawkbit-mgmt-resource/src/test/resources/log4j2.xml
Normal file
26
hawkbit-mgmt-resource/src/test/resources/log4j2.xml
Normal file
@@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
|
||||
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
|
||||
|
||||
-->
|
||||
<Configuration status="WARN" monitorInterval="30">
|
||||
|
||||
<Appenders>
|
||||
<Console name="Console" target="SYSTEM_OUT" follow="true">
|
||||
<PatternLayout pattern="[%t] [%-5level] %logger{36} - %msg%n" charset="UTF-8"/>
|
||||
</Console>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<Logger name="org.eclipse.hawkbit.MockMvcResultPrinter" level="error" />
|
||||
|
||||
<Root level="error">
|
||||
<AppenderRef ref="Console"/>
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
Reference in New Issue
Block a user