From 43f717fc8dac3efae1e4557bd9212311386df7c1 Mon Sep 17 00:00:00 2001 From: Avgustin Marinov Date: Mon, 4 Aug 2025 12:54:12 +0300 Subject: [PATCH] Improve JsonBuilder's (#2585) Signed-off-by: Avgustin Marinov --- .../ddi/rest/resource/DdiConfigDataTest.java | 6 +- .../rest/resource/DdiRootControllerTest.java | 1 - .../ddi/rest/resource/JsonBuilder.java | 58 ++ .../mgmt/rest/resource/JsonBuilder.java | 285 +++++++++ .../rest/resource/MgmtContentTypeTest.java | 36 +- .../MgmtDistributionSetResourceTest.java | 59 +- .../MgmtDistributionSetTagResourceTest.java | 13 +- .../MgmtDistributionSetTypeResourceTest.java | 53 +- .../resource/MgmtRolloutResourceTest.java | 1 - .../MgmtSoftwareModuleResourceTest.java | 71 +-- .../MgmtSoftwareModuleTypeResourceTest.java | 15 +- .../resource/MgmtTargetGroupResourceTest.java | 13 +- .../rest/resource/MgmtTargetResourceTest.java | 7 +- .../resource/MgmtTargetTagResourceTest.java | 24 +- .../resource/MgmtTargetTypeResourceTest.java | 17 +- .../jpa/cluster/DistributedLockTest.java | 4 +- .../rest/AbstractRestIntegrationTest.java | 8 + .../hawkbit/rest/util/JsonBuilder.java | 565 ------------------ 18 files changed, 512 insertions(+), 724 deletions(-) create mode 100644 hawkbit-ddi/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/JsonBuilder.java create mode 100644 hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/JsonBuilder.java delete mode 100644 hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/JsonBuilder.java diff --git a/hawkbit-ddi/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiConfigDataTest.java b/hawkbit-ddi/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiConfigDataTest.java index e2e734869..ec50b2769 100644 --- a/hawkbit-ddi/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiConfigDataTest.java +++ b/hawkbit-ddi/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiConfigDataTest.java @@ -33,7 +33,6 @@ import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.repository.exception.AssignmentQuotaExceededException; import org.eclipse.hawkbit.repository.exception.InvalidTargetAttributeException; import org.eclipse.hawkbit.repository.model.Target; -import org.eclipse.hawkbit.rest.util.JsonBuilder; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.junit.jupiter.api.Test; import org.springframework.hateoas.MediaTypes; @@ -42,12 +41,11 @@ import org.springframework.test.context.ActiveProfiles; /** * Test config data from the controller. - */ -@ActiveProfiles({ "im", "test" }) -/** + *

