hawkBit rest docs (management & DDI API) (#688)

* hawkBit REST docs.

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

* Fiy gitignore.

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

* Add to website.

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

* Switch to generated docs.

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

* Fix typos.

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

* Review findings.

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

* Otimizations.

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

* Revert accidental checkin.

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

* Add security link.
This commit is contained in:
Kai Zimmermann
2018-05-24 16:10:01 +02:00
committed by GitHub
parent 7126d68f31
commit 428e3af2bc
244 changed files with 11636 additions and 430 deletions

View File

@@ -0,0 +1,27 @@
/**
* 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.rest.RestConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Controller;
/**
* Enable {@link ComponentScan} in the resource package to setup all
* {@link Controller} annotated classes and setup the REST-Resources for the
* Management API.
*/
@Configuration
@ComponentScan
@Import(RestConfiguration.class)
public class MgmtApiConfiguration {
}

View File

@@ -0,0 +1,178 @@
/**
* 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.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.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.EntityFactory;
import org.eclipse.hawkbit.repository.builder.DistributionSetCreate;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult;
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
import org.eclipse.hawkbit.repository.model.MetaData;
import org.eclipse.hawkbit.rest.data.ResponseList;
/**
* A mapper which maps repository model to RESTful model representation and
* back.
*/
public final class MgmtDistributionSetMapper {
private MgmtDistributionSetMapper() {
// Utility class
}
/**
* {@link MgmtDistributionSetRequestBodyPost}s to {@link DistributionSet}s.
*
* @param sets
* to convert
* @return converted list of {@link DistributionSet}s
*/
static List<DistributionSetCreate> dsFromRequest(final Collection<MgmtDistributionSetRequestBodyPost> sets,
final EntityFactory entityFactory) {
return sets.stream().map(dsRest -> fromRequest(dsRest, entityFactory)).collect(Collectors.toList());
}
/**
* {@link MgmtDistributionSetRequestBodyPost} to {@link DistributionSet}.
*
* @param dsRest
* to convert
* @return converted {@link DistributionSet}
*/
private static DistributionSetCreate fromRequest(final MgmtDistributionSetRequestBodyPost dsRest,
final EntityFactory entityFactory) {
final List<Long> modules = new ArrayList<>();
if (dsRest.getOs() != null) {
modules.add(dsRest.getOs().getId());
}
if (dsRest.getApplication() != null) {
modules.add(dsRest.getApplication().getId());
}
if (dsRest.getRuntime() != null) {
modules.add(dsRest.getRuntime().getId());
}
if (dsRest.getModules() != null) {
dsRest.getModules().forEach(module -> modules.add(module.getId()));
}
return entityFactory.distributionSet().create().name(dsRest.getName()).version(dsRest.getVersion())
.description(dsRest.getDescription()).type(dsRest.getType()).modules(modules)
.requiredMigrationStep(dsRest.isRequiredMigrationStep());
}
static List<MetaData> fromRequestDsMetadata(final List<MgmtMetadata> metadata, final EntityFactory entityFactory) {
if (metadata == null) {
return Collections.emptyList();
}
return metadata.stream()
.map(metadataRest -> entityFactory.generateMetadata(metadataRest.getKey(), metadataRest.getValue()))
.collect(Collectors.toList());
}
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());
response.setDeleted(distributionSet.isDeleted());
distributionSet.getModules()
.forEach(module -> response.getModules().add(MgmtSoftwareModuleMapper.toResponse(module)));
response.setRequiredMigrationStep(distributionSet.isRequiredMigrationStep());
response.add(linkTo(methodOn(MgmtDistributionSetRestApi.class).getDistributionSet(response.getDsId()))
.withSelfRel());
return response;
}
static void addLinks(final DistributionSet distributionSet, final MgmtDistributionSet response) {
response.add(linkTo(methodOn(MgmtDistributionSetRestApi.class).getAssignedSoftwareModules(response.getDsId(),
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null))
.withRel(MgmtRestConstants.DISTRIBUTIONSET_V1_MODULE));
response.add(linkTo(methodOn(MgmtDistributionSetTypeRestApi.class)
.getDistributionSetType(distributionSet.getType().getId())).withRel("type"));
response.add(linkTo(methodOn(MgmtDistributionSetRestApi.class).getMetadata(response.getDsId(),
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null)).withRel("metadata"));
}
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 Collection<DistributionSet> sets) {
if (sets == null) {
return Collections.emptyList();
}
return new ResponseList<>(
sets.stream().map(MgmtDistributionSetMapper::toResponse).collect(Collectors.toList()));
}
static MgmtMetadata toResponseDsMetadata(final DistributionSetMetadata metadata) {
final MgmtMetadata metadataRest = new MgmtMetadata();
metadataRest.setKey(metadata.getKey());
metadataRest.setValue(metadata.getValue());
return metadataRest;
}
static List<MgmtMetadata> toResponseDsMetadata(final List<DistributionSetMetadata> metadata) {
final List<MgmtMetadata> mappedList = new ArrayList<>(metadata.size());
for (final DistributionSetMetadata distributionSetMetadata : metadata) {
mappedList.add(toResponseDsMetadata(distributionSetMetadata));
}
return mappedList;
}
static List<MgmtDistributionSet> toResponseFromDsList(final List<DistributionSet> sets) {
if (sets == null) {
return Collections.emptyList();
}
return sets.stream().map(MgmtDistributionSetMapper::toResponse).collect(Collectors.toList());
}
}

View File

