Improve JsonBuilder's (#2585)

Signed-off-by: Avgustin Marinov <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2025-08-04 12:54:12 +03:00
committed by GitHub
parent 1d4e0e9959
commit 43f717fc8d
18 changed files with 512 additions and 724 deletions

View File

@@ -0,0 +1,285 @@
/**
* Copyright (c) 2025 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.List;
import java.util.Map;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
import org.eclipse.hawkbit.repository.model.RolloutGroupConditionBuilder;
import org.eclipse.hawkbit.repository.model.RolloutGroupConditions;
import org.eclipse.hawkbit.repository.model.Target;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.util.CollectionUtils;
/**
* Builder class for building certain json strings.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
class JsonBuilder {
static String targets(final List<Target> targets, final boolean withToken) throws JSONException {
final StringBuilder builder = new StringBuilder();
builder.append("[");
int i = 0;
for (final Target target : targets) {
final String address = target.getAddress() != null ? target.getAddress().toString() : null;
final String targetType = target.getTargetType() != null ? target.getTargetType().getId().toString() : null;
final String token = withToken ? target.getSecurityToken() : null;
builder.append(new JSONObject().put("controllerId", target.getControllerId())
.put("description", target.getDescription()).put("name", target.getName()).put("createdAt", "0")
.put("updatedAt", "0").put("createdBy", "systemtest").put("updatedBy", "systemtest")
.put("address", address).put("securityToken", token).put("targetType", targetType).toString());
if (++i < targets.size()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
static String targets(final List<Target> targets, final boolean withToken, final long targetTypeId) throws JSONException {
final StringBuilder builder = new StringBuilder();
builder.append("[");
int i = 0;
for (final Target target : targets) {
final String address = target.getAddress() != null ? target.getAddress().toString() : null;
final String token = withToken ? target.getSecurityToken() : null;
builder.append(new JSONObject().put("controllerId", target.getControllerId())
.put("description", target.getDescription()).put("name", target.getName()).put("createdAt", "0")
.put("updatedAt", "0").put("createdBy", "fghdfkjghdfkjh").put("updatedBy", "fghdfkjghdfkjh")
.put("address", address).put("securityToken", token).put("targetType", targetTypeId).toString());
if (++i < targets.size()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
static String rollout(
final String name, final String description, final int groupSize,
final long distributionSetId, final String targetFilterQuery, final RolloutGroupConditions conditions) {
return rollout(name, description, groupSize, distributionSetId, targetFilterQuery, conditions, null, null, null,
null, null, null);
}
static String rolloutWithGroups(final String name, final String description, final Integer groupSize,
final long distributionSetId, final String targetFilterQuery, final RolloutGroupConditions conditions,
final List<RolloutGroup> groups) {
return rolloutWithGroups(name, description, groupSize, distributionSetId, targetFilterQuery, conditions, groups,
null, null, null);
}
static String rolloutWithGroups(final String name, final String description, final Integer groupSize,
final long distributionSetId, final String targetFilterQuery, final RolloutGroupConditions conditions,
final List<RolloutGroup> groups, final String type, final Integer weight,
final Boolean confirmationRequired) {
final List<String> rolloutGroupsJson = groups.stream().map(JsonBuilder::rolloutGroup).toList();
return rollout(
name, description, groupSize, distributionSetId, targetFilterQuery, conditions,
rolloutGroupsJson, type, weight, System.currentTimeMillis(), null, confirmationRequired);
}
static String rollout(final String name, final String description, final Integer groupSize,
final long distributionSetId, final String targetFilterQuery, final RolloutGroupConditions conditions,
final List<String> groupJsonList, final String type, final Integer weight, final Long startAt, final Long forceTime,
final Boolean confirmationRequired) {
return rollout(name, description, groupSize, distributionSetId, targetFilterQuery, conditions, groupJsonList, type,
weight, startAt, forceTime, confirmationRequired, false, null, 0);
}
static String rollout(final String name, final String description, final Integer groupSize,
final long distributionSetId, final String targetFilterQuery, final RolloutGroupConditions conditions,
final List<String> groupJsonList, final String type, final Integer weight, final Long startAt, final Long forceTime,
final Boolean confirmationRequired, final boolean isDynamic, final String dynamicGroupSuffix, final int dynamicGroupTargetsCount) {
final JSONObject json = new JSONObject();
try {
json.put("name", name);
json.put("description", description);
json.put("amountGroups", groupSize);
json.put("distributionSetId", distributionSetId);
json.put("targetFilterQuery", targetFilterQuery);
if (type != null) {
json.put("type", type);
}
if (weight != null) {
json.put("weight", weight);
}
if (startAt != null) {
json.put("startAt", startAt);
}
if (forceTime != null) {
json.put("forcetime", forceTime);
}
if (confirmationRequired != null) {
json.put("confirmationRequired", confirmationRequired);
}
if (conditions != null) {
final JSONObject successCondition = new JSONObject();
json.put("successCondition", successCondition);
successCondition.put("condition", conditions.getSuccessCondition().toString());
successCondition.put("expression", conditions.getSuccessConditionExp());
final JSONObject successAction = new JSONObject();
json.put("successAction", successAction);
successAction.put("action", conditions.getSuccessAction().toString());
successAction.put("expression", conditions.getSuccessActionExp());
final JSONObject errorCondition = new JSONObject();
json.put("errorCondition", errorCondition);
errorCondition.put("condition", conditions.getErrorCondition().toString());
errorCondition.put("expression", conditions.getErrorConditionExp());
final JSONObject errorAction = new JSONObject();
json.put("errorAction", errorAction);
errorAction.put("action", conditions.getErrorAction().toString());
errorAction.put("expression", conditions.getErrorActionExp());
}
if (isDynamic) {
json.put("dynamic", isDynamic);
final JSONObject dynamicGroupTemplate = new JSONObject();
json.put("dynamicGroupTemplate", dynamicGroupTemplate);
dynamicGroupTemplate.put("nameSuffix",
(dynamicGroupSuffix == null || dynamicGroupSuffix.isEmpty()) ? "-dynamic" : dynamicGroupSuffix);
dynamicGroupTemplate.put("targetCount", dynamicGroupTargetsCount < 0 ? 1 : dynamicGroupTargetsCount);
}
if (!CollectionUtils.isEmpty(groupJsonList)) {
final JSONArray jsonGroups = new JSONArray();
for (final String groupJson : groupJsonList) {
jsonGroups.put(new JSONObject(groupJson));
}
json.put("groups", jsonGroups);
}
} catch (final JSONException e) {
log.error("JSONException (skip)", e);
}
return json.toString();
}
static String rolloutGroup(final RolloutGroup rolloutGroup) {
final RolloutGroupConditions conditions = getConditions(rolloutGroup);
return rolloutGroup(rolloutGroup.getName(), rolloutGroup.getDescription(), rolloutGroup.getTargetFilterQuery(),
rolloutGroup.getTargetPercentage(), rolloutGroup.isConfirmationRequired(), conditions);
}
static String rolloutGroup(final String name, final String description, final String targetFilterQuery,
final Float targetPercentage, final Boolean confirmationRequired,
final RolloutGroupConditions rolloutGroupConditions) {
final JSONObject jsonGroup = new JSONObject();
try {
jsonGroup.put("name", name);
jsonGroup.put("description", description);
jsonGroup.put("targetFilterQuery", targetFilterQuery);
if (targetPercentage == null) {
jsonGroup.put("targetPercentage", 100F);
} else {
jsonGroup.put("targetPercentage", targetPercentage);
}
if (confirmationRequired != null) {
jsonGroup.put("confirmationRequired", confirmationRequired);
}
if (rolloutGroupConditions.getSuccessCondition() != null) {
final JSONObject successCondition = new JSONObject();
jsonGroup.put("successCondition", successCondition);
successCondition.put("condition", rolloutGroupConditions.getSuccessCondition().toString());
successCondition.put("expression", rolloutGroupConditions.getSuccessConditionExp());
}
if (rolloutGroupConditions.getSuccessAction() != null) {
final JSONObject successAction = new JSONObject();
jsonGroup.put("successAction", successAction);
successAction.put("action", rolloutGroupConditions.getSuccessAction().toString());
successAction.put("expression", rolloutGroupConditions.getSuccessActionExp());
}
if (rolloutGroupConditions.getErrorCondition() != null) {
final JSONObject errorCondition = new JSONObject();
jsonGroup.put("errorCondition", errorCondition);
errorCondition.put("condition", rolloutGroupConditions.getErrorCondition().toString());
errorCondition.put("expression", rolloutGroupConditions.getErrorConditionExp());
}
if (rolloutGroupConditions.getErrorAction() != null) {
final JSONObject errorAction = new JSONObject();
jsonGroup.put("errorAction", errorAction);
errorAction.put("action", rolloutGroupConditions.getErrorAction().toString());
errorAction.put("expression", rolloutGroupConditions.getErrorActionExp());
}
} catch (final JSONException e) {
log.error("JSONException (skip)", e);
fail("Cannot parse JSON for rollout group.");
}
return jsonGroup.toString();
}
static JSONObject configData(final Map<String, String> attributes) throws JSONException {
return configData(attributes, null);
}
static JSONObject configData(final Map<String, String> attributes, final String mode) throws JSONException {
final JSONObject data = new JSONObject();
attributes.forEach((key, value) -> {
try {
data.put(key, value);
} catch (final JSONException e) {
log.error("JSONException (skip)", e);
}
});
final JSONObject json = new JSONObject().put("data", data);
if (mode != null) {
json.put("mode", mode);
}
return json;
}
private static RolloutGroupConditions getConditions(final RolloutGroup rolloutGroup) {
return new RolloutGroupConditionBuilder()
.errorCondition(rolloutGroup.getErrorCondition(), rolloutGroup.getErrorConditionExp())
.errorAction(rolloutGroup.getErrorAction(), rolloutGroup.getErrorActionExp())
.successAction(rolloutGroup.getSuccessAction(), rolloutGroup.getSuccessActionExp())
.successCondition(rolloutGroup.getSuccessCondition(), rolloutGroup.getSuccessConditionExp()).build();
}
}

View File

@@ -16,11 +16,11 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Collections;
import java.util.List;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSetRequestBodyPost;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -45,11 +45,14 @@ import org.springframework.test.web.servlet.MvcResult;
public class MgmtContentTypeTest extends AbstractManagementApiIntegrationTest {
private static final String DS_NAME = "DS-ö";
private DistributionSetManagement.Create dsCreate;
private MgmtDistributionSetRequestBodyPost dsCreatePost;
@BeforeEach
public void setupBeforeTest() {
dsCreate = DistributionSetManagement.Create.builder().type(defaultDsType()).name(DS_NAME).version("1.0").build();
dsCreatePost = (MgmtDistributionSetRequestBodyPost)new MgmtDistributionSetRequestBodyPost()
.setType(defaultDsType().getKey())
.setName(DS_NAME)
.setVersion("1.0");
}
/**
@@ -58,8 +61,7 @@ public class MgmtContentTypeTest extends AbstractManagementApiIntegrationTest {
@Test
void postDistributionSet_ContentTypeJsonUtf8_woAccept() throws Exception {
final MvcResult result = mvc.perform(
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING).content(JsonBuilder.distributionSets(
Collections.singletonList(dsCreate)))
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING).content(toJson(List.of(dsCreatePost)))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isCreated())
@@ -75,8 +77,7 @@ public class MgmtContentTypeTest extends AbstractManagementApiIntegrationTest {
@Test
void postDistributionSet_ContentTypeJsonUtf8_wAcceptJson() throws Exception {
final MvcResult result = mvc.perform(
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING).content(JsonBuilder.distributionSets(
Collections.singletonList(dsCreate)))
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING).content(toJson(List.of(dsCreatePost)))
.contentType(MediaType.APPLICATION_JSON_UTF8).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isCreated())
@@ -92,8 +93,7 @@ public class MgmtContentTypeTest extends AbstractManagementApiIntegrationTest {
@Test
void postDistributionSet_ContentTypeJsonUtf8_wAcceptJsonUtf8() throws Exception {
final MvcResult result = mvc.perform(
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING).content(JsonBuilder.distributionSets(
Collections.singletonList(dsCreate)))
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING).content(toJson(List.of(dsCreatePost)))
.contentType(MediaType.APPLICATION_JSON_UTF8).accept(MediaType.APPLICATION_JSON_UTF8))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isCreated())
@@ -109,8 +109,7 @@ public class MgmtContentTypeTest extends AbstractManagementApiIntegrationTest {
@Test
void postDistributionSet_ContentTypeJsonUtf8_wAcceptHalJson() throws Exception {
final MvcResult result = mvc.perform(
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING).content(JsonBuilder.distributionSets(
Collections.singletonList(dsCreate)))
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING).content(toJson(List.of(dsCreatePost)))
.contentType(MediaType.APPLICATION_JSON_UTF8).accept(MediaTypes.HAL_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isCreated())
@@ -126,8 +125,7 @@ public class MgmtContentTypeTest extends AbstractManagementApiIntegrationTest {
@Test
void postDistributionSet_ContentTypeJson_woAccept() throws Exception {
final MvcResult result = mvc.perform(
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING).content(JsonBuilder.distributionSets(
Collections.singletonList(dsCreate)))
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING).content(toJson(List.of(dsCreatePost)))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isCreated())
@@ -143,8 +141,7 @@ public class MgmtContentTypeTest extends AbstractManagementApiIntegrationTest {
@Test
void postDistributionSet_ContentTypeJson_wAcceptJson() throws Exception {
final MvcResult result = mvc.perform(
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING).content(JsonBuilder.distributionSets(
Collections.singletonList(dsCreate)))
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING).content(toJson(List.of(dsCreatePost)))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isCreated())
@@ -159,9 +156,8 @@ public class MgmtContentTypeTest extends AbstractManagementApiIntegrationTest {
*/
@Test
void postDistributionSet_ContentTypeJson_wAcceptJsonUtf8() throws Exception {
final MvcResult result = mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING)
.content(JsonBuilder.distributionSets(Collections.singletonList(dsCreate))).contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON_UTF8))
final MvcResult result = mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING).content(toJson(List.of(dsCreatePost)))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON_UTF8))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isCreated())
.andExpect(jsonPath("[0]name", equalTo(DS_NAME)))
@@ -176,7 +172,7 @@ public class MgmtContentTypeTest extends AbstractManagementApiIntegrationTest {
@Test
void postDistributionSet_ContentTypeJson_wAcceptHalJson() throws Exception {
final MvcResult result = mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING)
.content(JsonBuilder.distributionSets(Collections.singletonList(dsCreate))).contentType(MediaType.APPLICATION_JSON)
.content(toJson(List.of(dsCreatePost))).contentType(MediaType.APPLICATION_JSON)
.accept(MediaTypes.HAL_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isCreated())

View File

@@ -28,7 +28,6 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -38,7 +37,11 @@ import java.util.stream.Stream;
import com.jayway.jsonpath.JsonPath;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.mgmt.json.model.MgmtId;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionType;
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.softwaremodule.MgmtSoftwareModuleAssignment;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.resource.util.ResourceUtility;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
@@ -60,7 +63,6 @@ import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.test.util.TestdataFactory;
import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.json.JSONArray;
import org.json.JSONException;
@@ -223,7 +225,7 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
// post assignment
mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")
.contentType(MediaType.APPLICATION_JSON).content(JsonBuilder.ids(smIDs)))
.contentType(MediaType.APPLICATION_JSON).content(toJson(smIDs.stream().map(MgmtId::new).toList())))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
// Test if size is 3
@@ -240,7 +242,7 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
}
// post assignment
final String jsonIDs = JsonBuilder.ids(moduleIDs.subList(0, maxSoftwareModules - smIDs.size()));
final String jsonIDs = toJson(moduleIDs.subList(0, maxSoftwareModules - smIDs.size()).stream().map(MgmtId::new).toList());
mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")
.contentType(MediaType.APPLICATION_JSON).content(jsonIDs))
.andDo(MockMvcResultPrinter.print())
@@ -255,7 +257,7 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
// post one more to cause the quota to be exceeded
mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonBuilder.ids(Collections.singletonList(moduleIDs.get(moduleIDs.size() - 1)))))
.content(toJson(List.of(moduleIDs.get(moduleIDs.size() - 1)).stream().map(MgmtId::new).toList())))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isForbidden())
.andExpect(jsonPath("$.exceptionClass", equalTo(AssignmentQuotaExceededException.class.getName())))
@@ -264,7 +266,7 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
// verify quota is also enforced for bulk uploads
final DistributionSet disSet2 = testdataFactory.createDistributionSetWithNoSoftwareModules("Saturn", "4.0");
mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet2.getId() + "/assignedSM")
.contentType(MediaType.APPLICATION_JSON).content(JsonBuilder.ids(moduleIDs)))
.contentType(MediaType.APPLICATION_JSON).content(toJson(moduleIDs.stream().map(MgmtId::new).toList())))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isForbidden())
.andExpect(jsonPath("$.exceptionClass", equalTo(AssignmentQuotaExceededException.class.getName())))
@@ -291,10 +293,9 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
.andExpect(status().isOk())
.andExpect(jsonPath("$.size", equalTo(amountOfSM)));
// test the removal of all software modules one by one
for (final Iterator<SoftwareModule> iter = set.getModules().iterator(); iter.hasNext(); ) {
final Long smId = iter.next().getId();
mvc.perform(delete(
MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM/" + smId))
for (final SoftwareModule softwareModule : set.getModules()) {
final Long smId = softwareModule.getId();
mvc.perform(delete(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM/" + smId))
.andExpect(status().isOk());
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM"))
.andDo(MockMvcResultPrinter.print())
@@ -361,8 +362,7 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
final SoftwareModule softwareModule = testdataFactory.createSoftwareModule("exampleKey");
final DistributionSetType type = testdataFactory.findOrCreateDistributionSetType(
"testKey", "testType", List.of(softwareModule.getType()), List.of());
final DistributionSet ds = testdataFactory.createDistributionSet("dsName", "dsVersion", type,
Collections.singletonList(softwareModule));
final DistributionSet ds = testdataFactory.createDistributionSet("dsName", "dsVersion", type, List.of(softwareModule));
final Target target = testdataFactory.createTarget("exampleControllerId");
assignDistributionSet(ds, target);
@@ -383,7 +383,7 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
"stanTest", "2", reloaded, Collections.singletonList(softwareModule));
final MvcResult mvcResult = mvc
.perform(post("/rest/v1/distributionsets")
.content(JsonBuilder.distributionSets(Collections.singletonList(generated)))
.content(toJson(toMgmtDistributionSetPost(List.of(generated))))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
@@ -938,9 +938,9 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
final long current = System.currentTimeMillis();
final MvcResult mvcResult = executeMgmtTargetPost(
testdataFactory.generateDistributionSet("one", "one", standardDsType, Arrays.asList(os, jvm, ah)),
testdataFactory.generateDistributionSet("two", "two", standardDsType, Arrays.asList(os, jvm, ah)),
testdataFactory.generateDistributionSet("three", "three", standardDsType, Arrays.asList(os, jvm, ah), true));
testdataFactory.generateDistributionSet("one", "one", standardDsType, List.of(os, jvm, ah)),
testdataFactory.generateDistributionSet("two", "two", standardDsType, List.of(os, jvm, ah)),
testdataFactory.generateDistributionSet("three", "three", standardDsType, List.of(os, jvm, ah), true));
final DistributionSet one = distributionSetManagement
.getWithDetails(distributionSetManagement.findByRsql("name==one", PAGE).getContent().get(0).getId()).orElseThrow();
@@ -1136,20 +1136,20 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
.andExpect(status().isBadRequest());
final DistributionSetManagement.Create missingName = DistributionSetManagement.Create.builder().build();
mvc.perform(post("/rest/v1/distributionsets").content(JsonBuilder.distributionSets(Collections.singletonList(missingName)))
mvc.perform(post("/rest/v1/distributionsets").content(toJson(List.of(missingName)))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
final DistributionSetManagement.Create toLongName =
testdataFactory.generateDistributionSet(randomString(NamedEntity.NAME_MAX_SIZE + 1));
mvc.perform(post("/rest/v1/distributionsets").content(JsonBuilder.distributionSets(Collections.singletonList(toLongName)))
mvc.perform(post("/rest/v1/distributionsets").content(toJson(List.of(toLongName)))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
// unsupported media type
mvc.perform(post("/rest/v1/distributionsets").content(JsonBuilder.distributionSets(sets))
mvc.perform(post("/rest/v1/distributionsets").content(toJson(sets))
.contentType(MediaType.APPLICATION_OCTET_STREAM))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isUnsupportedMediaType());
@@ -1828,8 +1828,7 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
final DistributionSetManagement.Create two,
final DistributionSetManagement.Create three) throws Exception {
return mvc
.perform(post("/rest/v1/distributionsets")
.content(JsonBuilder.distributionSets(Arrays.asList(one, two, three)))
.perform(post("/rest/v1/distributionsets").content(toJson(toMgmtDistributionSetPost(List.of(one, two, three))))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isCreated())
@@ -1876,6 +1875,22 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
.andReturn();
}
private static List<MgmtDistributionSetRequestBodyPut> toMgmtDistributionSetPost(final List<DistributionSetManagement.Create> creates) {
return creates.stream()
.map(create ->
new MgmtDistributionSetRequestBodyPost()
.setType(create.getType().getKey())
.setModules(create.getModules().stream()
.map(module -> new MgmtSoftwareModuleAssignment().setId(module.getId()))
.map(MgmtSoftwareModuleAssignment.class::cast)
.toList())
.setName(create.getName())
.setDescription(create.getDescription())
.setVersion(create.getVersion())
.setRequiredMigrationStep(create.getRequiredMigrationStep()))
.toList();
}
private Set<DistributionSet> createDistributionSetsAlphabetical(final int amount) {
char character = 'a';
final Set<DistributionSet> created = new HashSet<>(amount);
@@ -1886,4 +1901,4 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe
}
return created;
}
}
}

View File

@@ -42,7 +42,6 @@ import org.eclipse.hawkbit.repository.model.Tag;
import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
@@ -197,7 +196,7 @@ class MgmtDistributionSetTagResourceTest extends AbstractManagementApiIntegratio
final ResultActions result = mvc
.perform(post(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING)
.content(JsonBuilder.dsTags(List.of(tagOne, tagTwo)))
.content(toJson(List.of(tagOne, tagTwo)))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isCreated())
@@ -232,7 +231,7 @@ class MgmtDistributionSetTagResourceTest extends AbstractManagementApiIntegratio
final ResultActions result = mvc
.perform(put(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + original.getId())
.content(JsonBuilder.dsTag(update)).contentType(MediaType.APPLICATION_JSON)
.content(toJson(update)).contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk())
@@ -372,7 +371,7 @@ class MgmtDistributionSetTagResourceTest extends AbstractManagementApiIntegratio
final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(2);
mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.content(JsonBuilder.toArray(sets.stream().map(DistributionSet::getId).toList()))
.content(toJson(sets.stream().map(DistributionSet::getId).toList()))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
@@ -427,7 +426,7 @@ class MgmtDistributionSetTagResourceTest extends AbstractManagementApiIntegratio
distributionSetManagement.assignTag(sets.stream().map(DistributionSet::getId).toList(), tag.getId());
mvc.perform(delete(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.content(JsonBuilder.toArray(List.of(unassigned0.getId(), unassigned1.getId())))
.content(toJson(List.of(unassigned0.getId(), unassigned1.getId())))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
@@ -463,7 +462,7 @@ class MgmtDistributionSetTagResourceTest extends AbstractManagementApiIntegratio
mvc.perform(
post(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.content(JsonBuilder.toArray(withMissing))
.content(toJson(withMissing))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound())
@@ -472,7 +471,7 @@ class MgmtDistributionSetTagResourceTest extends AbstractManagementApiIntegratio
final Map<String, Object> info = exceptionInfo.getInfo();
assertThat(info).isNotNull();
assertThat(info.get(EntityNotFoundException.TYPE)).isEqualTo(DistributionSet.class.getSimpleName());
final List<String> notFound = (List<String>) info.get(EntityNotFoundException.ENTITY_ID);
final List<String> notFound = (List<String>)info.get(EntityNotFoundException.ENTITY_ID);
Collections.sort(notFound);
assertThat(notFound).isEqualTo(missing);
});

View File

@@ -31,6 +31,8 @@ import java.util.Set;
import com.jayway.jsonpath.JsonPath;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost;
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeAssignment;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.DistributionSetTypeManagement;
@@ -40,7 +42,6 @@ import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.NamedEntity;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
@@ -669,8 +670,7 @@ class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIntegrati
.optionalModuleTypes(Collections.emptySet())
.build();
mvc.perform(post("/rest/v1/distributionsettypes")
.content(JsonBuilder.distributionSetTypes(List.of(testNewType)))
mvc.perform(post("/rest/v1/distributionsettypes").content(toJson(List.of(testNewType)))
.contentType(MediaType.APPLICATION_OCTET_STREAM))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isUnsupportedMediaType());
@@ -696,8 +696,7 @@ class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIntegrati
.key("test123")
.name(randomString(NamedEntity.NAME_MAX_SIZE + 1))
.build();
mvc.perform(post("/rest/v1/distributionsettypes")
.content(JsonBuilder.distributionSetTypes(List.of(toLongName)))
mvc.perform(post("/rest/v1/distributionsettypes").content(toJson(List.of(toLongName)))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
@@ -763,7 +762,23 @@ class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIntegrati
private MvcResult runPostDistributionSetType(final List<DistributionSetTypeManagement.Create> types) throws Exception {
return mvc
.perform(post("/rest/v1/distributionsettypes").content(JsonBuilder.distributionSetTypes(types))
.perform(post("/rest/v1/distributionsettypes").content(toJson(types.stream()
.map(type -> new MgmtDistributionSetTypeRequestBodyPost()
.setMandatorymodules(type.getMandatoryModuleTypes().stream()
.map(SoftwareModuleType::getId)
.map(id -> new MgmtSoftwareModuleTypeAssignment().setId(id))
.map(MgmtSoftwareModuleTypeAssignment.class::cast)
.toList())
.setOptionalmodules(type.getOptionalModuleTypes().stream()
.map(SoftwareModuleType::getId)
.map(id -> new MgmtSoftwareModuleTypeAssignment().setId(id))
.map(MgmtSoftwareModuleTypeAssignment.class::cast)
.toList())
.setKey(type.getKey())
.setName(type.getName())
.setDescription(type.getDescription())
.setColour(type.getColour()))
.toList()))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isCreated())
@@ -789,19 +804,19 @@ class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIntegrati
assertThat(distributionSetTypeManagement.count()).isEqualTo(DEFAULT_DS_TYPES);
return Arrays.asList(
DistributionSetTypeManagement.Create.builder()
.key("testKey1").name("TestName1").description("Desc1").colour("col")
.mandatoryModuleTypes(Set.of(osType))
.optionalModuleTypes(Set.of(runtimeType))
.build(),
DistributionSetTypeManagement.Create.builder()
.key("testKey2").name("TestName2").description("Desc2").colour("col")
.optionalModuleTypes(Set.of(runtimeType, osType, appType))
.build(),
DistributionSetTypeManagement.Create.builder()
.key("testKey3").name("TestName3").description("Desc3").colour("col")
.mandatoryModuleTypes(Set.of(runtimeType, osType))
.build());
DistributionSetTypeManagement.Create.builder()
.key("testKey1").name("TestName1").description("Desc1").colour("col")
.mandatoryModuleTypes(Set.of(osType))
.optionalModuleTypes(Set.of(runtimeType))
.build(),
DistributionSetTypeManagement.Create.builder()
.key("testKey2").name("TestName2").description("Desc2").colour("col")
.optionalModuleTypes(Set.of(runtimeType, osType, appType))
.build(),
DistributionSetTypeManagement.Create.builder()
.key("testKey3").name("TestName3").description("Desc3").colour("col")
.mandatoryModuleTypes(Set.of(runtimeType, osType))
.build());
}
private DistributionSetType generateTestType() {

View File

@@ -55,7 +55,6 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.test.util.RolloutTestApprovalStrategy;
import org.eclipse.hawkbit.repository.test.util.SecurityContextSwitch;
import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.json.JSONObject;
import org.junit.jupiter.api.Assertions;

View File

@@ -32,7 +32,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@@ -41,6 +40,7 @@ import com.jayway.jsonpath.JsonPath;
import org.apache.commons.io.IOUtils;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact;
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleRequestBodyPost;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRepresentationMode;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.resource.util.ResourceUtility;
@@ -62,7 +62,6 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.test.util.HashGeneratorUtils;
import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.hamcrest.Matchers;
import org.json.JSONArray;
@@ -1021,14 +1020,14 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes
final SoftwareModuleManagement.Create toLongName = SoftwareModuleManagement.Create.builder().type(osType)
.name(randomString(80)).build();
mvc.perform(post("/rest/v1/softwaremodules").content(JsonBuilder.softwareModules(Collections.singletonList(toLongName)))
mvc.perform(post("/rest/v1/softwaremodules").content(toJson(Collections.singletonList(toLongName)))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
// unsupported media type
mvc.perform(post("/rest/v1/softwaremodules")
.content(JsonBuilder.softwareModules(List.of(SoftwareModuleManagement.Create.builder()
.content(toJson(List.of(SoftwareModuleManagement.Create.builder()
.type(sm.getType())
.name(sm.getName())
.version(sm.getVersion())
@@ -1042,7 +1041,7 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes
.version("version").vendor("vendor").description("description").encrypted(true).build();
// artifact decryption is not supported
mvc.perform(
post("/rest/v1/softwaremodules").content(JsonBuilder.softwareModules(List.of(swm)))
post("/rest/v1/softwaremodules").content(toJson(List.of(swm)))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
@@ -1271,28 +1270,26 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
void createSoftwareModules() throws Exception {
final SoftwareModuleManagement.Create os = SoftwareModuleManagement.Create.builder()
.name("name1")
.type(osType)
.version("version1")
.vendor("vendor1")
.description("description1")
.build();
final SoftwareModuleManagement.Create ah = SoftwareModuleManagement.Create.builder()
.name("name3")
.type(appType)
.version("version3")
.vendor("vendor3")
.description("description3")
.build();
final MgmtSoftwareModuleRequestBodyPost os = new MgmtSoftwareModuleRequestBodyPost()
.setType(osType.getKey())
.setName("name1")
.setVersion("version1")
.setVendor("vendor1")
.setDescription("description1");
final MgmtSoftwareModuleRequestBodyPost ah = new MgmtSoftwareModuleRequestBodyPost()
.setType(appType.getKey())
.setName("name3")
.setVersion("version3")
.setVendor("vendor3")
.setDescription("description3");
final List<SoftwareModuleManagement.Create> modules = Arrays.asList(os, ah);
final List<MgmtSoftwareModuleRequestBodyPost> modules = List.of(os, ah);
final long current = System.currentTimeMillis();
final MvcResult mvcResult = mvc.perform(
post("/rest/v1/softwaremodules").accept(MediaType.APPLICATION_JSON_VALUE)
.content(JsonBuilder.softwareModules(modules))
.content(toJson(modules))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isCreated())
@@ -1312,30 +1309,26 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes
.andExpect(jsonPath("[1].createdAt", not(equalTo(0))))
.andReturn();
final SoftwareModule osCreated = softwareModuleManagement.findByNameAndVersionAndType("name1", "version1",
osType.getId()).get();
final SoftwareModule appCreated = softwareModuleManagement.findByNameAndVersionAndType("name3", "version3",
appType.getId()).get();
final SoftwareModule osCreated = softwareModuleManagement.findByNameAndVersionAndType("name1", "version1", osType.getId()).get();
final SoftwareModule appCreated = softwareModuleManagement.findByNameAndVersionAndType("name3", "version3", appType.getId()).get();
assertThat(JsonPath.compile("[0]._links.self.href")
.read(mvcResult.getResponse().getContentAsString())
.toString()).as("Response contains invalid self href")
assertThat(JsonPath.compile("[0]._links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.as("Response contains invalid self href")
.isEqualTo("http://localhost/rest/v1/softwaremodules/" + osCreated.getId());
assertThat(JsonPath.compile("[1]._links.self.href")
.read(mvcResult.getResponse().getContentAsString())
.toString()).as("Response contains links self href")
assertThat(JsonPath.compile("[1]._links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.as("Response contains links self href")
.isEqualTo("http://localhost/rest/v1/softwaremodules/" + appCreated.getId());
assertThat(softwareModuleManagement.findAll(PAGE)).as("Wrong softwaremodule size").hasSize(2);
assertThat(softwareModuleManagement.findByType(osType.getId(), PAGE).getContent().get(0).getName()).as(
"Softwaremoudle name is wrong").isEqualTo(os.getName());
assertThat(softwareModuleManagement.findByType(osType.getId(), PAGE).getContent().get(0).getCreatedBy()).as(
"Softwaremoudle created by is wrong").isEqualTo("uploadTester");
assertThat(softwareModuleManagement.findByType(osType.getId(), PAGE).getContent().get(0).getCreatedAt()).as(
"Softwaremoudle created at is wrong").isGreaterThanOrEqualTo(current);
assertThat(softwareModuleManagement.findByType(appType.getId(), PAGE).getContent().get(0).getName()).as(
"Softwaremoudle name is wrong").isEqualTo(ah.getName());
assertThat(softwareModuleManagement.findByType(osType.getId(), PAGE).getContent().get(0).getName())
.as("Softwaremoudle name is wrong").isEqualTo(os.getName());
assertThat(softwareModuleManagement.findByType(osType.getId(), PAGE).getContent().get(0).getCreatedBy())
.as("Softwaremoudle created by is wrong").isEqualTo("uploadTester");
assertThat(softwareModuleManagement.findByType(osType.getId(), PAGE).getContent().get(0).getCreatedAt())
.as("Softwaremoudle created at is wrong").isGreaterThanOrEqualTo(current);
assertThat(softwareModuleManagement.findByType(appType.getId(), PAGE).getContent().get(0).getName())
.as("Softwaremoudle name is wrong").isEqualTo(ah.getName());
}
/**

View File

@@ -24,7 +24,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.jayway.jsonpath.JsonPath;
@@ -34,7 +33,6 @@ import org.eclipse.hawkbit.repository.SoftwareModuleTypeManagement;
import org.eclipse.hawkbit.repository.model.NamedEntity;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
@@ -166,7 +164,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
final List<SoftwareModuleTypeManagement.Create> types = new ArrayList<>();
types.add(SoftwareModuleTypeManagement.Create.builder().key("test-1").name("TestName-1").maxAssignments(-1).build());
mvc.perform(post("/rest/v1/softwaremoduletypes").content(JsonBuilder.softwareModuleTypeCreates(types))
mvc.perform(post("/rest/v1/softwaremoduletypes").content(toJson(types))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
@@ -174,7 +172,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
types.clear();
types.add(SoftwareModuleTypeManagement.Create.builder().key("test0").name("TestName0").maxAssignments(0).build());
mvc.perform(post("/rest/v1/softwaremoduletypes").content(JsonBuilder.softwareModuleTypeCreates(types))
mvc.perform(post("/rest/v1/softwaremoduletypes").content(toJson(types))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
@@ -196,7 +194,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
.colour("col3").maxAssignments(3).build());
final MvcResult mvcResult = mvc
.perform(post("/rest/v1/softwaremoduletypes").content(JsonBuilder.softwareModuleTypeCreates(types))
.perform(post("/rest/v1/softwaremoduletypes").content(toJson(types))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isCreated())
@@ -446,14 +444,13 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
.key("test123")
.name(randomString(NamedEntity.NAME_MAX_SIZE + 1))
.build();
mvc.perform(
post("/rest/v1/softwaremoduletypes").content(JsonBuilder.softwareModuleTypeCreates(Collections.singletonList(toLongName)))
.contentType(MediaType.APPLICATION_JSON))
mvc.perform(post("/rest/v1/softwaremoduletypes").content(toJson(List.of(toLongName)))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
// unsupported media type
mvc.perform(post("/rest/v1/softwaremoduletypes").content(JsonBuilder.softwareModuleTypeCreates(types))
mvc.perform(post("/rest/v1/softwaremoduletypes").content(toJson(types))
.contentType(MediaType.APPLICATION_OCTET_STREAM))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isUnsupportedMediaType());

View File

@@ -10,7 +10,6 @@
package org.eclipse.hawkbit.mgmt.rest.resource;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
@@ -90,7 +89,7 @@ public class MgmtTargetGroupResourceTest extends AbstractManagementApiIntegratio
mvc.perform(put(MgmtRestConstants.TARGET_GROUP_V1_REQUEST_MAPPING + "/newGroup/assigned")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonBuilder.toArray(Arrays.asList("target1", "target2", "target3"))))
.content(toJson(Arrays.asList("target1", "target2", "target3"))))
.andExpect(status().isOk());
@@ -108,7 +107,7 @@ public class MgmtTargetGroupResourceTest extends AbstractManagementApiIntegratio
void shouldReturnBadRequestWhenProvidingAnEmptyListOfControllerIds() throws Exception {
mvc.perform(put(MgmtRestConstants.TARGET_GROUP_V1_REQUEST_MAPPING + "/someGroup/assigned")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonBuilder.toArray(Collections.emptyList())))
.content(toJson(Collections.emptyList())))
.andExpect(status().isBadRequest());
}
@@ -120,7 +119,7 @@ public class MgmtTargetGroupResourceTest extends AbstractManagementApiIntegratio
mvc.perform(put(MgmtRestConstants.TARGET_GROUP_V1_REQUEST_MAPPING + "/assigned")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonBuilder.toArray(Arrays.asList("target1", "target2", "target3")))
.content(toJson(Arrays.asList("target1", "target2", "target3")))
.param("group", "Europe/East"))
.andExpect(status().isOk());
@@ -137,7 +136,7 @@ public class MgmtTargetGroupResourceTest extends AbstractManagementApiIntegratio
// expect bad request if empty controllerIds
mvc.perform(put(MgmtRestConstants.TARGET_GROUP_V1_REQUEST_MAPPING + "/assigned")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonBuilder.toArray(Collections.emptyList()))
.content(toJson(Collections.emptyList()))
.param("group", "doesNotMatter"))
.andExpect(status().isBadRequest());
}
@@ -170,7 +169,7 @@ public class MgmtTargetGroupResourceTest extends AbstractManagementApiIntegratio
mvc.perform(delete(MgmtRestConstants.TARGET_GROUP_V1_REQUEST_MAPPING + "/assigned")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonBuilder.toArray(Arrays.asList("target1", "target2"))))
.content(toJson(Arrays.asList("target1", "target2"))))
.andExpect(status().isOk());
mvc.perform(get(MgmtRestConstants.TARGET_GROUP_V1_REQUEST_MAPPING + "/assigned")
@@ -183,7 +182,7 @@ public class MgmtTargetGroupResourceTest extends AbstractManagementApiIntegratio
// expect bad request if empty
mvc.perform(delete(MgmtRestConstants.TARGET_GROUP_V1_REQUEST_MAPPING + "/assigned")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonBuilder.toArray(Collections.emptyList())))
.content(toJson(Collections.emptyList())))
.andExpect(status().isBadRequest());
}

View File

@@ -55,7 +55,6 @@ import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.resource.util.ResourceUtility;
import org.eclipse.hawkbit.repository.ActionFields;
import org.eclipse.hawkbit.repository.Identifiable;
import org.eclipse.hawkbit.repository.TargetTypeManagement;
import org.eclipse.hawkbit.repository.TargetTypeManagement.Create;
import org.eclipse.hawkbit.repository.builder.ActionStatusCreate;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
@@ -79,7 +78,6 @@ import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.exception.MessageNotReadableException;
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.eclipse.hawkbit.util.IpUtil;
import org.hamcrest.Matchers;
@@ -1018,10 +1016,9 @@ class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest {
final Target target = entityFactory.target().create().controllerId(randomString).build();
final String targetList = JsonBuilder.targets(Collections.singletonList(target), false);
final String targetList = JsonBuilder.targets(List.of(target), false);
final String expectedTargetName = randomString.substring(0,
Math.min(JpaTarget.CONTROLLER_ID_MAX_SIZE, NamedEntity.NAME_MAX_SIZE));
final String expectedTargetName = randomString.substring(0, Math.min(JpaTarget.CONTROLLER_ID_MAX_SIZE, NamedEntity.NAME_MAX_SIZE));
mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING).content(targetList)
.contentType(MediaType.APPLICATION_JSON))

View File

@@ -43,7 +43,6 @@ import org.eclipse.hawkbit.repository.model.TargetTag;
import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
@@ -163,7 +162,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
final ResultActions result = mvc
.perform(post(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING)
.content(JsonBuilder.targetTags(List.of(tagOne, tagTwo)))
.content(toJson(List.of(tagOne, tagTwo)))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isCreated())
@@ -178,8 +177,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
assertThat(createdTwo.getDescription()).isEqualTo(tagTwo.getDescription());
assertThat(createdTwo.getColour()).isEqualTo(tagTwo.getColour());
result.andExpect(applyTagMatcherOnArrayResult(createdOne))
.andExpect(applyTagMatcherOnArrayResult(createdTwo));
result.andExpect(applyTagMatcherOnArrayResult(createdOne)).andExpect(applyTagMatcherOnArrayResult(createdTwo));
}
/**
@@ -199,7 +197,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
final ResultActions result = mvc
.perform(put(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + original.getId())
.content(JsonBuilder.targetTag(update)).contentType(MediaType.APPLICATION_JSON)
.content(toJson(update)).contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk())
@@ -341,7 +339,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
final Target assigned1 = targets.get(1);
mvc.perform(post(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.content(JsonBuilder.toArray(Arrays.asList(assigned0.getControllerId(), assigned1.getControllerId())))
.content(toJson(List.of(assigned0.getControllerId(), assigned1.getControllerId())))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
@@ -376,7 +374,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
withMissing.addAll(missing);
mvc.perform(post(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.content(JsonBuilder.toArray(withMissing))
.content(toJson(withMissing))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound())
@@ -419,7 +417,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
mvc.perform(post(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.param("onNotFoundPolicy", MgmtTargetTagRestApi.OnNotFoundPolicy.ON_WHAT_FOUND_AND_FAIL.name())
.content(JsonBuilder.toArray(withMissing))
.content(toJson(withMissing))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound())
@@ -463,7 +461,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
mvc.perform(post(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.param("onNotFoundPolicy", MgmtTargetTagRestApi.OnNotFoundPolicy.ON_WHAT_FOUND_AND_SUCCESS.name())
.content(JsonBuilder.toArray(withMissing))
.content(toJson(withMissing))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
@@ -515,7 +513,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
targetManagement.assignTag(targets.stream().map(Target::getControllerId).toList(), tag.getId());
mvc.perform(delete(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.content(JsonBuilder.toArray(Arrays.asList(unassigned0.getControllerId(), unassigned1.getControllerId())))
.content(toJson(Arrays.asList(unassigned0.getControllerId(), unassigned1.getControllerId())))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
@@ -553,7 +551,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
targetManagement.assignTag(targets, tag.getId());
mvc.perform(delete(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.content(JsonBuilder.toArray(withMissing))
.content(toJson(withMissing))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound())
@@ -599,7 +597,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
mvc.perform(delete(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.param("onNotFoundPolicy", MgmtTargetTagRestApi.OnNotFoundPolicy.ON_WHAT_FOUND_AND_FAIL.name())
.content(JsonBuilder.toArray(withMissing))
.content(toJson(withMissing))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound())
@@ -644,7 +642,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT
mvc.perform(delete(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.param("onNotFoundPolicy", MgmtTargetTagRestApi.OnNotFoundPolicy.ON_WHAT_FOUND_AND_SUCCESS.name())
.content(JsonBuilder.toArray(withMissing))
.content(toJson(withMissing))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());

View File

@@ -26,13 +26,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import com.jayway.jsonpath.JsonPath;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.mgmt.json.model.MgmtId;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.TargetTypeManagement.Create;
import org.eclipse.hawkbit.repository.TargetTypeManagement.Update;
@@ -41,7 +41,6 @@ import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.NamedEntity;
import org.eclipse.hawkbit.repository.model.TargetType;
import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
@@ -58,10 +57,8 @@ import org.springframework.test.web.servlet.ResultActions;
class MgmtTargetTypeResourceTest extends AbstractManagementApiIntegrationTest {
private static final String TARGETTYPES_ENDPOINT = MgmtRestConstants.TARGETTYPE_V1_REQUEST_MAPPING;
private static final String TARGETTYPE_SINGLE_ENDPOINT = MgmtRestConstants.TARGETTYPE_V1_REQUEST_MAPPING
+ "/{typeid}";
private static final String TARGETTYPE_DSTYPES_ENDPOINT = TARGETTYPE_SINGLE_ENDPOINT + "/"
+ MgmtRestConstants.TARGETTYPE_V1_DS_TYPES;
private static final String TARGETTYPE_SINGLE_ENDPOINT = MgmtRestConstants.TARGETTYPE_V1_REQUEST_MAPPING + "/{typeid}";
private static final String TARGETTYPE_DSTYPES_ENDPOINT = TARGETTYPE_SINGLE_ENDPOINT + "/" + MgmtRestConstants.TARGETTYPE_V1_DS_TYPES;
private static final String TARGETTYPE_DSTYPE_SINGLE_ENDPOINT = TARGETTYPE_DSTYPES_ENDPOINT + "/{dstypeid}";
private static final String TEST_USER = "targetTypeTester";
@@ -527,7 +524,7 @@ class MgmtTargetTypeResourceTest extends AbstractManagementApiIntegrationTest {
// target types at creation time invalid
final TargetType testNewType = createTestTargetTypeInDB(typeName + "Another", Set.of(standardDsType));
mvc.perform(post(TARGETTYPES_ENDPOINT).content(JsonBuilder.targetTypes(Collections.singletonList(testNewType)))
mvc.perform(post(TARGETTYPES_ENDPOINT).content(toJson(List.of(testNewType)))
.contentType(MediaType.APPLICATION_OCTET_STREAM))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isUnsupportedMediaType());
@@ -550,7 +547,7 @@ class MgmtTargetTypeResourceTest extends AbstractManagementApiIntegrationTest {
.andExpect(status().isBadRequest());
final Create tooLongName = Create.builder().name(randomString(NamedEntity.NAME_MAX_SIZE + 1)).build();
mvc.perform(post(TARGETTYPES_ENDPOINT).content(JsonBuilder.targetTypesCreate(List.of(tooLongName)))
mvc.perform(post(TARGETTYPES_ENDPOINT).content(toJson(List.of(tooLongName)))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
@@ -643,7 +640,7 @@ class MgmtTargetTypeResourceTest extends AbstractManagementApiIntegrationTest {
// verify quota enforcement for distribution set types
mvc.perform(post(TARGETTYPE_DSTYPES_ENDPOINT, testType.getId())
.content(JsonBuilder.ids(dsTypeIds.subList(0, dsTypeIds.size() - 1)))
.content(toJson(dsTypeIds.subList(0, dsTypeIds.size() - 1).stream().map(MgmtId::new).toList()))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
@@ -696,7 +693,7 @@ class MgmtTargetTypeResourceTest extends AbstractManagementApiIntegrationTest {
private void runPostTargetTypeAndVerify(final List<Create> types) throws Exception {
int size = types.size();
ResultActions resultActions = mvc
.perform(post(TARGETTYPES_ENDPOINT).content(JsonBuilder.targetTypesCreate(types))
.perform(post(TARGETTYPES_ENDPOINT).content(toJson(types))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print());