* Feature: Component Tests - Direct Device Integration API
* Story: Config Data Resource */ +@ActiveProfiles({ "im", "test" }) class DdiConfigDataTest extends AbstractDDiApiIntegrationTest { private static final String TARGET1_ID = "4717"; diff --git a/hawkbit-ddi/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java b/hawkbit-ddi/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java index 014f4c1e0..d7cf320ce 100644 --- a/hawkbit-ddi/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java +++ b/hawkbit-ddi/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java @@ -60,7 +60,6 @@ import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; import org.eclipse.hawkbit.repository.test.util.WithUser; -import org.eclipse.hawkbit.rest.util.JsonBuilder; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.eclipse.hawkbit.security.HawkbitSecurityProperties; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties.TenantConfigurationKey; diff --git a/hawkbit-ddi/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/JsonBuilder.java b/hawkbit-ddi/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/JsonBuilder.java new file mode 100644 index 000000000..e1129bf7d --- /dev/null +++ b/hawkbit-ddi/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/JsonBuilder.java @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others + * + * 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.ddi.rest.resource; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +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 JSONObject configData(final Map attributes) throws JSONException { + return configData(attributes, null); + } + + static JSONObject configData(final Map 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; + } +} \ No newline at end of file diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/JsonBuilder.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/JsonBuilder.java new file mode 100644 index 000000000..d41527410 --- /dev/null +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/JsonBuilder.java @@ -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 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 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 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 groups, final String type, final Integer weight, + final Boolean confirmationRequired) { + final List 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 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 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 attributes) throws JSONException { + return configData(attributes, null); + } + + static JSONObject configData(final Map 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(); + } +} \ No newline at end of file diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtContentTypeTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtContentTypeTest.java index b090cd5cb..d2a2003c5 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtContentTypeTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtContentTypeTest.java @@ -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()) diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java index 2afa473f4..d12979e5c 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java @@ -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 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 toMgmtDistributionSetPost(final List 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 createDistributionSetsAlphabetical(final int amount) { char character = 'a'; final Set created = new HashSet<>(amount); @@ -1886,4 +1901,4 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe } return created; } -} +} \ No newline at end of file diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResourceTest.java index 6f0a09b66..1a53acded 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResourceTest.java @@ -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 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 info = exceptionInfo.getInfo(); assertThat(info).isNotNull(); assertThat(info.get(EntityNotFoundException.TYPE)).isEqualTo(DistributionSet.class.getSimpleName()); - final List notFound = (List) info.get(EntityNotFoundException.ENTITY_ID); + final List notFound = (List)info.get(EntityNotFoundException.ENTITY_ID); Collections.sort(notFound); assertThat(notFound).isEqualTo(missing); }); diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java index d8d21e066..e64cb0c09 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java @@ -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 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() { diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java index b34be41c3..0194fa9e9 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java @@ -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; diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java index 477cc3775..d273572e6 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java @@ -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 modules = Arrays.asList(os, ah); + final List 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()); } /** diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java index 3e4a4e4e2..c29326607 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java @@ -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 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()); diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetGroupResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetGroupResourceTest.java index 834852c9b..957f03d03 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetGroupResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetGroupResourceTest.java @@ -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()); } diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java index d679a927b..624e3964d 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java @@ -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)) diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResourceTest.java index b774f1656..3e5313cec 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResourceTest.java @@ -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()); diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTypeResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTypeResourceTest.java index 22f54dcbd..5271a6d56 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTypeResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTypeResourceTest.java @@ -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 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()); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/cluster/DistributedLockTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/cluster/DistributedLockTest.java index e8eeed7e4..626736c33 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/cluster/DistributedLockTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/cluster/DistributedLockTest.java @@ -136,7 +136,7 @@ class DistributedLockTest extends AbstractJpaIntegrationTest { try { final Instant timeout = Instant.now().plus(4 * lockProperties.getTtl(), ChronoUnit.MILLIS); while (Instant.now().isBefore(timeout)) { - log.info("lockThread1: loop, timeout: {}", new Date(timeout.toEpochMilli())); + log.debug("lockThread1: loop, timeout: {}", new Date(timeout.toEpochMilli())); assertThat(lock01.tryLock()).isFalse(); assertThat(lockRepository1.isAcquired(path0)).isFalse(); // check db state @@ -167,7 +167,7 @@ class DistributedLockTest extends AbstractJpaIntegrationTest { // asserts lockKey1 is kept by lock11 and could not be locked via lockRepository0 final Instant timeout = Instant.now().plus(4 * lockProperties.getTtl(), ChronoUnit.MILLIS); while (Instant.now().isBefore(timeout)) { - log.info("main thread: loop, timeout: {}", new Date(timeout.toEpochMilli())); + log.debug("main thread: loop, timeout: {}", new Date(timeout.toEpochMilli())); if (lock11Locked.get()) { try { assertThat(lock10.tryLock()).isFalse(); diff --git a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTest.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTest.java index 37197e068..624a6517b 100644 --- a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTest.java +++ b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTest.java @@ -9,6 +9,8 @@ */ package org.eclipse.hawkbit.rest; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import org.eclipse.hawkbit.repository.jpa.JpaRepositoryConfiguration; import org.eclipse.hawkbit.repository.test.TestConfiguration; import org.eclipse.hawkbit.repository.test.util.AbstractIntegrationTest; @@ -33,6 +35,8 @@ import org.springframework.web.filter.CharacterEncodingFilter; @AutoConfigureMockMvc public abstract class AbstractRestIntegrationTest extends AbstractIntegrationTest { + protected static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + protected MockMvc mvc; @Autowired protected WebApplicationContext webApplicationContext; @@ -56,4 +60,8 @@ public abstract class AbstractRestIntegrationTest extends AbstractIntegrationTes return createMvcWebAppContext; } + + protected static String toJson(final Object obj) throws JsonProcessingException { + return OBJECT_MAPPER.writeValueAsString(obj); + } } diff --git a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/JsonBuilder.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/JsonBuilder.java deleted file mode 100644 index 08a40b9d5..000000000 --- a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/JsonBuilder.java +++ /dev/null @@ -1,565 +0,0 @@ -/** - * Copyright (c) 2015 Bosch Software Innovations GmbH and others - * - * 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.rest.util; - -import static org.junit.jupiter.api.Assertions.fail; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import lombok.AccessLevel; -import lombok.NoArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.eclipse.hawkbit.repository.DistributionSetManagement; -import org.eclipse.hawkbit.repository.DistributionSetTagManagement; -import org.eclipse.hawkbit.repository.DistributionSetTypeManagement; -import org.eclipse.hawkbit.repository.SoftwareModuleManagement; -import org.eclipse.hawkbit.repository.SoftwareModuleTypeManagement; -import org.eclipse.hawkbit.repository.TargetTagManagement; -import org.eclipse.hawkbit.repository.TargetTypeManagement; -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.Tag; -import org.eclipse.hawkbit.repository.model.Target; -import org.eclipse.hawkbit.repository.model.TargetType; -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 -public class JsonBuilder { - - public static String ids(final Collection ids) throws JSONException { - final JSONArray list = new JSONArray(); - for (final Long smID : ids) { - list.put(new JSONObject().put("id", smID)); - } - return list.toString(); - } - - public static String toArray(final Collection ids) { - final JSONArray list = new JSONArray(); - for (final T smID : ids) { - list.put(smID); - } - return list.toString(); - } - - public static String tags(final List tags) throws JSONException { - final StringBuilder builder = new StringBuilder(); - - builder.append("["); - int i = 0; - for (final Tag tag : tags) { - createTagLine(builder, tag); - - if (++i < tags.size()) { - builder.append(","); - } - } - builder.append("]"); - - return builder.toString(); - } - public static String targetTag(final TargetTagManagement.Update dsTagUpdate) throws JSONException { - final StringBuilder builder = new StringBuilder(); - builder.append(new JSONObject() - .put("name", dsTagUpdate.getName()).put("description", dsTagUpdate.getDescription()) - .put("colour", dsTagUpdate.getColour()).toString()); - return builder.toString(); - } - - public static String targetTags(final List dsTagsCreate) throws JSONException { - final StringBuilder builder = new StringBuilder(); - - builder.append("["); - int i = 0; - for (final TargetTagManagement.Create tag : dsTagsCreate) { - builder.append(new JSONObject() - .put("name", tag.getName()).put("description", tag.getDescription()) - .put("colour", tag.getColour()).toString()); - - if (++i < dsTagsCreate.size()) { - builder.append(","); - } - } - builder.append("]"); - - return builder.toString(); - } - - public static String dsTag(final DistributionSetTagManagement.Update dsTagUpdate) throws JSONException { - final StringBuilder builder = new StringBuilder(); - builder.append(new JSONObject() - .put("name", dsTagUpdate.getName()).put("description", dsTagUpdate.getDescription()) - .put("colour", dsTagUpdate.getColour()).toString()); - return builder.toString(); - } - - public static String dsTags(final List dsTagsCreate) throws JSONException { - final StringBuilder builder = new StringBuilder(); - - builder.append("["); - int i = 0; - for (final DistributionSetTagManagement.Create tag : dsTagsCreate) { - builder.append(new JSONObject() - .put("name", tag.getName()).put("description", tag.getDescription()) - .put("colour", tag.getColour()).toString()); - - if (++i < dsTagsCreate.size()) { - builder.append(","); - } - } - builder.append("]"); - - return builder.toString(); - } - - public static String tag(final Tag tag) throws JSONException { - final StringBuilder builder = new StringBuilder(); - createTagLine(builder, tag); - return builder.toString(); - } - - public static String softwareModules(final List modules) throws JSONException { - final StringBuilder builder = new StringBuilder(); - - builder.append("["); - int i = 0; - for (final SoftwareModuleManagement.Create module : modules) { - builder.append(new JSONObject().put("name", module.getName()).put("description", module.getDescription()) - .put("type", module.getType().getKey()).put("id", Long.MAX_VALUE).put("vendor", module.getVendor()) - .put("version", module.getVersion()).put("createdAt", "0").put("updatedAt", "0") - .put("createdBy", "fghdfkjghdfkjh").put("updatedBy", "fghdfkjghdfkjh") - .put("encrypted", module.isEncrypted()).toString()); - - if (++i < modules.size()) { - builder.append(","); - } - } - builder.append("]"); - - return builder.toString(); - } - - public static String softwareModuleTypes(final List types) throws JSONException { - final StringBuilder builder = new StringBuilder(); - - builder.append("["); - int i = 0; - for (final SoftwareModuleTypeManagement.Create module : types) { - builder.append(new JSONObject().put("name", module.getName()).put("description", module.getDescription()) - .put("colour", module.getColour()).put("id", Long.MAX_VALUE).put("key", module.getKey()) - .put("maxAssignments", module.getMaxAssignments()).put("createdAt", "0").put("updatedAt", "0") - .put("createdBy", "fghdfkjghdfkjh").put("updatedBy", "fghdfkjghdfkjh").toString()); - - if (++i < types.size()) { - builder.append(","); - } - } - builder.append("]"); - - return builder.toString(); - } - - public static String softwareModuleTypeCreates(final List creates) throws JSONException { - final StringBuilder builder = new StringBuilder(); - - builder.append("["); - int i = 0; - for (final SoftwareModuleTypeManagement.Create module : creates) { - builder.append(new JSONObject().put("name", module.getName()).put("description", module.getDescription()) - .put("colour", module.getColour()).put("id", Long.MAX_VALUE).put("key", module.getKey()) - .put("maxAssignments", module.getMaxAssignments()).put("createdAt", "0").put("updatedAt", "0") - .put("createdBy", "fghdfkjghdfkjh").put("updatedBy", "fghdfkjghdfkjh").toString()); - - if (++i < creates.size()) { - builder.append(","); - } - } - builder.append("]"); - - return builder.toString(); - } - - public static String distributionSetTypes(final List types) throws JSONException { - final JSONArray result = new JSONArray(); - - for (final DistributionSetTypeManagement.Create type : types) { - final JSONArray osmTypes = new JSONArray(); - type.getOptionalModuleTypes().forEach(smt -> { - try { - osmTypes.put(new JSONObject().put("id", smt.getId())); - } catch (final JSONException e1) { - log.error("JSONException (skip)", e1); - } - }); - - final JSONArray msmTypes = new JSONArray(); - type.getMandatoryModuleTypes().forEach(smt -> { - try { - msmTypes.put(new JSONObject().put("id", smt.getId())); - } catch (final JSONException e) { - log.error("JSONException (skip)", e); - } - }); - - result.put(new JSONObject().put("name", type.getName()).put("description", type.getDescription()) - .put("colour", type.getColour()).put("id", Long.MAX_VALUE).put("key", type.getKey()) - .put("createdAt", "0").put("updatedAt", "0").put("createdBy", "fghdfkjghdfkjh") - .put("optionalmodules", osmTypes).put("mandatorymodules", msmTypes) - .put("updatedBy", "fghdfkjghdfkjh")); - - } - - return result.toString(); - } - - public static String distributionSets(final List sets) { - final JSONArray setsJson = new JSONArray(); - - sets.forEach(set -> { - try { - setsJson.put(distributionSet(set)); - } catch (final JSONException e) { - log.error("JSONException (skip)", e); - } - }); - - return setsJson.toString(); - } - - public static JSONObject distributionSet(final DistributionSetManagement.Create set) throws JSONException { - final List modules = set.getModules().stream().map(module -> { - try { - return new JSONObject().put("id", module.getId()); - } catch (final JSONException e) { - log.error("JSONException (skip)", e); - return null; - } - }).toList(); - - return new JSONObject().put("name", set.getName()).put("description", set.getDescription()) - .put("type", set.getType() == null ? null : set.getType().getKey()).put("id", Long.MAX_VALUE) - .put("version", set.getVersion()).put("createdAt", "0").put("updatedAt", "0") - .put("createdBy", "fghdfkjghdfkjh").put("updatedBy", "fghdfkjghdfkjh") - .put("requiredMigrationStep", set.getRequiredMigrationStep()).put("modules", new JSONArray(modules)); - } - - public static String targets(final List 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(); - } - - public static String targets(final List 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(); - } - - public static String targetTypes(final List types) throws JSONException { - final JSONArray result = new JSONArray(); - - for (final TargetType type : types) { - - final JSONArray dsTypes = new JSONArray(); - type.getDistributionSetTypes().forEach(dsType -> { - try { - dsTypes.put(new JSONObject().put("id", dsType.getId())); - } catch (final JSONException e1) { - log.error("JSONException (skip)", e1); - } - }); - - result.put(new JSONObject().put("name", type.getName()).put("description", type.getDescription()) - .put("id", Long.MAX_VALUE).put("colour", type.getColour()).put("createdAt", "0") - .put("updatedAt", "0").put("createdBy", "fghdfkjghdfkjh").put("updatedBy", "fghdfkjghdfkjh") - .put("distributionsets", dsTypes)); - - } - - return result.toString(); - } - - public static String targetTypesCreate(final List types) throws JSONException { - final JSONArray result = new JSONArray(); - - for (final TargetTypeManagement.Create type : types) { - - final JSONArray dsTypes = new JSONArray(); - type.getDistributionSetTypes().forEach(dsType -> { - try { - dsTypes.put(new JSONObject().put("id", dsType)); - } catch (final JSONException e1) { - log.error("JSONException (skip)", e1); - } - }); - - result.put(new JSONObject().put("name", type.getName()).put("description", type.getDescription()) - .put("id", Long.MAX_VALUE).put("colour", type.getColour()).put("createdAt", "0") - .put("updatedAt", "0").put("createdBy", "fghdfkjghdfkjh").put("updatedBy", "fghdfkjghdfkjh") - .put("distributionsets", dsTypes)); - - } - - return result.toString(); - } - - public 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); - } - - public static String rolloutWithGroups(final String name, final String description, final Integer groupSize, - final long distributionSetId, final String targetFilterQuery, final RolloutGroupConditions conditions, - final List groups) { - return rolloutWithGroups(name, description, groupSize, distributionSetId, targetFilterQuery, conditions, groups, - null, null, null); - } - - public static String rolloutWithGroups(final String name, final String description, final Integer groupSize, - final long distributionSetId, final String targetFilterQuery, final RolloutGroupConditions conditions, - final List groups, final String type, final Integer weight, - final Boolean confirmationRequired) { - final List rolloutGroupsJson = groups.stream().map(JsonBuilder::rolloutGroup).toList(); - return rollout( - name, description, groupSize, distributionSetId, targetFilterQuery, conditions, - rolloutGroupsJson, type, weight, System.currentTimeMillis(), null, confirmationRequired); - } - - public static String rollout(final String name, final String description, final Integer groupSize, - final long distributionSetId, final String targetFilterQuery, final RolloutGroupConditions conditions, - final List 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); - } - - public static String rollout(final String name, final String description, final Integer groupSize, - final long distributionSetId, final String targetFilterQuery, final RolloutGroupConditions conditions, - final List 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(); - } - - public static String rolloutGroup(final RolloutGroup rolloutGroup) { - final RolloutGroupConditions conditions = getConditions(rolloutGroup); - return rolloutGroup(rolloutGroup.getName(), rolloutGroup.getDescription(), rolloutGroup.getTargetFilterQuery(), - rolloutGroup.getTargetPercentage(), rolloutGroup.isConfirmationRequired(), conditions); - - } - - public 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(); - } - - public static JSONObject configData(final Map attributes) throws JSONException { - return configData(attributes, null); - } - - public static JSONObject configData(final Map 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 void createTagLine(final StringBuilder builder, final Tag tag) throws JSONException { - builder.append(new JSONObject().put("name", tag.getName()).put("description", tag.getDescription()) - .put("colour", tag.getColour()).put("createdAt", "0").put("updatedAt", "0") - .put("createdBy", "fghdfkjghdfkjh").put("updatedBy", "fghdfkjghdfkjh").toString()); - } - - 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(); - } -}