@@ -0,0 +1,387 @@
/**
* 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.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMaintenanceWindowRequestBody;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadataBodyPut;
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.json.model.targetfilter.MgmtTargetFilterQuery;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.DeploymentManagement;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.MaintenanceScheduleHelper;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement;
import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
import org.eclipse.hawkbit.repository.TargetManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult;
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.eclipse.hawkbit.repository.model.TargetWithActionType;
import org.eclipse.hawkbit.security.SystemSecurityContext;
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;
/**
* 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 SoftwareModuleManagement softwareModuleManagement;
@Autowired
private TargetManagement targetManagement;
@Autowired
private TargetFilterQueryManagement targetFilterQueryManagement;
@Autowired
private DeploymentManagement deployManagament;
@Autowired
private SystemManagement systemManagement;
@Autowired
private EntityFactory entityFactory;
@Autowired
private DistributionSetManagement distributionSetManagement;
@Autowired
private SystemSecurityContext systemSecurityContext;
@Override
public ResponseEntity<PagedList<MgmtDistributionSet>> getDistributionSets(
@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.sanitizeDistributionSetSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Slice<DistributionSet> findDsPage;
final long countModulesAll;
if (rsqlParam != null) {
findDsPage = distributionSetManagement.findByRsql(pageable, rsqlParam);
countModulesAll = ((Page<DistributionSet>) findDsPage).getTotalElements();
} else {
findDsPage = distributionSetManagement.findAll(pageable);
countModulesAll = distributionSetManagement.count();
}
final List<MgmtDistributionSet> rest = MgmtDistributionSetMapper.toResponseFromDsList(findDsPage.getContent());
return ResponseEntity.ok(new PagedList<>(rest, countModulesAll));
}
@Override
public ResponseEntity<MgmtDistributionSet> getDistributionSet(
@PathVariable("distributionSetId") final Long distributionSetId) {
final DistributionSet foundDs = findDistributionSetWithExceptionIfNotFound(distributionSetId);
final MgmtDistributionSet response = MgmtDistributionSetMapper.toResponse(foundDs);
MgmtDistributionSetMapper.addLinks(foundDs, response);
return ResponseEntity.ok(response);
}
@Override
public ResponseEntity<List<MgmtDistributionSet>> createDistributionSets(
@RequestBody final List<MgmtDistributionSetRequestBodyPost> sets) {
LOG.debug("creating {} distribution sets", sets.size());
// set default Ds type if ds type is null
final String defaultDsKey = systemSecurityContext
.runAsSystem(systemManagement.getTenantMetadata().getDefaultDsType()::getKey);
sets.stream().filter(ds -> ds.getType() == null).forEach(ds -> ds.setType(defaultDsKey));
final Collection<DistributionSet> createdDSets = distributionSetManagement
.create(MgmtDistributionSetMapper.dsFromRequest(sets, entityFactory));
LOG.debug("{} distribution sets created, return status {}", sets.size(), HttpStatus.CREATED);
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(createdDSets),
HttpStatus.CREATED);
}
@Override
public ResponseEntity<Void> deleteDistributionSet(@PathVariable("distributionSetId") final Long distributionSetId) {
distributionSetManagement.delete(distributionSetId);
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<MgmtDistributionSet> updateDistributionSet(
@PathVariable("distributionSetId") final Long distributionSetId,
@RequestBody final MgmtDistributionSetRequestBodyPut toUpdate) {
final DistributionSet updated = distributionSetManagement.update(entityFactory.distributionSet()
.update(distributionSetId).name(toUpdate.getName()).description(toUpdate.getDescription())
.version(toUpdate.getVersion()).requiredMigrationStep(toUpdate.isRequiredMigrationStep()));
final MgmtDistributionSet response = MgmtDistributionSetMapper.toResponse(updated);
MgmtDistributionSetMapper.addLinks(updated, response);
return ResponseEntity.ok(response);
}
@Override
public ResponseEntity<PagedList<MgmtTarget>> getAssignedTargets(
@PathVariable("distributionSetId") final Long distributionSetId,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTargetSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Page<Target> targetsAssignedDS;
if (rsqlParam != null) {
targetsAssignedDS = this.targetManagement.findByAssignedDistributionSetAndRsql(pageable, distributionSetId,
rsqlParam);
} else {
targetsAssignedDS = this.targetManagement.findByAssignedDistributionSet(pageable, distributionSetId);
}
return ResponseEntity.ok(new PagedList<>(MgmtTargetMapper.toResponse(targetsAssignedDS.getContent()),
targetsAssignedDS.getTotalElements()));
}
@Override
public ResponseEntity<PagedList<MgmtTarget>> getInstalledTargets(
@PathVariable("distributionSetId") final Long distributionSetId,
@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 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.findByInstalledDistributionSetAndRsql(pageable,
distributionSetId, rsqlParam);
} else {
targetsInstalledDS = this.targetManagement.findByInstalledDistributionSet(pageable, distributionSetId);
}
return ResponseEntity.ok(new PagedList<>(MgmtTargetMapper.toResponse(targetsInstalledDS.getContent()),
targetsInstalledDS.getTotalElements()));
}
@Override
public ResponseEntity<PagedList<MgmtTargetFilterQuery>> getAutoAssignTargetFilterQueries(
@PathVariable("distributionSetId") final Long distributionSetId,
@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.sanitizeTargetFilterQuerySortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Page<TargetFilterQuery> targetFilterQueries = targetFilterQueryManagement
.findByAutoAssignDSAndRsql(pageable, distributionSetId, rsqlParam);
return ResponseEntity
.ok(new PagedList<>(MgmtTargetFilterQueryMapper.toResponse(targetFilterQueries.getContent()),
targetFilterQueries.getTotalElements()));
}
@Override
public ResponseEntity<MgmtTargetAssignmentResponseBody> createAssignedTarget(
@PathVariable("distributionSetId") final Long distributionSetId,
@RequestBody final List<MgmtTargetAssignmentRequestBody> assignments,
@RequestParam(value = "offline", required = false) final boolean offline) {
if (offline) {
return ResponseEntity.ok(MgmtDistributionSetMapper
.toResponse(this.deployManagament.offlineAssignedDistributionSet(distributionSetId, assignments
.stream().map(MgmtTargetAssignmentRequestBody::getId).collect(Collectors.toList()))));
}
final DistributionSetAssignmentResult assignDistributionSet = this.deployManagament
.assignDistributionSet(distributionSetId, assignments.stream().map(t -> {
final MgmtMaintenanceWindowRequestBody maintenanceWindow = t.getMaintenanceWindow();
if (maintenanceWindow == null) {
return new TargetWithActionType(t.getId(), MgmtRestModelMapper.convertActionType(t.getType()),
t.getForcetime());
}
final String cronSchedule = maintenanceWindow.getSchedule();
final String duration = maintenanceWindow.getDuration();
final String timezone = maintenanceWindow.getTimezone();
MaintenanceScheduleHelper.validateMaintenanceSchedule(cronSchedule, duration, timezone);
return new TargetWithActionType(t.getId(), MgmtRestModelMapper.convertActionType(t.getType()),
t.getForcetime(), cronSchedule, duration, timezone);
}).collect(Collectors.toList()));
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponse(assignDistributionSet));
}
@Override
public ResponseEntity<PagedList<MgmtMetadata>> getMetadata(
@PathVariable("distributionSetId") final Long distributionSetId,
@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.sanitizeDistributionSetMetadataSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Page<DistributionSetMetadata> metaDataPage;
if (rsqlParam != null) {
metaDataPage = distributionSetManagement.findMetaDataByDistributionSetIdAndRsql(pageable, distributionSetId,
rsqlParam);
} else {
metaDataPage = distributionSetManagement.findMetaDataByDistributionSetId(pageable, distributionSetId);
}
return ResponseEntity
.ok(new PagedList<>(MgmtDistributionSetMapper.toResponseDsMetadata(metaDataPage.getContent()),
metaDataPage.getTotalElements()));
}
@Override
public ResponseEntity<MgmtMetadata> getMetadataValue(
@PathVariable("distributionSetId") final Long distributionSetId,
@PathVariable("metadataKey") final String metadataKey) {
// check if distribution set exists otherwise throw exception
// immediately
final DistributionSetMetadata findOne = distributionSetManagement
.getMetaDataByDistributionSetId(distributionSetId, metadataKey)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetMetadata.class, distributionSetId,
metadataKey));
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDsMetadata(findOne));
}
@Override
public ResponseEntity<MgmtMetadata> updateMetadata(@PathVariable("distributionSetId") final Long distributionSetId,
@PathVariable("metadataKey") final String metadataKey, @RequestBody final MgmtMetadataBodyPut metadata) {
// check if distribution set exists otherwise throw exception
// immediately
final DistributionSetMetadata updated = distributionSetManagement.updateMetaData(distributionSetId,
entityFactory.generateMetadata(metadataKey, metadata.getValue()));
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDsMetadata(updated));
}
@Override
public ResponseEntity<Void> deleteMetadata(@PathVariable("distributionSetId") final Long distributionSetId,
@PathVariable("metadataKey") final String metadataKey) {
// check if distribution set exists otherwise throw exception
// immediately
distributionSetManagement.deleteMetaData(distributionSetId, metadataKey);
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<List<MgmtMetadata>> createMetadata(
@PathVariable("distributionSetId") final Long distributionSetId,
@RequestBody final List<MgmtMetadata> metadataRest) {
// check if distribution set exists otherwise throw exception
// immediately
final List<DistributionSetMetadata> created = distributionSetManagement.createMetaData(distributionSetId,
MgmtDistributionSetMapper.fromRequestDsMetadata(metadataRest, entityFactory));
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDsMetadata(created), HttpStatus.CREATED);
}
@Override
public ResponseEntity<Void> assignSoftwareModules(@PathVariable("distributionSetId") final Long distributionSetId,
@RequestBody final List<MgmtSoftwareModuleAssigment> softwareModuleIDs) {
distributionSetManagement.assignSoftwareModules(distributionSetId,
softwareModuleIDs.stream().map(MgmtSoftwareModuleAssigment::getId).collect(Collectors.toList()));
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<Void> deleteAssignSoftwareModules(
@PathVariable("distributionSetId") final Long distributionSetId,
@PathVariable("softwareModuleId") final Long softwareModuleId) {
distributionSetManagement.unassignSoftwareModule(distributionSetId, softwareModuleId);
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<PagedList<MgmtSoftwareModule>> getAssignedSoftwareModules(
@PathVariable("distributionSetId") final Long distributionSetId,
@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) {
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 = softwareModuleManagement.findByAssignedTo(pageable,
distributionSetId);
return ResponseEntity.ok(new PagedList<>(MgmtSoftwareModuleMapper.toResponse(softwaremodules.getContent()),
softwaremodules.getTotalElements()));
}
private DistributionSet findDistributionSetWithExceptionIfNotFound(final Long distributionSetId) {
return distributionSetManagement.get(distributionSetId)
.orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, distributionSetId));
}
}

View File

@@ -0,0 +1,249 @@
/**
* 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.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.DistributionSetTagManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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 DistributionSetTag} CRUD operations.
*
*/
@RestController
public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRestApi {
private static final Logger LOG = LoggerFactory.getLogger(MgmtDistributionSetTagResource.class);
@Autowired
private DistributionSetTagManagement distributionSetTagManagement;
@Autowired
private DistributionSetManagement distributionSetManagement;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<PagedList<MgmtTag>> getDistributionSetTags(
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTagSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Slice<DistributionSetTag> distributionSetTags;
final long count;
if (rsqlParam == null) {
distributionSetTags = distributionSetTagManagement.findAll(pageable);
count = distributionSetTagManagement.count();
} else {
final Page<DistributionSetTag> page = distributionSetTagManagement.findByRsql(pageable, rsqlParam);
distributionSetTags = page;
count = page.getTotalElements();
}
final List<MgmtTag> rest = MgmtTagMapper.toResponseDistributionSetTag(distributionSetTags.getContent());
return ResponseEntity.ok(new PagedList<>(rest, count));
}
@Override
public ResponseEntity<MgmtTag> getDistributionSetTag(
@PathVariable("distributionsetTagId") final Long distributionsetTagId) {
final DistributionSetTag distributionSetTag = findDistributionTagById(distributionsetTagId);
final MgmtTag response = MgmtTagMapper.toResponse(distributionSetTag);
MgmtTagMapper.addLinks(distributionSetTag, response);
return ResponseEntity.ok(response);
}
@Override
public ResponseEntity<List<MgmtTag>> createDistributionSetTags(
@RequestBody final List<MgmtTagRequestBodyPut> tags) {
LOG.debug("creating {} ds tags", tags.size());
final List<DistributionSetTag> createdTags = distributionSetTagManagement
.create(MgmtTagMapper.mapTagFromRequest(entityFactory, tags));
return new ResponseEntity<>(MgmtTagMapper.toResponseDistributionSetTag(createdTags), HttpStatus.CREATED);
}
@Override
public ResponseEntity<MgmtTag> updateDistributionSetTag(
@PathVariable("distributionsetTagId") final Long distributionsetTagId,
@RequestBody final MgmtTagRequestBodyPut restDSTagRest) {
final DistributionSetTag distributionSetTag = distributionSetTagManagement
.update(entityFactory.tag().update(distributionsetTagId).name(restDSTagRest.getName())
.description(restDSTagRest.getDescription()).colour(restDSTagRest.getColour()));
final MgmtTag response = MgmtTagMapper.toResponse(distributionSetTag);
MgmtTagMapper.addLinks(distributionSetTag, response);
return ResponseEntity.ok(response);
}
@Override
public ResponseEntity<Void> deleteDistributionSetTag(
@PathVariable("distributionsetTagId") final Long distributionsetTagId) {
LOG.debug("Delete {} distribution set tag", distributionsetTagId);
final DistributionSetTag tag = findDistributionTagById(distributionsetTagId);
distributionSetTagManagement.delete(tag.getName());
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<List<MgmtDistributionSet>> getAssignedDistributionSets(
@PathVariable("distributionsetTagId") final Long distributionsetTagId) {
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDistributionSets(distributionSetManagement
.findByTag(new PageRequest(0, MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT),
distributionsetTagId)
.getContent()));
}
@Override
public ResponseEntity<PagedList<MgmtDistributionSet>> getAssignedDistributionSets(
@PathVariable("distributionsetTagId") final Long distributionsetTagId,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTagSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
Page<DistributionSet> findDistrAll;
if (rsqlParam == null) {
findDistrAll = distributionSetManagement.findByTag(pageable, distributionsetTagId);
} else {
findDistrAll = distributionSetManagement.findByRsqlAndTag(pageable, rsqlParam, distributionsetTagId);
}
final List<MgmtDistributionSet> rest = MgmtDistributionSetMapper
.toResponseFromDsList(findDistrAll.getContent());
return ResponseEntity.ok(new PagedList<>(rest, findDistrAll.getTotalElements()));
}
@Override
public ResponseEntity<MgmtDistributionSetTagAssigmentResult> toggleTagAssignment(
@PathVariable("distributionsetTagId") final Long distributionsetTagId,
@RequestBody 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 ResponseEntity.ok(tagAssigmentResultRest);
}
@Override
public ResponseEntity<List<MgmtDistributionSet>> assignDistributionSets(
@PathVariable("distributionsetTagId") final Long distributionsetTagId,
@RequestBody final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies) {
LOG.debug("Assign DistributionSet {} for ds tag {}", assignedDSRequestBodies.size(), distributionsetTagId);
final List<DistributionSet> assignedDs = this.distributionSetManagement
.assignTag(findDistributionSetIds(assignedDSRequestBodies), distributionsetTagId);
LOG.debug("Assignd DistributionSet {}", assignedDs.size());
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDistributionSets(assignedDs));
}
@Override
public ResponseEntity<Void> unassignDistributionSet(
@PathVariable("distributionsetTagId") final Long distributionsetTagId,
@PathVariable("distributionsetId") final Long distributionsetId) {
LOG.debug("Unassign ds {} for ds tag {}", distributionsetId, distributionsetTagId);
this.distributionSetManagement.unAssignTag(distributionsetId, distributionsetTagId);
return ResponseEntity.ok().build();
}
private DistributionSetTag findDistributionTagById(final Long distributionsetTagId) {
return distributionSetTagManagement.get(distributionsetTagId)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, distributionsetTagId));
}
private static List<Long> findDistributionSetIds(
final List<MgmtAssignedDistributionSetRequestBody> assignedDistributionSetRequestBodies) {
return assignedDistributionSetRequestBodies.stream()
.map(MgmtAssignedDistributionSetRequestBody::getDistributionSetId).collect(Collectors.toList());
}
@Override
public ResponseEntity<MgmtDistributionSetTagAssigmentResult> toggleTagAssignmentUnpaged(
@PathVariable("distributionsetTagId") final Long distributionsetTagId,
@RequestBody final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies) {
return toggleTagAssignment(distributionsetTagId, assignedDSRequestBodies);
}
@Override
public ResponseEntity<List<MgmtDistributionSet>> assignDistributionSetsUnpaged(
@PathVariable("distributionsetTagId") final Long distributionsetTagId,
@RequestBody final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies) {
return assignDistributionSets(distributionsetTagId, assignedDSRequestBodies);
}
@Override
public ResponseEntity<Void> unassignDistributionSetUnpaged(
@PathVariable("distributionsetTagId") final Long distributionsetTagId,
@PathVariable("distributionsetId") final Long distributionsetId) {
return unassignDistributionSet(distributionsetTagId, distributionsetId);
}
}

View File

@@ -0,0 +1,108 @@
/**
* 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.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetType;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost;
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeAssigment;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTypeRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.builder.DistributionSetTypeCreate;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
/**
* A mapper which maps repository model to RESTful model representation and
* back.
*
*/
final class MgmtDistributionSetTypeMapper {
// private constructor, utility class
private MgmtDistributionSetTypeMapper() {
}
static List<DistributionSetTypeCreate> smFromRequest(final EntityFactory entityFactory,
final Collection<MgmtDistributionSetTypeRequestBodyPost> smTypesRest) {
if (smTypesRest == null) {
return Collections.emptyList();
}
return smTypesRest.stream().map(smRest -> fromRequest(entityFactory, smRest)).collect(Collectors.toList());
}
private static DistributionSetTypeCreate fromRequest(final EntityFactory entityFactory,
final MgmtDistributionSetTypeRequestBodyPost smsRest) {
return entityFactory.distributionSetType().create().key(smsRest.getKey()).name(smsRest.getName())
.description(smsRest.getDescription()).colour(smsRest.getColour())
.mandatory(getMandatoryModules(smsRest)).optional(getOptionalmodules(smsRest));
}
private static Collection<Long> getMandatoryModules(final MgmtDistributionSetTypeRequestBodyPost smsRest) {
return Optional.ofNullable(smsRest.getMandatorymodules()).map(
modules -> modules.stream().map(MgmtSoftwareModuleTypeAssigment::getId).collect(Collectors.toList()))
.orElse(Collections.emptyList());
}
private static Collection<Long> getOptionalmodules(final MgmtDistributionSetTypeRequestBodyPost smsRest) {
return Optional.ofNullable(smsRest.getOptionalmodules()).map(
modules -> modules.stream().map(MgmtSoftwareModuleTypeAssigment::getId).collect(Collectors.toList()))
.orElse(Collections.emptyList());
}
static List<MgmtDistributionSetType> toTypesResponse(final List<DistributionSetType> types) {
if (types == null) {
return Collections.emptyList();
}
return types.stream().map(MgmtDistributionSetTypeMapper::toResponse).collect(Collectors.toList());
}
static List<MgmtDistributionSetType> toListResponse(final List<DistributionSetType> types) {
if (types == null) {
return Collections.emptyList();
}
return types.stream().map(MgmtDistributionSetTypeMapper::toResponse).collect(Collectors.toList());
}
static MgmtDistributionSetType toResponse(final DistributionSetType type) {
final MgmtDistributionSetType result = new MgmtDistributionSetType();
MgmtRestModelMapper.mapNamedToNamed(result, type);
result.setKey(type.getKey());
result.setModuleId(type.getId());
result.setDeleted(type.isDeleted());
result.add(linkTo(methodOn(MgmtDistributionSetTypeRestApi.class).getDistributionSetType(result.getModuleId()))
.withSelfRel());
return result;
}
static void addLinks(final MgmtDistributionSetType result) {
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));
}
}

View File

