From 66297d7c27c31056d1e1d2d7545f9d30eb328af8 Mon Sep 17 00:00:00 2001 From: kaizimmerm Date: Tue, 20 Sep 2016 13:40:51 +0200 Subject: [PATCH] reduced empty collections. Fixed Ui eventbus memory leak. Signed-off-by: kaizimmerm --- .../java/org/eclipse/hawkbit/app/MyUI.java | 8 +- .../simulator/amqp/AmqpConfiguration.java | 7 +- .../java/org/eclipse/hawkbit/app/MyUI.java | 8 +- .../rest/resource/DataConversionHelper.java | 9 +- .../hawkbit/amqp/AmqpConfiguration.java | 5 +- .../amqp/AmqpDeadletterProperties.java | 7 +- .../rollout/MgmtRolloutResponseBody.java | 3 +- .../resource/MgmtDistributionSetMapper.java | 55 ++++----- .../resource/MgmtDistributionSetResource.java | 3 +- .../MgmtDistributionSetTypeMapper.java | 32 ++--- .../MgmtDistributionSetTypeResource.java | 4 +- .../mgmt/rest/resource/MgmtRolloutMapper.java | 19 +-- .../resource/MgmtSoftwareModuleMapper.java | 76 +++++------- .../resource/MgmtSoftwareModuleResource.java | 6 +- .../MgmtSoftwareModuleTypeMapper.java | 33 ++--- .../MgmtSoftwareModuleTypeResource.java | 2 +- .../mgmt/rest/resource/MgmtTargetMapper.java | 74 ++++++----- .../rest/resource/MgmtTargetResource.java | 3 +- .../MgmtDistributionSetTypeResourceTest.java | 3 +- .../MgmtSoftwareModuleResourceTest.java | 3 +- .../MgmtSoftwareModuleTypeResourceTest.java | 3 +- .../hawkbit/repository/EntityFactory.java | 38 +++--- .../repository/model/ActionStatus.java | 2 +- .../hawkbit/repository/model/Artifact.java | 2 +- .../hawkbit/repository/model/BaseEntity.java | 2 +- .../repository/model/RolloutGroup.java | 2 +- .../hawkbit/repository/model/TargetInfo.java | 3 +- .../hawkbit-repository-jpa/pom.xml | 4 + .../RepositoryApplicationConfiguration.java | 4 +- .../repository/jpa/ActionRepository.java | 3 +- .../jpa/JpaControllerManagement.java | 9 +- .../jpa/JpaDeploymentManagement.java | 2 +- .../jpa/JpaDistributionSetManagement.java | 55 ++++----- .../repository/jpa/JpaEntityFactory.java | 2 + .../jpa/JpaRolloutGroupManagement.java | 10 +- .../repository/jpa/JpaRolloutManagement.java | 8 +- .../repository/jpa/JpaSoftwareManagement.java | 47 ++++--- .../repository/jpa/JpaTagManagement.java | 17 +-- .../repository/jpa/JpaTargetManagement.java | 49 ++++---- .../ExceptionMappingAspectHandler.java | 7 +- .../jpa/model/AbstractJpaArtifact.java | 6 +- .../jpa/model/AbstractJpaBaseEntity.java | 9 +- .../jpa/model/AbstractJpaMetaData.java | 3 +- .../jpa/model/AbstractJpaNamedEntity.java | 2 +- .../AbstractJpaNamedVersionedEntity.java | 2 +- .../repository/jpa/model/AbstractJpaTag.java | 2 +- .../repository/jpa/model/JpaAction.java | 7 +- .../repository/jpa/model/JpaActionStatus.java | 21 +++- .../jpa/model/JpaActionWithStatusCount.java | 2 +- .../jpa/model/JpaDistributionSet.java | 71 +++++++++-- .../jpa/model/JpaDistributionSetTag.java | 7 +- .../jpa/model/JpaDistributionSetType.java | 39 +++++- .../repository/jpa/model/JpaRollout.java | 9 +- .../repository/jpa/model/JpaRolloutGroup.java | 18 +-- .../jpa/model/JpaSoftwareModule.java | 65 +++++----- .../repository/jpa/model/JpaTarget.java | 50 ++++++-- .../repository/jpa/model/JpaTargetInfo.java | 2 +- .../repository/jpa/model/JpaTargetTag.java | 7 +- ...ThresholdRolloutGroupSuccessCondition.java | 4 +- .../jpa/DeploymentManagementTest.java | 10 +- .../jpa/DistributionSetManagementTest.java | 6 +- .../jpa/SoftwareManagementTest.java | 10 +- .../jpa/TargetManagementSearchTest.java | 5 +- .../repository/jpa/TargetManagementTest.java | 26 ++-- .../jpa/rsql/RSQLActionFieldsTest.java | 7 +- .../details/ArtifactDetailsLayout.java | 11 +- .../event/UploadViewAcceptCriteria.java | 11 +- .../UploadViewConfirmationWindowLayout.java | 4 +- .../smtable/SoftwareModuleTable.java | 4 +- .../client/renderers/HtmlLabelRenderer.java | 25 ++-- .../dstable/DistributionSetDetails.java | 17 ++- .../dstable/DistributionSetTable.java | 5 +- .../DistributionsViewAcceptCriteria.java | 6 +- ...DistributionsConfirmationWindowLayout.java | 5 +- .../distributions/smtable/SwModuleTable.java | 4 +- .../smtype/DistSMTypeFilterButtons.java | 6 +- .../state/ManageDistUIState.java | 6 +- .../CreateOrUpdateFilterTable.java | 4 +- .../filtermanagement/TargetFilterTable.java | 3 +- .../DistributionAddUpdateWindowLayout.java | 6 +- .../management/dstable/DistributionTable.java | 4 +- .../dstag/DistributionTagButtons.java | 6 +- .../event/ManagementViewAcceptCriteria.java | 9 +- .../ManangementConfirmationWindowLayout.java | 3 +- .../management/state/ManagementUIState.java | 7 +- .../TargetBulkUpdateWindowLayout.java | 12 +- .../management/targettable/TargetTable.java | 115 ++++++------------ .../targettag/TargetFilterQueryButtons.java | 6 +- .../ui/push/DelayedEventBusPushStrategy.java | 75 ++++++++---- .../ui/rollout/rollout/RolloutListGrid.java | 5 +- .../hawkbit/ui/utils/HawkbitCommonUtil.java | 8 +- .../hawkbit/ui/utils/SPDateTimeUtil.java | 4 +- 92 files changed, 743 insertions(+), 647 deletions(-) diff --git a/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/MyUI.java b/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/MyUI.java index 5ef632d10..964994317 100644 --- a/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/MyUI.java +++ b/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/MyUI.java @@ -8,6 +8,8 @@ package org.eclipse.hawkbit.app; * http://www.eclipse.org/legal/epl-v10.html */ +import java.util.concurrent.ScheduledExecutorService; + import org.eclipse.hawkbit.ui.HawkbitUI; import org.eclipse.hawkbit.ui.UIEventProvider; import org.eclipse.hawkbit.ui.push.DelayedEventBusPushStrategy; @@ -38,8 +40,8 @@ public class MyUI extends HawkbitUI { private static final long serialVersionUID = 1L; @Autowired - public MyUI(final EventBus systemEventBus, final org.vaadin.spring.events.EventBus.SessionEventBus eventBus, - final UIEventProvider provider) { - super(new DelayedEventBusPushStrategy(eventBus, systemEventBus, provider)); + public MyUI(final ScheduledExecutorService executorService, final EventBus systemEventBus, + final org.vaadin.spring.events.EventBus.SessionEventBus eventBus, final UIEventProvider provider) { + super(new DelayedEventBusPushStrategy(executorService, eventBus, systemEventBus, provider)); } } diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/AmqpConfiguration.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/AmqpConfiguration.java index 5e9b3e049..f024f174b 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/AmqpConfiguration.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/AmqpConfiguration.java @@ -11,7 +11,6 @@ package org.eclipse.hawkbit.simulator.amqp; import static org.eclipse.hawkbit.simulator.amqp.AmqpProperties.CONFIGURATION_PREFIX; import java.time.Duration; -import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; @@ -36,6 +35,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.retry.backoff.ExponentialBackOffPolicy; import org.springframework.retry.support.RetryTemplate; +import com.google.gwt.thirdparty.guava.common.collect.Maps; + /** * The spring AMQP configuration to use a AMQP for communication with SP update * server. @@ -200,13 +201,13 @@ public class AmqpConfiguration { } private Map getDeadLetterExchangeArgs() { - final Map args = new HashMap<>(); + final Map args = Maps.newHashMapWithExpectedSize(1); args.put("x-dead-letter-exchange", amqpProperties.getDeadLetterExchange()); return args; } private static Map getTTLMaxArgs() { - final Map args = new HashMap<>(); + final Map args = Maps.newHashMapWithExpectedSize(2); args.put("x-message-ttl", Duration.ofDays(1).toMillis()); args.put("x-max-length", 100_000); return args; diff --git a/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyUI.java b/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyUI.java index e5bc7535d..0316b68e5 100644 --- a/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyUI.java +++ b/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyUI.java @@ -8,6 +8,8 @@ */ package org.eclipse.hawkbit.app; +import java.util.concurrent.ScheduledExecutorService; + import org.eclipse.hawkbit.ui.HawkbitUI; import org.eclipse.hawkbit.ui.UIEventProvider; import org.eclipse.hawkbit.ui.push.DelayedEventBusPushStrategy; @@ -37,8 +39,8 @@ public class MyUI extends HawkbitUI { private static final long serialVersionUID = 1L; @Autowired - public MyUI(final EventBus systemEventBus, final org.vaadin.spring.events.EventBus.SessionEventBus eventBus, - final UIEventProvider provider) { - super(new DelayedEventBusPushStrategy(eventBus, systemEventBus, provider)); + public MyUI(final ScheduledExecutorService scheduledExecutorService, final EventBus systemEventBus, + final org.vaadin.spring.events.EventBus.SessionEventBus eventBus, final UIEventProvider provider) { + super(new DelayedEventBusPushStrategy(scheduledExecutorService, eventBus, systemEventBus, provider)); } } diff --git a/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DataConversionHelper.java b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DataConversionHelper.java index 55be6f58a..3a50ede61 100644 --- a/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DataConversionHelper.java +++ b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DataConversionHelper.java @@ -12,7 +12,6 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.io.IOException; -import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @@ -73,16 +72,16 @@ public final class DataConversionHelper { * of the target * @param module * the software module + * @param artifactUrlHandler + * for creating download URLs * @return a list of artifacts or a empty list. Cannot be . */ public static List createArtifacts(final String targetid, final org.eclipse.hawkbit.repository.model.SoftwareModule module, final ArtifactUrlHandler artifactUrlHandler) { - final List files = new ArrayList<>(); - module.getLocalArtifacts() - .forEach(artifact -> files.add(createArtifact(targetid, artifactUrlHandler, artifact))); - return files; + return module.getLocalArtifacts().stream() + .map(artifact -> createArtifact(targetid, artifactUrlHandler, artifact)).collect(Collectors.toList()); } private static DdiArtifact createArtifact(final String targetid, final ArtifactUrlHandler artifactUrlHandler, diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpConfiguration.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpConfiguration.java index 09edd41d3..b8cbb8162 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpConfiguration.java +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpConfiguration.java @@ -9,7 +9,6 @@ package org.eclipse.hawkbit.amqp; import java.time.Duration; -import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; @@ -47,6 +46,8 @@ import org.springframework.retry.backoff.ExponentialBackOffPolicy; import org.springframework.retry.support.RetryTemplate; import org.springframework.util.ErrorHandler; +import com.google.common.collect.Maps; + /** * Spring configuration for AMQP 0.9 based DMF communication for indirect device * integration. @@ -306,7 +307,7 @@ public class AmqpConfiguration { } private static Map getTTLMaxArgsAuthenticationQueue() { - final Map args = new HashMap<>(); + final Map args = Maps.newHashMapWithExpectedSize(2); args.put("x-message-ttl", Duration.ofSeconds(30).toMillis()); args.put("x-max-length", 1_000); return args; diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpDeadletterProperties.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpDeadletterProperties.java index 7ed5e90c1..723caf44c 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpDeadletterProperties.java +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpDeadletterProperties.java @@ -9,12 +9,13 @@ package org.eclipse.hawkbit.amqp; import java.time.Duration; -import java.util.HashMap; import java.util.Map; import org.springframework.amqp.core.Queue; import org.springframework.boot.context.properties.ConfigurationProperties; +import com.google.common.collect.Maps; + /** * Bean which holds the necessary properties for configuring the AMQP deadletter * queue. @@ -36,7 +37,7 @@ public class AmqpDeadletterProperties { * @return map which holds the properties */ public Map getDeadLetterExchangeArgs(final String exchange) { - final Map args = new HashMap<>(); + final Map args = Maps.newHashMapWithExpectedSize(1); args.put("x-dead-letter-exchange", exchange); return args; } @@ -53,7 +54,7 @@ public class AmqpDeadletterProperties { } private Map getTTLArgs() { - final Map args = new HashMap<>(); + final Map args = Maps.newHashMapWithExpectedSize(1); args.put("x-message-ttl", getTtl()); return args; } diff --git a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutResponseBody.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutResponseBody.java index 79455f501..ce74b4c8d 100644 --- a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutResponseBody.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutResponseBody.java @@ -8,7 +8,6 @@ */ package org.eclipse.hawkbit.mgmt.json.model.rollout; -import java.util.HashMap; import java.util.Map; import org.eclipse.hawkbit.mgmt.json.model.MgmtNamedEntity; @@ -38,7 +37,7 @@ public class MgmtRolloutResponseBody extends MgmtNamedEntity { private Long totalTargets; @JsonProperty(required = true) - private final Map totalTargetsPerStatus = new HashMap<>(); + private Map totalTargetsPerStatus; /** * @return the status diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetMapper.java index 4a0f8d90e..acd088c85 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetMapper.java @@ -12,7 +12,10 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata; import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet; @@ -34,10 +37,6 @@ import org.eclipse.hawkbit.repository.model.SoftwareModule; /** * A mapper which maps repository model to RESTful model representation and * back. - * - * - * - * */ public final class MgmtDistributionSetMapper { private MgmtDistributionSetMapper() { @@ -75,15 +74,13 @@ public final class MgmtDistributionSetMapper { * to use for conversion * @return converted list of {@link DistributionSet}s */ - static List dsFromRequest(final Iterable sets, + static List dsFromRequest(final Collection sets, final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement, final EntityFactory entityFactory) { - final List mappedList = new ArrayList<>(); - for (final MgmtDistributionSetRequestBodyPost dsRest : sets) { - mappedList.add(fromRequest(dsRest, softwareManagement, distributionSetManagement, entityFactory)); - } - return mappedList; + return sets.stream() + .map(dsRest -> fromRequest(dsRest, softwareManagement, distributionSetManagement, entityFactory)) + .collect(Collectors.toList()); } @@ -139,15 +136,12 @@ public final class MgmtDistributionSetMapper { */ static List fromRequestDsMetadata(final DistributionSet ds, final List metadata, final EntityFactory entityFactory) { - final List mappedList = new ArrayList<>(metadata.size()); - for (final MgmtMetadata metadataRest : metadata) { - if (metadataRest.getKey() == null) { - throw new IllegalArgumentException("the key of the metadata must be present"); - } - mappedList.add( - entityFactory.generateDistributionSetMetadata(ds, metadataRest.getKey(), metadataRest.getValue())); + if (metadata == null) { + return Collections.emptyList(); } - return mappedList; + + return metadata.stream().map(metadataRest -> entityFactory.generateDistributionSetMetadata(ds, + metadataRest.getKey(), metadataRest.getValue())).collect(Collectors.toList()); } /** @@ -196,15 +190,12 @@ public final class MgmtDistributionSetMapper { return result; } - static List toResponseDistributionSets(final Iterable sets) { - final List response = new ArrayList<>(); - if (sets != null) { - - for (final DistributionSet set : sets) { - response.add(toResponse(set)); - } + static List toResponseDistributionSets(final Collection sets) { + if (sets == null) { + return Collections.emptyList(); } - return response; + + return sets.stream().map(MgmtDistributionSetMapper::toResponse).collect(Collectors.toList()); } static MgmtMetadata toResponseDsMetadata(final DistributionSetMetadata metadata) { @@ -224,14 +215,10 @@ public final class MgmtDistributionSetMapper { } static List toResponseFromDsList(final List sets) { - final List mappedList = new ArrayList<>(); - if (sets != null) { - for (final DistributionSet set : sets) { - final MgmtDistributionSet response = toResponse(set); - - mappedList.add(response); - } + if (sets == null) { + return Collections.emptyList(); } - return mappedList; + + return sets.stream().map(MgmtDistributionSetMapper::toResponse).collect(Collectors.toList()); } } diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java index 721995d88..b49654460 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java @@ -8,6 +8,7 @@ */ package org.eclipse.hawkbit.mgmt.rest.resource; +import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -123,7 +124,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi { .runAsSystem(() -> this.systemManagement.getTenantMetadata().getDefaultDsType().getKey()); sets.stream().filter(ds -> ds.getType() == null).forEach(ds -> ds.setType(defaultDsKey)); - final Iterable createdDSets = this.distributionSetManagement + final Collection createdDSets = this.distributionSetManagement .createDistributionSets(MgmtDistributionSetMapper.dsFromRequest(sets, this.softwareManagement, this.distributionSetManagement, entityFactory)); diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeMapper.java index 675fe9df0..33b81ab73 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeMapper.java @@ -11,8 +11,10 @@ package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; -import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetType; import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost; @@ -39,13 +41,13 @@ final class MgmtDistributionSetTypeMapper { static List smFromRequest(final EntityFactory entityFactory, final SoftwareManagement softwareManagement, - final Iterable smTypesRest) { - final List mappedList = new ArrayList<>(); - - for (final MgmtDistributionSetTypeRequestBodyPost smRest : smTypesRest) { - mappedList.add(fromRequest(entityFactory, softwareManagement, smRest)); + final Collection smTypesRest) { + if (smTypesRest == null) { + return Collections.emptyList(); } - return mappedList; + + return smTypesRest.stream().map(smRest -> fromRequest(entityFactory, softwareManagement, smRest)) + .collect(Collectors.toList()); } static DistributionSetType fromRequest(final EntityFactory entityFactory, @@ -91,19 +93,19 @@ final class MgmtDistributionSetTypeMapper { } static List toTypesResponse(final List types) { - final List response = new ArrayList<>(); - for (final DistributionSetType dsType : types) { - response.add(toResponse(dsType)); + if (types == null) { + return Collections.emptyList(); } - return response; + + return types.stream().map(MgmtDistributionSetTypeMapper::toResponse).collect(Collectors.toList()); } static List toListResponse(final List types) { - final List response = new ArrayList<>(); - for (final DistributionSetType dsType : types) { - response.add(toResponse(dsType)); + if (types == null) { + return Collections.emptyList(); } - return response; + + return types.stream().map(MgmtDistributionSetTypeMapper::toResponse).collect(Collectors.toList()); } static MgmtDistributionSetType toResponse(final DistributionSetType type) { diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java index d69e4d8d4..762e0e104 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java @@ -146,7 +146,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR @PathVariable("distributionSetTypeId") final Long distributionSetTypeId) { final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); - return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toListResponse(foundType.getMandatoryModuleTypes()), + return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toTypesResponse(foundType.getMandatoryModuleTypes()), HttpStatus.OK); } @@ -190,7 +190,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); - return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toListResponse(foundType.getOptionalModuleTypes()), + return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toTypesResponse(foundType.getOptionalModuleTypes()), HttpStatus.OK); } diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutMapper.java index 7467a45b0..2a092851d 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutMapper.java @@ -11,8 +11,9 @@ package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutCondition.Condition; import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutErrorAction.ErrorAction; @@ -48,9 +49,11 @@ final class MgmtRolloutMapper { } static List toResponseRollout(final List rollouts) { - final List result = new ArrayList<>(rollouts.size()); - rollouts.forEach(r -> result.add(toResponseRollout(r))); - return result; + if (rollouts == null) { + return Collections.emptyList(); + } + + return rollouts.stream().map(MgmtRolloutMapper::toResponseRollout).collect(Collectors.toList()); } static MgmtRolloutResponseBody toResponseRollout(final Rollout rollout) { @@ -103,9 +106,11 @@ final class MgmtRolloutMapper { } static List toResponseRolloutGroup(final List rollouts) { - final List result = new ArrayList<>(rollouts.size()); - rollouts.forEach(r -> result.add(toResponseRolloutGroup(r))); - return result; + if (rollouts == null) { + return Collections.emptyList(); + } + + return rollouts.stream().map(MgmtRolloutMapper::toResponseRolloutGroup).collect(Collectors.toList()); } static MgmtRolloutGroupResponseBody toResponseRolloutGroup(final RolloutGroup rolloutGroup) { diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleMapper.java index 3960fb3c2..2166a7e43 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleMapper.java @@ -11,8 +11,10 @@ package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; -import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata; import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact; @@ -65,60 +67,46 @@ public final class MgmtSoftwareModuleMapper { } static List fromRequestSwMetadata(final EntityFactory entityFactory, - final SoftwareModule sw, final List metadata) { - final List mappedList = new ArrayList<>(metadata.size()); - for (final MgmtMetadata metadataRest : metadata) { - if (metadataRest.getKey() == null) { - throw new IllegalArgumentException("the key of the metadata must be present"); - } - mappedList.add( - entityFactory.generateSoftwareModuleMetadata(sw, metadataRest.getKey(), metadataRest.getValue())); + final SoftwareModule sw, final Collection metadata) { + if (metadata == null) { + return Collections.emptyList(); } - return mappedList; + + return metadata.stream().map(metadataRest -> entityFactory.generateSoftwareModuleMetadata(sw, + metadataRest.getKey(), metadataRest.getValue())).collect(Collectors.toList()); } static List smFromRequest(final EntityFactory entityFactory, - final Iterable smsRest, final SoftwareManagement softwareManagement) { - final List mappedList = new ArrayList<>(); - for (final MgmtSoftwareModuleRequestBodyPost smRest : smsRest) { - mappedList.add(fromRequest(entityFactory, smRest, softwareManagement)); + final Collection smsRest, final SoftwareManagement softwareManagement) { + if (smsRest == null) { + return Collections.emptyList(); } - return mappedList; + + return smsRest.stream().map(smRest -> fromRequest(entityFactory, smRest, softwareManagement)) + .collect(Collectors.toList()); } /** * Create response for sw modules. * - * @param baseSoftareModules + * @param softwareModules * the modules * @return the response */ - public static List toResponse(final List baseSoftareModules) { - final List mappedList = new ArrayList<>(); - if (baseSoftareModules != null) { - for (final SoftwareModule target : baseSoftareModules) { - final MgmtSoftwareModule response = toResponse(target); - - mappedList.add(response); - } + public static List toResponse(final Collection softwareModules) { + if (softwareModules == null) { + return Collections.emptyList(); } - return mappedList; + + return softwareModules.stream().map(MgmtSoftwareModuleMapper::toResponse).collect(Collectors.toList()); } - static List toResponseSoftwareModules(final Iterable softwareModules) { - final List response = new ArrayList<>(); - for (final SoftwareModule softwareModule : softwareModules) { - response.add(toResponse(softwareModule)); + static List toResponseSwMetadata(final Collection metadata) { + if (metadata == null) { + return Collections.emptyList(); } - return response; - } - static List toResponseSwMetadata(final List metadata) { - final List mappedList = new ArrayList<>(metadata.size()); - for (final SoftwareModuleMetadata distributionSetMetadata : metadata) { - mappedList.add(toResponseSwMetadata(distributionSetMetadata)); - } - return mappedList; + return metadata.stream().map(MgmtSoftwareModuleMapper::toResponseSwMetadata).collect(Collectors.toList()); } static MgmtMetadata toResponseSwMetadata(final SoftwareModuleMetadata metadata) { @@ -194,15 +182,11 @@ public final class MgmtSoftwareModuleMapper { return artifactRest; } - static List artifactsToResponse(final List artifacts) { - final List mappedList = new ArrayList<>(); - - if (artifacts != null) { - for (final Artifact artifact : artifacts) { - final MgmtArtifact response = toResponse(artifact); - mappedList.add(response); - } + static List artifactsToResponse(final Collection artifacts) { + if (artifacts == null) { + return Collections.emptyList(); } - return mappedList; + + return artifacts.stream().map(MgmtSoftwareModuleMapper::toResponse).collect(Collectors.toList()); } } diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java index b475c473f..f3759d94f 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java @@ -9,6 +9,7 @@ package org.eclipse.hawkbit.mgmt.rest.resource; import java.io.IOException; +import java.util.Collection; import java.util.List; import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata; @@ -158,12 +159,11 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi { public ResponseEntity> createSoftwareModules( @RequestBody final List softwareModules) { LOG.debug("creating {} softwareModules", softwareModules.size()); - final Iterable createdSoftwareModules = softwareManagement.createSoftwareModule( + final Collection createdSoftwareModules = softwareManagement.createSoftwareModule( MgmtSoftwareModuleMapper.smFromRequest(entityFactory, softwareModules, softwareManagement)); LOG.debug("{} softwareModules created, return status {}", softwareModules.size(), HttpStatus.CREATED); - return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponseSoftwareModules(createdSoftwareModules), - HttpStatus.CREATED); + return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponse(createdSoftwareModules), HttpStatus.CREATED); } @Override diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeMapper.java index 565af7eb8..e14ed27fa 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeMapper.java @@ -11,9 +11,10 @@ package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; -import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleType; import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPost; @@ -25,9 +26,6 @@ import org.eclipse.hawkbit.repository.model.SoftwareModuleType; * A mapper which maps repository model to RESTful model representation and * back. * - * - * - * */ final class MgmtSoftwareModuleTypeMapper { @@ -37,13 +35,12 @@ final class MgmtSoftwareModuleTypeMapper { } static List smFromRequest(final EntityFactory entityFactory, - final Iterable smTypesRest) { - final List mappedList = new ArrayList<>(); - - for (final MgmtSoftwareModuleTypeRequestBodyPost smRest : smTypesRest) { - mappedList.add(fromRequest(entityFactory, smRest)); + final Collection smTypesRest) { + if (smTypesRest == null) { + return Collections.emptyList(); } - return mappedList; + + return smTypesRest.stream().map(smRest -> fromRequest(entityFactory, smRest)).collect(Collectors.toList()); } static SoftwareModuleType fromRequest(final EntityFactory entityFactory, @@ -57,20 +54,12 @@ final class MgmtSoftwareModuleTypeMapper { return result; } - static List toTypesResponse(final List types) { - final List response = new ArrayList<>(); - for (final SoftwareModuleType softwareModule : types) { - response.add(toResponse(softwareModule)); + static List toTypesResponse(final Collection types) { + if (types == null) { + return Collections.emptyList(); } - return response; - } - static List toListResponse(final Collection types) { - final List response = new ArrayList<>(); - for (final SoftwareModuleType softwareModule : types) { - response.add(toResponse(softwareModule)); - } - return response; + return types.stream().map(MgmtSoftwareModuleTypeMapper::toResponse).collect(Collectors.toList()); } static MgmtSoftwareModuleType toResponse(final SoftwareModuleType type) { diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java index 353cf16e5..762dd7c1c 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java @@ -72,7 +72,7 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes } final List rest = MgmtSoftwareModuleTypeMapper - .toListResponse(findModuleTypessAll.getContent()); + .toTypesResponse(findModuleTypessAll.getContent()); return new ResponseEntity<>(new PagedList<>(rest, countModulesAll), HttpStatus.OK); } diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetMapper.java index a889edc35..014d0e9e3 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetMapper.java @@ -13,9 +13,11 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.net.URI; import java.time.ZoneId; -import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.Date; import java.util.List; +import java.util.stream.Collectors; import org.eclipse.hawkbit.mgmt.json.model.MgmtPollStatus; import org.eclipse.hawkbit.mgmt.json.model.action.MgmtAction; @@ -92,17 +94,17 @@ public final class MgmtTargetMapper { * the targets * @return the response */ - public static List toResponseWithLinksAndPollStatus(final Iterable targets) { - final List mappedList = new ArrayList<>(); - if (targets != null) { - for (final Target target : targets) { - final MgmtTarget response = toResponse(target); - addPollStatus(target, response); - addTargetLinks(response); - mappedList.add(response); - } + public static List toResponseWithLinksAndPollStatus(final Collection targets) { + if (targets == null) { + return Collections.emptyList(); } - return mappedList; + + return targets.stream().map(target -> { + final MgmtTarget response = toResponse(target); + addPollStatus(target, response); + addTargetLinks(response); + return response; + }).collect(Collectors.toList()); } /** @@ -112,15 +114,12 @@ public final class MgmtTargetMapper { * list of targets * @return the response */ - public static List toResponse(final Iterable targets) { - final List mappedList = new ArrayList<>(); - if (targets != null) { - for (final Target target : targets) { - final MgmtTarget response = toResponse(target); - mappedList.add(response); - } + public static List toResponse(final Collection targets) { + if (targets == null) { + return Collections.emptyList(); } - return mappedList; + + return targets.stream().map(MgmtTargetMapper::toResponse).collect(Collectors.toList()); } /** @@ -173,12 +172,13 @@ public final class MgmtTargetMapper { } static List fromRequest(final EntityFactory entityFactory, - final Iterable targetsRest) { - final List mappedList = new ArrayList<>(); - for (final MgmtTargetRequestBody targetRest : targetsRest) { - mappedList.add(fromRequest(entityFactory, targetRest)); + final Collection targetsRest) { + if (targetsRest == null) { + return Collections.emptyList(); } - return mappedList; + + return targetsRest.stream().map(targetRest -> fromRequest(entityFactory, targetRest)) + .collect(Collectors.toList()); } static Target fromRequest(final EntityFactory entityFactory, final MgmtTargetRequestBody targetRest) { @@ -190,17 +190,12 @@ public final class MgmtTargetMapper { return target; } - static List toActionStatusRestResponse(final List actionStatus) { - final List mappedList = new ArrayList<>(); - - if (actionStatus != null) { - for (final ActionStatus status : actionStatus) { - final MgmtActionStatus response = toResponse(status); - mappedList.add(response); - } + static List toActionStatusRestResponse(final Collection actionStatus) { + if (actionStatus == null) { + return Collections.emptyList(); } - return mappedList; + return actionStatus.stream().map(MgmtTargetMapper::toResponse).collect(Collectors.toList()); } static MgmtAction toResponse(final String targetId, final Action action, final boolean isActive) { @@ -222,14 +217,13 @@ public final class MgmtTargetMapper { return result; } - static List toResponse(final String targetId, final List actions) { - final List mappedList = new ArrayList<>(); - - for (final Action action : actions) { - final MgmtAction response = toResponse(targetId, action, action.isActive()); - mappedList.add(response); + static List toResponse(final String targetId, final Collection actions) { + if (actions == null) { + return Collections.emptyList(); } - return mappedList; + + return actions.stream().map(action -> toResponse(targetId, action, action.isActive())) + .collect(Collectors.toList()); } private static String getNameOfActionStatusType(final Action.Status type) { diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java index 5ddb74314..d0d72be40 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java @@ -11,6 +11,7 @@ package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; +import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -108,7 +109,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi { @Override public ResponseEntity> createTargets(@RequestBody final List targets) { LOG.debug("creating {} targets", targets.size()); - final Iterable createdTargets = this.targetManagement + final Collection createdTargets = this.targetManagement .createTargets(MgmtTargetMapper.fromRequest(entityFactory, targets)); LOG.debug("{} targets created, return status {}", targets.size(), HttpStatus.CREATED); return new ResponseEntity<>(MgmtTargetMapper.toResponse(createdTargets), HttpStatus.CREATED); diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java index 9d5b0d002..f3b19f5c8 100644 --- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java @@ -26,6 +26,7 @@ import java.util.List; import org.apache.commons.lang3.RandomStringUtils; import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; @@ -554,7 +555,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isBadRequest()); - final DistributionSetType missingName = entityFactory.generateDistributionSetType("test123", null, "Desc123"); + final DistributionSetType missingName = new JpaDistributionSetType("test123", null, "Desc123"); mvc.perform(post("/rest/v1/distributionsettypes") .content(JsonBuilder.distributionSetTypes(Lists.newArrayList(missingName))) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java index f5c79fb6c..f3f86fbc7 100644 --- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java @@ -37,6 +37,7 @@ import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact; import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.LocalArtifact; @@ -457,7 +458,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isBadRequest()); - final SoftwareModule missingName = entityFactory.generateSoftwareModule(osType, null, "version 1", null, null); + final SoftwareModule missingName = new JpaSoftwareModule(osType, null, "version 1", null, null); mvc.perform( post("/rest/v1/softwaremodules").content(JsonBuilder.softwareModules(Lists.newArrayList(missingName))) .contentType(MediaType.APPLICATION_JSON)) diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java index 8c60815e3..a0a5b397b 100644 --- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java @@ -26,6 +26,7 @@ import java.util.List; import org.apache.commons.lang3.RandomStringUtils; import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.repository.test.util.WithUser; @@ -337,7 +338,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isBadRequest()); - final SoftwareModuleType missingName = entityFactory.generateSoftwareModuleType("test123", null, "Desc123", 5); + final SoftwareModuleType missingName = new JpaSoftwareModuleType("test123", null, "Desc123", 5); mvc.perform(post("/rest/v1/softwaremoduletypes") .content(JsonBuilder.softwareModuleTypes(Lists.newArrayList(missingName))) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/EntityFactory.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/EntityFactory.java index 87919729e..925351807 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/EntityFactory.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/EntityFactory.java @@ -11,6 +11,8 @@ package org.eclipse.hawkbit.repository; import java.util.Collection; import java.util.concurrent.TimeUnit; +import javax.validation.constraints.NotNull; + import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.ActionStatus; @@ -64,7 +66,7 @@ public interface EntityFactory { * * @return {@link ActionStatus} object */ - ActionStatus generateActionStatus(Action action, Status status, Long occurredAt); + ActionStatus generateActionStatus(@NotNull Action action, @NotNull Status status, Long occurredAt); /** * Generates an {@link ActionStatus} object without persisting it. @@ -81,7 +83,7 @@ public interface EntityFactory { * * @return {@link ActionStatus} object */ - ActionStatus generateActionStatus(Action action, final Status status, Long occurredAt, + ActionStatus generateActionStatus(@NotNull Action action, @NotNull Status status, Long occurredAt, final Collection messages); /** @@ -99,7 +101,8 @@ public interface EntityFactory { * * @return {@link ActionStatus} object */ - ActionStatus generateActionStatus(Action action, Status status, Long occurredAt, final String message); + ActionStatus generateActionStatus(@NotNull Action action, @NotNull Status status, Long occurredAt, + final String message); /** * Generates an empty {@link DistributionSet} without persisting it. @@ -124,8 +127,8 @@ public interface EntityFactory { * * @return {@link DistributionSet} object */ - DistributionSet generateDistributionSet(String name, String version, String description, DistributionSetType type, - Collection moduleList); + DistributionSet generateDistributionSet(@NotNull String name, @NotNull String version, String description, + @NotNull DistributionSetType type, Collection moduleList); /** * Generates an empty {@link DistributionSetMetadata} element without @@ -148,7 +151,8 @@ public interface EntityFactory { * * @return {@link DistributionSetMetadata} object */ - DistributionSetMetadata generateDistributionSetMetadata(DistributionSet distributionSet, String key, String value); + DistributionSetMetadata generateDistributionSetMetadata(@NotNull DistributionSet distributionSet, + @NotNull String key, String value); /** * Generates an empty {@link DistributionSetTag} without persisting it. @@ -164,7 +168,7 @@ public interface EntityFactory { * of the tag * @return {@link DistributionSetTag} object */ - DistributionSetTag generateDistributionSetTag(String name); + DistributionSetTag generateDistributionSetTag(@NotNull String name); /** * Generates a {@link DistributionSetTag} without persisting it. @@ -177,7 +181,7 @@ public interface EntityFactory { * of the tag * @return {@link DistributionSetTag} object */ - DistributionSetTag generateDistributionSetTag(String name, String description, String colour); + DistributionSetTag generateDistributionSetTag(@NotNull String name, String description, String colour); /** * Generates an empty {@link DistributionSetType} without persisting it. @@ -198,7 +202,7 @@ public interface EntityFactory { * * @return {@link DistributionSetType} object */ - DistributionSetType generateDistributionSetType(String key, String name, String description); + DistributionSetType generateDistributionSetType(@NotNull String key, @NotNull String name, String description); /** * Generates an empty {@link Rollout} without persisting it. @@ -237,8 +241,8 @@ public interface EntityFactory { * * @return {@link SoftwareModule} object */ - SoftwareModule generateSoftwareModule(SoftwareModuleType type, String name, String version, String description, - String vendor); + SoftwareModule generateSoftwareModule(@NotNull SoftwareModuleType type, @NotNull String name, + @NotNull String version, String description, String vendor); /** * Generates an empty {@link SoftwareModuleMetadata} pair without persisting @@ -260,7 +264,8 @@ public interface EntityFactory { * * @return {@link SoftwareModuleMetadata} object */ - SoftwareModuleMetadata generateSoftwareModuleMetadata(SoftwareModule softwareModule, String key, String value); + SoftwareModuleMetadata generateSoftwareModuleMetadata(@NotNull SoftwareModule softwareModule, @NotNull String key, + String value); /** * Generates an empty {@link SoftwareModuleType} without persisting it. @@ -283,7 +288,8 @@ public interface EntityFactory { * * @return {@link SoftwareModuleType} object */ - SoftwareModuleType generateSoftwareModuleType(String key, String name, String description, int maxAssignments); + SoftwareModuleType generateSoftwareModuleType(@NotNull String key, @NotNull String name, String description, + int maxAssignments); /** * Generates an empty {@link Target} without persisting it. @@ -307,7 +313,7 @@ public interface EntityFactory { * * @return {@link Target} object */ - Target generateTarget(@NotEmpty String controllerID, @NotEmpty String securityToken); + Target generateTarget(@NotEmpty String controllerID, String securityToken); /** * Generates an empty {@link TargetFilterQuery} without persisting it. @@ -330,7 +336,7 @@ public interface EntityFactory { * of the tag * @return {@link TargetTag} object */ - TargetTag generateTargetTag(String name); + TargetTag generateTargetTag(@NotNull String name); /** * Generates a {@link TargetTag} without persisting it. @@ -343,7 +349,7 @@ public interface EntityFactory { * of the tag * @return {@link TargetTag} object */ - TargetTag generateTargetTag(String name, String description, String colour); + TargetTag generateTargetTag(@NotNull String name, String description, String colour); /** * Generates an empty {@link LocalArtifact} without persisting it. diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ActionStatus.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ActionStatus.java index e83108fe8..d38bc4f75 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ActionStatus.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ActionStatus.java @@ -47,7 +47,7 @@ public interface ActionStatus extends TenantAwareBaseEntity { * @return current {@link Status#DOWNLOAD} progress if known by the update * server. */ - int getDownloadProgressPercent(); + short getDownloadProgressPercent(); /** * @return list of message entries that can be added to the diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Artifact.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Artifact.java index cc726839d..e0a142b43 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Artifact.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Artifact.java @@ -37,6 +37,6 @@ public interface Artifact extends TenantAwareBaseEntity { /** * @return size of the artifact in bytes. */ - Long getSize(); + long getSize(); } diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/BaseEntity.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/BaseEntity.java index 2a9948bc5..c6717d021 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/BaseEntity.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/BaseEntity.java @@ -44,6 +44,6 @@ public interface BaseEntity extends Serializable, Identifiable { /** * @return version of the {@link BaseEntity}. */ - long getOptLockRevision(); + int getOptLockRevision(); } diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java index 3180fdb6a..286085eba 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java @@ -155,7 +155,7 @@ public interface RolloutGroup extends NamedEntity { /** * @return the total amount of targets containing in this group */ - long getTotalTargets(); + int getTotalTargets(); /** * @return the totalTargetCountStatus diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetInfo.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetInfo.java index 2eb2f05c7..76a975f75 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetInfo.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetInfo.java @@ -36,7 +36,8 @@ public interface TargetInfo extends Serializable { /** * @return time in {@link TimeUnit#MILLISECONDS} GMT when the {@link Target} - * polled the server the last time. + * polled the server the last time or null if target + * has never queried yet. */ Long getLastTargetQuery(); diff --git a/hawkbit-repository/hawkbit-repository-jpa/pom.xml b/hawkbit-repository/hawkbit-repository-jpa/pom.xml index 3a66a0a9d..9f7a0bbb7 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/pom.xml +++ b/hawkbit-repository/hawkbit-repository-jpa/pom.xml @@ -89,6 +89,10 @@ cz.jirutka.rsql rsql-parser + + org.apache.commons + commons-collections4 + diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java index a62de9a06..f0e1a1301 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java @@ -8,7 +8,6 @@ */ package org.eclipse.hawkbit; -import java.util.HashMap; import java.util.Map; import org.eclipse.hawkbit.repository.ArtifactManagement; @@ -73,6 +72,7 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; +import com.google.common.collect.Maps; import com.google.common.eventbus.EventBus; /** @@ -197,7 +197,7 @@ public class RepositoryApplicationConfiguration extends JpaBaseConfiguration { @Override protected Map getVendorProperties() { - final Map properties = new HashMap<>(); + final Map properties = Maps.newHashMapWithExpectedSize(5); // Turn off dynamic weaving to disable LTW lookup in static weaving mode properties.put("eclipselink.weaving", "false"); // needed for reports diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionRepository.java index 8989a5a41..b39d760c3 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionRepository.java @@ -30,6 +30,7 @@ import org.springframework.cache.annotation.CacheEvict; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; +import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.EntityGraph.EntityGraphType; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; @@ -103,7 +104,7 @@ public interface ActionRepository extends BaseEntityRepository, * @return the found {@link Action} */ @EntityGraph(value = "Action.ds", type = EntityGraphType.LOAD) - Optional findFirstByTargetAndActiveOrderByIdAsc(final JpaTarget target, boolean active); + Optional findFirstByTargetAndActive(final Sort sort, final JpaTarget target, boolean active); /** * Retrieves latest {@link UpdateAction} for given target and diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java index 41ad6f179..c12838c9b 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java @@ -9,7 +9,7 @@ package org.eclipse.hawkbit.repository.jpa; import java.net.URI; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; @@ -54,6 +54,8 @@ import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Modifying; import org.springframework.transaction.annotation.Isolation; @@ -163,12 +165,13 @@ public class JpaControllerManagement implements ControllerManagement { @Override public Optional findOldestActiveActionByTarget(final Target target) { - return actionRepository.findFirstByTargetAndActiveOrderByIdAsc((JpaTarget) target, true); + return actionRepository.findFirstByTargetAndActive(new Sort(Direction.ASC, "id"), (JpaTarget) target, true); } @Override public List findSoftwareModulesByDistributionSet(final DistributionSet distributionSet) { - return new ArrayList<>(softwareModuleRepository.findByAssignedTo((JpaDistributionSet) distributionSet)); + return Collections + .unmodifiableList(softwareModuleRepository.findByAssignedTo((JpaDistributionSet) distributionSet)); } @Override diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDeploymentManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDeploymentManagement.java index 5a2c6fdda..09c308a3b 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDeploymentManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDeploymentManagement.java @@ -593,7 +593,7 @@ public class JpaDeploymentManagement implements DeploymentManagement { multiselect.where(cb.equal(actionRoot.get(JpaAction_.target), target)); multiselect.orderBy(cb.desc(actionRoot.get(JpaAction_.id))); multiselect.groupBy(actionRoot.get(JpaAction_.id)); - return new ArrayList<>(entityManager.createQuery(multiselect).getResultList()); + return Collections.unmodifiableList(entityManager.createQuery(multiselect).getResultList()); } @Override diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDistributionSetManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDistributionSetManagement.java index e170ccad7..a4295cdae 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDistributionSetManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDistributionSetManagement.java @@ -126,26 +126,24 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { final DistributionSetTag myTag = tagManagement.findDistributionSetTag(tagName); DistributionSetTagAssignmentResult result; - final List toBeChangedDSs = new ArrayList<>(); - for (final JpaDistributionSet set : sets) { - if (set.getTags().add(myTag)) { - toBeChangedDSs.add(set); - } - } + + final List toBeChangedDSs = sets.stream().filter(set -> set.addTag(myTag)) + .collect(Collectors.toList()); // un-assignment case if (toBeChangedDSs.isEmpty()) { for (final JpaDistributionSet set : sets) { - if (set.getTags().remove(myTag)) { + if (set.removeTag(myTag)) { toBeChangedDSs.add(set); } } result = new DistributionSetTagAssignmentResult(dsIds.size() - toBeChangedDSs.size(), 0, toBeChangedDSs.size(), Collections.emptyList(), - new ArrayList<>(distributionSetRepository.save(toBeChangedDSs)), myTag); + Collections.unmodifiableList(distributionSetRepository.save(toBeChangedDSs)), myTag); } else { result = new DistributionSetTagAssignmentResult(dsIds.size() - toBeChangedDSs.size(), toBeChangedDSs.size(), - 0, new ArrayList<>(distributionSetRepository.save(toBeChangedDSs)), Collections.emptyList(), myTag); + 0, Collections.unmodifiableList(distributionSetRepository.save(toBeChangedDSs)), + Collections.emptyList(), myTag); } final DistributionSetTagAssignmentResult resultAssignment = result; @@ -174,8 +172,6 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) public void deleteDistributionSet(final Long... distributionSetIDs) { - final List toHardDelete = new ArrayList<>(); - final List assigned = distributionSetRepository .findAssignedToTargetDistributionSetsById(distributionSetIDs); assigned.addAll(distributionSetRepository.findAssignedToRolloutDistributionSetsById(distributionSetIDs)); @@ -186,13 +182,10 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { } // mark the rest as hard delete - for (final Long setId : distributionSetIDs) { - if (!assigned.contains(setId)) { - toHardDelete.add(setId); - } - } + final List toHardDelete = Arrays.stream(distributionSetIDs).filter(setId -> !assigned.contains(setId)) + .collect(Collectors.toList()); - // hard delete the rest if exixts + // hard delete the rest if exists if (!toHardDelete.isEmpty()) { // don't give the delete statement an empty list, JPA/Oracle cannot // handle the empty list @@ -239,7 +232,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { @SuppressWarnings({ "unchecked", "rawtypes" }) final Collection toSave = (Collection) distributionSets; - return new ArrayList<>(distributionSetRepository.save(toSave)); + return Collections.unmodifiableList(distributionSetRepository.save(toSave)); } @Override @@ -292,7 +285,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { } private static Page convertDsTPage(final Page findAll) { - return new PageImpl<>(new ArrayList<>(findAll.getContent())); + return new PageImpl<>(Collections.unmodifiableList(findAll.getContent())); } @Override @@ -310,7 +303,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { private static Page convertDsPage(final Page findAll, final Pageable pageable) { - return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements()); } /** @@ -333,7 +326,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { @Override public Page findDistributionSetsByDeletedAndOrCompleted(final Pageable pageReq, final Boolean deleted, final Boolean complete) { - final List> specList = new ArrayList<>(); + final List> specList = new ArrayList<>(2); if (deleted != null) { final Specification spec = DistributionSetSpecification.isDeleted(deleted); @@ -354,11 +347,12 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { final Specification spec = RSQLUtility.parse(rsqlParam, DistributionSetFields.class); - final List> specList = new ArrayList<>(); + final List> specList = new LinkedList<>(); if (deleted != null) { specList.add(DistributionSetSpecification.isDeleted(deleted)); } specList.add(spec); + return convertDsPage(findByCriteriaAPI(pageReq, specList), pageReq); } @@ -414,7 +408,8 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { @Override public List findDistributionSetsAll(final Collection dist) { - return new ArrayList<>(distributionSetRepository.findAll(DistributionSetSpecification.byIds(dist))); + return Collections + .unmodifiableList(distributionSetRepository.findAll(DistributionSetSpecification.byIds(dist))); } @Override @@ -555,7 +550,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { @Override public List findDistributionSetMetadataByDistributionSetId(final Long distributionSetId) { - return new ArrayList<>(distributionSetMetadataRepository + return Collections.unmodifiableList(distributionSetMetadataRepository .findAll((Specification) (root, query, cb) -> cb.equal( root.get(JpaDistributionSetMetadata_.distributionSet).get(JpaDistributionSet_.id), distributionSetId))); @@ -579,7 +574,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { private static Page convertMdPage(final Page findAll, final Pageable pageable) { - return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements()); } @Override @@ -604,7 +599,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { private static List> buildDistributionSetSpecifications( final DistributionSetFilter distributionSetFilter) { - final List> specList = new ArrayList<>(); + final List> specList = new LinkedList<>(); Specification spec; @@ -705,9 +700,9 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { public List assignTag(final Collection dsIds, final DistributionSetTag tag) { final List allDs = findDistributionSetListWithDetails(dsIds); - allDs.forEach(ds -> ds.getTags().add(tag)); + allDs.forEach(ds -> ds.addTag(tag)); - final List save = new ArrayList<>(distributionSetRepository.save(allDs)); + final List save = Collections.unmodifiableList(distributionSetRepository.save(allDs)); afterCommit.afterCommit(() -> { @@ -727,7 +722,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { @SuppressWarnings({ "unchecked", "rawtypes" }) final Collection distributionSets = (Collection) tag.getAssignedToDistributionSet(); - return new ArrayList<>(unAssignTag(distributionSets, tag)); + return Collections.unmodifiableList(unAssignTag(distributionSets, tag)); } @Override @@ -741,7 +736,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { private List unAssignTag(final Collection distributionSets, final DistributionSetTag tag) { - distributionSets.forEach(ds -> ds.getTags().remove(tag)); + distributionSets.forEach(ds -> ds.removeTag(tag)); return distributionSetRepository.save(distributionSets); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaEntityFactory.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaEntityFactory.java index 51b59f08f..1bc8063ec 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaEntityFactory.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaEntityFactory.java @@ -43,11 +43,13 @@ import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetTag; +import org.springframework.validation.annotation.Validated; /** * JPA Implementation of {@link EntityFactory}. * */ +@Validated public class JpaEntityFactory implements EntityFactory { @Override diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutGroupManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutGroupManagement.java index 9f63204b1..64d81cb70 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutGroupManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutGroupManagement.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -81,11 +81,11 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement { } private static Page convertPage(final Page findAll, final Pageable pageable) { - return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements()); } private static Page convertTPage(final Page findAll, final Pageable pageable) { - return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements()); } @Override @@ -114,7 +114,7 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement { for (final RolloutGroup rolloutGroup : rolloutGroups) { final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus( - allStatesForRollout.get(rolloutGroup.getId()), rolloutGroup.getTotalTargets()); + allStatesForRollout.get(rolloutGroup.getId()), new Long(rolloutGroup.getTotalTargets())); rolloutGroup.setTotalTargetCountStatus(totalTargetCountStatus); } @@ -128,7 +128,7 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement { .getStatusCountByRolloutGroupId(rolloutGroupId); final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus(rolloutStatusCountItems, - rolloutGroup.getTotalTargets()); + new Long(rolloutGroup.getTotalTargets())); rolloutGroup.setTotalTargetCountStatus(totalTargetCountStatus); return rolloutGroup; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutManagement.java index 3a903ea89..1cb763f3a 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutManagement.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; @@ -140,11 +140,11 @@ public class JpaRolloutManagement implements RolloutManagement { } private static Page convertPage(final Page findAll, final Pageable pageable) { - return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements()); } private static Slice convertPage(final Slice findAll, final Pageable pageable) { - return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, 0); + return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, 0); } @Override @@ -651,7 +651,7 @@ public class JpaRolloutManagement implements RolloutManagement { @Override public float getFinishedPercentForRunningGroup(final Long rolloutId, final RolloutGroup rolloutGroup) { - final Long totalGroup = rolloutGroup.getTotalTargets(); + final int totalGroup = rolloutGroup.getTotalTargets(); final Long finished = actionRepository.countByRolloutIdAndRolloutGroupIdAndStatus(rolloutId, rolloutGroup.getId(), Action.Status.FINISHED); if (totalGroup == 0) { diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSoftwareManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSoftwareManagement.java index 3f8c1a54b..62ebfcb69 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSoftwareManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSoftwareManagement.java @@ -11,12 +11,15 @@ package org.eclipse.hawkbit.repository.jpa; import static com.google.common.base.Preconditions.checkNotNull; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; +import java.util.stream.Stream; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; @@ -65,6 +68,7 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import com.google.common.base.Strings; +import com.google.common.collect.Lists; import com.google.common.collect.Sets; /** @@ -166,7 +170,7 @@ public class JpaSoftwareManagement implements SoftwareManagement { @SuppressWarnings({ "unchecked", "rawtypes" }) final Collection jpaCast = (Collection) swModules; - return new ArrayList<>(softwareModuleRepository.save(jpaCast)); + return Collections.unmodifiableList(softwareModuleRepository.save(jpaCast)); } @Override @@ -185,22 +189,22 @@ public class JpaSoftwareManagement implements SoftwareManagement { private static Slice convertSmPage(final Slice findAll, final Pageable pageable) { - return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, 0); + return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, 0); } private static Page convertSmPage(final Page findAll, final Pageable pageable) { - return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements()); } private static Page convertSmMdPage(final Page findAll, final Pageable pageable) { - return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements()); } @Override public Long countSoftwareModulesByType(final SoftwareModuleType type) { - final List> specList = new ArrayList<>(); + final List> specList = new LinkedList<>(); Specification spec = SoftwareModuleSpecification.equalType((JpaSoftwareModuleType) type); specList.add(spec); @@ -277,7 +281,7 @@ public class JpaSoftwareManagement implements SoftwareManagement { @Override public Slice findSoftwareModulesAll(final Pageable pageable) { - final List> specList = new ArrayList<>(); + final List> specList = new ArrayList<>(2); Specification spec = SoftwareModuleSpecification.isDeletedFalse(); specList.add(spec); @@ -296,13 +300,9 @@ public class JpaSoftwareManagement implements SoftwareManagement { @Override public Long countSoftwareModulesAll() { - - final List> specList = new ArrayList<>(); - final Specification spec = SoftwareModuleSpecification.isDeletedFalse(); - specList.add(spec); - return countSwModuleByCriteriaAPI(specList); + return countSwModuleByCriteriaAPI(Lists.newArrayList(spec)); } @Override @@ -327,20 +327,20 @@ public class JpaSoftwareManagement implements SoftwareManagement { private static Page convertSmTPage(final Page findAll, final Pageable pageable) { - return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements()); } @Override @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) public List findSoftwareModulesById(final Collection ids) { - return new ArrayList<>(softwareModuleRepository.findByIdIn(ids)); + return Collections.unmodifiableList(softwareModuleRepository.findByIdIn(ids)); } @Override public Slice findSoftwareModuleByFilters(final Pageable pageable, final String searchText, final SoftwareModuleType type) { - final List> specList = new ArrayList<>(); + final List> specList = new ArrayList<>(4); Specification spec = SoftwareModuleSpecification.isDeletedFalse(); specList.add(spec); @@ -438,7 +438,7 @@ public class JpaSoftwareManagement implements SoftwareManagement { private static List> buildSpecificationList(final String searchText, final JpaSoftwareModuleType type) { - final List> specList = new ArrayList<>(); + final List> specList = new ArrayList<>(3); if (!Strings.isNullOrEmpty(searchText)) { specList.add(SoftwareModuleSpecification.likeNameOrVersion(searchText)); } @@ -452,18 +452,15 @@ public class JpaSoftwareManagement implements SoftwareManagement { private Predicate[] specificationsToPredicate(final List> specifications, final Root root, final CriteriaQuery query, final CriteriaBuilder cb, final Predicate... additionalPredicates) { - final List predicates = new ArrayList<>(); - specifications.forEach(spec -> predicates.add(spec.toPredicate(root, query, cb))); - for (final Predicate predicate : additionalPredicates) { - predicates.add(predicate); - } - return predicates.toArray(new Predicate[predicates.size()]); + + return Stream.concat(specifications.stream().map(spec -> spec.toPredicate(root, query, cb)), + Arrays.stream(additionalPredicates)).toArray(Predicate[]::new); } @Override public Long countSoftwareModuleByFilters(final String searchText, final SoftwareModuleType type) { - final List> specList = new ArrayList<>(); + final List> specList = new ArrayList<>(3); Specification spec = SoftwareModuleSpecification.isDeletedFalse(); specList.add(spec); @@ -573,7 +570,7 @@ public class JpaSoftwareManagement implements SoftwareManagement { checkAndThrowAlreadyExistsIfSoftwareModuleMetadataExists(softwareModuleMetadata.getId()); } metadata.forEach(m -> entityManager.merge((JpaSoftwareModule) m.getSoftwareModule()).setLastModifiedAt(-1L)); - return new ArrayList<>(softwareModuleMetadataRepository.save(metadata)); + return Collections.unmodifiableList(softwareModuleMetadataRepository.save(metadata)); } @Override @@ -623,8 +620,8 @@ public class JpaSoftwareManagement implements SoftwareManagement { @Override public List findSoftwareModuleMetadataBySoftwareModuleId(final Long softwareModuleId) { - return new ArrayList<>( - softwareModuleMetadataRepository + return Collections + .unmodifiableList(softwareModuleMetadataRepository .findAll((Specification) (root, query, cb) -> cb.and(cb.equal( root.get(JpaSoftwareModuleMetadata_.softwareModule).get(JpaSoftwareModule_.id), diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTagManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTagManagement.java index e881d8ef8..fb4b1999f 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTagManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTagManagement.java @@ -10,8 +10,8 @@ package org.eclipse.hawkbit.repository.jpa; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.LinkedList; import java.util.List; @@ -111,7 +111,7 @@ public class JpaTagManagement implements TagManagement { } }); - final List save = new ArrayList<>(targetTagRepository.save(targetTags)); + final List save = Collections.unmodifiableList(targetTagRepository.save(targetTags)); afterCommit .afterCommit(() -> eventBus.post(new TargetTagCreatedBulkEvent(tenantAware.getCurrentTenant(), save))); return save; @@ -141,7 +141,7 @@ public class JpaTagManagement implements TagManagement { @Override public List findAllTargetTags() { - return new ArrayList<>(targetTagRepository.findAll()); + return Collections.unmodifiableList(targetTagRepository.findAll()); } @Override @@ -152,12 +152,12 @@ public class JpaTagManagement implements TagManagement { } private static Page convertTPage(final Page findAll, final Pageable pageable) { - return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements()); } private static Page convertDsPage(final Page findAll, final Pageable pageable) { - return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements()); } @Override @@ -213,7 +213,8 @@ public class JpaTagManagement implements TagManagement { throw new EntityAlreadyExistsException(); } } - final List save = new ArrayList<>(distributionSetTagRepository.save(distributionSetTags)); + final List save = Collections + .unmodifiableList(distributionSetTagRepository.save(distributionSetTags)); afterCommit.afterCommit( () -> eventBus.post(new DistributionSetTagCreatedBulkEvent(tenantAware.getCurrentTenant(), save))); @@ -228,7 +229,7 @@ public class JpaTagManagement implements TagManagement { final List changed = new LinkedList<>(); for (final JpaDistributionSet set : distributionSetRepository.findByTag(tag)) { - set.getTags().remove(tag); + set.removeTag(tag); changed.add(set); } @@ -254,7 +255,7 @@ public class JpaTagManagement implements TagManagement { @Override public List findAllDistributionSetTags() { - return new ArrayList<>(distributionSetTagRepository.findAll()); + return Collections.unmodifiableList(distributionSetTagRepository.findAll()); } @Override diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetManagement.java index 225c0b4b2..67c28216d 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetManagement.java @@ -13,6 +13,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; @@ -127,7 +128,7 @@ public class JpaTargetManagement implements TargetManagement { @Override public List findTargetByControllerID(final Collection controllerIDs) { - return new ArrayList<>(targetRepository + return Collections.unmodifiableList(targetRepository .findAll(TargetSpecifications.byControllerIdWithStatusAndAssignedInJoin(controllerIDs))); } @@ -193,7 +194,7 @@ public class JpaTargetManagement implements TargetManagement { toUpdate.forEach(target -> target.setNew(false)); - return new ArrayList<>(targetRepository.save(toUpdate)); + return Collections.unmodifiableList(targetRepository.save(toUpdate)); } @Override @@ -236,11 +237,11 @@ public class JpaTargetManagement implements TargetManagement { } private static Page convertPage(final Page findAll, final Pageable pageable) { - return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements()); } private static Slice convertPage(final Slice findAll, final Pageable pageable) { - return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, 0); + return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, 0); } @Override @@ -289,7 +290,7 @@ public class JpaTargetManagement implements TargetManagement { private static List> buildSpecificationList(final Collection status, final String searchText, final Long installedOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, final boolean fetch, final String... tagNames) { - final List> specList = new ArrayList<>(); + final List> specList = new LinkedList<>(); if (status != null && !status.isEmpty()) { specList.add(TargetSpecifications.hasTargetUpdateStatus(status, fetch)); } @@ -342,7 +343,7 @@ public class JpaTargetManagement implements TargetManagement { // all are already assigned -> unassign if (alreadyAssignedTargets.size() == allTargets.size()) { - alreadyAssignedTargets.forEach(target -> target.getTags().remove(tag)); + alreadyAssignedTargets.forEach(target -> ((JpaTarget) target).removeTag(tag)); final TargetTagAssignmentResult result = new TargetTagAssignmentResult(0, 0, alreadyAssignedTargets.size(), Collections.emptyList(), alreadyAssignedTargets, tag); @@ -352,9 +353,10 @@ public class JpaTargetManagement implements TargetManagement { allTargets.removeAll(alreadyAssignedTargets); // some or none are assigned -> assign - allTargets.forEach(target -> target.getTags().add(tag)); + allTargets.forEach(target -> target.addTag(tag)); final TargetTagAssignmentResult result = new TargetTagAssignmentResult(alreadyAssignedTargets.size(), - allTargets.size(), 0, new ArrayList<>(targetRepository.save(allTargets)), Collections.emptyList(), tag); + allTargets.size(), 0, Collections.unmodifiableList(targetRepository.save(allTargets)), + Collections.emptyList(), tag); afterCommit.afterCommit(() -> eventBus.post(new TargetTagAssigmentResultEvent(result))); @@ -370,8 +372,8 @@ public class JpaTargetManagement implements TargetManagement { final List allTargets = targetRepository .findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(targetIds)); - allTargets.forEach(target -> target.getTags().add(tag)); - final List save = new ArrayList<>(targetRepository.save(allTargets)); + allTargets.forEach(target -> target.addTag(tag)); + final List save = Collections.unmodifiableList(targetRepository.save(allTargets)); afterCommit.afterCommit(() -> { final TargetTagAssignmentResult assigmentResult = new TargetTagAssignmentResult(0, save.size(), 0, save, @@ -385,9 +387,9 @@ public class JpaTargetManagement implements TargetManagement { private List unAssignTag(final Collection targets, final TargetTag tag) { final Collection toUnassign = (Collection) targets; - toUnassign.forEach(target -> target.getTags().remove(tag)); + toUnassign.forEach(target -> target.removeTag(tag)); - final List save = new ArrayList<>(targetRepository.save(toUnassign)); + final List save = Collections.unmodifiableList(targetRepository.save(toUnassign)); afterCommit.afterCommit(() -> { final TargetTagAssignmentResult assigmentResult = new TargetTagAssignmentResult(0, 0, save.size(), Collections.emptyList(), save, tag); @@ -407,7 +409,7 @@ public class JpaTargetManagement implements TargetManagement { @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) public Target unAssignTag(final String controllerID, final TargetTag targetTag) { - final List allTargets = new ArrayList<>(targetRepository + final List allTargets = Collections.unmodifiableList(targetRepository .findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(Arrays.asList(controllerID)))); final List unAssignTag = unAssignTag(allTargets, targetTag); return unAssignTag.isEmpty() ? null : unAssignTag.get(0); @@ -463,7 +465,7 @@ public class JpaTargetManagement implements TargetManagement { final List resultList = entityManager.createQuery(query).setFirstResult(pageable.getOffset()) .setMaxResults(pageSize + 1).getResultList(); final boolean hasNext = resultList.size() > pageSize; - return new SliceImpl<>(new ArrayList<>(resultList), pageable, hasNext); + return new SliceImpl<>(Collections.unmodifiableList(resultList), pageable, hasNext); } private static Predicate[] specificationsToPredicate(final List> specifications, @@ -545,11 +547,8 @@ public class JpaTargetManagement implements TargetManagement { targetRoot.get(JpaTarget_.controllerId), targetRoot.get(JpaTarget_.name), targetRoot.get(sortProperty)); final Specification spec = RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class); - final List> specList = new ArrayList<>(); - specList.add(spec); - - final Predicate[] specificationsForMultiSelect = specificationsToPredicate(specList, targetRoot, multiselect, - cb); + final Predicate[] specificationsForMultiSelect = specificationsToPredicate(Lists.newArrayList(spec), targetRoot, + multiselect, cb); // if we have some predicates then add it to the where clause of the // multiselect @@ -611,18 +610,16 @@ public class JpaTargetManagement implements TargetManagement { targets.stream().map(target -> target.getControllerId()).collect(Collectors.toList())) > 0) { throw new EntityAlreadyExistsException(); } - final List savedTargets = new ArrayList<>(); - for (final Target t : targets) { - final Target myTarget = createTarget(t, TargetUpdateStatus.UNKNOWN, null, t.getTargetInfo().getAddress()); - savedTargets.add(myTarget); - } - return savedTargets; + + return targets.stream() + .map(t -> createTarget(t, TargetUpdateStatus.UNKNOWN, null, t.getTargetInfo().getAddress())) + .collect(Collectors.toList()); } @Override public List findTargetsByTag(final String tagName) { final JpaTargetTag tag = targetTagRepository.findByNameEquals(tagName); - return new ArrayList<>(targetRepository.findByTag(tag)); + return Collections.unmodifiableList(targetRepository.findByTag(tag)); } @Override diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/aspects/ExceptionMappingAspectHandler.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/aspects/ExceptionMappingAspectHandler.java index c18f614fd..5dfb70633 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/aspects/ExceptionMappingAspectHandler.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/aspects/ExceptionMappingAspectHandler.java @@ -10,7 +10,6 @@ package org.eclipse.hawkbit.repository.jpa.aspects; import java.sql.SQLException; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -36,6 +35,8 @@ import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.security.access.AccessDeniedException; import org.springframework.transaction.TransactionSystemException; +import com.google.common.collect.Maps; + /** * {@link Aspect} catches persistence exceptions and wraps them to custom * specific exceptions Additionally it checks and prevents access to certain @@ -49,14 +50,14 @@ public class ExceptionMappingAspectHandler implements Ordered { private static final Logger LOG = LoggerFactory.getLogger(ExceptionMappingAspectHandler.class); - private static final Map EXCEPTION_MAPPING = new HashMap<>(); + private static final Map EXCEPTION_MAPPING = Maps.newHashMapWithExpectedSize(4); /** * this is required to enable a certain order of exception and to select the * most specific mappable exception according to the type hierarchy of the * exception. */ - private static final List> MAPPED_EXCEPTION_ORDER = new ArrayList<>(); + private static final List> MAPPED_EXCEPTION_ORDER = new ArrayList<>(4); @Autowired private JpaVendorAdapter jpaVendorAdapter; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaArtifact.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaArtifact.java index 6ead1df9e..1cf6921a4 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaArtifact.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaArtifact.java @@ -32,7 +32,7 @@ public abstract class AbstractJpaArtifact extends AbstractJpaTenantAwareBaseEnti private String md5Hash; @Column(name = "file_size") - private Long size; + private long size; @Override public abstract SoftwareModule getSoftwareModule(); @@ -56,11 +56,11 @@ public abstract class AbstractJpaArtifact extends AbstractJpaTenantAwareBaseEnti } @Override - public Long getSize() { + public long getSize() { return size; } - public void setSize(final Long size) { + public void setSize(final long size) { this.size = size; } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaBaseEntity.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaBaseEntity.java index ef1868c3f..983cb2763 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaBaseEntity.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaBaseEntity.java @@ -48,7 +48,7 @@ public abstract class AbstractJpaBaseEntity implements BaseEntity { @Version @Column(name = "optlock_revision") - private long optLockRevision; + private int optLockRevision; /** * Default constructor needed for JPA entities. @@ -106,11 +106,11 @@ public abstract class AbstractJpaBaseEntity implements BaseEntity { } @Override - public long getOptLockRevision() { + public int getOptLockRevision() { return optLockRevision; } - public void setOptLockRevision(final long optLockRevision) { + public void setOptLockRevision(final int optLockRevision) { this.optLockRevision = optLockRevision; } @@ -142,7 +142,7 @@ public abstract class AbstractJpaBaseEntity implements BaseEntity { final int prime = 31; int result = 1; result = prime * result + (id == null ? 0 : id.hashCode()); - result = prime * result + (int) (optLockRevision ^ optLockRevision >>> 32); + result = prime * result + optLockRevision; result = prime * result + this.getClass().getName().hashCode(); return result; } @@ -179,5 +179,4 @@ public abstract class AbstractJpaBaseEntity implements BaseEntity { return true; } - } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaMetaData.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaMetaData.java index a9f93cb86..c6df089f7 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaMetaData.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaMetaData.java @@ -26,7 +26,7 @@ public abstract class AbstractJpaMetaData implements MetaData { private static final long serialVersionUID = 1L; @Id - @Column(name = "meta_key", length = 128) + @Column(name = "meta_key", nullable = false, length = 128) @Size(min = 1, max = 128) @NotNull private String key; @@ -37,7 +37,6 @@ public abstract class AbstractJpaMetaData implements MetaData { private String value; public AbstractJpaMetaData(final String key, final String value) { - super(); this.key = key; this.value = value; } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedEntity.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedEntity.java index 0011cc2da..634d4490f 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedEntity.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedEntity.java @@ -40,7 +40,7 @@ public abstract class AbstractJpaNamedEntity extends AbstractJpaTenantAwareBaseE * Default constructor. */ public AbstractJpaNamedEntity() { - super(); + // Default constructor needed for JPA entities } /** diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedVersionedEntity.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedVersionedEntity.java index 9c78f976c..9e45f3a76 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedVersionedEntity.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedVersionedEntity.java @@ -47,7 +47,7 @@ public abstract class AbstractJpaNamedVersionedEntity extends AbstractJpaNamedEn } AbstractJpaNamedVersionedEntity() { - super(); + // Default constructor needed for JPA entities } @Override diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaTag.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaTag.java index 12aad8d6d..f759d16fc 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaTag.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaTag.java @@ -31,7 +31,7 @@ public abstract class AbstractJpaTag extends AbstractJpaNamedEntity implements T private String colour; protected AbstractJpaTag() { - super(); + // Default constructor needed for JPA entities } /** diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaAction.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaAction.java index 4b5b6567e..ee3e17b8b 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaAction.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaAction.java @@ -8,6 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.model; +import java.util.Collections; import java.util.List; import javax.persistence.CascadeType; @@ -134,7 +135,11 @@ public class JpaAction extends AbstractJpaTenantAwareBaseEntity implements Actio @Override public List getActionStatus() { - return actionStatus; + if (actionStatus == null) { + return Collections.emptyList(); + } + + return Collections.unmodifiableList(actionStatus); } @Override diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionStatus.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionStatus.java index 102b25952..f442f552a 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionStatus.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionStatus.java @@ -8,7 +8,8 @@ */ package org.eclipse.hawkbit.repository.jpa.model; -import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; import java.util.List; import javax.persistence.CollectionTable; @@ -67,14 +68,14 @@ public class JpaActionStatus extends AbstractJpaTenantAwareBaseEntity implements @CollectionTable(name = "sp_action_status_messages", joinColumns = @JoinColumn(name = "action_status_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_stat_msg_act_stat")), indexes = { @Index(name = "sp_idx_action_status_msgs_01", columnList = "action_status_id") }) @Column(name = "detail_message", length = 512) - private final List messages = new ArrayList<>(); + private List messages; /** * Note: filled only in {@link Status#DOWNLOAD}. */ @Transient @CacheField(key = CacheKeys.DOWNLOAD_PROGRESS_PERCENT) - private int downloadProgressPercent; + private short downloadProgressPercent; /** * Creates a new {@link ActionStatus} object. @@ -86,7 +87,7 @@ public class JpaActionStatus extends AbstractJpaTenantAwareBaseEntity implements * @param occurredAt * the occurred timestamp */ - public JpaActionStatus(final Action action, final Status status, final Long occurredAt) { + public JpaActionStatus(final Action action, final Status status, final long occurredAt) { this.action = (JpaAction) action; this.status = status; this.occurredAt = occurredAt; @@ -119,7 +120,7 @@ public class JpaActionStatus extends AbstractJpaTenantAwareBaseEntity implements } @Override - public int getDownloadProgressPercent() { + public short getDownloadProgressPercent() { return downloadProgressPercent; } @@ -135,6 +136,10 @@ public class JpaActionStatus extends AbstractJpaTenantAwareBaseEntity implements @Override public final void addMessage(final String message) { + if (messages == null) { + messages = new LinkedList<>(); + } + if (message != null) { Splitter.fixedLength(512).split(message).forEach(messages::add); } @@ -142,7 +147,11 @@ public class JpaActionStatus extends AbstractJpaTenantAwareBaseEntity implements @Override public List getMessages() { - return messages; + if (messages == null) { + messages = Collections.emptyList(); + } + + return Collections.unmodifiableList(messages); } @Override diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionWithStatusCount.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionWithStatusCount.java index 32b01cbe2..648ba344b 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionWithStatusCount.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionWithStatusCount.java @@ -59,7 +59,7 @@ public class JpaActionWithStatusCount implements ActionWithStatusCount { // Exception squid:S00107 - needed this way for JPA to fill the view @SuppressWarnings("squid:S00107") public JpaActionWithStatusCount(final Long actionId, final ActionType actionType, final boolean active, - final long forcedTime, final Status status, final Long actionCreatedAt, final Long actionLastModifiedAt, + final Long forcedTime, final Status status, final Long actionCreatedAt, final Long actionLastModifiedAt, final Long dsId, final String dsName, final String dsVersion, final Long actionStatusCount, final String rolloutName) { this.dsId = dsId; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSet.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSet.java index 9fc27f1e8..349d8f7e7 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSet.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSet.java @@ -8,7 +8,6 @@ */ package org.eclipse.hawkbit.repository.jpa.model; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; @@ -82,13 +81,13 @@ public class JpaDistributionSet extends AbstractJpaNamedVersionedEntity implemen @JoinTable(name = "sp_ds_module", joinColumns = { @JoinColumn(name = "ds_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_module_ds")) }, inverseJoinColumns = { @JoinColumn(name = "module_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_module_module")) }) - private final Set modules = new HashSet<>(); + private Set modules; @ManyToMany(targetEntity = JpaDistributionSetTag.class) @JoinTable(name = "sp_ds_dstag", joinColumns = { @JoinColumn(name = "ds", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_dstag_ds")) }, inverseJoinColumns = { @JoinColumn(name = "TAG", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_dstag_tag")) }) - private Set tags = new HashSet<>(); + private Set tags; @Column(name = "deleted") private boolean deleted; @@ -106,7 +105,7 @@ public class JpaDistributionSet extends AbstractJpaNamedVersionedEntity implemen @OneToMany(fetch = FetchType.LAZY, targetEntity = JpaDistributionSetMetadata.class, cascade = { CascadeType.REMOVE }) @JoinColumn(name = "ds_id", insertable = false, updatable = false) - private final List metadata = new ArrayList<>(); + private List metadata; @ManyToOne(fetch = FetchType.LAZY, targetEntity = JpaDistributionSetType.class) @JoinColumn(name = "ds_id", nullable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_dstype_ds")) @@ -152,7 +151,27 @@ public class JpaDistributionSet extends AbstractJpaNamedVersionedEntity implemen @Override public Set getTags() { - return tags; + if (tags == null) { + return Collections.emptySet(); + } + + return Collections.unmodifiableSet(tags); + } + + public boolean addTag(final DistributionSetTag tag) { + if (tags == null) { + tags = new HashSet<>(); + } + + return tags.add(tag); + } + + public boolean removeTag(final DistributionSetTag tag) { + if (tags == null) { + return false; + } + + return tags.remove(tag); } @Override @@ -162,11 +181,19 @@ public class JpaDistributionSet extends AbstractJpaNamedVersionedEntity implemen @Override public List getMetadata() { + if (metadata == null) { + return Collections.emptyList(); + } + return Collections.unmodifiableList(metadata); } public List getActions() { - return actions; + if (actions == null) { + return Collections.emptyList(); + } + + return Collections.unmodifiableList(actions); } @Override @@ -186,19 +213,22 @@ public class JpaDistributionSet extends AbstractJpaNamedVersionedEntity implemen return this; } - public DistributionSet setTags(final Set tags) { - this.tags = tags; - return this; - } - @Override public List getAssignedTargets() { - return assignedToTargets; + if (assignedToTargets == null) { + return Collections.emptyList(); + } + + return Collections.unmodifiableList(assignedToTargets); } @Override public List getInstalledTargets() { - return installedAtTargets; + if (installedAtTargets == null) { + return Collections.emptyList(); + } + + return Collections.unmodifiableList(installedAtTargets); } @Override @@ -209,11 +239,18 @@ public class JpaDistributionSet extends AbstractJpaNamedVersionedEntity implemen @Override public Set getModules() { + if (modules == null) { + return Collections.emptySet(); + } + return Collections.unmodifiableSet(modules); } @Override public boolean addModule(final SoftwareModule softwareModule) { + if (modules == null) { + modules = new HashSet<>(); + } // we cannot allow that modules are added without a type defined if (type == null) { @@ -251,6 +288,10 @@ public class JpaDistributionSet extends AbstractJpaNamedVersionedEntity implemen @Override public boolean removeModule(final SoftwareModule softwareModule) { + if (modules == null) { + return false; + } + final Optional found = modules.stream() .filter(module -> module.getId().equals(softwareModule.getId())).findFirst(); @@ -266,6 +307,10 @@ public class JpaDistributionSet extends AbstractJpaNamedVersionedEntity implemen @Override public SoftwareModule findFirstModuleByType(final SoftwareModuleType type) { + if (modules == null) { + return null; + } + final Optional result = modules.stream().filter(module -> module.getType().equals(type)) .findFirst(); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetTag.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetTag.java index 1663fb620..84818685f 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetTag.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetTag.java @@ -8,6 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.model; +import java.util.Collections; import java.util.List; import javax.persistence.Entity; @@ -68,7 +69,11 @@ public class JpaDistributionSetTag extends AbstractJpaTag implements Distributio @Override public List getAssignedToDistributionSet() { - return assignedToDistributionSet; + if (assignedToDistributionSet == null) { + return Collections.emptyList(); + } + + return Collections.unmodifiableList(assignedToDistributionSet); } @Override diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetType.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetType.java index 2a696aac9..e7bc9d347 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetType.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetType.java @@ -8,6 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.model; +import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Set; @@ -24,6 +25,7 @@ import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.Size; +import org.apache.commons.collections4.CollectionUtils; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; @@ -48,7 +50,7 @@ public class JpaDistributionSetType extends AbstractJpaNamedEntity implements Di @OneToMany(targetEntity = DistributionSetTypeElement.class, cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, orphanRemoval = true) @JoinColumn(name = "distribution_set_type", insertable = false, updatable = false) - private final Set elements = new HashSet<>(); + private Set elements; @Column(name = "type_key", nullable = false, length = 64) @Size(max = 64) @@ -108,23 +110,44 @@ public class JpaDistributionSetType extends AbstractJpaNamedEntity implements Di @Override public Set getMandatoryModuleTypes() { + if (elements == null) { + return Collections.emptySet(); + } + return elements.stream().filter(element -> element.isMandatory()).map(element -> element.getSmType()) .collect(Collectors.toSet()); } @Override public Set getOptionalModuleTypes() { + if (elements == null) { + return Collections.emptySet(); + } + return elements.stream().filter(element -> !element.isMandatory()).map(element -> element.getSmType()) .collect(Collectors.toSet()); } @Override public boolean areModuleEntriesIdentical(final DistributionSetType dsType) { + if (!(dsType instanceof JpaDistributionSetType)) { + return false; + } else if (CollectionUtils.isEmpty(elements) + && CollectionUtils.isEmpty(((JpaDistributionSetType) dsType).elements)) { + return true; + } else if (CollectionUtils.isEmpty(elements)) { + return false; + } + return new HashSet(((JpaDistributionSetType) dsType).elements).equals(elements); } @Override public DistributionSetType addOptionalModuleType(final SoftwareModuleType smType) { + if (elements == null) { + elements = new HashSet<>(); + } + elements.add(new DistributionSetTypeElement(this, (JpaSoftwareModuleType) smType, false)); return this; @@ -132,6 +155,10 @@ public class JpaDistributionSetType extends AbstractJpaNamedEntity implements Di @Override public DistributionSetType addMandatoryModuleType(final SoftwareModuleType smType) { + if (elements == null) { + elements = new HashSet<>(); + } + elements.add(new DistributionSetTypeElement(this, (JpaSoftwareModuleType) smType, true)); return this; @@ -139,6 +166,10 @@ public class JpaDistributionSetType extends AbstractJpaNamedEntity implements Di @Override public DistributionSetType removeModuleType(final Long smTypeId) { + if (elements == null) { + return this; + } + // we search by id (standard equals compares also revison) final Optional found = elements.stream() .filter(element -> element.getSmType().getId().equals(smTypeId)).findFirst(); @@ -177,7 +208,11 @@ public class JpaDistributionSetType extends AbstractJpaNamedEntity implements Di } public Set getElements() { - return elements; + if (elements == null) { + return Collections.emptySet(); + } + + return Collections.unmodifiableSet(elements); } @Override diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRollout.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRollout.java index 6d720a75d..dc1b82ac2 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRollout.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRollout.java @@ -8,6 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.model; +import java.util.Collections; import java.util.List; import javax.persistence.Column; @@ -108,11 +109,11 @@ public class JpaRollout extends AbstractJpaNamedEntity implements Rollout, Event @Override public List getRolloutGroups() { - return rolloutGroups; - } + if (rolloutGroups == null) { + return Collections.emptyList(); + } - public void setRolloutGroups(final List rolloutGroups) { - this.rolloutGroups = rolloutGroups; + return Collections.unmodifiableList(rolloutGroups); } @Override diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRolloutGroup.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRolloutGroup.java index 750e61185..2c17a41c7 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRolloutGroup.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRolloutGroup.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.model; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; import javax.persistence.CascadeType; @@ -58,7 +58,7 @@ public class JpaRolloutGroup extends AbstractJpaNamedEntity implements RolloutGr @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }, targetEntity = RolloutTargetGroup.class) @JoinColumn(name = "rolloutGroup_Id", insertable = false, updatable = false) - private final List rolloutTargetGroup = new ArrayList<>(); + private List rolloutTargetGroup; @ManyToOne(fetch = FetchType.LAZY) private JpaRolloutGroup parent; @@ -92,7 +92,7 @@ public class JpaRolloutGroup extends AbstractJpaNamedEntity implements RolloutGr private String errorActionExp; @Column(name = "total_targets") - private long totalTargets; + private int totalTargets; @Transient private transient TotalTargetCountStatus totalTargetCountStatus; @@ -118,7 +118,11 @@ public class JpaRolloutGroup extends AbstractJpaNamedEntity implements RolloutGr } public List getRolloutTargetGroup() { - return rolloutTargetGroup; + if (rolloutTargetGroup == null) { + return Collections.emptyList(); + } + + return Collections.unmodifiableList(rolloutTargetGroup); } @Override @@ -201,11 +205,11 @@ public class JpaRolloutGroup extends AbstractJpaNamedEntity implements RolloutGr } @Override - public long getTotalTargets() { + public int getTotalTargets() { return totalTargets; } - public void setTotalTargets(final long totalTargets) { + public void setTotalTargets(final int totalTargets) { this.totalTargets = totalTargets; } @@ -223,7 +227,7 @@ public class JpaRolloutGroup extends AbstractJpaNamedEntity implements RolloutGr @Override public TotalTargetCountStatus getTotalTargetCountStatus() { if (totalTargetCountStatus == null) { - totalTargetCountStatus = new TotalTargetCountStatus(totalTargets); + totalTargetCountStatus = new TotalTargetCountStatus(new Long(totalTargets)); } return totalTargetCountStatus; } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModule.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModule.java index e52857c37..49ff030d4 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModule.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModule.java @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.jpa.model; -import java.util.ArrayList; import java.util.Collections; +import java.util.LinkedList; import java.util.List; import java.util.Optional; @@ -40,6 +40,8 @@ import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.persistence.annotations.CascadeOnDelete; +import com.google.common.collect.Lists; + /** * Base Software Module that is supported by OS level provisioning mechanism on * the edge controller, e.g. OS, JVM, AgentHub. @@ -64,7 +66,7 @@ public class JpaSoftwareModule extends AbstractJpaNamedVersionedEntity implement private JpaSoftwareModuleType type; @ManyToMany(mappedBy = "modules", targetEntity = JpaDistributionSet.class, fetch = FetchType.LAZY) - private final List assignedTo = new ArrayList<>(); + private List assignedTo; @Column(name = "deleted") private boolean deleted; @@ -82,13 +84,13 @@ public class JpaSoftwareModule extends AbstractJpaNamedVersionedEntity implement @CascadeOnDelete @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }, targetEntity = JpaSoftwareModuleMetadata.class) @JoinColumn(name = "sw_id", insertable = false, updatable = false) - private final List metadata = new ArrayList<>(); + private List metadata; /** * Default constructor. */ public JpaSoftwareModule() { - super(); + } /** @@ -119,7 +121,9 @@ public class JpaSoftwareModule extends AbstractJpaNamedVersionedEntity implement @Override public void addArtifact(final LocalArtifact artifact) { if (null == artifacts) { - artifacts = new ArrayList<>(4); + artifacts = new LinkedList<>(); + artifacts.add(artifact); + return; } if (!artifacts.contains(artifact)) { @@ -134,7 +138,9 @@ public class JpaSoftwareModule extends AbstractJpaNamedVersionedEntity implement @Override public void addArtifact(final ExternalArtifact artifact) { if (null == externalArtifacts) { - externalArtifacts = new ArrayList<>(4); + externalArtifacts = new LinkedList<>(); + externalArtifacts.add(artifact); + return; } if (!externalArtifacts.contains(artifact)) { @@ -143,28 +149,18 @@ public class JpaSoftwareModule extends AbstractJpaNamedVersionedEntity implement } - /** - * @param artifactId - * to look for - * @return found {@link Artifact} - */ @Override public Optional getLocalArtifact(final Long artifactId) { - if (null == artifacts) { + if (artifacts == null) { return Optional.empty(); } return artifacts.stream().filter(artifact -> artifact.getId().equals(artifactId)).findFirst(); } - /** - * @param fileName - * to look for - * @return found {@link Artifact} - */ @Override public Optional getLocalArtifactByFilename(final String fileName) { - if (null == artifacts) { + if (artifacts == null) { return Optional.empty(); } @@ -177,11 +173,18 @@ public class JpaSoftwareModule extends AbstractJpaNamedVersionedEntity implement */ @Override public List getArtifacts() { - final List result = new ArrayList<>(); - result.addAll(artifacts); + if (artifacts == null && externalArtifacts == null) { + return Collections.emptyList(); + } else if (artifacts == null) { + return Collections.unmodifiableList(externalArtifacts); + } else if (externalArtifacts == null) { + return Collections.unmodifiableList(artifacts); + } + + final List result = Lists.newLinkedList(artifacts); result.addAll(externalArtifacts); - return result; + return Collections.unmodifiableList(result); } /** @@ -207,7 +210,7 @@ public class JpaSoftwareModule extends AbstractJpaNamedVersionedEntity implement */ @Override public void removeArtifact(final LocalArtifact artifact) { - if (null != artifacts) { + if (artifacts != null) { artifacts.remove(artifact); } } @@ -218,7 +221,7 @@ public class JpaSoftwareModule extends AbstractJpaNamedVersionedEntity implement */ @Override public void removeArtifact(final ExternalArtifact artifact) { - if (null != externalArtifacts) { + if (externalArtifacts != null) { externalArtifacts.remove(artifact); } } @@ -248,11 +251,12 @@ public class JpaSoftwareModule extends AbstractJpaNamedVersionedEntity implement this.type = (JpaSoftwareModuleType) type; } - /** - * @return immutable list of meta data elements. - */ @Override public List getMetadata() { + if (metadata == null) { + return Collections.emptyList(); + } + return Collections.unmodifiableList(metadata); } @@ -262,12 +266,13 @@ public class JpaSoftwareModule extends AbstractJpaNamedVersionedEntity implement + ", revision=" + getOptLockRevision() + ", Id=" + getId() + ", type=" + getType().getName() + "]"; } - /** - * @return the assignedTo - */ @Override public List getAssignedTo() { - return assignedTo; + if (assignedTo == null) { + return Collections.emptyList(); + } + + return Collections.unmodifiableList(assignedTo); } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTarget.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTarget.java index 476dea18b..7756c947e 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTarget.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTarget.java @@ -9,7 +9,9 @@ package org.eclipse.hawkbit.repository.jpa.model; import java.util.ArrayList; +import java.util.Collections; import java.util.HashSet; +import java.util.LinkedList; import java.util.List; import java.util.Set; @@ -85,13 +87,13 @@ public class JpaTarget extends AbstractJpaNamedEntity implements Persistable tags = new HashSet<>(); + private Set tags; @CascadeOnDelete @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, cascade = { CascadeType.REMOVE }, targetEntity = JpaAction.class) @JoinColumn(name = "target", insertable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_targ_act_hist_targ")) - private final List actions = new ArrayList<>(); + private List actions; @ManyToOne(optional = true, fetch = FetchType.LAZY, targetEntity = JpaDistributionSet.class) @JoinColumn(name = "assigned_distribution_set", nullable = true, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_target_assign_ds")) @@ -141,12 +143,8 @@ public class JpaTarget extends AbstractJpaNamedEntity implements Persistable getTags() { + if (tags == null) { + return Collections.emptySet(); + } + return tags; } + public boolean addTag(final TargetTag tag) { + if (tags == null) { + tags = new HashSet<>(); + } + + return tags.add(tag); + } + + public boolean removeTag(final TargetTag tag) { + if (tags == null) { + return false; + } + + return tags.remove(tag); + } + public void setAssignedDistributionSet(final DistributionSet assignedDistributionSet) { this.assignedDistributionSet = (JpaDistributionSet) assignedDistributionSet; } @@ -172,13 +190,21 @@ public class JpaTarget extends AbstractJpaNamedEntity implements Persistable tags) { - this.tags = tags; - } - @Override public List getActions() { - return actions; + if (actions == null) { + return Collections.emptyList(); + } + + return Collections.unmodifiableList(actions); + } + + public boolean addAction(final Action action) { + if (actions == null) { + actions = new LinkedList<>(); + } + + return actions.add(action); } @Override diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetInfo.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetInfo.java index ea3713fa3..6dbe2fcd7 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetInfo.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetInfo.java @@ -220,7 +220,7 @@ public class JpaTargetInfo implements Persistable, TargetInfo, EventAwareE return lastTargetQuery; } - public void setLastTargetQuery(final Long lastTargetQuery) { + public void setLastTargetQuery(final long lastTargetQuery) { this.lastTargetQuery = lastTargetQuery; } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetTag.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetTag.java index 96989f14a..a04933b6d 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetTag.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetTag.java @@ -8,6 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.model; +import java.util.Collections; import java.util.List; import javax.persistence.Entity; @@ -65,7 +66,11 @@ public class JpaTargetTag extends AbstractJpaTag implements TargetTag { @Override public List getAssignedToTargets() { - return assignedToTargets; + if (assignedToTargets == null) { + return Collections.emptyList(); + } + + return Collections.unmodifiableList(assignedToTargets); } @Override diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/ThresholdRolloutGroupSuccessCondition.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/ThresholdRolloutGroupSuccessCondition.java index 3e098c701..676cd9ad1 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/ThresholdRolloutGroupSuccessCondition.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/ThresholdRolloutGroupSuccessCondition.java @@ -29,8 +29,8 @@ public class ThresholdRolloutGroupSuccessCondition implements RolloutGroupCondit @Override public boolean eval(final Rollout rollout, final RolloutGroup rolloutGroup, final String expression) { - final Long totalGroup = rolloutGroup.getTotalTargets(); - final Long finished = this.actionRepository.countByRolloutIdAndRolloutGroupIdAndStatus(rollout.getId(), + final long totalGroup = rolloutGroup.getTotalTargets(); + final long finished = this.actionRepository.countByRolloutIdAndRolloutGroupIdAndStatus(rollout.getId(), rolloutGroup.getId(), Action.Status.FINISHED); try { final Integer threshold = Integer.valueOf(expression); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java index 565513107..d5cc7f029 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java @@ -106,7 +106,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { assertThat(findActionsWithStatusCountByTarget).as("wrong action size").hasSize(1); assertThat(findActionsWithStatusCountByTarget.get(0).getActionStatusCount()).as("wrong action status size") - .isEqualTo(3L); + .isEqualTo(3); } @Test @@ -842,8 +842,8 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { final DistributionSet ds = testdataFactory.createDistributionSet("a"); // assign ds to create an action final DistributionSetAssignmentResult assignDistributionSet = deploymentManagement.assignDistributionSet( - ds.getId(), ActionType.SOFT, org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME, - target.getControllerId()); + ds.getId(), ActionType.SOFT, + org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME, target.getControllerId()); final Action action = deploymentManagement.findActionWithDetails(assignDistributionSet.getActions().get(0)); // verify preparation Action findAction = deploymentManagement.findAction(action.getId()); @@ -865,8 +865,8 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { final DistributionSet ds = testdataFactory.createDistributionSet("a"); // assign ds to create an action final DistributionSetAssignmentResult assignDistributionSet = deploymentManagement.assignDistributionSet( - ds.getId(), ActionType.FORCED, org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME, - target.getControllerId()); + ds.getId(), ActionType.FORCED, + org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME, target.getControllerId()); final Action action = deploymentManagement.findActionWithDetails(assignDistributionSet.getActions().get(0)); // verify perparation Action findAction = deploymentManagement.findAction(action.getId()); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DistributionSetManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DistributionSetManagementTest.java index b5ba12946..bcb6a1f32 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DistributionSetManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DistributionSetManagementTest.java @@ -396,14 +396,14 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { // create a DS final DistributionSet ds = testdataFactory.createDistributionSet("testDs"); // initial opt lock revision must be zero - assertThat(ds.getOptLockRevision()).isEqualTo(1L); + assertThat(ds.getOptLockRevision()).isEqualTo(1); // create an DS meta data entry final DistributionSetMetadata dsMetadata = distributionSetManagement .createDistributionSetMetadata(new JpaDistributionSetMetadata(knownKey, ds, knownValue)); DistributionSet changedLockRevisionDS = distributionSetManagement.findDistributionSetById(ds.getId()); - assertThat(changedLockRevisionDS.getOptLockRevision()).isEqualTo(2L); + assertThat(changedLockRevisionDS.getOptLockRevision()).isEqualTo(2); // modifying the meta data value dsMetadata.setValue(knownUpdateValue); @@ -419,7 +419,7 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { // module so opt lock // revision must be three changedLockRevisionDS = distributionSetManagement.findDistributionSetById(ds.getId()); - assertThat(changedLockRevisionDS.getOptLockRevision()).isEqualTo(3L); + assertThat(changedLockRevisionDS.getOptLockRevision()).isEqualTo(3); assertThat(changedLockRevisionDS.getLastModifiedAt()).isGreaterThan(0L); // verify updated meta data contains the updated value diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SoftwareManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SoftwareManagementTest.java index 739cf7f64..4f44d260c 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SoftwareManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SoftwareManagementTest.java @@ -848,7 +848,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTestWithMongoD final SoftwareModule ah = softwareManagement .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); - assertThat(ah.getOptLockRevision()).isEqualTo(1L); + assertThat(ah.getOptLockRevision()).isEqualTo(1); final SoftwareModuleMetadata swMetadata1 = new JpaSoftwareModuleMetadata(knownKey1, ah, knownValue1); @@ -858,7 +858,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTestWithMongoD .createSoftwareModuleMetadata(Lists.newArrayList(swMetadata1, swMetadata2)); final SoftwareModule changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId()); - assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(2L); + assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(2); assertThat(softwareModuleMetadata).hasSize(2); assertThat(softwareModuleMetadata.get(0)).isNotNull(); @@ -900,7 +900,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTestWithMongoD final SoftwareModule ah = softwareManagement .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); // initial opt lock revision must be 1 - assertThat(ah.getOptLockRevision()).isEqualTo(1L); + assertThat(ah.getOptLockRevision()).isEqualTo(1); // create an software module meta data entry final List softwareModuleMetadata = softwareManagement.createSoftwareModuleMetadata( @@ -910,7 +910,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTestWithMongoD // because we are modifying the // base software module SoftwareModule changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId()); - assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(2L); + assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(2); // modifying the meta data value softwareModuleMetadata.get(0).setValue(knownUpdateValue); @@ -925,7 +925,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTestWithMongoD // module so opt lock // revision must be two changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId()); - assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(3L); + assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(3); // verify updated meta data contains the updated value assertThat(updated).isNotNull(); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java index 1e8f102c7..35e326f4a 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java @@ -686,7 +686,8 @@ public class TargetManagementSearchTest extends AbstractJpaIntegrationTest { final DistributionSet ds = testdataFactory.createDistributionSet("a"); - targAssigned = deploymentManagement.assignDistributionSet(ds, targAssigned).getAssignedEntity(); + targAssigned = Lists + .newLinkedList(deploymentManagement.assignDistributionSet(ds, targAssigned).getAssignedEntity()); targInstalled = deploymentManagement.assignDistributionSet(ds, targInstalled).getAssignedEntity(); targInstalled = sendUpdateActionStatusToTargets(ds, targInstalled, Status.FINISHED, "installed"); @@ -756,7 +757,7 @@ public class TargetManagementSearchTest extends AbstractJpaIntegrationTest { private List sendUpdateActionStatusToTargets(final DistributionSet dsA, final Iterable targs, final Status status, final String... msgs) { - final List result = new ArrayList(); + final List result = new ArrayList<>(); for (final Target t : targs) { final List findByTarget = actionRepository.findByTarget((JpaTarget) t); for (final Action action : findByTarget) { diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementTest.java index 06f853db6..4671f701d 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementTest.java @@ -541,28 +541,30 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest { @Test @Description("Tests the assigment of tags to the a single target.") public void targetTagAssignment() { - Target t1 = testdataFactory.generateTarget("id-1", "blablub"); + final Target t1 = testdataFactory.generateTarget("id-1", "blablub"); final int noT2Tags = 4; final int noT1Tags = 3; final List t1Tags = tagManagement .createTargetTags(testdataFactory.generateTargetTags(noT1Tags, "tag1")); - t1.getTags().addAll(t1Tags); - t1 = targetManagement.createTarget(t1); - Target t2 = testdataFactory.generateTarget("id-2", "blablub"); + t1Tags.forEach(tag -> ((JpaTarget) t1).addTag(tag)); + + targetManagement.createTarget(t1); + final Target t2 = testdataFactory.generateTarget("id-2", "blablub"); final List t2Tags = tagManagement .createTargetTags(testdataFactory.generateTargetTags(noT2Tags, "tag2")); - t2.getTags().addAll(t2Tags); - t2 = targetManagement.createTarget(t2); - t1 = targetManagement.findTargetByControllerID(t1.getControllerId()); - assertThat(t1.getTags()).as("Tag size is wrong").hasSize(noT1Tags).containsAll(t1Tags); - assertThat(t1.getTags()).as("Tag size is wrong").hasSize(noT1Tags) + t2Tags.forEach(tag -> ((JpaTarget) t2).addTag(tag)); + targetManagement.createTarget(t2); + + final Target t11 = targetManagement.findTargetByControllerID(t1.getControllerId()); + assertThat(t11.getTags()).as("Tag size is wrong").hasSize(noT1Tags).containsAll(t1Tags); + assertThat(t11.getTags()).as("Tag size is wrong").hasSize(noT1Tags) .doesNotContain(Iterables.toArray(t2Tags, TargetTag.class)); - t2 = targetManagement.findTargetByControllerID(t2.getControllerId()); - assertThat(t2.getTags()).as("Tag size is wrong").hasSize(noT2Tags).containsAll(t2Tags); - assertThat(t2.getTags()).as("Tag size is wrong").hasSize(noT2Tags) + final Target t21 = targetManagement.findTargetByControllerID(t2.getControllerId()); + assertThat(t21.getTags()).as("Tag size is wrong").hasSize(noT2Tags).containsAll(t2Tags); + assertThat(t21.getTags()).as("Tag size is wrong").hasSize(noT2Tags) .doesNotContain(Iterables.toArray(t1Tags, TargetTag.class)); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java index 3138c9f86..884b02459 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java @@ -18,7 +18,6 @@ import org.eclipse.hawkbit.repository.jpa.model.JpaAction; import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.ActionType; -import org.eclipse.hawkbit.repository.model.Target; import org.junit.Before; import org.junit.Test; import org.springframework.data.domain.PageRequest; @@ -32,7 +31,7 @@ import ru.yandex.qatools.allure.annotations.Stories; @Stories("RSQL filter actions") public class RSQLActionFieldsTest extends AbstractJpaIntegrationTest { - private Target target; + private JpaTarget target; private JpaAction action; @Before @@ -42,7 +41,7 @@ public class RSQLActionFieldsTest extends AbstractJpaIntegrationTest { targetManagement.createTarget(target); action = new JpaAction(); action.setActionType(ActionType.SOFT); - target.getActions().add(action); + target.addAction(action); action.setTarget(target); actionRepository.save(action); for (int i = 0; i < 10; i++) { @@ -51,7 +50,7 @@ public class RSQLActionFieldsTest extends AbstractJpaIntegrationTest { newAction.setActive(i % 2 == 0); newAction.setTarget(target); actionRepository.save(newAction); - target.getActions().add(newAction); + target.addAction(newAction); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/details/ArtifactDetailsLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/details/ArtifactDetailsLayout.java index 8408f7c74..9a77af933 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/details/ArtifactDetailsLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/details/ArtifactDetailsLayout.java @@ -9,8 +9,8 @@ package org.eclipse.hawkbit.ui.artifacts.details; import java.util.ArrayList; +import java.util.Collections; import java.util.Date; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -46,6 +46,7 @@ import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; import com.google.common.base.Strings; +import com.google.common.collect.Maps; import com.vaadin.data.Container; import com.vaadin.server.FontAwesome; import com.vaadin.shared.ui.label.ContentMode; @@ -207,8 +208,7 @@ public class ArtifactDetailsLayout extends VerticalLayout { } private Container createArtifactLazyQueryContainer() { - final Map queryConfiguration = new HashMap<>(); - return getArtifactLazyQueryContainer(queryConfiguration); + return getArtifactLazyQueryContainer(Collections.emptyMap()); } private LazyQueryContainer getArtifactLazyQueryContainer(final Map queryConfig) { @@ -429,9 +429,12 @@ public class ArtifactDetailsLayout extends VerticalLayout { titleOfArtifactDetails.setContentMode(ContentMode.HTML); } } - final Map queryConfiguration = new HashMap<>(); + final Map queryConfiguration; if (baseSwModuleId != null) { + queryConfiguration = Maps.newHashMapWithExpectedSize(1); queryConfiguration.put(SPUIDefinitions.BY_BASE_SOFTWARE_MODULE, baseSwModuleId); + } else { + queryConfiguration = Collections.emptyMap(); } final LazyQueryContainer artifactContainer = getArtifactLazyQueryContainer(queryConfiguration); artifactDetailsTable.setContainerDataSource(artifactContainer); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadViewAcceptCriteria.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadViewAcceptCriteria.java index 8cfeaea81..0fab13f84 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadViewAcceptCriteria.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadViewAcceptCriteria.java @@ -9,13 +9,13 @@ package org.eclipse.hawkbit.ui.artifacts.event; import java.util.Arrays; -import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.hawkbit.ui.common.AbstractAcceptCriteria; import org.eclipse.hawkbit.ui.utils.SPUIComponentIdProvider; +import com.google.gwt.thirdparty.guava.common.collect.Maps; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; import com.vaadin.ui.Component; @@ -54,16 +54,17 @@ public class UploadViewAcceptCriteria extends AbstractAcceptCriteria { } private static Map> createDropConfigurations() { - final Map> config = new HashMap<>(); + final Map> config = Maps.newHashMapWithExpectedSize(1); // Delete drop area droppable components - config.put(SPUIComponentIdProvider.DELETE_BUTTON_WRAPPER_ID, Arrays.asList( - SPUIComponentIdProvider.UPLOAD_SOFTWARE_MODULE_TABLE, SPUIComponentIdProvider.UPLOAD_TYPE_BUTTON_PREFIX)); + config.put(SPUIComponentIdProvider.DELETE_BUTTON_WRAPPER_ID, + Arrays.asList(SPUIComponentIdProvider.UPLOAD_SOFTWARE_MODULE_TABLE, + SPUIComponentIdProvider.UPLOAD_TYPE_BUTTON_PREFIX)); return config; } private static Map createDropHintConfigurations() { - final Map config = new HashMap<>(); + final Map config = Maps.newHashMapWithExpectedSize(2); config.put(SPUIComponentIdProvider.UPLOAD_TYPE_BUTTON_PREFIX, UploadArtifactUIEvent.SOFTWARE_TYPE_DRAG_START); config.put(SPUIComponentIdProvider.UPLOAD_SOFTWARE_MODULE_TABLE, UploadArtifactUIEvent.SOFTWARE_DRAG_START); return config; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/UploadViewConfirmationWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/UploadViewConfirmationWindowLayout.java index 49b271b6b..a8fee345c 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/UploadViewConfirmationWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/UploadViewConfirmationWindowLayout.java @@ -9,7 +9,6 @@ package org.eclipse.hawkbit.ui.artifacts.footer; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -26,6 +25,7 @@ import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.springframework.beans.factory.annotation.Autowired; +import com.google.gwt.thirdparty.guava.common.collect.Maps; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.data.util.IndexedContainer; @@ -64,7 +64,7 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind @Override protected Map getConfimrationTabs() { - final Map tabs = new HashMap<>(); + final Map tabs = Maps.newHashMapWithExpectedSize(2); if (!artifactUploadState.getDeleteSofwareModules().isEmpty()) { tabs.put(i18n.get("caption.delete.swmodule.accordion.tab"), createSMDeleteConfirmationTab()); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTable.java index 98e309396..7fd895623 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTable.java @@ -8,7 +8,6 @@ */ package org.eclipse.hawkbit.ui.artifacts.smtable; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -37,6 +36,7 @@ import org.vaadin.addons.lazyquerycontainer.LazyQueryDefinition; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; +import com.google.gwt.thirdparty.guava.common.collect.Maps; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.event.dd.DragAndDropEvent; @@ -97,7 +97,7 @@ public class SoftwareModuleTable extends AbstractNamedVersionTable prepareQueryConfigFilters() { - final Map queryConfig = new HashMap<>(); + final Map queryConfig = Maps.newHashMapWithExpectedSize(2); artifactUploadState.getSoftwareModuleFilters().getSearchText() .ifPresent(value -> queryConfig.put(SPUIDefinitions.FILTER_BY_TEXT, value)); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/renderers/HtmlLabelRenderer.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/renderers/HtmlLabelRenderer.java index c6b2d9b64..535150f04 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/renderers/HtmlLabelRenderer.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/renderers/HtmlLabelRenderer.java @@ -8,9 +8,9 @@ */ package org.eclipse.hawkbit.ui.customrenderers.client.renderers; -import java.util.HashMap; import java.util.Map; +import com.google.common.collect.Maps; import com.google.gwt.core.client.GWT; import com.vaadin.client.renderers.WidgetRenderer; import com.vaadin.client.ui.VLabel; @@ -29,11 +29,11 @@ public class HtmlLabelRenderer extends WidgetRenderer { } @Override - public void render(RendererCellReference cell, String input, VLabel label) { - Map map = formatInput(input); - String value = map.containsKey("value") ? map.get("value") : null; - String style = map.containsKey("style") ? map.get("style") : null; - String id = map.containsKey("id") ? map.get("id") : null; + public void render(final RendererCellReference cell, final String input, final VLabel label) { + final Map map = formatInput(input); + final String value = map.containsKey("value") ? map.get("value") : null; + final String style = map.containsKey("style") ? map.get("style") : null; + final String id = map.containsKey("id") ? map.get("id") : null; if (value != null) { label.setHTML("&#x" + Integer.toHexString(Integer.parseInt(value)) + ";"); @@ -44,7 +44,7 @@ public class HtmlLabelRenderer extends WidgetRenderer { label.getElement().setId(id); } - private void applyStyle(VLabel label, String style) { + private void applyStyle(final VLabel label, final String style) { label.setStyleName(VLabel.CLASSNAME); label.addStyleName(getStyle("small")); label.addStyleName(getStyle("font-icon")); @@ -57,11 +57,12 @@ public class HtmlLabelRenderer extends WidgetRenderer { return new StringBuilder(style).append(" ").append(VLabel.CLASSNAME).append("-").append(style).toString(); } - private Map formatInput(String input) { - Map details = new HashMap<>(); - String[] tempData = input.split(","); - for (String statusWithCount : tempData) { - String[] statusWithCountList = statusWithCount.split(":"); + private Map formatInput(final String input) { + + final String[] tempData = input.split(","); + final Map details = Maps.newHashMapWithExpectedSize(tempData.length); + for (final String statusWithCount : tempData) { + final String[] statusWithCountList = statusWithCount.split(":"); details.put(statusWithCountList[0], statusWithCountList[1]); } return details; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java index 06b23c51b..8d474bede 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java @@ -93,7 +93,7 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet private VerticalLayout tagsLayout; - private final Map assignedSWModule = new HashMap<>(); + private Map assignedSWModule; /** * softwareLayout Initialize the component. @@ -144,6 +144,10 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet } if (null != softwareModuleIdNameList) { + if (assignedSWModule == null) { + assignedSWModule = new HashMap<>(); + } + for (final SoftwareModuleIdName swIdName : softwareModuleIdNameList) { final SoftwareModule softwareModule = softwareManagement.findSoftwareModuleById(swIdName.getId()); if (assignedSWModule.containsKey(softwareModule.getType().getName())) { @@ -186,6 +190,9 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet @SuppressWarnings("unchecked") private void updateSoftwareModule(final SoftwareModule module) { + if (assignedSWModule == null) { + assignedSWModule = new HashMap<>(); + } softwareModuleTable.getContainerDataSource().getItemIds(); if (assignedSWModule.containsKey(module.getType().getName())) { @@ -363,7 +370,9 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet if ((saveActionWindowEvent == SaveActionWindowEvent.SAVED_ASSIGNMENTS || saveActionWindowEvent == SaveActionWindowEvent.DISCARD_ALL_ASSIGNMENTS) && getSelectedBaseEntity() != null) { - assignedSWModule.clear(); + if (assignedSWModule != null) { + assignedSWModule.clear(); + } setSelectedBaseEntity( distributionSetManagement.findDistributionSetByIdWithDetails(getSelectedBaseEntityId())); UI.getCurrent().access(() -> populateModule()); @@ -375,7 +384,9 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet if (saveActionWindowEvent == SaveActionWindowEvent.DISCARD_ASSIGNMENT || saveActionWindowEvent == SaveActionWindowEvent.DISCARD_ALL_ASSIGNMENTS || saveActionWindowEvent == SaveActionWindowEvent.DELETE_ALL_SOFWARE) { - assignedSWModule.clear(); + if (assignedSWModule != null) { + assignedSWModule.clear(); + } showUnsavedAssignment(); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java index 94bc6690e..fc21ddd5b 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java @@ -57,6 +57,7 @@ import org.vaadin.addons.lazyquerycontainer.LazyQueryDefinition; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; +import com.google.common.collect.Maps; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.event.dd.DragAndDropEvent; @@ -167,7 +168,7 @@ public class DistributionSetTable extends AbstractNamedVersionTable prepareQueryConfigFilters() { - final Map queryConfig = new HashMap<>(); + final Map queryConfig = Maps.newHashMapWithExpectedSize(2); manageDistUIState.getManageDistFilters().getSearchText() .ifPresent(value -> queryConfig.put(SPUIDefinitions.FILTER_BY_TEXT, value)); @@ -530,7 +531,7 @@ public class DistributionSetTable extends AbstractNamedVersionTable> createDropConfigurations() { - final Map> config = new HashMap<>(); + final Map> config = Maps.newHashMapWithExpectedSize(2); // Delete drop area droppable components config.put(SPUIComponentIdProvider.DELETE_BUTTON_WRAPPER_ID, @@ -82,7 +82,7 @@ public class DistributionsViewAcceptCriteria extends AbstractAcceptCriteria { } private static Map createDropHintConfigurations() { - final Map config = new HashMap<>(); + final Map config = Maps.newHashMapWithExpectedSize(4); config.put(SPUIDefinitions.DISTRIBUTION_TYPE_ID_PREFIXS, DragEvent.DISTRIBUTION_TYPE_DRAG); config.put(SPUIComponentIdProvider.DIST_TABLE_ID, DragEvent.DISTRIBUTION_DRAG); config.put(SPUIComponentIdProvider.UPLOAD_SOFTWARE_MODULE_TABLE, DragEvent.SOFTWAREMODULE_DRAG); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java index 290d2ff54..bc8c3a28b 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java @@ -8,7 +8,6 @@ */ package org.eclipse.hawkbit.ui.distributions.footer; -import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -37,6 +36,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; +import com.google.common.collect.Maps; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.data.util.IndexedContainer; @@ -90,7 +90,7 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW @Override protected Map getConfimrationTabs() { - final Map tabs = new HashMap<>(); + final Map tabs = Maps.newHashMapWithExpectedSize(5); /* Create tab for SW Modules delete */ if (!manageDistUIState.getDeleteSofwareModulesList().isEmpty()) { tabs.put(i18n.get("caption.delete.swmodule.accordion.tab"), createSMDeleteConfirmationTab()); @@ -112,7 +112,6 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW } /* Create tab for Assign Software Module */ - if (!manageDistUIState.getAssignedList().isEmpty()) { tabs.put(i18n.get("caption.assign.dist.accordion.tab"), createAssignSWModuleConfirmationTab()); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleTable.java index 9af813788..150deaaf7 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleTable.java @@ -8,7 +8,6 @@ */ package org.eclipse.hawkbit.ui.distributions.smtable; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -40,6 +39,7 @@ import org.vaadin.addons.lazyquerycontainer.LazyQueryDefinition; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; +import com.google.common.collect.Maps; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.event.dd.DragAndDropEvent; @@ -143,7 +143,7 @@ public class SwModuleTable extends AbstractNamedVersionTable prepareQueryConfigFilters() { - final Map queryConfig = new HashMap<>(); + final Map queryConfig = Maps.newHashMapWithExpectedSize(3); manageDistUIState.getSoftwareModuleFilters().getSearchText() .ifPresent(value -> queryConfig.put(SPUIDefinitions.FILTER_BY_TEXT, value)); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtype/DistSMTypeFilterButtons.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtype/DistSMTypeFilterButtons.java index 9fe3ec3f1..c061b1389 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtype/DistSMTypeFilterButtons.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtype/DistSMTypeFilterButtons.java @@ -13,8 +13,7 @@ import static org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleTypeEvent.Sof import static org.eclipse.hawkbit.ui.utils.SPUIComponentIdProvider.SW_MODULE_TYPE_TABLE_ID; import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_NAME; -import java.util.HashMap; -import java.util.Map; +import java.util.Collections; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleTypeEvent; import org.eclipse.hawkbit.ui.common.SoftwareModuleTypeBeanQuery; @@ -59,10 +58,9 @@ public class DistSMTypeFilterButtons extends AbstractFilterButtons { @Override protected LazyQueryContainer createButtonsLazyQueryContainer() { - final Map queryConfig = new HashMap<>(); final BeanQueryFactory typeQF = new BeanQueryFactory<>( SoftwareModuleTypeBeanQuery.class); - typeQF.setQueryConfiguration(queryConfig); + typeQF.setQueryConfiguration(Collections.emptyMap()); return new LazyQueryContainer(new LazyQueryDefinition(true, 20, VAR_NAME), typeQF); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java index caac53147..3a2075afc 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java @@ -52,7 +52,7 @@ public class ManageDistUIState implements ManagmentEntityState selectedSoftwareModules = emptySet(); - private Set selectedDeleteDistSetTypes = new HashSet<>(); + private final Set selectedDeleteDistSetTypes = new HashSet<>(); private Set selectedDeleteSWModuleTypes = new HashSet<>(); @@ -201,10 +201,6 @@ public class ManageDistUIState implements ManagmentEntityState selectedDeleteDistSetTypes) { - this.selectedDeleteDistSetTypes = selectedDeleteDistSetTypes; - } - public Set getSelectedDeleteSWModuleTypes() { return selectedDeleteSWModuleTypes; } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterTable.java index e447a257a..89df1c615 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterTable.java @@ -10,7 +10,6 @@ package org.eclipse.hawkbit.ui.filtermanagement; import java.util.ArrayList; import java.util.Date; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -37,6 +36,7 @@ import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; import com.google.common.base.Strings; +import com.google.common.collect.Maps; import com.vaadin.data.Item; import com.vaadin.server.FontAwesome; import com.vaadin.shared.ui.label.ContentMode; @@ -142,7 +142,7 @@ public class CreateOrUpdateFilterTable extends Table { } private Map prepareQueryConfigFilters() { - final Map queryConfig = new HashMap<>(); + final Map queryConfig = Maps.newHashMapWithExpectedSize(2); if (!Strings.isNullOrEmpty(filterManagementUIState.getFilterQueryValue())) { queryConfig.put(SPUIDefinitions.FILTER_BY_QUERY, filterManagementUIState.getFilterQueryValue()); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterTable.java index 5ee3be084..1ca72d855 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterTable.java @@ -38,6 +38,7 @@ import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; +import com.google.common.collect.Maps; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.server.FontAwesome; @@ -128,7 +129,7 @@ public class TargetFilterTable extends Table { } private Map prepareQueryConfigFilters() { - final Map queryConfig = new HashMap<>(); + final Map queryConfig = Maps.newHashMapWithExpectedSize(1); filterManagementUIState.getCustomFilterSearchText() .ifPresent(value -> queryConfig.put(SPUIDefinitions.FILTER_BY_TEXT, value)); return queryConfig; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java index e0bf9b1df..eb66f02a6 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java @@ -8,9 +8,8 @@ */ package org.eclipse.hawkbit.ui.management.dstable; -import java.util.HashMap; +import java.util.Collections; import java.util.HashSet; -import java.util.Map; import java.util.Set; import javax.annotation.PostConstruct; @@ -178,10 +177,9 @@ public class DistributionAddUpdateWindowLayout extends CustomComponent { * @return */ private LazyQueryContainer getDistSetTypeLazyQueryContainer() { - final Map queryConfig = new HashMap<>(); final BeanQueryFactory dtQF = new BeanQueryFactory<>( DistributionSetTypeBeanQuery.class); - dtQF.setQueryConfiguration(queryConfig); + dtQF.setQueryConfiguration(Collections.emptyMap()); final LazyQueryContainer disttypeContainer = new LazyQueryContainer( new LazyQueryDefinition(true, SPUIDefinitions.DIST_TYPE_SIZE, SPUILabelDefinitions.VAR_NAME), dtQF); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java index 3bf60df52..aae6ba477 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java @@ -9,7 +9,6 @@ package org.eclipse.hawkbit.ui.management.dstable; import java.util.ArrayList; -import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -56,6 +55,7 @@ import org.vaadin.addons.lazyquerycontainer.LazyQueryDefinition; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; +import com.google.common.collect.Maps; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.event.dd.DragAndDropEvent; @@ -240,7 +240,7 @@ public class DistributionTable extends AbstractNamedVersionTable prepareQueryConfigFilters() { - final Map queryConfig = new HashMap<>(); + final Map queryConfig = Maps.newHashMapWithExpectedSize(4); managementUIState.getDistributionTableFilters().getSearchText() .ifPresent(value -> queryConfig.put(SPUIDefinitions.FILTER_BY_TEXT, value)); managementUIState.getDistributionTableFilters().getPinnedTargetId() diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagButtons.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagButtons.java index 8b5ee85cf..d4da4d764 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagButtons.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagButtons.java @@ -8,8 +8,7 @@ */ package org.eclipse.hawkbit.ui.management.dstag; -import java.util.HashMap; -import java.util.Map; +import java.util.Collections; import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagCreatedBulkEvent; @@ -101,9 +100,8 @@ public class DistributionTagButtons extends AbstractFilterButtons { @Override protected LazyQueryContainer createButtonsLazyQueryContainer() { - final Map queryConfig = new HashMap<>(); final BeanQueryFactory tagQF = new BeanQueryFactory<>(DistributionTagBeanQuery.class); - tagQF.setQueryConfiguration(queryConfig); + tagQF.setQueryConfiguration(Collections.emptyMap()); return HawkbitCommonUtil.createDSLazyQueryContainer( new BeanQueryFactory(DistributionTagBeanQuery.class)); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/ManagementViewAcceptCriteria.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/ManagementViewAcceptCriteria.java index be50f7b79..629fea06e 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/ManagementViewAcceptCriteria.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/ManagementViewAcceptCriteria.java @@ -9,7 +9,6 @@ package org.eclipse.hawkbit.ui.management.event; import java.util.Arrays; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -17,6 +16,7 @@ import org.eclipse.hawkbit.ui.common.AbstractAcceptCriteria; import org.eclipse.hawkbit.ui.utils.SPUIComponentIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; +import com.google.common.collect.Maps; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; import com.vaadin.ui.Component; @@ -67,7 +67,7 @@ public class ManagementViewAcceptCriteria extends AbstractAcceptCriteria { } private static Map> createDropConfigurations() { - final Map> config = new HashMap<>(); + final Map> config = Maps.newHashMapWithExpectedSize(6); // Delete drop area acceptable components config.put(SPUIComponentIdProvider.DELETE_BUTTON_WRAPPER_ID, @@ -82,7 +82,8 @@ public class ManagementViewAcceptCriteria extends AbstractAcceptCriteria { Arrays.asList(SPUIDefinitions.TARGET_TAG_ID_PREFIXS, SPUIComponentIdProvider.DIST_TABLE_ID)); // Target table header acceptable components - config.put(SPUIComponentIdProvider.TARGET_DROP_FILTER_ICON, Arrays.asList(SPUIComponentIdProvider.DIST_TABLE_ID)); + config.put(SPUIComponentIdProvider.TARGET_DROP_FILTER_ICON, + Arrays.asList(SPUIComponentIdProvider.DIST_TABLE_ID)); // Distribution table acceptable components config.put(SPUIComponentIdProvider.DIST_TABLE_ID, Arrays.asList(SPUIDefinitions.TARGET_TAG_ID_PREFIXS, @@ -94,7 +95,7 @@ public class ManagementViewAcceptCriteria extends AbstractAcceptCriteria { } private static Map createDropHintConfigurations() { - final Map config = new HashMap<>(); + final Map config = Maps.newHashMapWithExpectedSize(4); config.put(SPUIDefinitions.TARGET_TAG_ID_PREFIXS, DragEvent.TARGET_TAG_DRAG); config.put(SPUIComponentIdProvider.TARGET_TABLE_ID, DragEvent.TARGET_DRAG); config.put(SPUIComponentIdProvider.DIST_TABLE_ID, DragEvent.DISTRIBUTION_DRAG); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java index e4c56b165..4524f6d9c 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java @@ -39,6 +39,7 @@ import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.springframework.beans.factory.annotation.Autowired; +import com.google.common.collect.Maps; import com.vaadin.data.Item; import com.vaadin.data.util.IndexedContainer; import com.vaadin.server.FontAwesome; @@ -88,7 +89,7 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin @Override protected Map getConfimrationTabs() { - final Map tabs = new HashMap<>(); + final Map tabs = Maps.newHashMapWithExpectedSize(3); if (!managementUIState.getDeletedDistributionList().isEmpty()) { tabs.put(i18n.get("caption.delete.dist.accordion.tab"), createDeletedDistributionTab()); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java index ac3261895..2f40f5def 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java @@ -87,10 +87,9 @@ public class ManagementUIState implements ManagmentEntityState queryConfiguration = new HashMap<>(); + final Map queryConfiguration = Maps.newHashMapWithExpectedSize(2); final List list = new ArrayList<>(); queryConfiguration.put(SPUIDefinitions.FILTER_BY_NO_TAG, diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java index 26211f67d..7f53b729e 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java @@ -19,10 +19,10 @@ import static org.eclipse.hawkbit.ui.management.event.TargetFilterEvent.REMOVE_F import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -43,12 +43,6 @@ import org.eclipse.hawkbit.ui.common.ManagmentEntityState; import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.common.table.AbstractTable; import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; -import org.eclipse.hawkbit.ui.filter.FilterExpression; -import org.eclipse.hawkbit.ui.filter.Filters; -import org.eclipse.hawkbit.ui.filter.target.CustomTargetFilter; -import org.eclipse.hawkbit.ui.filter.target.TargetSearchTextFilter; -import org.eclipse.hawkbit.ui.filter.target.TargetStatusFilter; -import org.eclipse.hawkbit.ui.filter.target.TargetTagFilter; import org.eclipse.hawkbit.ui.management.event.DragEvent; import org.eclipse.hawkbit.ui.management.event.ManagementUIEvent; import org.eclipse.hawkbit.ui.management.event.ManagementViewAcceptCriteria; @@ -78,6 +72,7 @@ import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; import com.google.common.base.Strings; +import com.google.common.collect.Maps; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.event.dd.DragAndDropEvent; @@ -140,11 +135,14 @@ public class TargetTable extends AbstractTable { if (TargetCreatedEvent.class.isInstance(firstEvent)) { onTargetCreatedEvents(); } else if (TargetInfoUpdateEvent.class.isInstance(firstEvent)) { - onTargetInfoUpdateEvents((List) events); + onTargetUpdateEvents(((List) events).stream() + .map(targetInfoUpdateEvent -> targetInfoUpdateEvent.getEntity().getTarget()) + .collect(Collectors.toList())); } else if (TargetDeletedEvent.class.isInstance(firstEvent)) { onTargetDeletedEvent((List) events); } else if (TargetUpdatedEvent.class.isInstance(firstEvent)) { - onTargetUpdateEvents((List) events); + onTargetUpdateEvents(((List) events).stream() + .map(targetInfoUpdateEvent -> targetInfoUpdateEvent.getEntity()).collect(Collectors.toList())); } } @@ -348,7 +346,7 @@ public class TargetTable extends AbstractTable { } private Map prepareQueryConfigFilters() { - final Map queryConfig = new HashMap<>(); + final Map queryConfig = Maps.newHashMapWithExpectedSize(7); managementUIState.getTargetTableFilters().getSearchText() .ifPresent(value -> queryConfig.put(SPUIDefinitions.FILTER_BY_TEXT, value)); managementUIState.getTargetTableFilters().getDistributionSet() @@ -746,16 +744,17 @@ public class TargetTable extends AbstractTable { } @SuppressWarnings("unchecked") - private void updateVisibleItemOnEvent(final TargetInfo targetInfo, final Target target, - final TargetIdName targetIdName) { + private void updateVisibleItemOnEvent(final TargetInfo targetInfo) { + final Target target = targetInfo.getTarget(); + final TargetIdName targetIdName = target.getTargetIdName(); + final LazyQueryContainer targetContainer = (LazyQueryContainer) getContainerDataSource(); final Item item = targetContainer.getItem(targetIdName); + item.getItemProperty(SPUILabelDefinitions.VAR_NAME).setValue(target.getName()); - if (targetInfo != null) { - item.getItemProperty(SPUILabelDefinitions.VAR_POLL_STATUS_TOOL_TIP) - .setValue(HawkbitCommonUtil.getPollStatusToolTip(targetInfo.getPollStatus(), i18n)); - item.getItemProperty(SPUILabelDefinitions.VAR_TARGET_STATUS).setValue(targetInfo.getUpdateStatus()); - } + item.getItemProperty(SPUILabelDefinitions.VAR_POLL_STATUS_TOOL_TIP) + .setValue(HawkbitCommonUtil.getPollStatusToolTip(targetInfo.getPollStatus(), i18n)); + item.getItemProperty(SPUILabelDefinitions.VAR_TARGET_STATUS).setValue(targetInfo.getUpdateStatus()); } private boolean isLastSelectedTarget(final TargetIdName targetIdName) { @@ -767,62 +766,30 @@ public class TargetTable extends AbstractTable { * EventListener method which is called by the event bus to notify about a * list of {@link TargetInfoUpdateEvent}. * - * @param targetInfoUpdateEvents - * list of target info update event + * @param updatedTargets + * list of updated targets */ - private void onTargetInfoUpdateEvents(final List targetInfoUpdateEvents) { + private void onTargetUpdateEvents(final List updatedTargets) { @SuppressWarnings("unchecked") final List visibleItemIds = (List) getVisibleItemIds(); - boolean shoulTargetsUpdated = false; - Target lastSelectedTarget = null; - for (final TargetInfoUpdateEvent targetInfoUpdateEvent : targetInfoUpdateEvents) { - final TargetInfo targetInfo = targetInfoUpdateEvent.getEntity(); - final Target target = targetInfo.getTarget(); - final TargetIdName targetIdName = target.getTargetIdName(); - if (Filters.or(getTargetTableFilters(target)).doFilter()) { - shoulTargetsUpdated = true; - } else { - if (visibleItemIds.contains(targetIdName)) { - updateVisibleItemOnEvent(targetInfo, target, targetIdName); - } - } - // workaround until push is available for action history, re-select - // the updated target so the action history gets refreshed. - if (isLastSelectedTarget(targetIdName)) { - lastSelectedTarget = target; - } - } - if (shoulTargetsUpdated) { - refreshTargets(); - } - if (lastSelectedTarget != null) { - eventBus.publish(this, new TargetTableEvent(BaseEntityEventType.SELECTED_ENTITY, lastSelectedTarget)); - } - } - private void onTargetUpdateEvents(final List events) { - final List visibleItemIds = (List) getVisibleItemIds(); - boolean shoulTargetsUpdated = false; - Target lastSelectedTarget = null; - for (final TargetUpdatedEvent targetUpdatedEvent : events) { - final Target target = targetUpdatedEvent.getEntity(); - final TargetIdName targetIdName = target.getTargetIdName(); - if (Filters.or(getTargetTableFilters(target)).doFilter()) { - shoulTargetsUpdated = true; - } else { - if (visibleItemIds.contains(targetIdName)) { - updateVisibleItemOnEvent(null, target, targetIdName); - } - } - if (isLastSelectedTarget(targetIdName)) { - lastSelectedTarget = target; - } - } - if (shoulTargetsUpdated) { + if (isFilterEnabled()) { + LOG.debug("Filter enabled on UI {}. Refresh targets from database.", getUI().getUIId()); refreshTargets(); + } else { + updatedTargets.stream().filter(target -> visibleItemIds.contains(target.getTargetIdName())) + .forEach(target -> updateVisibleItemOnEvent(target.getTargetInfo())); } - if (lastSelectedTarget != null) { - eventBus.publish(this, new TargetTableEvent(BaseEntityEventType.SELECTED_ENTITY, lastSelectedTarget)); + + // workaround until push is available for action + // history, re-select + // the updated target so the action history gets + // refreshed. + final Optional selected = updatedTargets.stream() + .filter(target -> isLastSelectedTarget(target.getTargetIdName())).findAny(); + if (selected.isPresent()) { + LOG.debug("Selected element has changed on UI {}. Reselect to update action history.", getUI().getUIId()); + eventBus.publish(this, new TargetTableEvent(BaseEntityEventType.SELECTED_ENTITY, selected.get())); } } @@ -830,17 +797,11 @@ public class TargetTable extends AbstractTable { refreshTargets(); } - private List getTargetTableFilters(final Target target) { + private boolean isFilterEnabled() { final TargetTableFilters targetTableFilters = managementUIState.getTargetTableFilters(); - final List filters = new ArrayList<>(); - if (targetTableFilters.getSearchText().isPresent()) { - filters.add(new TargetSearchTextFilter(target, targetTableFilters.getSearchText().get())); - } - filters.add(new TargetStatusFilter(targetTableFilters.getClickedStatusTargetTags())); - filters.add(new TargetTagFilter(target, targetTableFilters.getClickedTargetTags(), - targetTableFilters.isNoTagSelected())); - filters.add(new CustomTargetFilter(targetTableFilters.getTargetFilterQuery())); - return filters; + return targetTableFilters.getSearchText().isPresent() || !targetTableFilters.getClickedTargetTags().isEmpty() + || !targetTableFilters.getClickedStatusTargetTags().isEmpty() + || targetTableFilters.getTargetFilterQuery().isPresent(); } /** diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetFilterQueryButtons.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetFilterQueryButtons.java index 571656c64..2a45af064 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetFilterQueryButtons.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetFilterQueryButtons.java @@ -9,9 +9,8 @@ package org.eclipse.hawkbit.ui.management.targettag; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Collections; import java.util.List; -import java.util.Map; import javax.annotation.PreDestroy; @@ -102,8 +101,7 @@ public class TargetFilterQueryButtons extends Table { protected LazyQueryContainer createButtonsLazyQueryContainer() { final BeanQueryFactory queryFactory = new BeanQueryFactory<>( TargetFilterBeanQuery.class); - final Map queryConfig = new HashMap<>(); - queryFactory.setQueryConfiguration(queryConfig); + queryFactory.setQueryConfiguration(Collections.emptyMap()); return new LazyQueryContainer(new LazyQueryDefinition(true, 20, "id"), queryFactory); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/DelayedEventBusPushStrategy.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/DelayedEventBusPushStrategy.java index 023979ead..bbb9335a3 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/DelayedEventBusPushStrategy.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/DelayedEventBusPushStrategy.java @@ -8,11 +8,11 @@ */ package org.eclipse.hawkbit.ui.push; -import java.util.LinkedList; +import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.BlockingDeque; -import java.util.concurrent.Executors; +import java.util.concurrent.ExecutionException; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; @@ -57,10 +57,11 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { private static final Logger LOG = LoggerFactory.getLogger(DelayedEventBusPushStrategy.class); private static final int BLOCK_SIZE = 10_000; - private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + private final ScheduledExecutorService executorService; private final BlockingDeque queue = new LinkedBlockingDeque<>(BLOCK_SIZE); private final EventBus.SessionEventBus eventBus; private final com.google.common.eventbus.EventBus systemEventBus; + private int uiid = -1; private ScheduledFuture jobHandle; @@ -68,15 +69,20 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { /** * Constructor. - * + * + * @param executorService + * for scheduled execution of event forwarding to the UI * @param eventBus * the session event bus to where the events should be dispatched * @param systemEventBus * the system event bus where to retrieve the events from the * back-end + * @param eventProvider + * for event delegation to UI */ - public DelayedEventBusPushStrategy(final SessionEventBus eventBus, + public DelayedEventBusPushStrategy(final ScheduledExecutorService executorService, final SessionEventBus eventBus, final com.google.common.eventbus.EventBus systemEventBus, final UIEventProvider eventProvider) { + this.executorService = executorService; this.eventBus = eventBus; this.systemEventBus = systemEventBus; this.eventProvider = eventProvider; @@ -100,7 +106,7 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { } if (!queue.offer(event)) { - LOG.warn("Deque limit is reached, cannot add more events!!! Dropped event is {}", event); + LOG.trace("Deque limit is reached, cannot add more events for UI {}! Dropped event is {}", uiid, event); return; } } @@ -112,7 +118,12 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { @Override public void init(final UI vaadinUI) { - LOG.debug("Initialize delayed event push strategy"); + uiid = vaadinUI.getUIId(); + LOG.info("Initialize delayed event push strategy for UI {}", uiid); + if (vaadinUI.getSession() == null) { + LOG.error("Vaadin session of UI {} is null! Event push disabled!", uiid); + } + jobHandle = executorService.scheduleWithFixedDelay(new DispatchRunnable(vaadinUI, vaadinUI.getSession()), 500, 2000, TimeUnit.MILLISECONDS); systemEventBus.register(this); @@ -120,10 +131,9 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { @Override public void clean() { - LOG.debug("Cleanup resources"); - jobHandle.cancel(true); + LOG.info("Cleanup delayed event push strategy for UI", uiid); systemEventBus.unregister(this); - executorService.shutdownNow(); + jobHandle.cancel(true); queue.clear(); } @@ -138,7 +148,7 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { * @return {@code true} if the event can be dispatched to the UI otherwise * {@code false} */ - protected boolean eventSecurityCheck(final SecurityContext userContext, + protected static boolean eventSecurityCheck(final SecurityContext userContext, final org.eclipse.hawkbit.eventbus.event.Event event) { if (userContext == null || userContext.getAuthentication() == null) { return false; @@ -163,27 +173,29 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { @Override public void run() { - LOG.debug("UI EventBus aggregator started"); + LOG.debug("UI EventBus aggregator started for UI {}", uiid); final long timestamp = System.currentTimeMillis(); - final List events = new LinkedList<>(); - for (int i = 0; i < BLOCK_SIZE; i++) { + + final int size = queue.size(); + if (size <= 0) { + LOG.debug("UI EventBus aggregator for UI {} has nothing to do.", uiid); + return; + } + + final List events = new ArrayList<>(size); + for (int i = 0; i < size; i++) { final org.eclipse.hawkbit.eventbus.event.Event pollEvent = queue.poll(); if (pollEvent == null) { continue; } - events.add(pollEvent); + events.add(i, pollEvent); } if (events.isEmpty()) { + LOG.debug("UI EventBus aggregator for UI {} has nothing to do.", uiid); return; } - if (vaadinSession == null) { - return; - } - - LOG.debug("UI EventBus aggregator session: {}", vaadinSession); - final WrappedSession wrappedSession = vaadinSession.getSession(); if (wrappedSession == null) { return; @@ -191,10 +203,13 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { final int eventsSize = events.size(); + LOG.debug("UI EventBus aggregator dispatches {} events for session {} for UI {}", eventsSize, vaadinSession, + uiid); + doDispatch(events, wrappedSession); - LOG.debug("UI EventBus aggregator done with sending {} events in {} ms", eventsSize, - System.currentTimeMillis() - timestamp); + LOG.debug("UI EventBus aggregator done with sending {} events in {} ms for UI {}", eventsSize, + System.currentTimeMillis() - timestamp, uiid); } @@ -210,9 +225,13 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { if (vaadinSession.getState() != State.OPEN) { return; } + LOG.debug("UI EventBus aggregator of UI {} got lock on session.", uiid); fowardSingleEvents(events, userContext); fowardBulkEvents(events, userContext); - }); + LOG.debug("UI EventBus aggregator of UI {} left lock on session.", uiid); + }).get(); + } catch (InterruptedException | ExecutionException e) { + LOG.error("Wait for Vaadin session for UI {} interrupted!", uiid, e); } finally { SecurityContextHolder.setContext(oldContext); } @@ -222,10 +241,7 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { final SecurityContext userContext) { final Set> filterBulkEvenTypes = eventProvider.getFilteredBulkEventsType(events); publishBulkEvent(events, userContext, filterBulkEvenTypes); - } - private void publishBulkEvent(final List events, - final SecurityContext userContext, final Set> filterBulkEvenTypes) { for (final Class bulkType : filterBulkEvenTypes) { final List listBulkEvents = events.stream() .filter(event -> DelayedEventBusPushStrategy.this.eventSecurityCheck(userContext, event) @@ -237,6 +253,11 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { } } + private void publishBulkEvent(final List events, + final SecurityContext userContext, final Set> filterBulkEvenTypes) { + + } + private void fowardSingleEvents(final List events, final SecurityContext userContext) { events.stream() diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java index be7339324..7c423f758 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java @@ -21,7 +21,6 @@ import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_TOTAL_TARGET import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; -import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; @@ -57,6 +56,7 @@ import org.vaadin.addons.lazyquerycontainer.LazyQueryDefinition; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; +import com.google.common.collect.Maps; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.data.util.converter.Converter; @@ -495,7 +495,8 @@ public class RolloutListGrid extends AbstractGrid { * Contains all expected rollout status per column to enable or disable * the button. */ - private static final Map EXPECTED_ROLLOUT_STATUS_ENABLE_BUTTON = new HashMap<>(); + private static final Map EXPECTED_ROLLOUT_STATUS_ENABLE_BUTTON = Maps + .newHashMapWithExpectedSize(2); private final Container.Indexed containerDataSource; static { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java index d8e93350b..105886fb2 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java @@ -9,8 +9,8 @@ package org.eclipse.hawkbit.ui.utils; import java.util.Arrays; +import java.util.Collections; import java.util.Date; -import java.util.HashMap; import java.util.Map; import java.util.TimeZone; @@ -435,8 +435,7 @@ public final class HawkbitCommonUtil { */ public static LazyQueryContainer createLazyQueryContainer( final BeanQueryFactory> queryFactory) { - final Map queryConfig = new HashMap<>(); - queryFactory.setQueryConfiguration(queryConfig); + queryFactory.setQueryConfiguration(Collections.emptyMap()); return new LazyQueryContainer(new LazyQueryDefinition(true, 20, SPUILabelDefinitions.VAR_NAME), queryFactory); } @@ -448,8 +447,7 @@ public final class HawkbitCommonUtil { */ public static LazyQueryContainer createDSLazyQueryContainer( final BeanQueryFactory> queryFactory) { - final Map queryConfig = new HashMap<>(); - queryFactory.setQueryConfiguration(queryConfig); + queryFactory.setQueryConfiguration(Collections.emptyMap()); return new LazyQueryContainer(new LazyQueryDefinition(true, 20, "tagIdName"), queryFactory); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPDateTimeUtil.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPDateTimeUtil.java index 49bae86e1..df8cf27d6 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPDateTimeUtil.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPDateTimeUtil.java @@ -11,7 +11,6 @@ package org.eclipse.hawkbit.ui.utils; import java.text.SimpleDateFormat; import java.time.ZoneId; import java.util.Date; -import java.util.HashMap; import java.util.Map; import java.util.TimeZone; @@ -19,6 +18,7 @@ import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DurationFormatUtils; import org.eclipse.hawkbit.repository.model.BaseEntity; +import com.google.common.collect.Maps; import com.vaadin.server.WebBrowser; /** @@ -32,7 +32,7 @@ import com.vaadin.server.WebBrowser; public final class SPDateTimeUtil { private static final String DURATION_FORMAT = "y','M','d','H','m','s"; - private static final Map DURATION_I18N = new HashMap<>(); + private static final Map DURATION_I18N = Maps.newHashMapWithExpectedSize(6); static { DURATION_I18N.put(0, CalendarI18N.YEAR);