diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DDISimulatedDevice.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DDISimulatedDevice.java index 1417c3153..b58d3a413 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DDISimulatedDevice.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DDISimulatedDevice.java @@ -10,7 +10,6 @@ package org.eclipse.hawkbit.simulator; import java.util.concurrent.ScheduledExecutorService; -import org.eclipse.hawkbit.simulator.DeviceSimulatorUpdater.UpdaterCallback; import org.eclipse.hawkbit.simulator.http.ControllerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -82,28 +81,27 @@ public class DDISimulatedDevice extends AbstractSimulatedDevice { final String deploymentJson = controllerResource.getDeployment(getTenant(), getId(), actionId); final String swVersion = JsonPath.parse(deploymentJson).read("deployment.chunks[0].version"); currentActionId = actionId; - deviceUpdater.startUpdate(getTenant(), getId(), actionId, swVersion, new UpdaterCallback() { - @Override - public void updateFinished(final AbstractSimulatedDevice device, final Long actionId) { - switch (device.getResponseStatus()) { - case SUCCESSFUL: - controllerResource.postSuccessFeedback(getTenant(), getId(), actionId); - break; - case ERROR: - controllerResource.postErrorFeedback(getTenant(), getId(), actionId); - break; - default: - throw new IllegalStateException("simulated device has an unknown response status + " - + device.getResponseStatus()); - } - currentActionId = null; + deviceUpdater.startUpdate(getTenant(), getId(), actionId, swVersion, (device, actionId1) -> { + switch (device.getResponseStatus()) { + case SUCCESSFUL: + controllerResource.postSuccessFeedback(getTenant(), getId(), + actionId1); + break; + case ERROR: + controllerResource.postErrorFeedback(getTenant(), getId(), + actionId1); + break; + default: + throw new IllegalStateException( + "simulated device has an unknown response status + " + device.getResponseStatus()); } + currentActionId = null; }); } } catch (final PathNotFoundException e) { // href might not be in the json response, so ignore // exception here. - LOGGER.trace("Response does not contain a deploymentbase href link, ignoring."); + LOGGER.trace("Response does not contain a deploymentbase href link, ignoring.", e); } } diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulatorUpdater.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulatorUpdater.java index 6e93b7d04..075f30ba0 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulatorUpdater.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulatorUpdater.java @@ -8,6 +8,7 @@ */ package org.eclipse.hawkbit.simulator; +import java.security.SecureRandom; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -41,7 +42,7 @@ public class DeviceSimulatorUpdater { /** * Starting an simulated update process of an simulated device. - * + * * @param tenant * the tenant of the device * @param id @@ -66,7 +67,7 @@ public class DeviceSimulatorUpdater { } private static final class DeviceSimulatorUpdateThread implements Runnable { - private static final Random rndSleep = new Random(); + private static final Random rndSleep = new SecureRandom(); private final AbstractSimulatedDevice device; private final SpSenderService spSenderService; @@ -74,9 +75,8 @@ public class DeviceSimulatorUpdater { private final EventBus eventbus; private final UpdaterCallback callback; - private DeviceSimulatorUpdateThread(final AbstractSimulatedDevice device, - final SpSenderService spSenderService, final long actionId, final EventBus eventbus, - final UpdaterCallback callback) { + private DeviceSimulatorUpdateThread(final AbstractSimulatedDevice device, final SpSenderService spSenderService, + final long actionId, final EventBus eventbus, final UpdaterCallback callback) { this.device = device; this.spSenderService = spSenderService; this.actionId = actionId; @@ -89,8 +89,9 @@ public class DeviceSimulatorUpdater { final double newProgress = device.getProgress() + 0.2; device.setProgress(newProgress); if (newProgress < 1.0) { - threadPool.schedule(new DeviceSimulatorUpdateThread(device, spSenderService, actionId, eventbus, - callback), rndSleep.nextInt(3000), TimeUnit.MILLISECONDS); + threadPool.schedule( + new DeviceSimulatorUpdateThread(device, spSenderService, actionId, eventbus, callback), + rndSleep.nextInt(3000), TimeUnit.MILLISECONDS); } else { callback.updateFinished(device, actionId); } @@ -102,7 +103,7 @@ public class DeviceSimulatorUpdater { * Callback interface which is called when the simulated update process has * been finished and the caller of starting the simulated update process can * send the result to the hawkbit update server back. - * + * * @author Michael Hirsch * */ @@ -111,7 +112,7 @@ public class DeviceSimulatorUpdater { /** * Callback method to indicate that the simulated update process has * been finished. - * + * * @param device * the device which has been updated * @param actionId diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/NextPollTimeController.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/NextPollTimeController.java index 81acf897e..9c78ec65a 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/NextPollTimeController.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/NextPollTimeController.java @@ -16,6 +16,8 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.eclipse.hawkbit.simulator.event.NextPollCounterUpdate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -24,13 +26,15 @@ import com.google.common.eventbus.EventBus; /** * Poll time trigger which executes the {@link DDISimulatedDevice#poll()} every * second. - * + * * @author Michael Hirsch * */ @Component public class NextPollTimeController { + private static final Logger LOGGER = LoggerFactory.getLogger(NextPollTimeController.class); + private static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); private static final ExecutorService pollService = Executors.newFixedThreadPool(1); @@ -58,14 +62,9 @@ public class NextPollTimeController { if (nextCounter < 0) { if (device instanceof DDISimulatedDevice) { try { - pollService.submit(new Runnable() { - @Override - public void run() { - ((DDISimulatedDevice) device).poll(); - } - }); - } catch (final Exception e) { - + pollService.submit(() -> ((DDISimulatedDevice) device).poll()); + } catch (final IllegalStateException e) { + LOGGER.trace("Device could not be polled", e); } nextCounter = ((DDISimulatedDevice) device).getPollDelaySec(); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/DataReportSeries.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/DataReportSeries.java index 97623d9d0..39c8f5723 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/DataReportSeries.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/DataReportSeries.java @@ -8,19 +8,22 @@ */ package org.eclipse.hawkbit.report.model; +import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; /** * A data report series which contains a list of {@link DataReportSeriesItem}. - * + * * * * @param * the type of the report series item */ -public class DataReportSeries extends AbstractReportSeries { +public class DataReportSeries extends AbstractReportSeries { + + private static final long serialVersionUID = 1L; private final List> data = new ArrayList<>(); @@ -46,7 +49,7 @@ public class DataReportSeries extends AbstractReportSeries { } private void setData(final List> values) { - this.data.clear(); + data.clear(); data.addAll(values); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/DataReportSeriesItem.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/DataReportSeriesItem.java index 3369ef1c0..492e27e1e 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/DataReportSeriesItem.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/DataReportSeriesItem.java @@ -8,6 +8,8 @@ */ package org.eclipse.hawkbit.report.model; +import java.io.Serializable; + /** * An data report series item which contains a type and a value. * @@ -16,8 +18,9 @@ package org.eclipse.hawkbit.report.model; * @param * the type of the report series item */ -public class DataReportSeriesItem { +public class DataReportSeriesItem implements Serializable { + private static final long serialVersionUID = 1L; private final T type; private final Number data; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/InnerOuterDataReportSeries.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/InnerOuterDataReportSeries.java index 1568847de..b63935b39 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/InnerOuterDataReportSeries.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/InnerOuterDataReportSeries.java @@ -8,6 +8,8 @@ */ package org.eclipse.hawkbit.report.model; +import java.io.Serializable; + /** * A double data series which contains an inner and an outer series ideal for * showing donut charts. @@ -17,7 +19,7 @@ package org.eclipse.hawkbit.report.model; * @param * The type parameter for the report series data */ -public class InnerOuterDataReportSeries { +public class InnerOuterDataReportSeries { private final DataReportSeries innerSeries; private final DataReportSeries outerSeries; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java index 0a3838354..d22a77f75 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java @@ -22,10 +22,6 @@ import java.util.stream.Collectors; import javax.persistence.Entity; import javax.persistence.EntityManager; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; import javax.validation.constraints.NotNull; import org.eclipse.hawkbit.eventbus.event.DistributionSetTagAssigmentResultEvent; @@ -53,13 +49,13 @@ import org.eclipse.hawkbit.repository.model.Tag; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.specifications.DistributionSetSpecification; import org.eclipse.hawkbit.repository.specifications.DistributionSetTypeSpecification; +import org.eclipse.hawkbit.repository.specifications.SpecificationsBuilder; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; -import org.springframework.data.jpa.domain.Specifications; import org.springframework.data.jpa.repository.Modifying; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; @@ -203,7 +199,8 @@ public class DistributionSetManagement { } final DistributionSetTagAssigmentResult resultAssignment = result; - afterCommit.afterCommit(() -> eventBus.post(new DistributionSetTagAssigmentResultEvent(resultAssignment))); + afterCommit + .afterCommit(() -> eventBus.post(new DistributionSetTagAssigmentResultEvent(resultAssignment))); // no reason to persist the tag entityManager.detach(myTag); @@ -263,7 +260,7 @@ public class DistributionSetManagement { @Transactional @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) public void deleteDistributionSet(@NotNull final DistributionSet set) { - this.deleteDistributionSet(set.getId()); + deleteDistributionSet(set.getId()); } /** @@ -321,14 +318,10 @@ public class DistributionSetManagement { @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) public DistributionSet createDistributionSet(@NotNull final DistributionSet dSet) { prepareDsSave(dSet); - if (dSet.getType() == null) { dSet.setType(systemManagement.getTenantMetadata().getDefaultDsType()); } - - final DistributionSet result = distributionSetRepository.save(dSet); - - return result; + return distributionSetRepository.save(dSet); } private void prepareDsSave(final DistributionSet dSet) { @@ -400,7 +393,7 @@ public class DistributionSetManagement { @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public DistributionSet unassignSoftwareModule(@NotNull final DistributionSet ds, final SoftwareModule softwareModule) { - final Set softwareModules = new HashSet(); + final Set softwareModules = new HashSet<>(); softwareModules.add(softwareModule); ds.removeModule(softwareModule); checkDistributionSetSoftwareModulesIsAllowedToModify(ds, softwareModules); @@ -491,20 +484,11 @@ public class DistributionSetManagement { @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) private DistributionSet findDistributionSetsByFiltersAndInstalledOrAssignedTarget( final DistributionSetFilter distributionSetFilter) { - final List> specList = buildDistributionSetSpecifications(distributionSetFilter); - - Specifications specs = null; - if (!specList.isEmpty()) { - specs = Specifications.where(specList.get(0)); + if (specList == null || specList.isEmpty()) { + return null; } - if (specList.size() > 1) { - specList.remove(0); - for (final Specification s : specList) { - specs = specs.and(s); - } - } - return distributionSetRepository.findOne(specs); + return distributionSetRepository.findOne(SpecificationsBuilder.combineWithAnd(specList)); } /** @@ -531,7 +515,7 @@ public class DistributionSetManagement { @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) public Page findDistributionSetsAll(@NotNull final Pageable pageReq, final Boolean deleted, final Boolean complete) { - final List> specList = new ArrayList>(); + final List> specList = new ArrayList<>(); if (deleted != null) { final Specification spec = DistributionSetSpecification.isDeleted(deleted); @@ -563,7 +547,7 @@ public class DistributionSetManagement { @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) public Page findDistributionSetsAll(@NotNull final Specification spec, @NotNull final Pageable pageReq, final Boolean deleted) { - final List> specList = new ArrayList>(); + final List> specList = new ArrayList<>(); if (deleted != null) { specList.add(DistributionSetSpecification.isDeleted(deleted)); } @@ -635,17 +619,6 @@ public class DistributionSetManagement { return new PageImpl<>(resultSet, pageable, findDistributionSetsByFilters.getTotalElements()); } - private Long countDistributionSetByCriteriaAPI(@NotEmpty final List> specList) { - Specifications specs = Specifications.where(specList.get(0)); - if (specList.size() > 1) { - for (final Specification s : specList.subList(1, specList.size())) { - specs = specs.and(s); - } - } - - return distributionSetRepository.count(specs); - } - /** * Find distribution set by name and version. * @@ -689,12 +662,12 @@ public class DistributionSetManagement { @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) public Long countDistributionSetsAll() { - final List> specList = new ArrayList>(); + final List> specList = new ArrayList<>(); final Specification spec = DistributionSetSpecification.isDeleted(Boolean.FALSE); specList.add(spec); - return countDistributionSetByCriteriaAPI(specList); + return distributionSetRepository.count(SpecificationsBuilder.combineWithAnd(specList)); } /** @@ -869,17 +842,10 @@ public class DistributionSetManagement { public Page findDistributionSetMetadataByDistributionSetId( @NotNull final Long distributionSetId, @NotNull final Pageable pageable) { - return distributionSetMetadataRepository.findAll(new Specification() { - @Override - public Predicate toPredicate(final Root root, final CriteriaQuery query, - final CriteriaBuilder cb) { - - final Predicate predicate = cb.equal( - root.get(DistributionSetMetadata_.distributionSet).get(DistributionSet_.id), distributionSetId); - - return predicate; - } - }, pageable); + return distributionSetMetadataRepository.findAll( + (Specification) (root, query, cb) -> cb.equal( + root.get(DistributionSetMetadata_.distributionSet).get(DistributionSet_.id), distributionSetId), + pageable); } @@ -899,14 +865,14 @@ public class DistributionSetManagement { public Page findDistributionSetMetadataByDistributionSetId( @NotNull final Long distributionSetId, @NotNull final Specification spec, @NotNull final Pageable pageable) { - return distributionSetMetadataRepository.findAll(new Specification() { - @Override - public Predicate toPredicate(final Root root, final CriteriaQuery query, - final CriteriaBuilder cb) { - return cb.and(cb.equal(root.get(DistributionSetMetadata_.distributionSet).get(DistributionSet_.id), - distributionSetId), spec.toPredicate(root, query, cb)); - } - }, pageable); + return distributionSetMetadataRepository + .findAll( + (Specification) (root, query, + cb) -> cb.and( + cb.equal(root.get(DistributionSetMetadata_.distributionSet) + .get(DistributionSet_.id), distributionSetId), + spec.toPredicate(root, query, cb)), + pageable); } /** @@ -956,7 +922,7 @@ public class DistributionSetManagement { /** * Checking Distribution Set is already using while assign Software module. - * + * * @param distributionSet * @param softwareModules */ @@ -969,9 +935,9 @@ public class DistributionSetManagement { private List> buildDistributionSetSpecifications( final DistributionSetFilter distributionSetFilter) { - final List> specList = new ArrayList>(); + final List> specList = new ArrayList<>(); - Specification spec = null; + Specification spec; if (null != distributionSetFilter.getIsComplete()) { spec = DistributionSetSpecification.isCompleted(distributionSetFilter.getIsComplete()); @@ -1053,21 +1019,12 @@ public class DistributionSetManagement { */ private Page findByCriteriaAPI(@NotNull final Pageable pageable, final List> specList) { - Specifications specs = null; - if (!specList.isEmpty()) { - specs = Specifications.where(specList.get(0)); - } - if (specList.size() > 1) { - for (final Specification s : specList.subList(1, specList.size())) { - specs = specs.and(s); - } + + if (specList == null || specList.isEmpty()) { + return distributionSetRepository.findAll(pageable); } - if (specs == null) { - return distributionSetRepository.findAll(pageable); - } else { - return distributionSetRepository.findAll(specs, pageable); - } + return distributionSetRepository.findAll(SpecificationsBuilder.combineWithAnd(specList), pageable); } private void checkAndThrowAlreadyIfDistributionSetMetadataExists(final DsMetadataCompositeKey metadataId) { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java index 801f6c80d..8f87f9209 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java @@ -213,8 +213,8 @@ public class ReportManagement { * count */ @Cacheable("targetsCreatedOverPeriod") - public DataReportSeries targetsCreatedOverPeriod(final DateType dateType, final LocalDateTime from, - final LocalDateTime to) { + public DataReportSeries targetsCreatedOverPeriod(final DateType dateType, + final LocalDateTime from, final LocalDateTime to) { final Query createNativeQuery = entityManager .createNativeQuery(getTargetsCreatedQueryTemplate(dateType, from, to)); final List resultList = createNativeQuery.getResultList(); @@ -223,8 +223,7 @@ public class ReportManagement { .map(r -> new DataReportSeriesItem<>(dateType.format((String) r[0]), ((Number) r[1]).longValue())) .collect(Collectors.toList()); - final DataReportSeries report = new DataReportSeries<>("CreatedTargets", reportItems); - return report; + return new DataReportSeries<>("CreatedTargets", reportItems); } private String getTargetsCreatedQueryTemplate(final DateType dateType, final LocalDateTime from, @@ -276,8 +275,8 @@ public class ReportManagement { * count */ @Cacheable("feedbackReceivedOverTime") - public DataReportSeries feedbackReceivedOverTime(final DateType dateType, final LocalDateTime from, - final LocalDateTime to) { + public DataReportSeries feedbackReceivedOverTime(final DateType dateType, + final LocalDateTime from, final LocalDateTime to) { final Query createNativeQuery = entityManager .createNativeQuery(getFeedbackReceivedQueryTemplate(dateType, from, to)); final List resultList = createNativeQuery.getResultList(); @@ -286,8 +285,7 @@ public class ReportManagement { .map(r -> new DataReportSeriesItem<>(dateType.format((String) r[0]), ((Number) r[1]).longValue())) .collect(Collectors.toList()); - final DataReportSeries report = new DataReportSeries<>("FeedbackRecieved", reportItems); - return report; + return new DataReportSeries<>("FeedbackRecieved", reportItems); } /** @@ -433,7 +431,7 @@ public class ReportManagement { } private DataReportSeriesItem toItem() { - return new DataReportSeriesItem(name.getName() != null ? name.getName() : "misc", count); + return new DataReportSeriesItem<>(name.getName() != null ? name.getName() : "misc", count); } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java index 98cb1f418..1f610d29c 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java @@ -40,6 +40,7 @@ import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.repository.model.SoftwareModule_; import org.eclipse.hawkbit.repository.model.SwMetadataCompositeKey; import org.eclipse.hawkbit.repository.specifications.SoftwareModuleSpecification; +import org.eclipse.hawkbit.repository.specifications.SpecificationsBuilder; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.AuditorAware; @@ -48,7 +49,6 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; import org.springframework.data.domain.SliceImpl; import org.springframework.data.jpa.domain.Specification; -import org.springframework.data.jpa.domain.Specifications; import org.springframework.data.jpa.repository.Modifying; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; @@ -198,7 +198,7 @@ public class SoftwareManagement { /** * retrieves the {@link SoftwareModule}s by their {@link SoftwareModuleType} * . - * + * * @param pageable * page parameters * @param type @@ -209,7 +209,7 @@ public class SoftwareManagement { public Slice findSoftwareModulesByType(@NotNull final Pageable pageable, @NotNull final SoftwareModuleType type) { - final List> specList = new ArrayList>(); + final List> specList = new ArrayList<>(); Specification spec = SoftwareModuleSpecification.equalType(type); specList.add(spec); @@ -230,7 +230,7 @@ public class SoftwareManagement { @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) public Long countSoftwareModulesByType(@NotNull final SoftwareModuleType type) { - final List> specList = new ArrayList>(); + final List> specList = new ArrayList<>(); Specification spec = SoftwareModuleSpecification.equalType(type); specList.add(spec); @@ -257,7 +257,7 @@ public class SoftwareManagement { /** * retrieves {@link SoftwareModule}s by their name AND version. - * + * * @param name * of the {@link SoftwareModule} * @param version @@ -273,7 +273,7 @@ public class SoftwareManagement { /** * Deletes the given {@link SoftwareModule} {@link Entity}. - * + * * @param bsm * is the {@link SoftwareModule} to be deleted */ @@ -291,26 +291,12 @@ public class SoftwareManagement { private Slice findSwModuleByCriteriaAPI(@NotNull final Pageable pageable, @NotEmpty final List> specList) { - - Specifications specs = Specifications.where(specList.get(0)); - if (specList.size() > 1) { - for (final Specification s : specList.subList(1, specList.size())) { - specs = specs.and(s); - } - } - - return criteriaNoCountDao.findAll(specs, pageable, SoftwareModule.class); + return criteriaNoCountDao.findAll(SpecificationsBuilder.combineWithAnd(specList), pageable, + SoftwareModule.class); } private Long countSwModuleByCriteriaAPI(@NotEmpty final List> specList) { - Specifications specs = Specifications.where(specList.get(0)); - if (specList.size() > 1) { - for (final Specification s : specList.subList(1, specList.size())) { - specs = specs.and(s); - } - } - - return softwareModuleRepository.count(specs); + return softwareModuleRepository.count(SpecificationsBuilder.combineWithAnd(specList)); } private void deleteGridFsArtifacts(final SoftwareModule swModule) { @@ -321,7 +307,7 @@ public class SoftwareManagement { /** * Deletes {@link SoftwareModule}s which is any if the given ids. - * + * * @param ids * of the Software Moduels to be deleted */ @@ -366,20 +352,16 @@ public class SoftwareManagement { @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) public Slice findSoftwareModulesAll(@NotNull final Pageable pageable) { - final List> specList = new ArrayList>(); + final List> specList = new ArrayList<>(); Specification spec = SoftwareModuleSpecification.isDeletedFalse(); specList.add(spec); - spec = new Specification() { - @Override - public Predicate toPredicate(final Root root, final CriteriaQuery query, - final CriteriaBuilder cb) { - if (!query.getResultType().isAssignableFrom(Long.class)) { - root.fetch(SoftwareModule_.type); - } - return cb.conjunction(); + spec = (root, query, cb) -> { + if (!query.getResultType().isAssignableFrom(Long.class)) { + root.fetch(SoftwareModule_.type); } + return cb.conjunction(); }; specList.add(spec); @@ -396,7 +378,7 @@ public class SoftwareManagement { @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) public Long countSoftwareModulesAll() { - final List> specList = new ArrayList>(); + final List> specList = new ArrayList<>(); final Specification spec = SoftwareModuleSpecification.isDeletedFalse(); specList.add(spec); @@ -479,7 +461,7 @@ public class SoftwareManagement { public Slice findSoftwareModuleByFilters(@NotNull final Pageable pageable, final String searchText, final SoftwareModuleType type) { - final List> specList = new ArrayList>(); + final List> specList = new ArrayList<>(); Specification spec = SoftwareModuleSpecification.isDeletedFalse(); specList.add(spec); @@ -494,15 +476,11 @@ public class SoftwareManagement { specList.add(spec); } - spec = new Specification() { - @Override - public Predicate toPredicate(final Root root, final CriteriaQuery query, - final CriteriaBuilder cb) { - if (!query.getResultType().isAssignableFrom(Long.class)) { - root.fetch(SoftwareModule_.type); - } - return cb.conjunction(); + spec = (root, query, cb) -> { + if (!query.getResultType().isAssignableFrom(Long.class)) { + root.fetch(SoftwareModule_.type); } + return cb.conjunction(); }; specList.add(spec); @@ -592,7 +570,7 @@ public class SoftwareManagement { private List> buildSpecificationList(final String searchText, final SoftwareModuleType type) { - final List> specList = new ArrayList>(); + final List> specList = new ArrayList<>(); if (!Strings.isNullOrEmpty(searchText)) { specList.add(SoftwareModuleSpecification.likeNameOrVersion(searchText)); } @@ -631,7 +609,7 @@ public class SoftwareManagement { @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) public Long countSoftwareModuleByFilters(final String searchText, final SoftwareModuleType type) { - final List> specList = new ArrayList>(); + final List> specList = new ArrayList<>(); Specification spec = SoftwareModuleSpecification.isDeletedFalse(); specList.add(spec); @@ -788,7 +766,7 @@ public class SoftwareManagement { /** * creates or updates a single software module meta data entry. - * + * * @param metadata * the meta data entry to create or update * @return the updated or created software module meta data entry @@ -813,7 +791,7 @@ public class SoftwareManagement { /** * creates a list of software module meta data entries. - * + * * @param metadata * the meta data entries to create or update * @return the updated or created software module meta data entries @@ -835,7 +813,7 @@ public class SoftwareManagement { /** * updates a distribution set meta data value if corresponding entry exists. - * + * * @param metadata * the meta data entry to be updated * @return the updated meta data entry @@ -858,7 +836,7 @@ public class SoftwareManagement { /** * deletes a software module meta data entry. - * + * * @param id * the ID of the software module meta data to delete */ @@ -871,7 +849,7 @@ public class SoftwareManagement { /** * finds all meta data by the given software module id. - * + * * @param swId * the software module id to retrieve the meta data from * @param pageable @@ -887,7 +865,7 @@ public class SoftwareManagement { /** * finds all meta data by the given software module id. - * + * * @param softwareModuleId * the software module id to retrieve the meta data from * @param spec @@ -900,20 +878,19 @@ public class SoftwareManagement { @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) public Page findSoftwareModuleMetadataBySoftwareModuleId(final Long softwareModuleId, @NotNull final Specification spec, @NotNull final Pageable pageable) { - return softwareModuleMetadataRepository.findAll(new Specification() { - @Override - public Predicate toPredicate(final Root root, final CriteriaQuery query, - final CriteriaBuilder cb) { - - return cb.and(cb.equal(root.get(SoftwareModuleMetadata_.softwareModule).get(SoftwareModule_.id), - softwareModuleId), spec.toPredicate(root, query, cb)); - } - }, pageable); + return softwareModuleMetadataRepository + .findAll( + (Specification) (root, query, + cb) -> cb.and( + cb.equal(root.get(SoftwareModuleMetadata_.softwareModule) + .get(SoftwareModule_.id), softwareModuleId), + spec.toPredicate(root, query, cb)), + pageable); } /** * finds a single software module meta data by its id. - * + * * @param id * the id of the software module meta data containing the meta * data key and the ID of the software module diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java index 11781559e..c55127d0f 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java @@ -16,6 +16,7 @@ import javax.validation.constraints.NotNull; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; +import org.eclipse.hawkbit.repository.specifications.SpecificationsBuilder; import org.eclipse.hawkbit.repository.specifications.TargetFilterQuerySpecification; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; @@ -33,7 +34,7 @@ import com.google.common.base.Strings; /** * Business service facade for managing {@link TargetFilterQuery}s. - * + * * * */ @@ -47,7 +48,7 @@ public class TargetFilterQueryManagement { /** * creating new {@link TargetFilterQuery}. - * + * * @param customTargetFilter * @return the created {@link TargetFilterQuery} */ @@ -60,13 +61,12 @@ public class TargetFilterQueryManagement { if (targetFilterQueryRepository.findByName(customTargetFilter.getName()) != null) { throw new EntityAlreadyExistsException(customTargetFilter.getName()); } - final TargetFilterQuery filter = targetFilterQueryRepository.save(customTargetFilter); - return filter; + return targetFilterQueryRepository.save(customTargetFilter); } /** * Delete target filter query. - * + * * @param targetFilterQueryId * IDs of target filter query to be deleted */ @@ -78,9 +78,9 @@ public class TargetFilterQueryManagement { } /** - * + * * Retrieves all target filter query{@link TargetFilterQuery}. - * + * * @param pageable * pagination parameter * @return the found {@link TargetFilterQuery}s @@ -92,8 +92,8 @@ public class TargetFilterQueryManagement { /** * Retrieves all target filter query which {@link TargetFilterQuery}. - * - * + * + * * @param pageable * pagination parameter * @param name @@ -102,7 +102,7 @@ public class TargetFilterQueryManagement { */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) public Page findTargetFilterQueryByFilters(@NotNull final Pageable pageable, final String name) { - final List> specList = new ArrayList>(); + final List> specList = new ArrayList<>(); if (!Strings.isNullOrEmpty(name)) { specList.add(TargetFilterQuerySpecification.likeName(name)); } @@ -110,7 +110,7 @@ public class TargetFilterQueryManagement { } /** - * + * * @param pageable * pagination parameter * @param specList @@ -119,29 +119,21 @@ public class TargetFilterQueryManagement { */ private Page findTargetFilterQueryByCriteriaAPI(@NotNull final Pageable pageable, final List> specList) { - Specifications specs = null; - if (!specList.isEmpty()) { - specs = Specifications.where(specList.get(0)); - } - if (specList.size() > 1) { - for (final Specification s : specList.subList(1, specList.size())) { - specs = specs.and(s); - } - } - if (specs == null) { + if (specList == null || specList.isEmpty()) { return targetFilterQueryRepository.findAll(pageable); - } else { - return targetFilterQueryRepository.findAll(specs, pageable); } + + final Specifications specs = SpecificationsBuilder.combineWithAnd(specList); + return targetFilterQueryRepository.findAll(specs, pageable); } /** * Find target filter query by name. - * + * * @param targetFilterQueryName * Target filter query name * @return the found {@link TargetFilterQuery} - * + * */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) public TargetFilterQuery findTargetFilterQueryByName(@NotNull final String targetFilterQueryName) { @@ -150,11 +142,11 @@ public class TargetFilterQueryManagement { /** * Find target filter query by id. - * + * * @param targetFilterQueryId * Target filter query id * @return the found {@link TargetFilterQuery} - * + * */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) public TargetFilterQuery findTargetFilterQueryById(@NotNull final Long targetFilterQueryId) { @@ -163,7 +155,7 @@ public class TargetFilterQueryManagement { /** * updates the {@link TargetFilterQuery}. - * + * * @param targetFilterQuery * to be updated * @return the updated {@link TargetFilterQuery} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java index 75e8c67f3..e790d0a5e 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java @@ -47,6 +47,7 @@ import org.eclipse.hawkbit.repository.model.TargetTagAssigmentResult; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.Target_; import org.eclipse.hawkbit.repository.rsql.RSQLUtility; +import org.eclipse.hawkbit.repository.specifications.SpecificationsBuilder; import org.eclipse.hawkbit.repository.specifications.TargetSpecifications; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.beans.factory.annotation.Autowired; @@ -59,7 +60,6 @@ import org.springframework.data.domain.SliceImpl; 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.domain.Specifications; import org.springframework.data.jpa.repository.Modifying; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; @@ -508,39 +508,18 @@ public class TargetManagement { * @return the page with the found {@link Target} */ private Slice findByCriteriaAPI(final Pageable pageable, final List> specList) { - final Specifications specs = creatingTargetSpecifications(specList); - - if (specs == null) { + if (specList == null || specList.isEmpty()) { return criteriaNoCountDao.findAll(pageable, Target.class); - } else { - return criteriaNoCountDao.findAll(specs, pageable, Target.class); } - + return criteriaNoCountDao.findAll(SpecificationsBuilder.combineWithAnd(specList), pageable, Target.class); } private Long countByCriteriaAPI(final List> specList) { - final Specifications specs = creatingTargetSpecifications(specList); - - if (specs == null) { + if (specList == null || specList.isEmpty()) { return targetRepository.count(); - } else { - return targetRepository.count(specs); } - } - - private static Specifications creatingTargetSpecifications(final List> specList) { - Specifications specs = null; - if (!specList.isEmpty()) { - specs = Specifications.where(specList.get(0)); - } - if (specList.size() > 1) { - specList.remove(0); - for (final Specification s : specList) { - specs = specs.and(s); - } - } - return specs; + return targetRepository.count(SpecificationsBuilder.combineWithAnd(specList)); } /** diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Rollout.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Rollout.java index 3b678ec48..83e541ed5 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Rollout.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Rollout.java @@ -77,7 +77,7 @@ public class Rollout extends NamedEntity { private int rolloutGroupsCreated = 0; @Transient - private TotalTargetCountStatus totalTargetCountStatus; + private transient TotalTargetCountStatus totalTargetCountStatus; /** * @return the distributionSet @@ -234,7 +234,7 @@ public class Rollout extends NamedEntity { */ public TotalTargetCountStatus getTotalTargetCountStatus() { if (totalTargetCountStatus == null) { - this.totalTargetCountStatus = new TotalTargetCountStatus(totalTargets); + totalTargetCountStatus = new TotalTargetCountStatus(totalTargets); } return totalTargetCountStatus; } @@ -255,11 +255,11 @@ public class Rollout extends NamedEntity { } /** - * + * * @author Michael Hirsch * */ - public static enum RolloutStatus { + public enum RolloutStatus { /** * Rollouts is beeing created. diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java index ad7efdf1f..dcb95b254 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java @@ -27,7 +27,7 @@ import javax.persistence.UniqueConstraint; /** * JPA entity definition of persisting a group of an rollout. - * + * * @author Michael Hirsch * */ @@ -116,7 +116,7 @@ public class RolloutGroup extends NamedEntity { } public void setSuccessCondition(final RolloutGroupSuccessCondition finishCondition) { - this.successCondition = finishCondition; + successCondition = finishCondition; } public String getSuccessConditionExp() { @@ -124,7 +124,7 @@ public class RolloutGroup extends NamedEntity { } public void setSuccessConditionExp(final String finishExp) { - this.successConditionExp = finishExp; + successConditionExp = finishExp; } public RolloutGroupErrorCondition getErrorCondition() { @@ -140,7 +140,7 @@ public class RolloutGroup extends NamedEntity { } public void setErrorConditionExp(final String errorExp) { - this.errorConditionExp = errorExp; + errorConditionExp = errorExp; } public RolloutGroupErrorAction getErrorAction() { @@ -188,7 +188,7 @@ public class RolloutGroup extends NamedEntity { */ public TotalTargetCountStatus getTotalTargetCountStatus() { if (totalTargetCountStatus == null) { - this.totalTargetCountStatus = new TotalTargetCountStatus(totalTargets); + totalTargetCountStatus = new TotalTargetCountStatus(totalTargets); } return totalTargetCountStatus; } @@ -210,7 +210,7 @@ public class RolloutGroup extends NamedEntity { } /** - * + * * @author Michael Hirsch * */ @@ -343,7 +343,7 @@ public class RolloutGroup extends NamedEntity { } public void setSuccessCondition(final RolloutGroupSuccessCondition finishCondition) { - this.successCondition = finishCondition; + successCondition = finishCondition; } public String getSuccessConditionExp() { @@ -351,7 +351,7 @@ public class RolloutGroup extends NamedEntity { } public void setSuccessConditionExp(final String finishConditionExp) { - this.successConditionExp = finishConditionExp; + successConditionExp = finishConditionExp; } public RolloutGroupSuccessAction getSuccessAction() { @@ -416,7 +416,7 @@ public class RolloutGroup extends NamedEntity { /** * Sets the finish condition and expression on the builder. - * + * * @param condition * the finish condition * @param expression @@ -432,7 +432,7 @@ public class RolloutGroup extends NamedEntity { /** * Sets the success action and expression on the builder. - * + * * @param action * the success action * @param expression @@ -448,7 +448,7 @@ public class RolloutGroup extends NamedEntity { /** * Sets the error condition and expression on the builder. - * + * * @param condition * the error condition * @param expression @@ -464,7 +464,7 @@ public class RolloutGroup extends NamedEntity { /** * Sets the error action and expression on the builder. - * + * * @param action * the error action * @param expression diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroup.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroup.java index a185f481f..f1d4fe718 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroup.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroup.java @@ -8,6 +8,7 @@ */ package org.eclipse.hawkbit.repository.model; +import java.io.Serializable; import java.util.List; import javax.persistence.CascadeType; @@ -30,16 +31,18 @@ import javax.persistence.Table; @IdClass(RolloutTargetGroupId.class) @Entity @Table(name = "sp_rollouttargetgroup") -public class RolloutTargetGroup { +public class RolloutTargetGroup implements Serializable { + + private static final long serialVersionUID = 1L; @Id @ManyToOne(targetEntity = RolloutGroup.class, fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }) - @JoinColumn(name = "rolloutGroup_Id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rollouttargetgroup_group")) + @JoinColumn(name = "rolloutGroup_Id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rollouttargetgroup_group") ) private RolloutGroup rolloutGroup; @Id @ManyToOne(targetEntity = Target.class, fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }) - @JoinColumn(name = "target_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rollouttargetgroup_target")) + @JoinColumn(name = "target_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rollouttargetgroup_target") ) private Target target; @OneToMany(targetEntity = Action.class, fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }) diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TotalTargetCountStatus.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TotalTargetCountStatus.java index f403ecc3d..13c41baf3 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TotalTargetCountStatus.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TotalTargetCountStatus.java @@ -9,12 +9,12 @@ package org.eclipse.hawkbit.repository.model; import java.util.Collections; -import java.util.HashMap; +import java.util.EnumMap; import java.util.List; import java.util.Map; /** - * + * * Store all states with the target count of a rollout or rolloutgroup. * */ @@ -27,12 +27,12 @@ public class TotalTargetCountStatus { SCHEDULED, RUNNING, ERROR, FINISHED, CANCELLED, NOTSTARTED } - private final Map statusTotalCountMap = new HashMap<>(); + private final Map statusTotalCountMap = new EnumMap<>(Status.class); private final Long totalTargetCount; /** * Create a new states map with the target count for each state. - * + * * @param targetCountActionStatus * the action state map * @param totalTargets @@ -46,7 +46,7 @@ public class TotalTargetCountStatus { /** * Create a new states map with the target count for each state. - * + * * @param totalTargetCount * the total target count */ @@ -56,7 +56,7 @@ public class TotalTargetCountStatus { /** * The current state mape which the total target count - * + * * @return the statusTotalCountMap the state map */ public Map getStatusTotalCountMap() { @@ -65,7 +65,7 @@ public class TotalTargetCountStatus { /** * Gets the total target count from a state. - * + * * @param status * the state key * @return the current target count cannot be @@ -77,7 +77,7 @@ public class TotalTargetCountStatus { /** * Populate all target status to a the given map - * + * * @param statusTotalCountMap * the map * @param rolloutStatusCountItems diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/SpecificationsBuilder.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/SpecificationsBuilder.java new file mode 100644 index 000000000..83a4c6f8b --- /dev/null +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/SpecificationsBuilder.java @@ -0,0 +1,46 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.repository.specifications; + +import java.util.List; + +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.domain.Specifications; + +/** + * Helper class to easily combine {@link Specification} instances. + * + */ +public final class SpecificationsBuilder { + + private SpecificationsBuilder() { + + } + + /** + * Combine all given specification with and. The first specification is the + * where clause. + * + * @param specList + * all specification wich will combine + * @return if the given specification list is empty + */ + public static Specifications combineWithAnd(final List> specList) { + if (specList.isEmpty()) { + return null; + } + Specifications specs = Specifications.where(specList.get(0)); + specList.remove(0); + for (final Specification specification : specList) { + specs = specs.and(specification); + } + return specs; + } + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/RolloutGroupConditionEvaluator.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/RolloutGroupConditionEvaluator.java index 73580fd19..62c9050b1 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/RolloutGroupConditionEvaluator.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/RolloutGroupConditionEvaluator.java @@ -16,7 +16,19 @@ import org.eclipse.hawkbit.repository.model.RolloutGroup; */ public interface RolloutGroupConditionEvaluator { - boolean verifyExpression(final String expression); + default boolean verifyExpression(final String expression) { + // percentage value between 0 and 100 + try { + final Integer value = Integer.valueOf(expression); + if (value >= 0 || value <= 100) { + return true; + } + return true; + } catch (final NumberFormatException e) { + + return false; + } + } boolean eval(Rollout rollout, RolloutGroup rolloutGroup, final String expression); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/ThresholdRolloutGroupErrorCondition.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/ThresholdRolloutGroupErrorCondition.java index 2c2bc361f..6e63efa8e 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/ThresholdRolloutGroupErrorCondition.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/ThresholdRolloutGroupErrorCondition.java @@ -18,31 +18,16 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** - * + * */ @Component("thresholdRolloutGroupErrorCondition") public class ThresholdRolloutGroupErrorCondition implements RolloutGroupConditionEvaluator { - private static Logger logger = LoggerFactory.getLogger(ThresholdRolloutGroupErrorCondition.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ThresholdRolloutGroupErrorCondition.class); @Autowired private ActionRepository actionRepository; - @Override - public boolean verifyExpression(final String expression) { - // percentage value between 0 and 100 - try { - final Integer value = Integer.valueOf(expression); - if (value >= 0 || value <= 100) { - return true; - } - return true; - } catch (final RuntimeException e) { - - } - return false; - } - @Override public boolean eval(final Rollout rollout, final RolloutGroup rolloutGroup, final String expression) { final Long totalGroup = actionRepository.countByRolloutAndRolloutGroup(rollout, rolloutGroup); @@ -60,7 +45,7 @@ public class ThresholdRolloutGroupErrorCondition implements RolloutGroupConditio // calculate threshold return ((float) error / (float) totalGroup) > ((float) threshold / 100F); } catch (final NumberFormatException e) { - logger.error("Cannot evaluate condition expression " + expression, e); + LOGGER.error("Cannot evaluate condition expression " + expression, e); return false; } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/ThresholdRolloutGroupSuccessCondition.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/ThresholdRolloutGroupSuccessCondition.java index 81b5c7286..fcf9762c6 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/ThresholdRolloutGroupSuccessCondition.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/ThresholdRolloutGroupSuccessCondition.java @@ -12,47 +12,41 @@ import org.eclipse.hawkbit.repository.ActionRepository; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.RolloutGroup; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** - * + * */ @Component("thresholdRolloutGroupSuccessCondition") public class ThresholdRolloutGroupSuccessCondition implements RolloutGroupConditionEvaluator { + private static final Logger LOGGER = LoggerFactory.getLogger(ThresholdRolloutGroupSuccessCondition.class); @Autowired private ActionRepository actionRepository; - @Override - public boolean verifyExpression(final String expression) { - // percentage value between 0 and 100 - try { - final Integer value = Integer.valueOf(expression); - if (value >= 0 || value <= 100) { - return true; - } - return true; - } catch (final RuntimeException e) { - - } - return false; - } - @Override public boolean eval(final Rollout rollout, final RolloutGroup rolloutGroup, final String expression) { final Long totalGroup = rolloutGroup.getTotalTargets(); - final Long finished = actionRepository.countByRolloutIdAndRolloutGroupIdAndStatus(rollout.getId(), + final Long finished = this.actionRepository.countByRolloutIdAndRolloutGroupIdAndStatus(rollout.getId(), rolloutGroup.getId(), Action.Status.FINISHED); - final Integer threshold = Integer.valueOf(expression); + try { + final Integer threshold = Integer.valueOf(expression); - if (totalGroup == 0) { - // in case e.g. targets has been deleted we don't have any actions - // left for this group, so the group is finished - return true; + if (totalGroup == 0) { + // in case e.g. targets has been deleted we don't have any + // actions + // left for this group, so the group is finished + return true; + } + // calculate threshold + return ((float) finished / (float) totalGroup) >= ((float) threshold / 100F); + } catch (final NumberFormatException e) { + LOGGER.error("Cannot evaluate condition expression " + expression, e); + return false; } - // calculate threshold - return ((float) finished / (float) totalGroup) >= ((float) threshold / 100F); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/HawkbitUI.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/HawkbitUI.java index b8e5545f3..d352211f6 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/HawkbitUI.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/HawkbitUI.java @@ -75,7 +75,7 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener { private SpringViewProvider viewProvider; @Autowired - private ApplicationContext context; + private transient ApplicationContext context; @Autowired private I18N i18n; @@ -89,13 +89,13 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener { private ErrorView errorview; @Autowired - protected EventBus.SessionEventBus eventBus; + protected transient EventBus.SessionEventBus eventBus; /** * An {@link com.google.common.eventbus.EventBus} subscriber which * subscribes {@link EntityEvent} from the repository to dispatch these * events to the UI {@link SessionEventBus}. - * + * * @param event * the entity event which has been published from the repository */ @@ -103,21 +103,28 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener { @AllowConcurrentEvents public void dispatch(final org.eclipse.hawkbit.eventbus.event.Event event) { final VaadinSession session = getSession(); - if (session != null && session.getState() == State.OPEN) { - final WrappedSession wrappedSession = session.getSession(); - if (wrappedSession != null) { - final SecurityContext userContext = (SecurityContext) wrappedSession - .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); - if (eventSecurityCheck(userContext, event)) { - final SecurityContext oldContext = SecurityContextHolder.getContext(); - try { - access(new DispatcherRunnable(eventBus, session, userContext, event)); - } finally { - SecurityContextHolder.setContext(oldContext); - } - } - } + if (session == null || session.getState() != State.OPEN) { + return; } + + final WrappedSession wrappedSession = session.getSession(); + if (wrappedSession == null) { + return; + } + + final SecurityContext userContext = (SecurityContext) wrappedSession + .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); + if (!eventSecurityCheck(userContext, event)) { + return; + } + + final SecurityContext oldContext = SecurityContextHolder.getContext(); + try { + access(new DispatcherRunnable(eventBus, session, userContext, event)); + } finally { + SecurityContextHolder.setContext(oldContext); + } + } protected boolean eventSecurityCheck(final SecurityContext userContext, @@ -134,7 +141,7 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener { /* * (non-Javadoc) - * + * * @see * com.vaadin.server.ClientConnector.DetachListener#detach(com.vaadin.server * .ClientConnector. DetachEvent) @@ -225,7 +232,7 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener { /** * Get Specific Locale. - * + * * @param availableLocalesInApp * as set * @return String as preferred locale 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 537a76a70..49e9ab59f 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 @@ -44,9 +44,9 @@ import com.vaadin.ui.themes.ValoTheme; /** * Abstract layout of confirm actions window. - * * - * + * + * */ @SpringComponent @ViewScope @@ -84,13 +84,13 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind /* * (non-Javadoc) - * + * * @see org.eclipse.hawkbit.server.ui.common.confirmwindow.layout. * AbstractConfirmationWindowLayout# getConfimrationTabs() */ @Override protected Map getConfimrationTabs() { - final Map tabs = new HashMap(); + final Map tabs = new HashMap<>(); if (!artifactUploadState.getDeleteSofwareModules().isEmpty()) { tabs.put(i18n.get("caption.delete.swmodule.accordion.tab"), createSMDeleteConfirmationTab()); } @@ -145,7 +145,7 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind /** * Get SWModule table container. - * + * * @return IndexedContainer */ @SuppressWarnings("unchecked") @@ -153,9 +153,8 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind final IndexedContainer swcontactContainer = new IndexedContainer(); swcontactContainer.addContainerProperty("SWModuleId", String.class, ""); swcontactContainer.addContainerProperty(SW_MODULE_NAME_MSG, String.class, ""); - Item item = null; for (final Long swModuleID : artifactUploadState.getDeleteSofwareModules().keySet()) { - item = swcontactContainer.addItem(swModuleID); + final Item item = swcontactContainer.addItem(swModuleID); item.getItemProperty("SWModuleId").setValue(swModuleID.toString()); item.getItemProperty(SW_MODULE_NAME_MSG) .setValue(artifactUploadState.getDeleteSofwareModules().get(swModuleID)); @@ -197,7 +196,7 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind for (final CustomFile customFile : artifactUploadState.getFileSelected()) { final String swNameVersion = HawkbitCommonUtil.getFormattedNameVersion( customFile.getBaseSoftwareModuleName(), customFile.getBaseSoftwareModuleVersion()); - if (HawkbitCommonUtil.bothSame(deleteSoftwareNameVersion, swNameVersion)) { + if (deleteSoftwareNameVersion != null && deleteSoftwareNameVersion.equals(swNameVersion)) { tobeRemoved.add(customFile); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java index d653bb371..62a09c83b 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java @@ -38,13 +38,13 @@ public class ArtifactUploadState implements Serializable { private final Map deleteSofwareModules = new HashMap<>(); - private final Set fileSelected = new HashSet(); + private final Set fileSelected = new HashSet<>(); private Long selectedBaseSwModuleId; private SoftwareModule selectedBaseSoftwareModule; - private final Map baseSwModuleList = new HashMap(); + private final Map baseSwModuleList = new HashMap<>(); private Set selectedSoftwareModules = Collections.emptySet(); @@ -60,7 +60,7 @@ public class ArtifactUploadState implements Serializable { /** * Set software. - * + * * @return */ public SoftwareModuleFilters getSoftwareModuleFilters() { @@ -85,7 +85,7 @@ public class ArtifactUploadState implements Serializable { * @return the selectedBaseSwModuleId */ public Optional getSelectedBaseSwModuleId() { - return this.selectedBaseSwModuleId != null ? Optional.of(this.selectedBaseSwModuleId) : Optional.empty(); + return selectedBaseSwModuleId != null ? Optional.of(selectedBaseSwModuleId) : Optional.empty(); } /** @@ -100,8 +100,7 @@ public class ArtifactUploadState implements Serializable { * @return the selectedBaseSoftwareModule */ public Optional getSelectedBaseSoftwareModule() { - return this.selectedBaseSoftwareModule == null ? Optional.empty() - : Optional.of(this.selectedBaseSoftwareModule); + return selectedBaseSoftwareModule == null ? Optional.empty() : Optional.of(selectedBaseSoftwareModule); } /** diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/CustomFile.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/CustomFile.java index ff350511a..3dbbcc7db 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/CustomFile.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/CustomFile.java @@ -10,8 +10,6 @@ package org.eclipse.hawkbit.ui.artifacts.state; import java.io.Serializable; -import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; - /** * Custom file to hold details of uploaded file. * @@ -168,36 +166,50 @@ public class CustomFile implements Serializable { return failureReason; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ @Override - public int hashCode() { // NOSONAR - as this is generated + public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + (fileName == null ? 0 : fileName.hashCode()); + result = prime * result + ((baseSoftwareModuleName == null) ? 0 : baseSoftwareModuleName.hashCode()); + result = prime * result + ((baseSoftwareModuleVersion == null) ? 0 : baseSoftwareModuleVersion.hashCode()); + result = prime * result + ((fileName == null) ? 0 : fileName.hashCode()); return result; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } - if (!(obj instanceof CustomFile)) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { return false; } final CustomFile other = (CustomFile) obj; - return HawkbitCommonUtil.bothSame(fileName, other.fileName) - && HawkbitCommonUtil.bothSame(baseSoftwareModuleName, other.baseSoftwareModuleName) - && HawkbitCommonUtil.bothSame(baseSoftwareModuleVersion, other.baseSoftwareModuleVersion); + if (baseSoftwareModuleName == null) { + if (other.baseSoftwareModuleName != null) { + return false; + } + } else if (!baseSoftwareModuleName.equals(other.baseSoftwareModuleName)) { + return false; + } + if (baseSoftwareModuleVersion == null) { + if (other.baseSoftwareModuleVersion != null) { + return false; + } + } else if (!baseSoftwareModuleVersion.equals(other.baseSoftwareModuleVersion)) { + return false; + } + if (fileName == null) { + if (other.fileName != null) { + return false; + } + } else if (!fileName.equals(other.fileName)) { + return false; + } + return true; } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/filterlayout/AbstractFilterSingleButtonClick.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/filterlayout/AbstractFilterSingleButtonClick.java index ccfbc922c..03b74b08d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/filterlayout/AbstractFilterSingleButtonClick.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/filterlayout/AbstractFilterSingleButtonClick.java @@ -8,8 +8,6 @@ */ package org.eclipse.hawkbit.ui.common.filterlayout; -import java.util.Optional; - import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; import com.vaadin.ui.Button; @@ -17,20 +15,20 @@ import com.vaadin.ui.Button.ClickEvent; /** * Abstract Single button click behaviour of filter buttons layout. - * * * - * + * + * */ public abstract class AbstractFilterSingleButtonClick extends AbstractFilterButtonClickBehaviour { private static final long serialVersionUID = 478874092615793581L; - private Optional