@@ -0,0 +1,226 @@
/**
* 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.Arrays;
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.MgmtDistributionSetType;
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.softwaremoduletype.MgmtSoftwareModuleType;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTypeRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.DistributionSetTypeManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareModuleTypeManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.SoftwareModuleTypeNotInDistributionSetTypeException;
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.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 SoftwareModuleTypeManagement softwareModuleTypeManagement;
@Autowired
private DistributionSetTypeManagement distributionSetTypeManagement;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<PagedList<MgmtDistributionSetType>> 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 = distributionSetTypeManagement.findByRsql(pageable, rsqlParam);
countModulesAll = ((Page<DistributionSetType>) findModuleTypessAll).getTotalElements();
} else {
findModuleTypessAll = distributionSetTypeManagement.findAll(pageable);
countModulesAll = distributionSetTypeManagement.count();
}
final List<MgmtDistributionSetType> rest = MgmtDistributionSetTypeMapper
.toListResponse(findModuleTypessAll.getContent());
return ResponseEntity.ok(new PagedList<>(rest, countModulesAll));
}
@Override
public ResponseEntity<MgmtDistributionSetType> getDistributionSetType(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId) {
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
final MgmtDistributionSetType reponse = MgmtDistributionSetTypeMapper.toResponse(foundType);
MgmtDistributionSetTypeMapper.addLinks(reponse);
return ResponseEntity.ok(reponse);
}
@Override
public ResponseEntity<Void> deleteDistributionSetType(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId) {
distributionSetTypeManagement.delete(distributionSetTypeId);
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<MgmtDistributionSetType> updateDistributionSetType(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId,
@RequestBody final MgmtDistributionSetTypeRequestBodyPut restDistributionSetType) {
final DistributionSetType updated = distributionSetTypeManagement.update(entityFactory.distributionSetType()
.update(distributionSetTypeId).description(restDistributionSetType.getDescription())
.colour(restDistributionSetType.getColour()));
final MgmtDistributionSetType reponse = MgmtDistributionSetTypeMapper.toResponse(updated);
MgmtDistributionSetTypeMapper.addLinks(reponse);
return ResponseEntity.ok(reponse);
}
@Override
public ResponseEntity<List<MgmtDistributionSetType>> createDistributionSetTypes(
@RequestBody final List<MgmtDistributionSetTypeRequestBodyPost> distributionSetTypes) {
final List<DistributionSetType> createdSoftwareModules = distributionSetTypeManagement
.create(MgmtDistributionSetTypeMapper.smFromRequest(entityFactory, distributionSetTypes));
return ResponseEntity.status(HttpStatus.CREATED)
.body(MgmtDistributionSetTypeMapper.toTypesResponse(createdSoftwareModules));
}
private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final Long distributionSetTypeId) {
return distributionSetTypeManagement.get(distributionSetTypeId)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, distributionSetTypeId));
}
@Override
public ResponseEntity<List<MgmtSoftwareModuleType>> getMandatoryModules(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId) {
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
return ResponseEntity.ok(MgmtSoftwareModuleTypeMapper.toTypesResponse(foundType.getMandatoryModuleTypes()));
}
@Override
public ResponseEntity<MgmtSoftwareModuleType> getMandatoryModule(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId,
@PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) {
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
final SoftwareModuleType foundSmType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
if (!foundType.containsMandatoryModuleType(foundSmType)) {
throw new SoftwareModuleTypeNotInDistributionSetTypeException(softwareModuleTypeId, distributionSetTypeId);
}
return ResponseEntity.ok(MgmtSoftwareModuleTypeMapper.toResponse(foundSmType));
}
@Override
public ResponseEntity<MgmtSoftwareModuleType> getOptionalModule(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId,
@PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) {
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
final SoftwareModuleType foundSmType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
if (!foundType.containsOptionalModuleType(foundSmType)) {
throw new SoftwareModuleTypeNotInDistributionSetTypeException(softwareModuleTypeId, distributionSetTypeId);
}
return ResponseEntity.ok(MgmtSoftwareModuleTypeMapper.toResponse(foundSmType));
}
@Override
public ResponseEntity<List<MgmtSoftwareModuleType>> getOptionalModules(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId) {
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
return ResponseEntity.ok(MgmtSoftwareModuleTypeMapper.toTypesResponse(foundType.getOptionalModuleTypes()));
}
@Override
public ResponseEntity<Void> removeMandatoryModule(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId,
@PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) {
distributionSetTypeManagement.unassignSoftwareModuleType(distributionSetTypeId, softwareModuleTypeId);
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<Void> removeOptionalModule(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId,
@PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) {
return removeMandatoryModule(distributionSetTypeId, softwareModuleTypeId);
}
@Override
public ResponseEntity<Void> addMandatoryModule(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @RequestBody final MgmtId smtId) {
distributionSetTypeManagement.assignMandatorySoftwareModuleTypes(distributionSetTypeId,
Arrays.asList(smtId.getId()));
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<Void> addOptionalModule(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @RequestBody final MgmtId smtId) {
distributionSetTypeManagement.assignOptionalSoftwareModuleTypes(distributionSetTypeId,
Arrays.asList(smtId.getId()));
return ResponseEntity.ok().build();
}
private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) {
return softwareModuleTypeManagement.get(softwareModuleTypeId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, softwareModuleTypeId));
}
}

View File

@@ -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 java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.hawkbit.artifact.repository.model.AbstractDbArtifact;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDownloadArtifactRestApi;
import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement;
import org.eclipse.hawkbit.repository.exception.ArtifactBinaryNotFoundException;
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.rest.util.FileStreamingUtil;
import org.eclipse.hawkbit.rest.util.HttpUtil;
import org.eclipse.hawkbit.rest.util.RequestResponseContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
/**
*
*/
@RestController
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class MgmtDownloadArtifactResource implements MgmtDownloadArtifactRestApi {
@Autowired
private SoftwareModuleManagement softwareModuleManagement;
@Autowired
private ArtifactManagement artifactManagement;
@Autowired
private RequestResponseContextHolder requestResponseContextHolder;
/**
* Handles the GET request for downloading an artifact.
*
* @param softwareModuleId
* of the parent SoftwareModule
* @param artifactId
* of the related Artifact
*
* @return responseEntity with status ok if successful
*/
@Override
public ResponseEntity<InputStream> downloadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("artifactId") final Long artifactId) {
final SoftwareModule module = softwareModuleManagement.get(softwareModuleId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
final Artifact artifact = module.getArtifact(artifactId)
.orElseThrow(() -> new EntityNotFoundException(Artifact.class, artifactId));
final AbstractDbArtifact file = artifactManagement.loadArtifactBinary(artifact.getSha1Hash())
.orElseThrow(() -> new ArtifactBinaryNotFoundException(artifact.getSha1Hash()));
final HttpServletRequest request = requestResponseContextHolder.getHttpServletRequest();
final String ifMatch = request.getHeader(HttpHeaders.IF_MATCH);
if (ifMatch != null && !HttpUtil.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) {
return new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED);
}
return FileStreamingUtil.writeFileResponse(file, artifact.getFilename(), artifact.getCreatedAt(),
requestResponseContextHolder.getHttpServletResponse(), request, null);
}
}

View File

@@ -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 java.io.InputStream;
import org.eclipse.hawkbit.artifact.repository.ArtifactRepository;
import org.eclipse.hawkbit.artifact.repository.model.AbstractDbArtifact;
import org.eclipse.hawkbit.cache.DownloadArtifactCache;
import org.eclipse.hawkbit.cache.DownloadIdCache;
import org.eclipse.hawkbit.cache.DownloadType;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDownloadRestApi;
import org.eclipse.hawkbit.rest.util.FileStreamingUtil;
import org.eclipse.hawkbit.rest.util.RequestResponseContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
/**
* A resource for download artifacts.
*/
@RestController
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class MgmtDownloadResource implements MgmtDownloadRestApi {
private static final Logger LOGGER = LoggerFactory.getLogger(MgmtDownloadResource.class);
@Autowired
private ArtifactRepository artifactRepository;
@Autowired
private DownloadIdCache downloadIdCache;
@Autowired
private RequestResponseContextHolder requestResponseContextHolder;
@Override
@ResponseBody
public ResponseEntity<InputStream> downloadArtifactByDownloadId(@PathVariable("tenant") final String tenant,
@PathVariable("downloadId") final String downloadId) {
try {
final DownloadArtifactCache artifactCache = downloadIdCache.get(downloadId);
if (artifactCache == null) {
LOGGER.warn("Download Id {} could not be found", downloadId);
return ResponseEntity.notFound().build();
}
AbstractDbArtifact artifact = null;
if (DownloadType.BY_SHA1.equals(artifactCache.getDownloadType())) {
artifact = artifactRepository.getArtifactBySha1(tenant, artifactCache.getId());
} else {
LOGGER.warn("Download Type {} not supported", artifactCache.getDownloadType());
}
if (artifact == null) {
LOGGER.warn("Artifact with cached id {} and download type {} could not be found.",
artifactCache.getId(), artifactCache.getDownloadType());
return ResponseEntity.notFound().build();
}
return FileStreamingUtil.writeFileResponse(artifact, downloadId, 0L,
requestResponseContextHolder.getHttpServletResponse(),
requestResponseContextHolder.getHttpServletRequest(), null);
} finally {
downloadIdCache.evict(downloadId);
}
}
}

View File

@@ -0,0 +1,99 @@
/**
* 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() > 0) {
response.setCreatedAt(base.getCreatedAt());
}
if (base.getLastModifiedAt() > 0) {
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 the given {@link MgmtActionType} into a corresponding repository
* {@link ActionType}.
*
* @param actionTypeRest
* the REST representation of the action type
*
* @return <null> or the repository action 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");
}
}
/**
* Converts the given repository {@link ActionType} into a corresponding
* {@link MgmtActionType}.
*
* @param actionType
* the repository representation of the action type
*
* @return <null> or the REST action type
*/
public static MgmtActionType convertActionType(final ActionType actionType) {
if (actionType == null) {
return null;
}
switch (actionType) {
case SOFT:
return MgmtActionType.SOFT;
case FORCED:
return MgmtActionType.FORCED;
case TIMEFORCED:
return MgmtActionType.TIMEFORCED;
default:
throw new IllegalStateException("Action Type is not supported");
}
}
}

View File

