JpaDistributionSet#metadata made Map (#2411)

Signed-off-by: Avgustin Marinov <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2025-05-21 13:45:18 +03:00
committed by GitHub
parent ceba4f5cfb
commit 452d8618d7
26 changed files with 382 additions and 1216 deletions

View File

@@ -35,6 +35,7 @@ import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget;
import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQuery;
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
@@ -44,6 +45,7 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* REST Resource handling for DistributionSet CRUD operations.
@@ -473,15 +475,50 @@ public interface MgmtDistributionSetRestApi {
@RequestBody List<MgmtTargetAssignmentRequestBody> assignments,
@RequestParam(value = "offline", required = false) Boolean offline);
/**
* Creates a list of meta-data for a specific distribution set.
*
* @param distributionSetId the ID of the distribution set to create meta data for
* @param metadataRest the list of meta-data entries to create
*/
@Operation(summary = "Create a list of meta data for a specific distribution set",
description = "Create a list of meta data entries Required permissions: READ_REPOSITORY and UPDATE_TARGET")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Successfully created"),
@ApiResponse(responseCode = "400", description = "Bad Request - e.g. invalid parameters",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ExceptionInfo.class))),
@ApiResponse(responseCode = "401", description = "The request requires user authentication.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "403", description = "Insufficient permissions, entity is not allowed to be " +
"changed (i.e. read-only) or data volume restriction applies.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "404", description = "Distribution Set not found.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "405", description = "The http request method is not allowed on the resource.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "406", description = "In case accept header is specified and not application/json.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "409", description = "E.g. in case an entity is created or modified by another " +
"user in another request at the same time. You may retry your modification request.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "415", description = "The request was attempt with a media-type which is not " +
"supported by the server for this resource.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "429", description = "Too many requests. The server will refuse further attempts " +
"and the client has to wait another second.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true)))
})
@PostMapping(value = MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/{distributionSetId}/metadata",
consumes = { MediaType.APPLICATION_JSON_VALUE, MediaTypes.HAL_JSON_VALUE })
@ResponseStatus(HttpStatus.CREATED)
void createMetadata(
@PathVariable("distributionSetId") Long distributionSetId,
@RequestBody List<MgmtMetadata> metadataRest);
/**
* Gets a paged list of meta-data for a distribution set.
*
* @param distributionSetId the ID of the distribution set for the meta-data
* @param pagingOffsetParam the offset of list of targets for pagination, might not be present in the rest request then default value will
* be applied
* @param pagingLimitParam the limit of the paged request, might not be present in the rest request then default value will be applied
* @param sortParam the sorting parameter in the request URL, syntax {@code field:direction, field:direction}
* @param rsqlParam the search parameter in the request URL, syntax {@code q=key==abc}
* @return status OK if get request is successful with the paged list of meta data
*/
@Operation(summary = "Return meta data for Distribution Set", description = "Get a paged list of meta data for a " +
@@ -507,37 +544,14 @@ public interface MgmtDistributionSetRestApi {
})
@GetMapping(value = MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/{distributionSetId}/metadata",
produces = { MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE })
ResponseEntity<PagedList<MgmtMetadata>> getMetadata(
@PathVariable("distributionSetId") Long distributionSetId,
@RequestParam(
value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET,
defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET)
@Schema(description = "The paging offset (default is 0)")
int pagingOffsetParam,
@RequestParam(
value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT,
defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT)
@Schema(description = "The maximum number of entries in a page (default is 50)")
int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false)
@Schema(description = """
The query parameter sort allows to define the sort order for the result of a query. A sort criteria
consists of the name of a field and the sort direction (ASC for ascending and DESC descending).
The sequence of the sort criteria (multiple can be used) defines the sort order of the entities
in the result.""")
String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false)
@Schema(description = """
Query fields based on the Feed Item Query Language (FIQL). See Entity Definitions for
available fields.""")
String rsqlParam);
ResponseEntity<PagedList<MgmtMetadata>> getMetadata(@PathVariable("distributionSetId") Long distributionSetId);
/**
* Gets a single meta data value for a specific key of a distribution set.
* Gets a single meta-data value for a specific key of a distribution set.
*
* @param distributionSetId the ID of the distribution set to get the meta data from
* @param metadataKey the key of the meta data entry to retrieve the value from
* @return status OK if get request is successful with the value of the meta data
* @param distributionSetId the ID of the distribution set to get the meta-data from
* @param metadataKey the key of the meta-data entry to retrieve the value from
* @return status OK with the value of the meta-data, if the request is successful
*/
@Operation(summary = "Return single meta data value for a specific key of a Distribution Set",
description = "Get a single meta data value for a meta data key. Required permission: READ_REPOSITORY")
@@ -567,12 +581,11 @@ public interface MgmtDistributionSetRestApi {
@PathVariable("metadataKey") String metadataKey);
/**
* Updates a single meta data value of a distribution set.
* Updates a single meta-data value of a distribution set.
*
* @param distributionSetId the ID of the distribution set to update the meta data entry
* @param metadataKey the key of the meta data to update the value
* @param metadataKey the key of the meta-data to update the value
* @param metadata update body
* @return status OK if the update request is successful and the updated meta data result
*/
@Operation(summary = "Update single meta data value of a distribution set", description = "Update a single meta " +
"data value for speficic key. Required permission: UPDATE_REPOSITORY")
@@ -601,9 +614,9 @@ public interface MgmtDistributionSetRestApi {
"and the client has to wait another second.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true)))
})
@PutMapping(value = MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/{distributionSetId}/metadata/{metadataKey}",
produces = { MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE })
ResponseEntity<MgmtMetadata> updateMetadata(
@PutMapping(value = MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/{distributionSetId}/metadata/{metadataKey}")
@ResponseStatus(HttpStatus.OK)
void updateMetadata(
@PathVariable("distributionSetId") Long distributionSetId,
@PathVariable("metadataKey") String metadataKey,
@RequestBody MgmtMetadataBodyPut metadata);
@@ -613,7 +626,6 @@ public interface MgmtDistributionSetRestApi {
*
* @param distributionSetId the ID of the distribution set to delete the meta data entry
* @param metadataKey the key of the meta data to delete
* @return status OK if the delete request is successful
*/
@Operation(summary = "Delete a single meta data entry from the distribution set", description = "Delete a single " +
"meta data. Required permission: UPDATE_REPOSITORY")
@@ -637,51 +649,11 @@ public interface MgmtDistributionSetRestApi {
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true)))
})
@DeleteMapping(value = MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/{distributionSetId}/metadata/{metadataKey}")
ResponseEntity<Void> deleteMetadata(
@ResponseStatus(HttpStatus.OK)
void deleteMetadata(
@PathVariable("distributionSetId") Long distributionSetId,
@PathVariable("metadataKey") String metadataKey);
/**
* Creates a list of meta data for a specific distribution set.
*
* @param distributionSetId the ID of the distribution set to create meta data for
* @param metadataRest the list of meta data entries to create
* @return status created if post request is successful with the value of the created meta data
*/
@Operation(summary = "Create a list of meta data for a specific distribution set", description = "Create a list " +
"of meta data entries Required permissions: READ_REPOSITORY and UPDATE_TARGET")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Successfully created"),
@ApiResponse(responseCode = "400", description = "Bad Request - e.g. invalid parameters",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ExceptionInfo.class))),
@ApiResponse(responseCode = "401", description = "The request requires user authentication.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "403", description = "Insufficient permissions, entity is not allowed to be " +
"changed (i.e. read-only) or data volume restriction applies.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "404", description = "Distribution Set not found.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "405", description = "The http request method is not allowed on the resource.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "406", description = "In case accept header is specified and not application/json.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "409", description = "E.g. in case an entity is created or modified by another " +
"user in another request at the same time. You may retry your modification request.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "415", description = "The request was attempt with a media-type which is not " +
"supported by the server for this resource.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true))),
@ApiResponse(responseCode = "429", description = "Too many requests. The server will refuse further attempts " +
"and the client has to wait another second.",
content = @Content(mediaType = "application/json", schema = @Schema(hidden = true)))
})
@PostMapping(value = MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/{distributionSetId}/metadata",
consumes = { MediaType.APPLICATION_JSON_VALUE, MediaTypes.HAL_JSON_VALUE },
produces = { MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE })
ResponseEntity<List<MgmtMetadata>> createMetadata(
@PathVariable("distributionSetId") Long distributionSetId,
@RequestBody List<MgmtMetadata> metadataRest);
/**
* Assigns a list of software modules to a distribution set.
*

View File

@@ -16,6 +16,8 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@@ -31,7 +33,6 @@ 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.json.model.ResponseList;
@@ -53,16 +54,6 @@ public final class MgmtDistributionSetMapper {
return sets.stream().map(dsRest -> fromRequest(dsRest, entityFactory)).toList();
}
static List<MetaData> fromRequestDsMetadata(final List<MgmtMetadata> metadata, final EntityFactory entityFactory) {
if (metadata == null) {
return Collections.emptyList();
}
return metadata.stream()
.map(metadataRest -> entityFactory.generateDsMetadata(metadataRest.getKey(), metadataRest.getValue()))
.toList();
}
static MgmtDistributionSet toResponse(final DistributionSet distributionSet) {
if (distributionSet == null) {
return null;
@@ -100,10 +91,8 @@ public final class MgmtDistributionSetMapper {
response.add(linkTo(methodOn(MgmtDistributionSetTypeRestApi.class)
.getDistributionSetType(distributionSet.getType().getId())).withRel("type").expand());
response.add(linkTo(methodOn(MgmtDistributionSetRestApi.class).getMetadata(response.getId(),
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null)).withRel("metadata")
.expand());
response.add(linkTo(methodOn(MgmtDistributionSetRestApi.class).getMetadata(response.getId()))
.withRel("metadata").expand());
}
static MgmtTargetAssignmentResponseBody toResponse(final DistributionSetAssignmentResult dsAssignmentResult) {
@@ -138,19 +127,21 @@ public final class MgmtDistributionSetMapper {
sets.stream().map(MgmtDistributionSetMapper::toResponse).toList());
}
static MgmtMetadata toResponseDsMetadata(final DistributionSetMetadata metadata) {
static MgmtMetadata toResponseDsMetadata(final String key, String value) {
final MgmtMetadata metadataRest = new MgmtMetadata();
metadataRest.setKey(metadata.getKey());
metadataRest.setValue(metadata.getValue());
metadataRest.setKey(key);
metadataRest.setValue(value);
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 Map<String, String> fromRequestDsMetadata(final List<MgmtMetadata> metadata) {
return metadata == null
? Collections.emptyMap()
: metadata.stream().collect(Collectors.toMap(MgmtMetadata::getKey, MgmtMetadata::getValue));
}
static List<MgmtMetadata> toResponseDsMetadata(final Map<String, String> metadata) {
return metadata.entrySet().stream().map(e -> toResponseDsMetadata(e.getKey(), e.getValue())).toList();
}
static List<MgmtDistributionSet> toResponseFromDsList(final List<DistributionSet> sets) {

View File

@@ -14,6 +14,7 @@ import java.util.AbstractMap.SimpleEntry;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;
@@ -54,7 +55,6 @@ import org.eclipse.hawkbit.repository.model.DeploymentRequest;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult;
import org.eclipse.hawkbit.repository.model.DistributionSetInvalidation;
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target;
@@ -279,64 +279,37 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
}
@Override
public ResponseEntity<PagedList<MgmtMetadata>> getMetadata(
final Long distributionSetId,
final int pagingOffsetParam, final int pagingLimitParam, final String sortParam, final String rsqlParam) {
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeDistributionSetMetadataSortParam(sortParam);
public void createMetadata(final Long distributionSetId, final List<MgmtMetadata> metadataRest) {
distributionSetManagement.createMetadata(distributionSetId, MgmtDistributionSetMapper.fromRequestDsMetadata(metadataRest));
}
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Page<DistributionSetMetadata> metaDataPage;
if (rsqlParam != null) {
metaDataPage = distributionSetManagement.findMetaDataByDistributionSetIdAndRsql(distributionSetId, rsqlParam, pageable
);
} else {
metaDataPage = distributionSetManagement.findMetaDataByDistributionSetId(distributionSetId, pageable);
}
return ResponseEntity
.ok(new PagedList<>(MgmtDistributionSetMapper.toResponseDsMetadata(metaDataPage.getContent()), metaDataPage.getTotalElements()));
@Override
public ResponseEntity<PagedList<MgmtMetadata>> getMetadata(final Long distributionSetId) {
final Map<String, String> metadata = distributionSetManagement.getMetadata(distributionSetId);
return ResponseEntity.ok(new PagedList<>(MgmtDistributionSetMapper.toResponseDsMetadata(metadata), metadata.size()));
}
@Override
public ResponseEntity<MgmtMetadata> getMetadataValue(final Long distributionSetId, final String metadataKey) {
// check if distribution set exists otherwise throw exception immediately
final DistributionSetMetadata findOne = distributionSetManagement
.findMetaDataByDistributionSetId(distributionSetId, metadataKey)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetMetadata.class, distributionSetId, metadataKey));
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDsMetadata(findOne));
final String metadataValue = distributionSetManagement.getMetadata(distributionSetId).get(metadataKey);
if (metadataValue == null) {
throw new EntityNotFoundException("Target metadata", distributionSetId + ":" + metadataKey);
}
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDsMetadata(metadataKey, metadataValue));
}
@Override
public ResponseEntity<MgmtMetadata> updateMetadata(
final Long distributionSetId, final String metadataKey, final MgmtMetadataBodyPut metadata) {
// check if distribution set exists otherwise throw exception immediately
final DistributionSetMetadata updated = distributionSetManagement.updateMetaData(distributionSetId,
entityFactory.generateDsMetadata(metadataKey, metadata.getValue()));
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDsMetadata(updated));
public void updateMetadata(final Long distributionSetId, final String metadataKey, final MgmtMetadataBodyPut metadata) {
distributionSetManagement.updateMetadata(distributionSetId, metadataKey, metadata.getValue());
}
@Override
public ResponseEntity<Void> deleteMetadata(final Long distributionSetId, final String metadataKey) {
// check if distribution set exists otherwise throw exception immediately
distributionSetManagement.deleteMetaData(distributionSetId, metadataKey);
return ResponseEntity.ok().build();
public void deleteMetadata(final Long distributionSetId, final String metadataKey) {
distributionSetManagement.deleteMetadata(distributionSetId, metadataKey);
}
@Override
public ResponseEntity<List<MgmtMetadata>> createMetadata(final Long distributionSetId, final List<MgmtMetadata> metadataRest) {
// check if distribution set exists otherwise throw exception immediately
final List<DistributionSetMetadata> created = distributionSetManagement.putMetaData(distributionSetId,
MgmtDistributionSetMapper.fromRequestDsMetadata(metadataRest, entityFactory));
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDsMetadata(created), HttpStatus.CREATED);
}
@Override
public ResponseEntity<Void> assignSoftwareModules(
final Long distributionSetId, final List<MgmtSoftwareModuleAssignment> softwareModuleIDs) {
public ResponseEntity<Void> assignSoftwareModules(final Long distributionSetId, final List<MgmtSoftwareModuleAssignment> softwareModuleIDs) {
distributionSetManagement.assignSoftwareModules(
distributionSetId,
softwareModuleIDs.stream()

View File

@@ -15,7 +15,6 @@ 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;
@@ -133,12 +132,12 @@ public final class PagingUtility {
return Sort.by(SortUtility.parse(ActionStatusFields.class, sortParam));
}
public static Sort sanitizeDistributionSetMetadataSortParam(final String sortParam) {
public static Sort sanitizeMetadataSortParam(final String sortParam) {
if (sortParam == null) {
// default
return Sort.by(Direction.ASC, DistributionSetMetadataFields.KEY.getJpaEntityFieldName());
return Sort.by(Direction.ASC, SoftwareModuleMetadataFields.KEY.getJpaEntityFieldName());
}
return Sort.by(SortUtility.parse(DistributionSetMetadataFields.class, sortParam));
return Sort.by(SortUtility.parse(SoftwareModuleMetadataFields.class, sortParam));
}
public static Sort sanitizeSoftwareModuleMetadataSortParam(final String sortParam) {

View File

@@ -30,6 +30,7 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.IntStream;
@@ -51,7 +52,6 @@ import org.eclipse.hawkbit.repository.jpa.specifications.ActionSpecifications;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.NamedEntity;
import org.eclipse.hawkbit.repository.model.Rollout;
@@ -890,20 +890,20 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
.getWithDetails(distributionSetManagement.findByRsql("name==three", PAGE).getContent().get(0).getId())
.get();
assertThat((Object)JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()))
assertThat((Object) JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()))
.hasToString("http://localhost/rest/v1/distributionsets/" + one.getId());
assertThat((Object)JsonPath.compile("[0]id").read(mvcResult.getResponse().getContentAsString()))
assertThat((Object) JsonPath.compile("[0]id").read(mvcResult.getResponse().getContentAsString()))
.hasToString(String.valueOf(one.getId()));
assertThat((Object)JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()))
assertThat((Object) JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()))
.hasToString("http://localhost/rest/v1/distributionsets/" + two.getId());
assertThat((Object)JsonPath.compile("[1]id").read(mvcResult.getResponse().getContentAsString()))
assertThat((Object) JsonPath.compile("[1]id").read(mvcResult.getResponse().getContentAsString()))
.hasToString(String.valueOf(two.getId()));
assertThat((Object)JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()))
assertThat((Object) JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()))
.hasToString("http://localhost/rest/v1/distributionsets/" + three.getId());
assertThat((Object)JsonPath.compile("[2]id").read(mvcResult.getResponse().getContentAsString()))
assertThat((Object) JsonPath.compile("[2]id").read(mvcResult.getResponse().getContentAsString()))
.hasToString(String.valueOf(three.getId()));
// check in database
@@ -1105,23 +1105,14 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
metaData1.put(new JSONObject().put("key", knownKey1).put("value", knownValue1));
metaData1.put(new JSONObject().put("key", knownKey2).put("value", knownValue2));
mvc.perform(post("/rest/v1/distributionsets/{dsId}/metadata", testDS.getId()).accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON).content(metaData1.toString()))
mvc.perform(post("/rest/v1/distributionsets/{dsId}/metadata", testDS.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(metaData1.toString()))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("[0]key", equalTo(knownKey1)))
.andExpect(jsonPath("[0]value", equalTo(knownValue1)))
.andExpect(jsonPath("[1]key", equalTo(knownKey2)))
.andExpect(jsonPath("[1]value", equalTo(knownValue2)));
.andExpect(status().isCreated());
final DistributionSetMetadata metaKey1 = distributionSetManagement
.findMetaDataByDistributionSetId(testDS.getId(), knownKey1).get();
final DistributionSetMetadata metaKey2 = distributionSetManagement
.findMetaDataByDistributionSetId(testDS.getId(), knownKey2).get();
assertThat(metaKey1.getValue()).isEqualTo(knownValue1);
assertThat(metaKey2.getValue()).isEqualTo(knownValue2);
assertThat(distributionSetManagement.getMetadata(testDS.getId()).get(knownKey1)).isEqualTo(knownValue1);
assertThat(distributionSetManagement.getMetadata(testDS.getId()).get(knownKey2)).isEqualTo(knownValue2);
// verify quota enforcement
final int maxMetaData = quotaManagement.getMaxMetaDataEntriesPerDistributionSet();
@@ -1131,17 +1122,14 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
metaData2.put(new JSONObject().put("key", knownKey1 + i).put("value", knownValue1 + i));
}
mvc.perform(post("/rest/v1/distributionsets/{dsId}/metadata", testDS.getId()).accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON).content(metaData2.toString()))
mvc.perform(post("/rest/v1/distributionsets/{dsId}/metadata", testDS.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(metaData2.toString()))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isForbidden());
// verify that the number of meta data entries has not changed
// (we cannot use the PAGE constant here as it tries to sort by ID)
assertThat(distributionSetManagement
.findMetaDataByDistributionSetId(testDS.getId(), PageRequest.of(0, Integer.MAX_VALUE))
.getTotalElements()).isEqualTo(metaData1.length());
// verify that the number of meta-data entries has not changed (we cannot use the PAGE constant here as it tries to sort by ID)
assertThat(distributionSetManagement.getMetadata(testDS.getId())).hasSize(metaData1.length());
}
@Test
@@ -1151,25 +1139,18 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
final String knownKey = "knownKey";
final String knownValue = "knownValue";
final String updateValue = "valueForUpdate";
final DistributionSet testDS = testdataFactory.createDistributionSet("one");
createDistributionSetMetadata(testDS.getId(), entityFactory.generateDsMetadata(knownKey, knownValue));
distributionSetManagement.createMetadata(testDS.getId(), Map.of(knownKey, knownValue));
final JSONObject jsonObject = new JSONObject().put("key", knownKey).put("value", updateValue);
mvc.perform(put("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey)
.accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(jsonObject.toString()))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("key", equalTo(knownKey)))
.andExpect(jsonPath("value", equalTo(updateValue)));
final DistributionSetMetadata assertDS = distributionSetManagement
.findMetaDataByDistributionSetId(testDS.getId(), knownKey).get();
assertThat(assertDS.getValue()).isEqualTo(updateValue);
.andExpect(status().isOk());
assertThat(distributionSetManagement.getMetadata(testDS.getId()).get(knownKey)).isEqualTo(updateValue);
}
@Test
@@ -1180,13 +1161,18 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
final String knownValue = "knownValue";
final DistributionSet testDS = testdataFactory.createDistributionSet("one");
createDistributionSetMetadata(testDS.getId(), entityFactory.generateDsMetadata(knownKey, knownValue));
distributionSetManagement.createMetadata(testDS.getId(), Map.of(knownKey, knownValue));
mvc.perform(delete("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
assertThat(distributionSetManagement.findMetaDataByDistributionSetId(testDS.getId(), knownKey)).isNotPresent();
// already deleted
mvc.perform(delete("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound());
assertThat(distributionSetManagement.getMetadata(testDS.getId()).get(knownKey)).isNull();
}
@Test
@@ -1195,9 +1181,8 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
// prepare and create metadata for deletion
final String knownKey = "knownKey";
final String knownValue = "knownValue";
final DistributionSet testDS = testdataFactory.createDistributionSet("one");
createDistributionSetMetadata(testDS.getId(), entityFactory.generateDsMetadata(knownKey, knownValue));
distributionSetManagement.createMetadata(testDS.getId(), Map.of(knownKey, knownValue));
mvc.perform(delete("/rest/v1/distributionsets/{dsId}/metadata/XXX", testDS.getId(), knownKey))
.andDo(MockMvcResultPrinter.print())
@@ -1207,17 +1192,17 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound());
assertThat(distributionSetManagement.findMetaDataByDistributionSetId(testDS.getId(), knownKey)).isPresent();
assertThat(distributionSetManagement.getMetadata(testDS.getId()).get(knownKey)).isNotNull();
}
@Test
@Description("Ensures that a metadata entry selection through API reflects the repository content.")
void geteMetadataKey() throws Exception {
void getMetadataKey() throws Exception {
// prepare and create metadata
final String knownKey = "knownKey";
final String knownValue = "knownValue";
final DistributionSet testDS = testdataFactory.createDistributionSet("one");
createDistributionSetMetadata(testDS.getId(), entityFactory.generateDsMetadata(knownKey, knownValue));
distributionSetManagement.createMetadata(testDS.getId(), Map.of(knownKey, knownValue));
mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey))
.andDo(MockMvcResultPrinter.print())
@@ -1234,43 +1219,15 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
final String knownValuePrefix = "knownValue";
final DistributionSet testDS = testdataFactory.createDistributionSet("one");
for (int index = 0; index < totalMetadata; index++) {
distributionSetManagement.putMetaData(testDS.getId(),
List.of(entityFactory.generateDsMetadata(knownKeyPrefix + index, knownValuePrefix + index)));
distributionSetManagement.createMetadata(testDS.getId(), Map.of(knownKeyPrefix + index, knownValuePrefix + index));
}
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/{distributionSetId}/metadata",
testDS.getId()))
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/{distributionSetId}/metadata", testDS.getId()))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaTypes.HAL_JSON));
}
@Test
@Description("Ensures that a metadata entry paged list selection through API reflectes the repository content.")
void getPagedListOfMetadata() throws Exception {
final int totalMetadata = 10;
final int limitParam = 5;
final String offsetParam = "0";
final String knownKeyPrefix = "knownKey";
final String knownValuePrefix = "knownValue";
final DistributionSet testDS = testdataFactory.createDistributionSet("one");
for (int index = 0; index < totalMetadata; index++) {
createDistributionSetMetadata(testDS.getId(),
entityFactory.generateDsMetadata(knownKeyPrefix + index, knownValuePrefix + index));
}
mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata?offset=" + offsetParam + "&limit=" + limitParam,
testDS.getId()))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk())
.andExpect(jsonPath("size", equalTo(limitParam)))
.andExpect(jsonPath("total", equalTo(totalMetadata)))
.andExpect(jsonPath("content[0].key", equalTo("knownKey0")))
.andExpect(jsonPath("content[0].value", equalTo("knownValue0")));
}
@Test
@Description("Ensures that a DS search with query parameters returns the expected result.")
void searchDistributionSetRsql() throws Exception {
@@ -1334,29 +1291,6 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
.andExpect(jsonPath("content[0].controllerId", equalTo("1")));
}
@Test
@Description("Ensures that a DS metadata filtered query with value==knownValue1 parameter returns only the metadata entries with that value.")
void searchDistributionSetMetadataRsql() throws Exception {
final int totalMetadata = 10;
final String knownKeyPrefix = "knownKey";
final String knownValuePrefix = "knownValue";
final DistributionSet testDS = testdataFactory.createDistributionSet("one");
for (int index = 0; index < totalMetadata; index++) {
createDistributionSetMetadata(testDS.getId(),
entityFactory.generateDsMetadata(knownKeyPrefix + index, knownValuePrefix + index));
}
final String rsqlSearchValue1 = "value==knownValue1";
mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata?q=" + rsqlSearchValue1, testDS.getId()))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk())
.andExpect(jsonPath("size", equalTo(1)))
.andExpect(jsonPath("total", equalTo(1)))
.andExpect(jsonPath("content[0].key", equalTo("knownKey1")))
.andExpect(jsonPath("content[0].value", equalTo("knownValue1")));
}
@Test
@Description("Ensures that multi target assignment through API is reflected by the repository in the case of "
+ "DOWNLOAD_ONLY.")