@@ -0,0 +1,250 @@
/**
* 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.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.json.model.rollout.AbstractMgmtRolloutConditionsEntity;
import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutCondition;
import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutCondition.Condition;
import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutErrorAction;
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;
import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutSuccessAction.SuccessAction;
import org.eclipse.hawkbit.mgmt.json.model.rolloutgroup.MgmtRolloutGroup;
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.EntityFactory;
import org.eclipse.hawkbit.repository.builder.RolloutCreate;
import org.eclipse.hawkbit.repository.builder.RolloutGroupCreate;
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.RolloutGroupConditionBuilder;
import org.eclipse.hawkbit.repository.model.RolloutGroupConditions;
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) {
if (rollouts == null) {
return Collections.emptyList();
}
return rollouts.stream().map(rollout -> toResponseRollout(rollout, false)).collect(Collectors.toList());
}
static MgmtRolloutResponseBody toResponseRollout(final Rollout rollout, final boolean withDetails) {
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());
body.setDeleted(rollout.isDeleted());
if (withDetails) {
for (final TotalTargetCountStatus.Status status : TotalTargetCountStatus.Status.values()) {
body.addTotalTargetsPerStatus(status.name().toLowerCase(),
rollout.getTotalTargetCountStatus().getTotalTargetCountByStatus(status));
}
body.add(linkTo(methodOn(MgmtRolloutRestApi.class).start(rollout.getId())).withRel("start"));
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(),
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null)).withRel("groups"));
}
body.add(linkTo(methodOn(MgmtRolloutRestApi.class).getRollout(rollout.getId())).withSelfRel());
return body;
}
static RolloutCreate fromRequest(final EntityFactory entityFactory, final MgmtRolloutRestRequestBody restRequest,
final DistributionSet distributionSet) {
return entityFactory.rollout().create().name(restRequest.getName()).description(restRequest.getDescription())
.set(distributionSet).targetFilterQuery(restRequest.getTargetFilterQuery())
.actionType(MgmtRestModelMapper.convertActionType(restRequest.getType()))
.forcedTime(restRequest.getForcetime()).startAt(restRequest.getStartAt());
}
static RolloutGroupCreate fromRequest(final EntityFactory entityFactory, final MgmtRolloutGroup restRequest) {
return entityFactory.rolloutGroup().create().name(restRequest.getName())
.description(restRequest.getDescription()).targetFilterQuery(restRequest.getTargetFilterQuery())
.targetPercentage(restRequest.getTargetPercentage()).conditions(fromRequest(restRequest, false));
}
static RolloutGroupConditions fromRequest(final AbstractMgmtRolloutConditionsEntity restRequest,
final boolean withDefaults) {
final RolloutGroupConditionBuilder conditions = new RolloutGroupConditionBuilder();
if (withDefaults) {
conditions.withDefaults();
}
if (restRequest.getSuccessCondition() != null) {
conditions.successCondition(mapFinishCondition(restRequest.getSuccessCondition().getCondition()),
restRequest.getSuccessCondition().getExpression());
}
if (restRequest.getSuccessAction() != null) {
conditions.successAction(map(restRequest.getSuccessAction().getAction()),
restRequest.getSuccessAction().getExpression());
}
if (restRequest.getErrorCondition() != null) {
conditions.errorCondition(mapErrorCondition(restRequest.getErrorCondition().getCondition()),
restRequest.getErrorCondition().getExpression());
}
if (restRequest.getErrorAction() != null) {
conditions.errorAction(map(restRequest.getErrorAction().getAction()),
restRequest.getErrorAction().getExpression());
}
return conditions.build();
}
static List<MgmtRolloutGroupResponseBody> toResponseRolloutGroup(final List<RolloutGroup> rollouts) {
if (rollouts == null) {
return Collections.emptyList();
}
return rollouts.stream().map(group -> toResponseRolloutGroup(group, false)).collect(Collectors.toList());
}
static MgmtRolloutGroupResponseBody toResponseRolloutGroup(final RolloutGroup rolloutGroup,
final boolean withDetailedStatus) {
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.setTargetPercentage(rolloutGroup.getTargetPercentage());
body.setTargetFilterQuery(rolloutGroup.getTargetFilterQuery());
body.setTotalTargets(rolloutGroup.getTotalTargets());
body.setSuccessCondition(new MgmtRolloutCondition(map(rolloutGroup.getSuccessCondition()),
rolloutGroup.getSuccessConditionExp()));
body.setSuccessAction(
new MgmtRolloutSuccessAction(map(rolloutGroup.getSuccessAction()), rolloutGroup.getSuccessActionExp()));
body.setErrorCondition(
new MgmtRolloutCondition(map(rolloutGroup.getErrorCondition()), rolloutGroup.getErrorConditionExp()));
body.setErrorAction(
new MgmtRolloutErrorAction(map(rolloutGroup.getErrorAction()), rolloutGroup.getErrorActionExp()));
if (withDetailedStatus) {
for (final TotalTargetCountStatus.Status status : TotalTargetCountStatus.Status.values()) {
body.addTotalTargetsPerStatus(status.name().toLowerCase(),
rolloutGroup.getTotalTargetCountStatus().getTotalTargetCountByStatus(status));
}
}
body.add(linkTo(methodOn(MgmtRolloutRestApi.class).getRolloutGroup(rolloutGroup.getRollout().getId(),
rolloutGroup.getId())).withSelfRel());
return body;
}
private static RolloutGroupErrorCondition mapErrorCondition(final Condition condition) {
if (Condition.THRESHOLD.equals(condition)) {
return RolloutGroupErrorCondition.THRESHOLD;
}
throw new IllegalArgumentException(createIllegalArgumentLiteral(condition));
}
private static RolloutGroupSuccessCondition mapFinishCondition(final Condition condition) {
if (Condition.THRESHOLD.equals(condition)) {
return RolloutGroupSuccessCondition.THRESHOLD;
}
throw new IllegalArgumentException(createIllegalArgumentLiteral(condition));
}
private static Condition map(final RolloutGroupSuccessCondition rolloutCondition) {
if (RolloutGroupSuccessCondition.THRESHOLD.equals(rolloutCondition)) {
return Condition.THRESHOLD;
}
throw new IllegalArgumentException("Rollout group condition " + rolloutCondition + NOT_SUPPORTED);
}
private static Condition map(final RolloutGroupErrorCondition rolloutCondition) {
if (RolloutGroupErrorCondition.THRESHOLD.equals(rolloutCondition)) {
return Condition.THRESHOLD;
}
throw new IllegalArgumentException("Rollout group condition " + rolloutCondition + NOT_SUPPORTED);
}
private static RolloutGroupErrorAction map(final ErrorAction action) {
if (ErrorAction.PAUSE.equals(action)) {
return RolloutGroupErrorAction.PAUSE;
}
throw new IllegalArgumentException("Error Action " + action + NOT_SUPPORTED);
}
private static RolloutGroupSuccessAction map(final SuccessAction action) {
if (SuccessAction.NEXTGROUP.equals(action)) {
return RolloutGroupSuccessAction.NEXTGROUP;
}
throw new IllegalArgumentException("Success Action " + action + NOT_SUPPORTED);
}
private static SuccessAction map(final RolloutGroupSuccessAction successAction) {
if (RolloutGroupSuccessAction.NEXTGROUP.equals(successAction)) {
return SuccessAction.NEXTGROUP;
}
throw new IllegalArgumentException("Rollout group success action " + successAction + NOT_SUPPORTED);
}
private static ErrorAction map(final RolloutGroupErrorAction errorAction) {
if (RolloutGroupErrorAction.PAUSE.equals(errorAction)) {
return ErrorAction.PAUSE;
}
throw new IllegalArgumentException("Rollout group error action " + errorAction + NOT_SUPPORTED);
}
private static String createIllegalArgumentLiteral(final Condition condition) {
return "Condition " + condition + NOT_SUPPORTED;
}
}

View File

@@ -0,0 +1,228 @@
/**
* 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 javax.validation.ValidationException;
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.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRolloutRestApi;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.RolloutGroupManagement;
import org.eclipse.hawkbit.repository.RolloutManagement;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
import org.eclipse.hawkbit.repository.builder.RolloutCreate;
import org.eclipse.hawkbit.repository.builder.RolloutGroupCreate;
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.RolloutGroupConditions;
import org.eclipse.hawkbit.repository.model.Target;
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.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 rollout CRUD operations.
*
*/
@RestController
public class MgmtRolloutResource implements MgmtRolloutRestApi {
@Autowired
private RolloutManagement rolloutManagement;
@Autowired
private RolloutGroupManagement rolloutGroupManagement;
@Autowired
private DistributionSetManagement distributionSetManagement;
@Autowired
private TargetFilterQueryManagement targetFilterQueryManagement;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<PagedList<MgmtRolloutResponseBody>> getRollouts(
@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.sanitizeRolloutSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Page<Rollout> findModulesAll;
if (rsqlParam != null) {
findModulesAll = this.rolloutManagement.findByRsql(pageable, rsqlParam, false);
} else {
findModulesAll = this.rolloutManagement.findAll(pageable, false);
}
final List<MgmtRolloutResponseBody> rest = MgmtRolloutMapper.toResponseRollout(findModulesAll.getContent());
return ResponseEntity.ok(new PagedList<>(rest, findModulesAll.getTotalElements()));
}
@Override
public ResponseEntity<MgmtRolloutResponseBody> getRollout(@PathVariable("rolloutId") final Long rolloutId) {
final Rollout findRolloutById = rolloutManagement.getWithDetailedStatus(rolloutId)
.orElseThrow(() -> new EntityNotFoundException(Rollout.class, rolloutId));
return ResponseEntity.ok(MgmtRolloutMapper.toResponseRollout(findRolloutById, true));
}
@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
targetFilterQueryManagement.verifyTargetFilterQuerySyntax(rolloutRequestBody.getTargetFilterQuery());
final DistributionSet distributionSet = findDistributionSetOrThrowException(rolloutRequestBody);
final RolloutGroupConditions rolloutGroupConditions = MgmtRolloutMapper.fromRequest(rolloutRequestBody, true);
final RolloutCreate create = MgmtRolloutMapper.fromRequest(entityFactory, rolloutRequestBody, distributionSet);
Rollout rollout;
if (rolloutRequestBody.getGroups() != null) {
final List<RolloutGroupCreate> rolloutGroups = rolloutRequestBody.getGroups().stream()
.map(mgmtRolloutGroup -> MgmtRolloutMapper.fromRequest(entityFactory, mgmtRolloutGroup))
.collect(Collectors.toList());
rollout = rolloutManagement.create(create, rolloutGroups, rolloutGroupConditions);
} else if (rolloutRequestBody.getAmountGroups() != null) {
rollout = rolloutManagement.create(create, rolloutRequestBody.getAmountGroups(),
rolloutGroupConditions);
} else {
throw new ValidationException("Either 'amountGroups' or 'groups' must be defined in the request");
}
return ResponseEntity.status(HttpStatus.CREATED).body(MgmtRolloutMapper.toResponseRollout(rollout, true));
}
@Override
public ResponseEntity<Void> start(@PathVariable("rolloutId") final Long rolloutId) {
this.rolloutManagement.start(rolloutId);
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<Void> pause(@PathVariable("rolloutId") final Long rolloutId) {
this.rolloutManagement.pauseRollout(rolloutId);
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<Void> delete(@PathVariable("rolloutId") final Long rolloutId) {
this.rolloutManagement.delete(rolloutId);
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<Void> resume(@PathVariable("rolloutId") final Long rolloutId) {
this.rolloutManagement.resumeRollout(rolloutId);
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<PagedList<MgmtRolloutGroupResponseBody>> getRolloutGroups(
@PathVariable("rolloutId") final Long rolloutId,
@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.sanitizeRolloutGroupSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Page<RolloutGroup> findRolloutGroupsAll;
if (rsqlParam != null) {
findRolloutGroupsAll = this.rolloutGroupManagement.findByRolloutAndRsql(pageable, rolloutId, rsqlParam);
} else {
findRolloutGroupsAll = this.rolloutGroupManagement.findByRollout(pageable, rolloutId);
}
final List<MgmtRolloutGroupResponseBody> rest = MgmtRolloutMapper
.toResponseRolloutGroup(findRolloutGroupsAll.getContent());
return ResponseEntity.ok(new PagedList<>(rest, findRolloutGroupsAll.getTotalElements()));
}
@Override
public ResponseEntity<MgmtRolloutGroupResponseBody> getRolloutGroup(@PathVariable("rolloutId") final Long rolloutId,
@PathVariable("groupId") final Long groupId) {
findRolloutOrThrowException(rolloutId);
final RolloutGroup rolloutGroup = rolloutGroupManagement.getWithDetailedStatus(groupId)
.orElseThrow(() -> new EntityNotFoundException(RolloutGroup.class, rolloutId));
return ResponseEntity.ok(MgmtRolloutMapper.toResponseRolloutGroup(rolloutGroup, true));
}
private void findRolloutOrThrowException(final Long rolloutId) {
if (!rolloutManagement.exists(rolloutId)) {
throw new EntityNotFoundException(Rollout.class, rolloutId);
}
}
@Override
public ResponseEntity<PagedList<MgmtTarget>> getRolloutGroupTargets(@PathVariable("rolloutId") final Long rolloutId,
@PathVariable("groupId") final Long groupId,
@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) {
findRolloutOrThrowException(rolloutId);
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) {
rolloutGroupTargets = this.rolloutGroupManagement.findTargetsOfRolloutGroupByRsql(pageable, groupId, rsqlParam);
} else {
final Page<Target> pageTargets = this.rolloutGroupManagement.findTargetsOfRolloutGroup(pageable, groupId);
rolloutGroupTargets = pageTargets;
}
final List<MgmtTarget> rest = MgmtTargetMapper.toResponse(rolloutGroupTargets.getContent());
return ResponseEntity.ok(new PagedList<>(rest, rolloutGroupTargets.getTotalElements()));
}
private DistributionSet findDistributionSetOrThrowException(final MgmtRolloutRestRequestBody rolloutRequestBody) {
return this.distributionSetManagement.get(rolloutRequestBody.getDistributionSetId())
.orElseThrow(() -> new EntityNotFoundException(DistributionSet.class,
rolloutRequestBody.getDistributionSetId()));
}
}

View File

@@ -0,0 +1,161 @@
/**
* 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.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
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.MgmtSoftwareModuleMetadata;
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.EntityFactory;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleCreate;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleMetadataCreate;
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.rest.data.ResponseList;
/**
* A mapper which maps repository model to RESTful model representation and
* back.
*
*/
public final class MgmtSoftwareModuleMapper {
private MgmtSoftwareModuleMapper() {
// Utility class
}
private static SoftwareModuleCreate fromRequest(final EntityFactory entityFactory,
final MgmtSoftwareModuleRequestBodyPost smsRest) {
return entityFactory.softwareModule().create().type(smsRest.getType()).name(smsRest.getName())
.version(smsRest.getVersion()).description(smsRest.getDescription()).vendor(smsRest.getVendor());
}
static List<SoftwareModuleMetadataCreate> fromRequestSwMetadata(final EntityFactory entityFactory,
final Long softwareModuleId, final Collection<MgmtSoftwareModuleMetadata> metadata) {
if (metadata == null) {
return Collections.emptyList();
}
return metadata.stream()
.map(metadataRest -> entityFactory.softwareModuleMetadata().create(softwareModuleId)
.key(metadataRest.getKey()).value(metadataRest.getValue())
.targetVisible(metadataRest.isTargetVisible()))
.collect(Collectors.toList());
}
static List<SoftwareModuleCreate> smFromRequest(final EntityFactory entityFactory,
final Collection<MgmtSoftwareModuleRequestBodyPost> smsRest) {
if (smsRest == null) {
return Collections.emptyList();
}
return smsRest.stream().map(smRest -> fromRequest(entityFactory, smRest)).collect(Collectors.toList());
}
static List<MgmtSoftwareModule> toResponse(final Collection<SoftwareModule> softwareModules) {
if (softwareModules == null) {
return Collections.emptyList();
}
return new ResponseList<>(
softwareModules.stream().map(MgmtSoftwareModuleMapper::toResponse).collect(Collectors.toList()));
}
static List<MgmtSoftwareModuleMetadata> toResponseSwMetadata(final Collection<SoftwareModuleMetadata> metadata) {
if (metadata == null) {
return Collections.emptyList();
}
return metadata.stream().map(MgmtSoftwareModuleMapper::toResponseSwMetadata).collect(Collectors.toList());
}
static MgmtSoftwareModuleMetadata toResponseSwMetadata(final SoftwareModuleMetadata metadata) {
final MgmtSoftwareModuleMetadata metadataRest = new MgmtSoftwareModuleMetadata();
metadataRest.setKey(metadata.getKey());
metadataRest.setValue(metadata.getValue());
metadataRest.setTargetVisible(metadata.isTargetVisible());
return metadataRest;
}
static MgmtSoftwareModule toResponse(final SoftwareModule softwareModule) {
if (softwareModule == null) {
return null;
}
final MgmtSoftwareModule response = new MgmtSoftwareModule();
MgmtRestModelMapper.mapNamedToNamed(response, softwareModule);
response.setModuleId(softwareModule.getId());
response.setVersion(softwareModule.getVersion());
response.setType(softwareModule.getType().getKey());
response.setVendor(softwareModule.getVendor());
response.setDeleted(softwareModule.isDeleted());
response.add(linkTo(methodOn(MgmtSoftwareModuleRestApi.class).getSoftwareModule(response.getModuleId()))
.withSelfRel());
return response;
}
static void addLinks(final SoftwareModule softwareModule, final MgmtSoftwareModule response) {
response.add(linkTo(methodOn(MgmtSoftwareModuleRestApi.class).getArtifacts(response.getModuleId()))
.withRel(MgmtRestConstants.SOFTWAREMODULE_V1_ARTIFACT));
response.add(linkTo(
methodOn(MgmtSoftwareModuleTypeRestApi.class).getSoftwareModuleType(softwareModule.getType().getId()))
.withRel(MgmtRestConstants.SOFTWAREMODULE_V1_TYPE));
response.add(linkTo(methodOn(MgmtSoftwareModuleResource.class).getMetadata(response.getModuleId(),
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null)).withRel("metadata")
.expand());
}
static MgmtArtifact toResponse(final Artifact artifact) {
final MgmtArtifact artifactRest = new MgmtArtifact();
artifactRest.setArtifactId(artifact.getId());
artifactRest.setSize(artifact.getSize());
artifactRest.setHashes(new MgmtArtifactHash(artifact.getSha1Hash(), artifact.getMd5Hash()));
artifactRest.setProvidedFilename(artifact.getFilename());
MgmtRestModelMapper.mapBaseToBase(artifactRest, artifact);
artifactRest.add(linkTo(methodOn(MgmtSoftwareModuleRestApi.class)
.getArtifact(artifact.getSoftwareModule().getId(), artifact.getId())).withSelfRel());
return artifactRest;
}
static void addLinks(final Artifact artifact, final MgmtArtifact response) {
response.add(linkTo(methodOn(MgmtDownloadArtifactResource.class)
.downloadArtifact(artifact.getSoftwareModule().getId(), artifact.getId())).withRel("download"));
}
static List<MgmtArtifact> artifactsToResponse(final Collection<Artifact> artifacts) {
if (artifacts == null) {
return Collections.emptyList();
}
return new ResponseList<>(
artifacts.stream().map(MgmtSoftwareModuleMapper::toResponse).collect(Collectors.toList()));
}
}

View File

@@ -0,0 +1,293 @@
/**
* 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.io.InputStream;
import java.util.Collection;
import java.util.List;
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.MgmtSoftwareModuleMetadata;
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleMetadataBodyPut;
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.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement;
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.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.ResponseBody;
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 SoftwareModuleManagement softwareModuleManagement;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<MgmtArtifact> uploadArtifact(@PathVariable("softwareModuleId") 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) {
if (file.isEmpty()) {
return ResponseEntity.badRequest().build();
}
String fileName = optionalFileName;
if (fileName == null) {
fileName = file.getOriginalFilename();
}
try (InputStream in = file.getInputStream()) {
final Artifact result = artifactManagement.create(in, softwareModuleId, fileName,
md5Sum == null ? null : md5Sum.toLowerCase(), sha1Sum == null ? null : sha1Sum.toLowerCase(), false,
file.getContentType(), file.getSize());
final MgmtArtifact reponse = MgmtSoftwareModuleMapper.toResponse(result);
MgmtSoftwareModuleMapper.addLinks(result, reponse);
return ResponseEntity.status(HttpStatus.CREATED).body(reponse);
} catch (final IOException e) {
LOG.error("Failed to store artifact", e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Override
public ResponseEntity<List<MgmtArtifact>> getArtifacts(
@PathVariable("softwareModuleId") final Long softwareModuleId) {
final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
return ResponseEntity.ok(MgmtSoftwareModuleMapper.artifactsToResponse(module.getArtifacts()));
}
@Override
@ResponseBody
// Exception squid:S3655 - Optional access is checked in
// findSoftwareModuleWithExceptionIfNotFound
// subroutine
@SuppressWarnings("squid:S3655")
public ResponseEntity<MgmtArtifact> getArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("artifactId") final Long artifactId) {
final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, artifactId);
final MgmtArtifact reponse = MgmtSoftwareModuleMapper.toResponse(module.getArtifact(artifactId).get());
MgmtSoftwareModuleMapper.addLinks(module.getArtifact(artifactId).get(), reponse);
return ResponseEntity.ok(reponse);
}
@Override
@ResponseBody
public ResponseEntity<Void> deleteArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("artifactId") final Long artifactId) {
findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, artifactId);
artifactManagement.delete(artifactId);
return ResponseEntity.ok().build();
}
@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 = softwareModuleManagement.findByRsql(pageable, rsqlParam);
countModulesAll = ((Page<SoftwareModule>) findModulesAll).getTotalElements();
} else {
findModulesAll = softwareModuleManagement.findAll(pageable);
countModulesAll = softwareModuleManagement.count();
}
final List<MgmtSoftwareModule> rest = MgmtSoftwareModuleMapper.toResponse(findModulesAll.getContent());
return ResponseEntity.ok(new PagedList<>(rest, countModulesAll));
}
@Override
public ResponseEntity<MgmtSoftwareModule> getSoftwareModule(
@PathVariable("softwareModuleId") final Long softwareModuleId) {
final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
final MgmtSoftwareModule response = MgmtSoftwareModuleMapper.toResponse(module);
MgmtSoftwareModuleMapper.addLinks(module, response);
return ResponseEntity.ok(response);
}
@Override
public ResponseEntity<List<MgmtSoftwareModule>> createSoftwareModules(
@RequestBody final List<MgmtSoftwareModuleRequestBodyPost> softwareModules) {
LOG.debug("creating {} softwareModules", softwareModules.size());
final Collection<SoftwareModule> createdSoftwareModules = softwareModuleManagement
.create(MgmtSoftwareModuleMapper.smFromRequest(entityFactory, softwareModules));
LOG.debug("{} softwareModules created, return status {}", softwareModules.size(), HttpStatus.CREATED);
return ResponseEntity.status(HttpStatus.CREATED)
.body(MgmtSoftwareModuleMapper.toResponse(createdSoftwareModules));
}
@Override
public ResponseEntity<MgmtSoftwareModule> updateSoftwareModule(
@PathVariable("softwareModuleId") final Long softwareModuleId,
@RequestBody final MgmtSoftwareModuleRequestBodyPut restSoftwareModule) {
final SoftwareModule module = softwareModuleManagement
.update(entityFactory.softwareModule().update(softwareModuleId)
.description(restSoftwareModule.getDescription()).vendor(restSoftwareModule.getVendor()));
final MgmtSoftwareModule response = MgmtSoftwareModuleMapper.toResponse(module);
MgmtSoftwareModuleMapper.addLinks(module, response);
return ResponseEntity.ok(response);
}
@Override
public ResponseEntity<Void> deleteSoftwareModule(@PathVariable("softwareModuleId") final Long softwareModuleId) {
final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
softwareModuleManagement.delete(module.getId());
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<PagedList<MgmtSoftwareModuleMetadata>> getMetadata(
@PathVariable("softwareModuleId") 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 = softwareModuleManagement.findMetaDataByRsql(pageable, softwareModuleId, rsqlParam);
} else {
metaDataPage = softwareModuleManagement.findMetaDataBySoftwareModuleId(pageable, softwareModuleId);
}
return ResponseEntity
.ok(new PagedList<>(MgmtSoftwareModuleMapper.toResponseSwMetadata(metaDataPage.getContent()),
metaDataPage.getTotalElements()));
}
@Override
public ResponseEntity<MgmtSoftwareModuleMetadata> getMetadataValue(
@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("metadataKey") final String metadataKey) {
final SoftwareModuleMetadata findOne = softwareModuleManagement
.getMetaDataBySoftwareModuleId(softwareModuleId, metadataKey).orElseThrow(
() -> new EntityNotFoundException(SoftwareModuleMetadata.class, softwareModuleId, metadataKey));
return ResponseEntity.ok(MgmtSoftwareModuleMapper.toResponseSwMetadata(findOne));
}
@Override
public ResponseEntity<MgmtSoftwareModuleMetadata> updateMetadata(
@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("metadataKey") final String metadataKey,
@RequestBody final MgmtSoftwareModuleMetadataBodyPut metadata) {
final SoftwareModuleMetadata updated = softwareModuleManagement
.updateMetaData(entityFactory.softwareModuleMetadata().update(softwareModuleId, metadataKey)
.value(metadata.getValue()).targetVisible(metadata.isTargetVisible()));
return ResponseEntity.ok(MgmtSoftwareModuleMapper.toResponseSwMetadata(updated));
}
@Override
public ResponseEntity<Void> deleteMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("metadataKey") final String metadataKey) {
softwareModuleManagement.deleteMetaData(softwareModuleId, metadataKey);
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<List<MgmtSoftwareModuleMetadata>> createMetadata(
@PathVariable("softwareModuleId") final Long softwareModuleId,
@RequestBody final List<MgmtSoftwareModuleMetadata> metadataRest) {
final List<SoftwareModuleMetadata> created = softwareModuleManagement.createMetaData(
MgmtSoftwareModuleMapper.fromRequestSwMetadata(entityFactory, softwareModuleId, metadataRest));
return ResponseEntity.status(HttpStatus.CREATED).body(MgmtSoftwareModuleMapper.toResponseSwMetadata(created));
}
private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId,
final Long artifactId) {
final SoftwareModule module = softwareModuleManagement.get(softwareModuleId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
if (artifactId != null && !module.getArtifact(artifactId).isPresent()) {
throw new EntityNotFoundException(Artifact.class, artifactId);
}
return module;
}
}

View File

@@ -0,0 +1,79 @@
/**
* 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.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
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.EntityFactory;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.rest.data.ResponseList;
/**
* A mapper which maps repository model to RESTful model representation and
* back.
*
*/
final class MgmtSoftwareModuleTypeMapper {
// private constructor, utility class
private MgmtSoftwareModuleTypeMapper() {
}
static List<SoftwareModuleTypeCreate> smFromRequest(final EntityFactory entityFactory,
final Collection<MgmtSoftwareModuleTypeRequestBodyPost> smTypesRest) {
if (smTypesRest == null) {
return Collections.emptyList();
}
return smTypesRest.stream().map(smRest -> fromRequest(entityFactory, smRest)).collect(Collectors.toList());
}
private static SoftwareModuleTypeCreate fromRequest(final EntityFactory entityFactory,
final MgmtSoftwareModuleTypeRequestBodyPost smsRest) {
return entityFactory.softwareModuleType().create().key(smsRest.getKey()).name(smsRest.getName())
.description(smsRest.getDescription()).colour(smsRest.getColour())
.maxAssignments(smsRest.getMaxAssignments());
}
static List<MgmtSoftwareModuleType> toTypesResponse(final Collection<SoftwareModuleType> types) {
if (types == null) {
return Collections.emptyList();
}
return new ResponseList<>(
types.stream().map(MgmtSoftwareModuleTypeMapper::toResponse).collect(Collectors.toList()));
}
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.setDeleted(type.isDeleted());
result.add(linkTo(methodOn(MgmtSoftwareModuleTypeRestApi.class).getSoftwareModuleType(result.getModuleId()))
.withSelfRel());
return result;
}
}

View File

@@ -0,0 +1,123 @@
/**
* 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.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareModuleTypeManagement;
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.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 MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRestApi {
@Autowired
private SoftwareModuleTypeManagement softwareModuleTypeManagement;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<PagedList<MgmtSoftwareModuleType>> getTypes(
@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.sanitizeSoftwareModuleTypeSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Slice<SoftwareModuleType> findModuleTypessAll;
Long countModulesAll;
if (rsqlParam != null) {
findModuleTypessAll = softwareModuleTypeManagement.findByRsql(pageable, rsqlParam);
countModulesAll = ((Page<SoftwareModuleType>) findModuleTypessAll).getTotalElements();
} else {
findModuleTypessAll = softwareModuleTypeManagement.findAll(pageable);
countModulesAll = softwareModuleTypeManagement.count();
}
final List<MgmtSoftwareModuleType> rest = MgmtSoftwareModuleTypeMapper
.toTypesResponse(findModuleTypessAll.getContent());
return ResponseEntity.ok(new PagedList<>(rest, countModulesAll));
}
@Override
public ResponseEntity<MgmtSoftwareModuleType> getSoftwareModuleType(
@PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) {
final SoftwareModuleType foundType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
return ResponseEntity.ok(MgmtSoftwareModuleTypeMapper.toResponse(foundType));
}
@Override
public ResponseEntity<Void> deleteSoftwareModuleType(
@PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) {
softwareModuleTypeManagement.delete(softwareModuleTypeId);
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<MgmtSoftwareModuleType> updateSoftwareModuleType(
@PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId,
@RequestBody final MgmtSoftwareModuleTypeRequestBodyPut restSoftwareModuleType) {
final SoftwareModuleType updatedSoftwareModuleType = softwareModuleTypeManagement
.update(entityFactory.softwareModuleType().update(softwareModuleTypeId)
.description(restSoftwareModuleType.getDescription())
.colour(restSoftwareModuleType.getColour()));
return ResponseEntity.ok(MgmtSoftwareModuleTypeMapper.toResponse(updatedSoftwareModuleType));
}
@Override
public ResponseEntity<List<MgmtSoftwareModuleType>> createSoftwareModuleTypes(
@RequestBody final List<MgmtSoftwareModuleTypeRequestBodyPost> softwareModuleTypes) {
final List<SoftwareModuleType> createdSoftwareModules = softwareModuleTypeManagement.create(
MgmtSoftwareModuleTypeMapper.smFromRequest(entityFactory, softwareModuleTypes));
return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toTypesResponse(createdSoftwareModules),
HttpStatus.CREATED);
}
private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) {
return softwareModuleTypeManagement.get(softwareModuleTypeId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, softwareModuleTypeId));
}
}

View File

@@ -0,0 +1,139 @@
/**
* 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.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.mgmt.json.model.systemmanagement.MgmtSystemCache;
import org.eclipse.hawkbit.mgmt.json.model.systemmanagement.MgmtSystemStatisticsRest;
import org.eclipse.hawkbit.mgmt.json.model.systemmanagement.MgmtSystemTenantServiceUsage;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSystemManagementRestApi;
import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.report.model.SystemUsageReportWithTenants;
import org.eclipse.hawkbit.repository.report.model.TenantUsage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* {@link SystemManagement} capabilities by REST.
*
*/
@RestController
public class MgmtSystemManagementResource implements MgmtSystemManagementRestApi {
private static final Logger LOGGER = LoggerFactory.getLogger(MgmtSystemManagementResource.class);
@Autowired
private SystemManagement systemManagement;
@Autowired
private CacheManager cacheManager;
/**
* Deletes the tenant data of a given tenant. USE WITH CARE!
*
* @param tenant
* to delete
* @return HttpStatus.OK
*/
@Override
public ResponseEntity<Void> deleteTenant(@PathVariable("tenant") final String tenant) {
systemManagement.deleteTenant(tenant);
return ResponseEntity.ok().build();
}
/**
* Collects and returns system usage statistics. It provides a system wide
* overview and tenant based stats.
*
* @return system usage statistics
*/
@Override
public ResponseEntity<MgmtSystemStatisticsRest> getSystemUsageStats() {
final SystemUsageReportWithTenants report = systemManagement.getSystemUsageStatisticsWithTenants();
final MgmtSystemStatisticsRest result = new MgmtSystemStatisticsRest()
.setOverallActions(report.getOverallActions()).setOverallArtifacts(report.getOverallArtifacts())
.setOverallArtifactVolumeInBytes(report.getOverallArtifactVolumeInBytes())
.setOverallTargets(report.getOverallTargets()).setOverallTenants(report.getTenants().size());
result.setTenantStats(report.getTenants().stream().map(MgmtSystemManagementResource::convertTenant)
.collect(Collectors.toList()));
return ResponseEntity.ok(result);
}
private static MgmtSystemTenantServiceUsage convertTenant(final TenantUsage tenant) {
final MgmtSystemTenantServiceUsage result = new MgmtSystemTenantServiceUsage();
result.setTenantName(tenant.getTenantName());
result.setActions(tenant.getActions());
result.setArtifacts(tenant.getArtifacts());
result.setOverallArtifactVolumeInBytes(tenant.getOverallArtifactVolumeInBytes());
result.setTargets(tenant.getTargets());
if (!tenant.getUsageData().isEmpty()) {
result.setUsageData(tenant.getUsageData());
}
return result;
}
/**
* Returns a list of all caches.
*
* @return a list of caches for all tenants
*/
@Override
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN)
public ResponseEntity<Collection<MgmtSystemCache>> getCaches() {
final Collection<String> cacheNames = cacheManager.getCacheNames();
return ResponseEntity
.ok(cacheNames.stream().map(cacheManager::getCache).map(this::cacheRest).collect(Collectors.toList()));
}
/**
* Invalidates all caches for all tenants.
*
* @return a list of cache names which has been invalidated
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN)
@Override
public ResponseEntity<Collection<String>> invalidateCaches() {
final Collection<String> cacheNames = cacheManager.getCacheNames();
LOGGER.info("Invalidating caches {}", cacheNames);
cacheNames.forEach(cacheName -> cacheManager.getCache(cacheName).clear());
return ResponseEntity.ok(cacheNames);
}
private MgmtSystemCache cacheRest(final Cache cache) {
final Object nativeCache = cache.getNativeCache();
if (nativeCache instanceof com.google.common.cache.Cache) {
return guavaCache(cache, nativeCache);
} else {
return new MgmtSystemCache(cache.getName(), Collections.emptyList());
}
}
@SuppressWarnings("unchecked")
private MgmtSystemCache guavaCache(final Cache cache, final Object nativeCache) {
final com.google.common.cache.Cache<Object, Object> guavaCache = (com.google.common.cache.Cache<Object, Object>) nativeCache;
final List<String> keys = guavaCache.asMap().keySet().stream().map(key -> key.toString())
.collect(Collectors.toList());
return new MgmtSystemCache(cache.getName(), keys);
}
}

View File

@@ -0,0 +1,125 @@
/**
* 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 java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTag;
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTagRequestBodyPut;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTagRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetTagRestApi;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.builder.TagCreate;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.Tag;
import org.eclipse.hawkbit.repository.model.TargetTag;
import org.eclipse.hawkbit.rest.data.ResponseList;
/**
* 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 new ResponseList<>(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())).withSelfRel());
return response;
}
static void addLinks(final TargetTag targetTag, final MgmtTag response) {
response.add(linkTo(methodOn(MgmtTargetTagRestApi.class).getAssignedTargets(targetTag.getId(),
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null))
.withRel("assignedTargets"));
}
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 new ResponseList<>(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()))
.withSelfRel());
return response;
}
static void addLinks(final DistributionSetTag distributionSetTag, final MgmtTag response) {
response.add(linkTo(methodOn(MgmtDistributionSetTagRestApi.class).getAssignedDistributionSets(
distributionSetTag.getId(), MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null))
.withRel("assignedDistributionSets"));
}
static List<TagCreate> mapTagFromRequest(final EntityFactory entityFactory,
final Collection<MgmtTagRequestBodyPut> tags) {
return tags.stream()
.map(tagRest -> entityFactory.tag().create().name(tagRest.getName())
.description(tagRest.getDescription()).colour(tagRest.getColour()))
.collect(Collectors.toList());
}
private static void mapTag(final MgmtTag response, final Tag tag) {
MgmtRestModelMapper.mapNamedToNamed(response, tag);
response.setTagId(tag.getId());
response.setColour(tag.getColour());
}
}

View File

@@ -0,0 +1,78 @@
/**
* 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.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQuery;
import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQueryRequestBody;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetFilterQueryRestApi;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.builder.TargetFilterQueryCreate;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.springframework.util.CollectionUtils;
/**
* A mapper which maps repository model to RESTful model representation and
* back.
*
*/
public final class MgmtTargetFilterQueryMapper {
private MgmtTargetFilterQueryMapper() {
// Utility class
}
static List<MgmtTargetFilterQuery> toResponse(final List<TargetFilterQuery> filters) {
if (CollectionUtils.isEmpty(filters)) {
return Collections.emptyList();
}
return filters.stream().map(MgmtTargetFilterQueryMapper::toResponse).collect(Collectors.toList());
}
static MgmtTargetFilterQuery toResponse(final TargetFilterQuery filter) {
final MgmtTargetFilterQuery targetRest = new MgmtTargetFilterQuery();
targetRest.setFilterId(filter.getId());
targetRest.setName(filter.getName());
targetRest.setQuery(filter.getQuery());
targetRest.setCreatedBy(filter.getCreatedBy());
targetRest.setLastModifiedBy(filter.getLastModifiedBy());
targetRest.setCreatedAt(filter.getCreatedAt());
targetRest.setLastModifiedAt(filter.getLastModifiedAt());
final DistributionSet distributionSet = filter.getAutoAssignDistributionSet();
if (distributionSet != null) {
targetRest.setAutoAssignDistributionSet(distributionSet.getId());
}
targetRest.add(linkTo(methodOn(MgmtTargetFilterQueryRestApi.class).getFilter(filter.getId())).withSelfRel());
return targetRest;
}
static void addLinks(final MgmtTargetFilterQuery targetRest) {
targetRest.add(linkTo(methodOn(MgmtTargetFilterQueryRestApi.class)
.postAssignedDistributionSet(targetRest.getFilterId(), null)).withRel("autoAssignDS"));
}
static TargetFilterQueryCreate fromRequest(final EntityFactory entityFactory,
final MgmtTargetFilterQueryRequestBody filterRest) {
return entityFactory.targetFilterQuery().create().name(filterRest.getName()).query(filterRest.getQuery());
}
}

View File

@@ -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 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.distributionset.MgmtDistributionSet;
import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQuery;
import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQueryRequestBody;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetFilterQueryRestApi;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
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;
/**
* REST Resource handling target CRUD operations.
*/
@RestController
public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestApi {
private static final Logger LOG = LoggerFactory.getLogger(MgmtTargetFilterQueryResource.class);
@Autowired
private TargetFilterQueryManagement filterManagement;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<MgmtTargetFilterQuery> getFilter(@PathVariable("filterId") final Long filterId) {
final TargetFilterQuery findTarget = findFilterWithExceptionIfNotFound(filterId);
// to single response include poll status
final MgmtTargetFilterQuery response = MgmtTargetFilterQueryMapper.toResponse(findTarget);
MgmtTargetFilterQueryMapper.addLinks(response);
return ResponseEntity.ok(response);
}
@Override
public ResponseEntity<PagedList<MgmtTargetFilterQuery>> getFilters(
@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.sanitizeTargetFilterQuerySortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Slice<TargetFilterQuery> findTargetFiltersAll;
final Long countTargetsAll;
if (rsqlParam != null) {
final Page<TargetFilterQuery> findFilterPage = filterManagement.findByRsql(pageable, rsqlParam);
countTargetsAll = findFilterPage.getTotalElements();
findTargetFiltersAll = findFilterPage;
} else {
findTargetFiltersAll = filterManagement.findAll(pageable);
countTargetsAll = filterManagement.count();
}
final List<MgmtTargetFilterQuery> rest = MgmtTargetFilterQueryMapper
.toResponse(findTargetFiltersAll.getContent());
return ResponseEntity.ok(new PagedList<>(rest, countTargetsAll));
}
@Override
public ResponseEntity<MgmtTargetFilterQuery> createFilter(
@RequestBody final MgmtTargetFilterQueryRequestBody filter) {
final TargetFilterQuery createdTarget = filterManagement
.create(MgmtTargetFilterQueryMapper.fromRequest(entityFactory, filter));
final MgmtTargetFilterQuery response = MgmtTargetFilterQueryMapper.toResponse(createdTarget);
MgmtTargetFilterQueryMapper.addLinks(response);
return new ResponseEntity<>(response, HttpStatus.CREATED);
}
@Override
public ResponseEntity<MgmtTargetFilterQuery> updateFilter(@PathVariable("filterId") final Long filterId,
@RequestBody final MgmtTargetFilterQueryRequestBody targetFilterRest) {
LOG.debug("updating target filter query {}", filterId);
final TargetFilterQuery updateFilter = filterManagement.update(entityFactory.targetFilterQuery()
.update(filterId).name(targetFilterRest.getName()).query(targetFilterRest.getQuery()));
final MgmtTargetFilterQuery response = MgmtTargetFilterQueryMapper.toResponse(updateFilter);
MgmtTargetFilterQueryMapper.addLinks(response);
return ResponseEntity.ok(response);
}
@Override
public ResponseEntity<Void> deleteFilter(@PathVariable("filterId") final Long filterId) {
filterManagement.delete(filterId);
LOG.debug("{} target filter query deleted, return status {}", filterId, HttpStatus.OK);
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<MgmtTargetFilterQuery> postAssignedDistributionSet(
@PathVariable("filterId") final Long filterId, @RequestBody final MgmtId dsId) {
final TargetFilterQuery updateFilter = filterManagement.updateAutoAssignDS(filterId, dsId.getId());
final MgmtTargetFilterQuery response = MgmtTargetFilterQueryMapper.toResponse(updateFilter);
MgmtTargetFilterQueryMapper.addLinks(response);
return ResponseEntity.ok(response);
}
@Override
public ResponseEntity<MgmtDistributionSet> getAssignedDistributionSet(
@PathVariable("filterId") final Long filterId) {
final TargetFilterQuery filter = findFilterWithExceptionIfNotFound(filterId);
final DistributionSet autoAssignDistributionSet = filter.getAutoAssignDistributionSet();
if (autoAssignDistributionSet == null) {
return ResponseEntity.noContent().build();
}
final MgmtDistributionSet response = MgmtDistributionSetMapper.toResponse(autoAssignDistributionSet);
MgmtDistributionSetMapper.addLinks(autoAssignDistributionSet, response);
return ResponseEntity.ok(response);
}
@Override
public ResponseEntity<Void> deleteAssignedDistributionSet(@PathVariable("filterId") final Long filterId) {
filterManagement.updateAutoAssignDS(filterId, null);
return ResponseEntity.noContent().build();
}
private TargetFilterQuery findFilterWithExceptionIfNotFound(final Long filterId) {
return filterManagement.get(filterId)
.orElseThrow(() -> new EntityNotFoundException(TargetFilterQuery.class, filterId));
}
}

View File

@@ -0,0 +1,264 @@
/**
* 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.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMaintenanceWindow;
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.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.EntityFactory;
import org.eclipse.hawkbit.repository.builder.TargetCreate;
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.PollStatus;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.rest.data.ResponseList;
import org.eclipse.hawkbit.rest.data.SortDirection;
import org.eclipse.hawkbit.util.IpUtil;
import org.springframework.data.domain.PageRequest;
/**
* A mapper which maps repository model to RESTful model representation and
* 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).expand());
}
static void addPollStatus(final Target target, final MgmtTarget targetRest) {
final PollStatus pollStatus = target.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 for targets.
*
* @param targets
* list of targets
* @return the response
*/
public static List<MgmtTarget> toResponse(final Collection<Target> targets) {
if (targets == null) {
return Collections.emptyList();
}
return new ResponseList<>(targets.stream().map(MgmtTargetMapper::toResponse).collect(Collectors.toList()));
}
/**
* 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(target.getUpdateStatus().name().toLowerCase());
final URI address = target.getAddress();
if (address != null) {
if (IpUtil.isIpAddresKnown(address)) {
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.getLastTargetQuery();
final Long installationDate = target.getInstallationDate();
if (lastTargetQuery != null) {
targetRest.setLastControllerRequestAt(lastTargetQuery);
}
if (installationDate != null) {
targetRest.setInstalledAt(installationDate);
}
targetRest.add(linkTo(methodOn(MgmtTargetRestApi.class).getTarget(target.getControllerId())).withSelfRel());
return targetRest;
}
static List<TargetCreate> fromRequest(final EntityFactory entityFactory,
final Collection<MgmtTargetRequestBody> targetsRest) {
if (targetsRest == null) {
return Collections.emptyList();
}
return targetsRest.stream().map(targetRest -> fromRequest(entityFactory, targetRest))
.collect(Collectors.toList());
}
private static TargetCreate fromRequest(final EntityFactory entityFactory, final MgmtTargetRequestBody targetRest) {
return entityFactory.target().create().controllerId(targetRest.getControllerId()).name(targetRest.getName())
.description(targetRest.getDescription()).securityToken(targetRest.getSecurityToken())
.address(targetRest.getAddress());
}
static List<MgmtActionStatus> toActionStatusRestResponse(final Collection<ActionStatus> actionStatus,
final DeploymentManagement deploymentManagement) {
if (actionStatus == null) {
return Collections.emptyList();
}
return actionStatus.stream().map(status -> toResponse(status,
deploymentManagement.findMessagesByActionStatusId(
new PageRequest(0, MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT), status.getId())
.getContent()))
.collect(Collectors.toList());
}
static MgmtAction toResponse(final String targetId, final Action action) {
final MgmtAction result = new MgmtAction();
result.setActionId(action.getId());
result.setType(getType(action));
if (ActionType.TIMEFORCED.equals(action.getActionType())) {
result.setForceTime(action.getForcedTime());
}
result.setForceType(MgmtRestModelMapper.convertActionType(action.getActionType()));
if (action.isActive()) {
result.setStatus(MgmtAction.ACTION_PENDING);
} else {
result.setStatus(MgmtAction.ACTION_FINISHED);
}
if (action.hasMaintenanceSchedule()) {
final MgmtMaintenanceWindow maintenanceWindow = new MgmtMaintenanceWindow();
maintenanceWindow.setSchedule(action.getMaintenanceWindowSchedule());
maintenanceWindow.setDuration(action.getMaintenanceWindowDuration());
maintenanceWindow.setTimezone(action.getMaintenanceWindowTimeZone());
action.getMaintenanceWindowStartTime()
.ifPresent(nextStart -> maintenanceWindow.setNextStartAt(nextStart.toInstant().toEpochMilli()));
result.setMaintenanceWindow(maintenanceWindow);
}
MgmtRestModelMapper.mapBaseToBase(result, action);
result.add(linkTo(methodOn(MgmtTargetRestApi.class).getAction(targetId, action.getId())).withSelfRel());
return result;
}
static MgmtAction toResponseWithLinks(final String controllerId, final Action action) {
final MgmtAction result = toResponse(controllerId, action);
if (action.isCancelingOrCanceled()) {
result.add(linkTo(methodOn(MgmtTargetRestApi.class).getAction(controllerId, action.getId()))
.withRel(MgmtRestConstants.TARGET_V1_CANCELED_ACTION));
} else {
result.add(linkTo(
methodOn(MgmtDistributionSetRestApi.class).getDistributionSet(action.getDistributionSet().getId()))
.withRel("distributionset"));
}
result.add(linkTo(methodOn(MgmtTargetRestApi.class).getActionStatusList(controllerId, action.getId(), 0,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE,
ActionStatusFields.ID.getFieldName() + ":" + SortDirection.DESC))
.withRel(MgmtRestConstants.TARGET_V1_ACTION_STATUS));
return result;
}
static List<MgmtAction> toResponse(final String targetId, final Collection<Action> actions) {
if (actions == null) {
return Collections.emptyList();
}
return actions.stream().map(action -> toResponse(targetId, action)).collect(Collectors.toList());
}
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 MgmtActionStatus toResponse(final ActionStatus actionStatus, final List<String> messages) {
final MgmtActionStatus result = new MgmtActionStatus();
result.setMessages(messages);
result.setReportedAt(actionStatus.getCreatedAt());
result.setStatusId(actionStatus.getId());
result.setType(actionStatus.getStatus().name().toLowerCase());
return result;
}
}

View File

@@ -0,0 +1,344 @@
/**
* 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.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.validation.ValidationException;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMaintenanceWindowRequestBody;
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.MgmtActionRequestBodyPut;
import org.eclipse.hawkbit.mgmt.json.model.action.MgmtActionStatus;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionType;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtTargetAssignmentResponseBody;
import org.eclipse.hawkbit.mgmt.json.model.target.MgmtDistributionSetAssignment;
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.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetRestApi;
import org.eclipse.hawkbit.repository.DeploymentManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.MaintenanceScheduleHelper;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
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.ActionStatus;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetWithActionType;
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;
/**
* 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;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<MgmtTarget> getTarget(@PathVariable("controllerId") final String controllerId) {
final Target findTarget = findTargetWithExceptionIfNotFound(controllerId);
// to single response include poll status
final MgmtTarget response = MgmtTargetMapper.toResponse(findTarget);
MgmtTargetMapper.addPollStatus(findTarget, response);
MgmtTargetMapper.addTargetLinks(response);
return ResponseEntity.ok(response);
}
@Override
public ResponseEntity<PagedList<MgmtTarget>> getTargets(
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTargetSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Slice<Target> findTargetsAll;
final long countTargetsAll;
if (rsqlParam != null) {
final Page<Target> findTargetPage = this.targetManagement.findByRsql(pageable, rsqlParam);
countTargetsAll = findTargetPage.getTotalElements();
findTargetsAll = findTargetPage;
} else {
findTargetsAll = this.targetManagement.findAll(pageable);
countTargetsAll = this.targetManagement.count();
}
final List<MgmtTarget> rest = MgmtTargetMapper.toResponse(findTargetsAll.getContent());
return ResponseEntity.ok(new PagedList<>(rest, countTargetsAll));
}
@Override
public ResponseEntity<List<MgmtTarget>> createTargets(@RequestBody final List<MgmtTargetRequestBody> targets) {
LOG.debug("creating {} targets", targets.size());
final Collection<Target> createdTargets = this.targetManagement
.create(MgmtTargetMapper.fromRequest(entityFactory, targets));
LOG.debug("{} targets created, return status {}", targets.size(), HttpStatus.CREATED);
return new ResponseEntity<>(MgmtTargetMapper.toResponse(createdTargets), HttpStatus.CREATED);
}
@Override
public ResponseEntity<MgmtTarget> updateTarget(@PathVariable("controllerId") final String controllerId,
@RequestBody final MgmtTargetRequestBody targetRest) {
final Target updateTarget = this.targetManagement.update(entityFactory.target().update(controllerId)
.name(targetRest.getName()).description(targetRest.getDescription()).address(targetRest.getAddress())
.securityToken(targetRest.getSecurityToken()));
final MgmtTarget response = MgmtTargetMapper.toResponse(updateTarget);
MgmtTargetMapper.addPollStatus(updateTarget, response);
MgmtTargetMapper.addTargetLinks(response);
return ResponseEntity.ok(response);
}
@Override
public ResponseEntity<Void> deleteTarget(@PathVariable("controllerId") final String controllerId) {
this.targetManagement.deleteByControllerID(controllerId);
LOG.debug("{} target deleted, return status {}", controllerId, HttpStatus.OK);
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<MgmtTargetAttributes> getAttributes(@PathVariable("controllerId") final String controllerId) {
final Map<String, String> controllerAttributes = targetManagement.getControllerAttributes(controllerId);
if (controllerAttributes.isEmpty()) {
return ResponseEntity.noContent().build();
}
final MgmtTargetAttributes result = new MgmtTargetAttributes();
result.putAll(controllerAttributes);
return ResponseEntity.ok(result);
}
@Override
public ResponseEntity<PagedList<MgmtAction>> getActionHistory(
@PathVariable("controllerId") final String controllerId,
@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) {
findTargetWithExceptionIfNotFound(controllerId);
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) {
activeActions = this.deploymentManagement.findActionsByTarget(rsqlParam, controllerId, pageable);
totalActionCount = this.deploymentManagement.countActionsByTarget(rsqlParam, controllerId);
} else {
activeActions = this.deploymentManagement.findActionsByTarget(controllerId, pageable);
totalActionCount = this.deploymentManagement.countActionsByTarget(controllerId);
}
return ResponseEntity.ok(new PagedList<>(MgmtTargetMapper.toResponse(controllerId, activeActions.getContent()),
totalActionCount));
}
@Override
public ResponseEntity<MgmtAction> getAction(@PathVariable("controllerId") final String controllerId,
@PathVariable("actionId") final Long actionId) {
final Action action = deploymentManagement.findAction(actionId)
.orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.getTarget().getControllerId().equals(controllerId)) {
LOG.warn("given action ({}) is not assigned to given target ({}).", action.getId(), controllerId);
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(MgmtTargetMapper.toResponseWithLinks(controllerId, action));
}
@Override
public ResponseEntity<Void> cancelAction(@PathVariable("controllerId") final String controllerId,
@PathVariable("actionId") final Long actionId,
@RequestParam(value = "force", required = false, defaultValue = "false") final boolean force) {
final Action action = deploymentManagement.findAction(actionId)
.orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.getTarget().getControllerId().equals(controllerId)) {
LOG.warn("given action ({}) is not assigned to given target ({}).", actionId, controllerId);
return ResponseEntity.notFound().build();
}
if (force) {
this.deploymentManagement.forceQuitAction(actionId);
} else {
this.deploymentManagement.cancelAction(actionId);
}
// both functions will throw an exception, when action is in wrong
// state, which is mapped by MgmtResponseExceptionHandler.
return ResponseEntity.noContent().build();
}
@Override
public ResponseEntity<PagedList<MgmtActionStatus>> getActionStatusList(
@PathVariable("controllerId") final String controllerId, @PathVariable("actionId") final Long actionId,
@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) {
final Target target = findTargetWithExceptionIfNotFound(controllerId);
final Action action = deploymentManagement.findAction(actionId)
.orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.getTarget().getId().equals(target.getId())) {
LOG.warn("given action ({}) is not assigned to given target ({}).", action.getId(), target.getId());
return ResponseEntity.notFound().build();
}
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.getId());
return ResponseEntity.ok(new PagedList<>(
MgmtTargetMapper.toActionStatusRestResponse(statusList.getContent(), deploymentManagement),
statusList.getTotalElements()));
}
@Override
public ResponseEntity<MgmtDistributionSet> getAssignedDistributionSet(
@PathVariable("controllerId") final String controllerId) {
final MgmtDistributionSet distributionSetRest = deploymentManagement.getAssignedDistributionSet(controllerId)
.map(ds -> {
final MgmtDistributionSet response = MgmtDistributionSetMapper.toResponse(ds);
MgmtDistributionSetMapper.addLinks(ds, response);
return response;
}).orElse(null);
if (distributionSetRest == null) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.ok(distributionSetRest);
}
@Override
public ResponseEntity<MgmtTargetAssignmentResponseBody> postAssignedDistributionSet(
@PathVariable("controllerId") final String controllerId,
@RequestBody final MgmtDistributionSetAssignment dsId,
@RequestParam(value = "offline", required = false) final boolean offline) {
if (offline) {
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponse(
deploymentManagement.offlineAssignedDistributionSet(dsId.getId(), Arrays.asList(controllerId))));
}
findTargetWithExceptionIfNotFound(controllerId);
final MgmtMaintenanceWindowRequestBody maintenanceWindow = dsId.getMaintenanceWindow();
if (maintenanceWindow == null) {
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponse(this.deploymentManagement
.assignDistributionSet(dsId.getId(), Arrays.asList(new TargetWithActionType(controllerId,
MgmtRestModelMapper.convertActionType(dsId.getType()), dsId.getForcetime())))));
}
final String cronSchedule = maintenanceWindow.getSchedule();
final String duration = maintenanceWindow.getDuration();
final String timezone = maintenanceWindow.getTimezone();
MaintenanceScheduleHelper.validateMaintenanceSchedule(cronSchedule, duration, timezone);
return ResponseEntity
.ok(MgmtDistributionSetMapper.toResponse(this.deploymentManagement.assignDistributionSet(dsId.getId(),
Arrays.asList(new TargetWithActionType(controllerId,
MgmtRestModelMapper.convertActionType(dsId.getType()), dsId.getForcetime(),
cronSchedule, duration, timezone)))));
}
@Override
public ResponseEntity<MgmtDistributionSet> getInstalledDistributionSet(
@PathVariable("controllerId") final String controllerId) {
final MgmtDistributionSet distributionSetRest = deploymentManagement.getInstalledDistributionSet(controllerId)
.map(set -> {
final MgmtDistributionSet response = MgmtDistributionSetMapper.toResponse(set);
MgmtDistributionSetMapper.addLinks(set, response);
return response;
}).orElse(null);
if (distributionSetRest == null) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.ok(distributionSetRest);
}
private Target findTargetWithExceptionIfNotFound(final String controllerId) {
return targetManagement.getByControllerID(controllerId)
.orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId));
}
@Override
public ResponseEntity<MgmtAction> updateAction(@PathVariable("controllerId") final String controllerId,
@PathVariable("actionId") final Long actionId, @RequestBody final MgmtActionRequestBodyPut actionUpdate) {
Action action = deploymentManagement.findAction(actionId)
.orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.getTarget().getControllerId().equals(controllerId)) {
LOG.warn("given action ({}) is not assigned to given target ({}).", action.getId(), controllerId);
return ResponseEntity.notFound().build();
}
if (!MgmtActionType.FORCED.equals(actionUpdate.getForceType())) {
throw new ValidationException("Resource supports only switch to FORCED.");
}
action = deploymentManagement.forceTargetAction(actionId);
return ResponseEntity.ok(MgmtTargetMapper.toResponseWithLinks(controllerId, action));
}
}

View File

@@ -0,0 +1,227 @@
/**
* 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.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetTagRestApi;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.TargetManagement;
import org.eclipse.hawkbit.repository.TargetTagManagement;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.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 tag CRUD operations.
*
*/
@RestController
public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
private static final Logger LOG = LoggerFactory.getLogger(MgmtTargetTagResource.class);
@Autowired
private TargetTagManagement tagManagement;
@Autowired
private TargetManagement targetManagement;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<PagedList<MgmtTag>> getTargetTags(
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTagSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
Page<TargetTag> findTargetsAll;
if (rsqlParam == null) {
findTargetsAll = this.tagManagement.findAll(pageable);
} else {
findTargetsAll = this.tagManagement.findByRsql(pageable, rsqlParam);
}
final List<MgmtTag> rest = MgmtTagMapper.toResponse(findTargetsAll.getContent());
return ResponseEntity.ok(new PagedList<>(rest, findTargetsAll.getTotalElements()));
}
@Override
public ResponseEntity<MgmtTag> getTargetTag(@PathVariable("targetTagId") final Long targetTagId) {
final TargetTag tag = findTargetTagById(targetTagId);
final MgmtTag response = MgmtTagMapper.toResponse(tag);
MgmtTagMapper.addLinks(tag, response);
return ResponseEntity.ok(response);
}
@Override
public ResponseEntity<List<MgmtTag>> createTargetTags(@RequestBody final List<MgmtTagRequestBodyPut> tags) {
LOG.debug("creating {} target tags", tags.size());
final List<TargetTag> createdTargetTags = this.tagManagement
.create(MgmtTagMapper.mapTagFromRequest(entityFactory, tags));
return new ResponseEntity<>(MgmtTagMapper.toResponse(createdTargetTags), HttpStatus.CREATED);
}
@Override
public ResponseEntity<MgmtTag> updateTargetTag(@PathVariable("targetTagId") final Long targetTagId,
@RequestBody final MgmtTagRequestBodyPut restTargetTagRest) {
LOG.debug("update {} target tag", restTargetTagRest);
final TargetTag updateTargetTag = tagManagement
.update(entityFactory.tag().update(targetTagId).name(restTargetTagRest.getName())
.description(restTargetTagRest.getDescription()).colour(restTargetTagRest.getColour()));
LOG.debug("target tag updated");
final MgmtTag response = MgmtTagMapper.toResponse(updateTargetTag);
MgmtTagMapper.addLinks(updateTargetTag, response);
return ResponseEntity.ok(response);
}
@Override
public ResponseEntity<Void> deleteTargetTag(@PathVariable("targetTagId") final Long targetTagId) {
LOG.debug("Delete {} target tag", targetTagId);
final TargetTag targetTag = findTargetTagById(targetTagId);
this.tagManagement.delete(targetTag.getName());
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<List<MgmtTarget>> getAssignedTargets(@PathVariable("targetTagId") final Long targetTagId) {
return ResponseEntity.ok(MgmtTargetMapper.toResponse(targetManagement
.findByTag(new PageRequest(0, MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT), targetTagId)
.getContent()));
}
@Override
public ResponseEntity<PagedList<MgmtTarget>> getAssignedTargets(@PathVariable("targetTagId") final Long targetTagId,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTargetSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
Page<Target> findTargetsAll;
if (rsqlParam == null) {
findTargetsAll = targetManagement.findByTag(pageable, targetTagId);
} else {
findTargetsAll = targetManagement.findByRsqlAndTag(pageable, rsqlParam, targetTagId);
}
final Long countTargetsAll = findTargetsAll.getTotalElements();
final List<MgmtTarget> rest = MgmtTargetMapper.toResponse(findTargetsAll.getContent());
return ResponseEntity.ok(new PagedList<>(rest, countTargetsAll));
}
@Override
public ResponseEntity<MgmtTargetTagAssigmentResult> toggleTagAssignment(
@PathVariable("targetTagId") final Long targetTagId,
@RequestBody 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 ResponseEntity.ok(tagAssigmentResultRest);
}
@Override
public ResponseEntity<List<MgmtTarget>> assignTargets(@PathVariable("targetTagId") final Long targetTagId,
@RequestBody final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) {
LOG.debug("Assign Targets {} for target tag {}", assignedTargetRequestBodies.size(), targetTagId);
final List<Target> assignedTarget = this.targetManagement
.assignTag(findTargetControllerIds(assignedTargetRequestBodies), targetTagId);
return ResponseEntity.ok(MgmtTargetMapper.toResponse(assignedTarget));
}
@Override
public ResponseEntity<Void> unassignTarget(@PathVariable("targetTagId") final Long targetTagId,
@PathVariable("controllerId") final String controllerId) {
LOG.debug("Unassign target {} for target tag {}", controllerId, targetTagId);
this.targetManagement.unAssignTag(controllerId, targetTagId);
return ResponseEntity.ok().build();
}
private TargetTag findTargetTagById(final Long targetTagId) {
return tagManagement.get(targetTagId)
.orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagId));
}
private List<String> findTargetControllerIds(
final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) {
return assignedTargetRequestBodies.stream().map(MgmtAssignedTargetRequestBody::getControllerId)
.collect(Collectors.toList());
}
@Override
public ResponseEntity<MgmtTargetTagAssigmentResult> toggleTagAssignmentUnpaged(
@PathVariable("targetTagId") final Long targetTagId,
@RequestBody final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) {
return toggleTagAssignment(targetTagId, assignedTargetRequestBodies);
}
@Override
public ResponseEntity<List<MgmtTarget>> assignTargetsUnpaged(@PathVariable("targetTagId") final Long targetTagId,
@RequestBody final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) {
return assignTargets(targetTagId, assignedTargetRequestBodies);
}
@Override
public ResponseEntity<Void> unassignTargetUnpaged(@PathVariable("targetTagId") final Long targetTagId,
@PathVariable("controllerId") final String controllerId) {
return unassignTarget(targetTagId, controllerId);
}
}

View File

@@ -0,0 +1,58 @@
/**
* 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.Map;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.json.model.system.MgmtSystemTenantConfigurationValue;
import org.eclipse.hawkbit.repository.TenantConfigurationManagement;
import org.eclipse.hawkbit.repository.model.TenantConfigurationValue;
import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties;
import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties.TenantConfigurationKey;
/**
* A mapper which maps repository model to RESTful model representation and
* back.
*/
public final class MgmtTenantManagementMapper {
private MgmtTenantManagementMapper() {
// Utility class
}
static Map<String, MgmtSystemTenantConfigurationValue> toResponse(
final TenantConfigurationManagement tenantConfigurationManagement,
final TenantConfigurationProperties tenantConfigurationProperties) {
return tenantConfigurationProperties.getConfigurationKeys().stream()
.collect(Collectors.toMap(TenantConfigurationKey::getKeyName, key -> toResponse(key.getKeyName(),
tenantConfigurationManagement.getConfigurationValue(key.getKeyName()))));
}
static MgmtSystemTenantConfigurationValue toResponse(final String key,
final TenantConfigurationValue<?> repoConfValue) {
final MgmtSystemTenantConfigurationValue restConfValue = new MgmtSystemTenantConfigurationValue();
restConfValue.setValue(repoConfValue.getValue());
restConfValue.setGlobal(repoConfValue.isGlobal());
restConfValue.setCreatedAt(repoConfValue.getCreatedAt());
restConfValue.setCreatedBy(repoConfValue.getCreatedBy());
restConfValue.setLastModifiedAt(repoConfValue.getLastModifiedAt());
restConfValue.setLastModifiedBy(repoConfValue.getLastModifiedBy());
restConfValue.add(
linkTo(methodOn(MgmtTenantManagementResource.class).getTenantConfigurationValue(key)).withSelfRel());
return restConfValue;
}
}

View File

@@ -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 java.io.Serializable;
import java.util.Map;
import org.eclipse.hawkbit.mgmt.json.model.system.MgmtSystemTenantConfigurationValue;
import org.eclipse.hawkbit.mgmt.json.model.system.MgmtSystemTenantConfigurationValueRequest;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTenantManagementRestApi;
import org.eclipse.hawkbit.repository.TenantConfigurationManagement;
import org.eclipse.hawkbit.repository.model.TenantConfigurationValue;
import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
/**
* REST Resource for handling tenant specific configuration operations.
*/
@RestController
public class MgmtTenantManagementResource implements MgmtTenantManagementRestApi {
private static final Logger LOG = LoggerFactory.getLogger(MgmtTenantManagementResource.class);
private final TenantConfigurationManagement tenantConfigurationManagement;
private final TenantConfigurationProperties tenantConfigurationProperties;
@Autowired
MgmtTenantManagementResource(final TenantConfigurationManagement tenantConfigurationManagement,
final TenantConfigurationProperties tenantConfigurationProperties) {
this.tenantConfigurationManagement = tenantConfigurationManagement;
this.tenantConfigurationProperties = tenantConfigurationProperties;
}
@Override
public ResponseEntity<Map<String, MgmtSystemTenantConfigurationValue>> getTenantConfiguration() {
return ResponseEntity.ok(
MgmtTenantManagementMapper.toResponse(tenantConfigurationManagement, tenantConfigurationProperties));
}
@Override
public ResponseEntity<Void> deleteTenantConfigurationValue(@PathVariable("keyName") final String keyName) {
tenantConfigurationManagement.deleteConfiguration(keyName);
LOG.debug("{} config value deleted, return status {}", keyName, HttpStatus.OK);
return ResponseEntity.ok().build();
}
@Override
public ResponseEntity<MgmtSystemTenantConfigurationValue> getTenantConfigurationValue(
@PathVariable("keyName") final String keyName) {
LOG.debug("{} config value getted, return status {}", keyName, HttpStatus.OK);
return ResponseEntity.ok(MgmtTenantManagementMapper.toResponse(keyName,
tenantConfigurationManagement.getConfigurationValue(keyName)));
}
@Override
public ResponseEntity<MgmtSystemTenantConfigurationValue> updateTenantConfigurationValue(
@PathVariable("keyName") final String keyName,
@RequestBody final MgmtSystemTenantConfigurationValueRequest configurationValueRest) {
final TenantConfigurationValue<? extends Serializable> updatedValue = tenantConfigurationManagement
.addOrUpdateConfiguration(keyName, configurationValueRest.getValue());
return ResponseEntity.ok(MgmtTenantManagementMapper.toResponse(keyName, updatedValue));
}
}

View File

@@ -0,0 +1,161 @@
/**
* 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.TagFields;
import org.eclipse.hawkbit.repository.TargetFields;
import org.eclipse.hawkbit.repository.TargetFilterQueryFields;
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 MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE;
}
return offset;
}
static int sanitizePageLimitParam(final int pageLimit) {
if (pageLimit < 1) {
return MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE;
} 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.CONTROLLERID.getFieldName());
}
return new Sort(SortUtility.parse(TargetFields.class, sortParam));
}
static Sort sanitizeTagSortParam(final String sortParam) {
if (sortParam == null) {
// default
return new Sort(Direction.ASC, TagFields.ID.getFieldName());
}
return new Sort(SortUtility.parse(TagFields.class, sortParam));
}
static Sort sanitizeTargetFilterQuerySortParam(final String sortParam) {
if (sortParam == null) {
// default
return new Sort(Direction.ASC, TargetFilterQueryFields.ID.getFieldName());
}
return new Sort(SortUtility.parse(TargetFilterQueryFields.class, sortParam));
}
static Sort sanitizeSoftwareModuleSortParam(final String sortParam) {
if (sortParam == null) {
// default
return new Sort(Direction.ASC, SoftwareModuleFields.ID.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.ID.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.ID.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.ID.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.ID.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.ID.getFieldName());
}
return new Sort(SortUtility.parse(RolloutGroupFields.class, sortParam));
}
}