Clean Code Refactoring

Signed-off-by: SirWayne <dennis.melzer@bosch-si.com>
This commit is contained in:
SirWayne
2016-02-09 10:16:07 +01:00
parent 9ae2ef0bc0
commit 1bb29338ac
35 changed files with 1614 additions and 1669 deletions

View File

@@ -10,7 +10,6 @@ package org.eclipse.hawkbit.simulator;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import org.eclipse.hawkbit.simulator.DeviceSimulatorUpdater.UpdaterCallback;
import org.eclipse.hawkbit.simulator.http.ControllerResource; import org.eclipse.hawkbit.simulator.http.ControllerResource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -62,48 +61,47 @@ public class DDISimulatedDevice extends AbstractSimulatedDevice {
@Override @Override
public void clean() { public void clean() {
super.clean(); super.clean();
removed = true; this.removed = true;
} }
public int getPollDelaySec() { public int getPollDelaySec() {
return pollDelaySec; return this.pollDelaySec;
} }
/** /**
* Polls the base URL for the DDI API interface. * Polls the base URL for the DDI API interface.
*/ */
public void poll() { public void poll() {
if (!removed) { if (!this.removed) {
final String basePollJson = controllerResource.get(getTenant(), getId()); final String basePollJson = this.controllerResource.get(getTenant(), getId());
try { try {
final String href = JsonPath.parse(basePollJson).read("_links.deploymentBase.href"); final String href = JsonPath.parse(basePollJson).read("_links.deploymentBase.href");
final long actionId = Long.parseLong(href.substring(href.lastIndexOf("/") + 1, href.indexOf("?"))); final long actionId = Long.parseLong(href.substring(href.lastIndexOf("/") + 1, href.indexOf("?")));
if (currentActionId == null) { if (this.currentActionId == null) {
final String deploymentJson = controllerResource.getDeployment(getTenant(), getId(), actionId); final String deploymentJson = this.controllerResource.getDeployment(getTenant(), getId(), actionId);
final String swVersion = JsonPath.parse(deploymentJson).read("deployment.chunks[0].version"); final String swVersion = JsonPath.parse(deploymentJson).read("deployment.chunks[0].version");
currentActionId = actionId; this.currentActionId = actionId;
deviceUpdater.startUpdate(getTenant(), getId(), actionId, swVersion, new UpdaterCallback() { this.deviceUpdater.startUpdate(getTenant(), getId(), actionId, swVersion, (device, actionId1) -> {
@Override switch (device.getResponseStatus()) {
public void updateFinished(final AbstractSimulatedDevice device, final Long actionId) { case SUCCESSFUL:
switch (device.getResponseStatus()) { DDISimulatedDevice.this.controllerResource.postSuccessFeedback(getTenant(), getId(),
case SUCCESSFUL: actionId1);
controllerResource.postSuccessFeedback(getTenant(), getId(), actionId); break;
break; case ERROR:
case ERROR: DDISimulatedDevice.this.controllerResource.postErrorFeedback(getTenant(), getId(),
controllerResource.postErrorFeedback(getTenant(), getId(), actionId); actionId1);
break; break;
default: default:
throw new IllegalStateException("simulated device has an unknown response status + " throw new IllegalStateException(
+ device.getResponseStatus()); "simulated device has an unknown response status + " + device.getResponseStatus());
}
currentActionId = null;
} }
DDISimulatedDevice.this.currentActionId = null;
}); });
} }
} catch (final PathNotFoundException e) { } catch (final PathNotFoundException e) {
// href might not be in the json response, so ignore // href might not be in the json response, so ignore
// exception here. // 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);
} }
} }

View File

@@ -8,6 +8,7 @@
*/ */
package org.eclipse.hawkbit.simulator; package org.eclipse.hawkbit.simulator;
import java.security.SecureRandom;
import java.util.Random; import java.util.Random;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
@@ -57,16 +58,17 @@ public class DeviceSimulatorUpdater {
*/ */
public void startUpdate(final String tenant, final String id, final long actionId, final String swVersion, public void startUpdate(final String tenant, final String id, final long actionId, final String swVersion,
final UpdaterCallback callback) { final UpdaterCallback callback) {
final AbstractSimulatedDevice device = repository.get(tenant, id); final AbstractSimulatedDevice device = this.repository.get(tenant, id);
device.setProgress(0.0); device.setProgress(0.0);
device.setSwversion(swVersion); device.setSwversion(swVersion);
eventbus.post(new InitUpdate(device)); this.eventbus.post(new InitUpdate(device));
threadPool.schedule(new DeviceSimulatorUpdateThread(device, spSenderService, actionId, eventbus, callback), threadPool.schedule(
2000, TimeUnit.MILLISECONDS); new DeviceSimulatorUpdateThread(device, this.spSenderService, actionId, this.eventbus, callback), 2000,
TimeUnit.MILLISECONDS);
} }
private static final class DeviceSimulatorUpdateThread implements Runnable { 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 AbstractSimulatedDevice device;
private final SpSenderService spSenderService; private final SpSenderService spSenderService;
@@ -74,9 +76,8 @@ public class DeviceSimulatorUpdater {
private final EventBus eventbus; private final EventBus eventbus;
private final UpdaterCallback callback; private final UpdaterCallback callback;
private DeviceSimulatorUpdateThread(final AbstractSimulatedDevice device, private DeviceSimulatorUpdateThread(final AbstractSimulatedDevice device, final SpSenderService spSenderService,
final SpSenderService spSenderService, final long actionId, final EventBus eventbus, final long actionId, final EventBus eventbus, final UpdaterCallback callback) {
final UpdaterCallback callback) {
this.device = device; this.device = device;
this.spSenderService = spSenderService; this.spSenderService = spSenderService;
this.actionId = actionId; this.actionId = actionId;
@@ -86,15 +87,15 @@ public class DeviceSimulatorUpdater {
@Override @Override
public void run() { public void run() {
final double newProgress = device.getProgress() + 0.2; final double newProgress = this.device.getProgress() + 0.2;
device.setProgress(newProgress); this.device.setProgress(newProgress);
if (newProgress < 1.0) { if (newProgress < 1.0) {
threadPool.schedule(new DeviceSimulatorUpdateThread(device, spSenderService, actionId, eventbus, threadPool.schedule(new DeviceSimulatorUpdateThread(this.device, this.spSenderService, this.actionId,
callback), rndSleep.nextInt(3000), TimeUnit.MILLISECONDS); this.eventbus, this.callback), rndSleep.nextInt(3000), TimeUnit.MILLISECONDS);
} else { } else {
callback.updateFinished(device, actionId); this.callback.updateFinished(this.device, this.actionId);
} }
eventbus.post(new ProgressUpdate(device)); this.eventbus.post(new ProgressUpdate(this.device));
} }
} }

View File

@@ -16,6 +16,8 @@ import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.eclipse.hawkbit.simulator.event.NextPollCounterUpdate; 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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -31,6 +33,8 @@ import com.google.common.eventbus.EventBus;
@Component @Component
public class NextPollTimeController { public class NextPollTimeController {
private static final Logger LOGGER = LoggerFactory.getLogger(NextPollTimeController.class);
private static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); private static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
private static final ExecutorService pollService = Executors.newFixedThreadPool(1); private static final ExecutorService pollService = Executors.newFixedThreadPool(1);
@@ -50,7 +54,7 @@ public class NextPollTimeController {
private class NextPollUpdaterRunnable implements Runnable { private class NextPollUpdaterRunnable implements Runnable {
@Override @Override
public void run() { public void run() {
final List<AbstractSimulatedDevice> devices = repository.getAll().stream() final List<AbstractSimulatedDevice> devices = NextPollTimeController.this.repository.getAll().stream()
.filter(device -> device instanceof DDISimulatedDevice).collect(Collectors.toList()); .filter(device -> device instanceof DDISimulatedDevice).collect(Collectors.toList());
devices.forEach(device -> { devices.forEach(device -> {
@@ -58,21 +62,16 @@ public class NextPollTimeController {
if (nextCounter < 0) { if (nextCounter < 0) {
if (device instanceof DDISimulatedDevice) { if (device instanceof DDISimulatedDevice) {
try { try {
pollService.submit(new Runnable() { pollService.submit(() -> ((DDISimulatedDevice) device).poll());
@Override } catch (final IllegalStateException e) {
public void run() { LOGGER.trace("Device could not be polled", e);
((DDISimulatedDevice) device).poll();
}
});
} catch (final Exception e) {
} }
nextCounter = ((DDISimulatedDevice) device).getPollDelaySec(); nextCounter = ((DDISimulatedDevice) device).getPollDelaySec();
} }
} }
device.setNextPollCounterSec(nextCounter); device.setNextPollCounterSec(nextCounter);
}); });
eventBus.post(new NextPollCounterUpdate(devices)); NextPollTimeController.this.eventBus.post(new NextPollCounterUpdate(devices));
} }
} }
} }

View File

@@ -8,6 +8,7 @@
*/ */
package org.eclipse.hawkbit.report.model; package org.eclipse.hawkbit.report.model;
import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -20,7 +21,9 @@ import java.util.stream.Stream;
* @param <T> * @param <T>
* the type of the report series item * the type of the report series item
*/ */
public class DataReportSeries<T extends Object> extends AbstractReportSeries { public class DataReportSeries<T extends Serializable> extends AbstractReportSeries {
private static final long serialVersionUID = 1L;
private final List<DataReportSeriesItem<T>> data = new ArrayList<>(); private final List<DataReportSeriesItem<T>> data = new ArrayList<>();
@@ -47,7 +50,7 @@ public class DataReportSeries<T extends Object> extends AbstractReportSeries {
private void setData(final List<DataReportSeriesItem<T>> values) { private void setData(final List<DataReportSeriesItem<T>> values) {
this.data.clear(); this.data.clear();
data.addAll(values); this.data.addAll(values);
} }
/** /**
@@ -55,10 +58,10 @@ public class DataReportSeries<T extends Object> extends AbstractReportSeries {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public DataReportSeriesItem<T>[] getData() { public DataReportSeriesItem<T>[] getData() {
return data.toArray(new DataReportSeriesItem[data.size()]); return this.data.toArray(new DataReportSeriesItem[this.data.size()]);
} }
public Stream<DataReportSeriesItem<T>> getDataStream() { public Stream<DataReportSeriesItem<T>> getDataStream() {
return data.stream(); return this.data.stream();
} }
} }

View File

@@ -8,6 +8,8 @@
*/ */
package org.eclipse.hawkbit.report.model; package org.eclipse.hawkbit.report.model;
import java.io.Serializable;
/** /**
* An data report series item which contains a type and a value. * An data report series item which contains a type and a value.
* *
@@ -16,8 +18,9 @@ package org.eclipse.hawkbit.report.model;
* @param <T> * @param <T>
* the type of the report series item * the type of the report series item
*/ */
public class DataReportSeriesItem<T extends Object> { public class DataReportSeriesItem<T extends Serializable> implements Serializable {
private static final long serialVersionUID = 1L;
private final T type; private final T type;
private final Number data; private final Number data;
@@ -36,13 +39,13 @@ public class DataReportSeriesItem<T extends Object> {
* @return the type of the data report item * @return the type of the data report item
*/ */
public T getType() { public T getType() {
return type; return this.type;
} }
/** /**
* @return the data of the data report item * @return the data of the data report item
*/ */
public Number getData() { public Number getData() {
return data; return this.data;
} }
} }

View File

@@ -8,6 +8,8 @@
*/ */
package org.eclipse.hawkbit.report.model; package org.eclipse.hawkbit.report.model;
import java.io.Serializable;
/** /**
* A double data series which contains an inner and an outer series ideal for * A double data series which contains an inner and an outer series ideal for
* showing donut charts. * showing donut charts.
@@ -17,7 +19,7 @@ package org.eclipse.hawkbit.report.model;
* @param <T> * @param <T>
* The type parameter for the report series data * The type parameter for the report series data
*/ */
public class InnerOuterDataReportSeries<T> { public class InnerOuterDataReportSeries<T extends Serializable> {
private final DataReportSeries<T> innerSeries; private final DataReportSeries<T> innerSeries;
private final DataReportSeries<T> outerSeries; private final DataReportSeries<T> outerSeries;
@@ -37,13 +39,13 @@ public class InnerOuterDataReportSeries<T> {
* @return the innerSeries * @return the innerSeries
*/ */
public DataReportSeries<T> getInnerSeries() { public DataReportSeries<T> getInnerSeries() {
return innerSeries; return this.innerSeries;
} }
/** /**
* @return the outerSeries * @return the outerSeries
*/ */
public DataReportSeries<T> getOuterSeries() { public DataReportSeries<T> getOuterSeries() {
return outerSeries; return this.outerSeries;
} }
} }

View File

@@ -22,10 +22,6 @@ import java.util.stream.Collectors;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.EntityManager; 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 javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.eventbus.event.DistributionSetTagAssigmentResultEvent; 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.model.Target;
import org.eclipse.hawkbit.repository.specifications.DistributionSetSpecification; import org.eclipse.hawkbit.repository.specifications.DistributionSetSpecification;
import org.eclipse.hawkbit.repository.specifications.DistributionSetTypeSpecification; import org.eclipse.hawkbit.repository.specifications.DistributionSetTypeSpecification;
import org.eclipse.hawkbit.repository.specifications.SpecificationsBuilder;
import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Modifying;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -121,7 +117,7 @@ public class DistributionSetManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public DistributionSet findDistributionSetByIdWithDetails(@NotNull final Long distid) { public DistributionSet findDistributionSetByIdWithDetails(@NotNull final Long distid) {
return distributionSetRepository.findOne(DistributionSetSpecification.byId(distid)); return this.distributionSetRepository.findOne(DistributionSetSpecification.byId(distid));
} }
/** /**
@@ -134,7 +130,7 @@ public class DistributionSetManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public DistributionSet findDistributionSetById(@NotNull final Long distid) { public DistributionSet findDistributionSetById(@NotNull final Long distid) {
return distributionSetRepository.findOne(distid); return this.distributionSetRepository.findOne(distid);
} }
/** /**
@@ -178,7 +174,7 @@ public class DistributionSetManagement {
@NotNull final String tagName) { @NotNull final String tagName) {
final Iterable<DistributionSet> sets = findDistributionSetListWithDetails(dsIds); final Iterable<DistributionSet> sets = findDistributionSetListWithDetails(dsIds);
final DistributionSetTag myTag = tagManagement.findDistributionSetTag(tagName); final DistributionSetTag myTag = this.tagManagement.findDistributionSetTag(tagName);
DistributionSetTagAssigmentResult result = null; DistributionSetTagAssigmentResult result = null;
final List<DistributionSet> allDSs = new ArrayList<>(); final List<DistributionSet> allDSs = new ArrayList<>();
@@ -196,17 +192,18 @@ public class DistributionSetManagement {
} }
} }
result = new DistributionSetTagAssigmentResult(dsIds.size() - allDSs.size(), 0, allDSs.size(), result = new DistributionSetTagAssigmentResult(dsIds.size() - allDSs.size(), 0, allDSs.size(),
Collections.emptyList(), distributionSetRepository.save(allDSs), myTag); Collections.emptyList(), this.distributionSetRepository.save(allDSs), myTag);
} else { } else {
result = new DistributionSetTagAssigmentResult(dsIds.size() - allDSs.size(), allDSs.size(), 0, result = new DistributionSetTagAssigmentResult(dsIds.size() - allDSs.size(), allDSs.size(), 0,
distributionSetRepository.save(allDSs), Collections.emptyList(), myTag); this.distributionSetRepository.save(allDSs), Collections.emptyList(), myTag);
} }
final DistributionSetTagAssigmentResult resultAssignment = result; final DistributionSetTagAssigmentResult resultAssignment = result;
afterCommit.afterCommit(() -> eventBus.post(new DistributionSetTagAssigmentResultEvent(resultAssignment))); this.afterCommit
.afterCommit(() -> this.eventBus.post(new DistributionSetTagAssigmentResultEvent(resultAssignment)));
// no reason to persist the tag // no reason to persist the tag
entityManager.detach(myTag); this.entityManager.detach(myTag);
return result; return result;
} }
@@ -221,7 +218,7 @@ public class DistributionSetManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public List<DistributionSet> findDistributionSetListWithDetails( public List<DistributionSet> findDistributionSetListWithDetails(
@NotEmpty final Collection<Long> distributionIdSet) { @NotEmpty final Collection<Long> distributionIdSet) {
return distributionSetRepository.findAll(DistributionSetSpecification.byIds(distributionIdSet)); return this.distributionSetRepository.findAll(DistributionSetSpecification.byIds(distributionIdSet));
} }
/** /**
@@ -241,7 +238,7 @@ public class DistributionSetManagement {
checkNotNull(ds.getId()); checkNotNull(ds.getId());
final DistributionSet persisted = findDistributionSetByIdWithDetails(ds.getId()); final DistributionSet persisted = findDistributionSetByIdWithDetails(ds.getId());
checkDistributionSetSoftwareModulesIsAllowedToModify(ds, persisted.getModules()); checkDistributionSetSoftwareModulesIsAllowedToModify(ds, persisted.getModules());
return distributionSetRepository.save(ds); return this.distributionSetRepository.save(ds);
} }
/** /**
@@ -280,11 +277,11 @@ public class DistributionSetManagement {
public void deleteDistributionSet(@NotEmpty final Long... distributionSetIDs) { public void deleteDistributionSet(@NotEmpty final Long... distributionSetIDs) {
final List<Long> toHardDelete = new ArrayList<>(); final List<Long> toHardDelete = new ArrayList<>();
final List<Long> assigned = distributionSetRepository.findAssignedDistributionSetsById(distributionSetIDs); final List<Long> assigned = this.distributionSetRepository.findAssignedDistributionSetsById(distributionSetIDs);
// soft delete assigned // soft delete assigned
if (!assigned.isEmpty()) { if (!assigned.isEmpty()) {
distributionSetRepository.deleteDistributionSet(assigned.toArray(new Long[assigned.size()])); this.distributionSetRepository.deleteDistributionSet(assigned.toArray(new Long[assigned.size()]));
} }
// mark the rest as hard delete // mark the rest as hard delete
@@ -299,7 +296,7 @@ public class DistributionSetManagement {
// don't give the delete statement an empty list, JPA/Oracle cannot // don't give the delete statement an empty list, JPA/Oracle cannot
// handle the empty list, // handle the empty list,
// see MECS-403 // see MECS-403
distributionSetRepository.deleteByIdIn(toHardDelete); this.distributionSetRepository.deleteByIdIn(toHardDelete);
} }
} }
@@ -322,9 +319,9 @@ public class DistributionSetManagement {
public DistributionSet createDistributionSet(@NotNull final DistributionSet dSet) { public DistributionSet createDistributionSet(@NotNull final DistributionSet dSet) {
prepareDsSave(dSet); prepareDsSave(dSet);
if (dSet.getType() == null) { if (dSet.getType() == null) {
dSet.setType(systemManagement.getTenantMetadata().getDefaultDsType()); dSet.setType(this.systemManagement.getTenantMetadata().getDefaultDsType());
} }
return distributionSetRepository.save(dSet); return this.distributionSetRepository.save(dSet);
} }
private void prepareDsSave(final DistributionSet dSet) { private void prepareDsSave(final DistributionSet dSet) {
@@ -332,7 +329,7 @@ public class DistributionSetManagement {
throw new EntityAlreadyExistsException("Parameter seems to be an existing, already persisted entity"); throw new EntityAlreadyExistsException("Parameter seems to be an existing, already persisted entity");
} }
if (distributionSetRepository.countByNameAndVersion(dSet.getName(), dSet.getVersion()) > 0) { if (this.distributionSetRepository.countByNameAndVersion(dSet.getName(), dSet.getVersion()) > 0) {
throw new EntityAlreadyExistsException("DistributionSet with that name and version already exists."); throw new EntityAlreadyExistsException("DistributionSet with that name and version already exists.");
} }
@@ -357,7 +354,7 @@ public class DistributionSetManagement {
for (final DistributionSet ds : distributionSets) { for (final DistributionSet ds : distributionSets) {
prepareDsSave(ds); prepareDsSave(ds);
} }
return distributionSetRepository.save(distributionSets); return this.distributionSetRepository.save(distributionSets);
} }
/** /**
@@ -378,7 +375,7 @@ public class DistributionSetManagement {
for (final SoftwareModule softwareModule : softwareModules) { for (final SoftwareModule softwareModule : softwareModules) {
ds.addModule(softwareModule); ds.addModule(softwareModule);
} }
return distributionSetRepository.save(ds); return this.distributionSetRepository.save(ds);
} }
/** /**
@@ -400,7 +397,7 @@ public class DistributionSetManagement {
softwareModules.add(softwareModule); softwareModules.add(softwareModule);
ds.removeModule(softwareModule); ds.removeModule(softwareModule);
checkDistributionSetSoftwareModulesIsAllowedToModify(ds, softwareModules); checkDistributionSetSoftwareModulesIsAllowedToModify(ds, softwareModules);
return distributionSetRepository.save(ds); return this.distributionSetRepository.save(ds);
} }
/** /**
@@ -422,17 +419,17 @@ public class DistributionSetManagement {
public DistributionSetType updateDistributionSetType(@NotNull final DistributionSetType dsType) { public DistributionSetType updateDistributionSetType(@NotNull final DistributionSetType dsType) {
checkNotNull(dsType.getId()); checkNotNull(dsType.getId());
final DistributionSetType persisted = distributionSetTypeRepository.findOne(dsType.getId()); final DistributionSetType persisted = this.distributionSetTypeRepository.findOne(dsType.getId());
// throw exception if user tries to update a DS type that is already in // throw exception if user tries to update a DS type that is already in
// use // use
if (!persisted.areModuleEntriesIdentical(dsType) && distributionSetRepository.countByType(persisted) > 0) { if (!persisted.areModuleEntriesIdentical(dsType) && this.distributionSetRepository.countByType(persisted) > 0) {
throw new EntityReadOnlyException( throw new EntityReadOnlyException(
String.format("distribution set type %s set is already assigned to targets and cannot be changed", String.format("distribution set type %s set is already assigned to targets and cannot be changed",
dsType.getName())); dsType.getName()));
} }
return distributionSetTypeRepository.save(dsType); return this.distributionSetTypeRepository.save(dsType);
} }
/** /**
@@ -448,7 +445,7 @@ public class DistributionSetManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Page<DistributionSetType> findDistributionSetTypesByPredicate( public Page<DistributionSetType> findDistributionSetTypesByPredicate(
@NotNull final Specification<DistributionSetType> spec, @NotNull final Pageable pageable) { @NotNull final Specification<DistributionSetType> spec, @NotNull final Pageable pageable) {
return distributionSetTypeRepository.findAll(spec, pageable); return this.distributionSetTypeRepository.findAll(spec, pageable);
} }
/** /**
@@ -458,7 +455,7 @@ public class DistributionSetManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Page<DistributionSetType> findDistributionSetTypesAll(@NotNull final Pageable pageable) { public Page<DistributionSetType> findDistributionSetTypesAll(@NotNull final Pageable pageable) {
return distributionSetTypeRepository.findByDeleted(pageable, false); return this.distributionSetTypeRepository.findByDeleted(pageable, false);
} }
/** /**
@@ -488,15 +485,10 @@ public class DistributionSetManagement {
private DistributionSet findDistributionSetsByFiltersAndInstalledOrAssignedTarget( private DistributionSet findDistributionSetsByFiltersAndInstalledOrAssignedTarget(
final DistributionSetFilter distributionSetFilter) { final DistributionSetFilter distributionSetFilter) {
final List<Specification<DistributionSet>> specList = buildDistributionSetSpecifications(distributionSetFilter); final List<Specification<DistributionSet>> specList = buildDistributionSetSpecifications(distributionSetFilter);
if (!specList.isEmpty()) { if (specList == null || specList.isEmpty()) {
Specifications<DistributionSet> specs = Specifications.where(specList.get(0)); return null;
specList.remove(0);
for (final Specification<DistributionSet> s : specList) {
specs = specs.and(s);
}
return distributionSetRepository.findOne(specs);
} }
return null; return this.distributionSetRepository.findOne(SpecificationsBuilder.combineWithAnd(specList));
} }
/** /**
@@ -627,17 +619,6 @@ public class DistributionSetManagement {
return new PageImpl<>(resultSet, pageable, findDistributionSetsByFilters.getTotalElements()); return new PageImpl<>(resultSet, pageable, findDistributionSetsByFilters.getTotalElements());
} }
private Long countDistributionSetByCriteriaAPI(@NotEmpty final List<Specification<DistributionSet>> specList) {
Specifications<DistributionSet> specs = Specifications.where(specList.get(0));
if (specList.size() > 1) {
for (final Specification<DistributionSet> s : specList.subList(1, specList.size())) {
specs = specs.and(s);
}
}
return distributionSetRepository.count(specs);
}
/** /**
* Find distribution set by name and version. * Find distribution set by name and version.
* *
@@ -652,7 +633,7 @@ public class DistributionSetManagement {
@NotEmpty final String version) { @NotEmpty final String version) {
final Specification<DistributionSet> spec = DistributionSetSpecification final Specification<DistributionSet> spec = DistributionSetSpecification
.equalsNameAndVersionIgnoreCase(distributionName, version); .equalsNameAndVersionIgnoreCase(distributionName, version);
return distributionSetRepository.findOne(spec); return this.distributionSetRepository.findOne(spec);
} }
@@ -669,7 +650,7 @@ public class DistributionSetManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Iterable<DistributionSet> findDistributionSetList(@NotEmpty final Collection<Long> dist) { public Iterable<DistributionSet> findDistributionSetList(@NotEmpty final Collection<Long> dist) {
return distributionSetRepository.findAll(dist); return this.distributionSetRepository.findAll(dist);
} }
/** /**
@@ -686,7 +667,7 @@ public class DistributionSetManagement {
final Specification<DistributionSet> spec = DistributionSetSpecification.isDeleted(Boolean.FALSE); final Specification<DistributionSet> spec = DistributionSetSpecification.isDeleted(Boolean.FALSE);
specList.add(spec); specList.add(spec);
return countDistributionSetByCriteriaAPI(specList); return this.distributionSetRepository.count(SpecificationsBuilder.combineWithAnd(specList));
} }
/** /**
@@ -694,7 +675,7 @@ public class DistributionSetManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Long countDistributionSetTypesAll() { public Long countDistributionSetTypesAll() {
return distributionSetTypeRepository.countByDeleted(false); return this.distributionSetTypeRepository.countByDeleted(false);
} }
/** /**
@@ -704,7 +685,7 @@ public class DistributionSetManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public DistributionSetType findDistributionSetTypeByName(@NotNull final String name) { public DistributionSetType findDistributionSetTypeByName(@NotNull final String name) {
return distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byName(name)); return this.distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byName(name));
} }
/** /**
@@ -714,7 +695,7 @@ public class DistributionSetManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public DistributionSetType findDistributionSetTypeById(@NotNull final Long id) { public DistributionSetType findDistributionSetTypeById(@NotNull final Long id) {
return distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byId(id)); return this.distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byId(id));
} }
/** /**
@@ -724,7 +705,7 @@ public class DistributionSetManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public DistributionSetType findDistributionSetTypeByKey(@NotNull final String key) { public DistributionSetType findDistributionSetTypeByKey(@NotNull final String key) {
return distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byKey(key)); return this.distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byKey(key));
} }
/** /**
@@ -742,7 +723,7 @@ public class DistributionSetManagement {
throw new EntityAlreadyExistsException("Given type contains an Id!"); throw new EntityAlreadyExistsException("Given type contains an Id!");
} }
return distributionSetTypeRepository.save(type); return this.distributionSetTypeRepository.save(type);
} }
/** /**
@@ -756,12 +737,12 @@ public class DistributionSetManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
public void deleteDistributionSetType(@NotNull final DistributionSetType type) { public void deleteDistributionSetType(@NotNull final DistributionSetType type) {
if (distributionSetRepository.countByType(type) > 0) { if (this.distributionSetRepository.countByType(type) > 0) {
final DistributionSetType toDelete = entityManager.merge(type); final DistributionSetType toDelete = this.entityManager.merge(type);
toDelete.setDeleted(true); toDelete.setDeleted(true);
distributionSetTypeRepository.save(toDelete); this.distributionSetTypeRepository.save(toDelete);
} else { } else {
distributionSetTypeRepository.delete(type.getId()); this.distributionSetTypeRepository.delete(type.getId());
} }
} }
@@ -779,15 +760,15 @@ public class DistributionSetManagement {
@Modifying @Modifying
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
public DistributionSetMetadata createDistributionSetMetadata(@NotNull final DistributionSetMetadata metadata) { public DistributionSetMetadata createDistributionSetMetadata(@NotNull final DistributionSetMetadata metadata) {
if (distributionSetMetadataRepository.exists(metadata.getId())) { if (this.distributionSetMetadataRepository.exists(metadata.getId())) {
throwMetadataKeyAlreadyExists(metadata.getId().getKey()); throwMetadataKeyAlreadyExists(metadata.getId().getKey());
} }
// merge base software module so optLockRevision gets updated and audit // merge base software module so optLockRevision gets updated and audit
// log written because // log written because
// modifying metadata is modifying the base distribution set itself for // modifying metadata is modifying the base distribution set itself for
// auditing purposes. // auditing purposes.
entityManager.merge(metadata.getDistributionSet()).setLastModifiedAt(0L); this.entityManager.merge(metadata.getDistributionSet()).setLastModifiedAt(0L);
return distributionSetMetadataRepository.save(metadata); return this.distributionSetMetadataRepository.save(metadata);
} }
/** /**
@@ -808,8 +789,8 @@ public class DistributionSetManagement {
for (final DistributionSetMetadata distributionSetMetadata : metadata) { for (final DistributionSetMetadata distributionSetMetadata : metadata) {
checkAndThrowAlreadyIfDistributionSetMetadataExists(distributionSetMetadata.getId()); checkAndThrowAlreadyIfDistributionSetMetadataExists(distributionSetMetadata.getId());
} }
metadata.forEach(m -> entityManager.merge(m.getDistributionSet()).setLastModifiedAt(-1L)); metadata.forEach(m -> this.entityManager.merge(m.getDistributionSet()).setLastModifiedAt(-1L));
return (List<DistributionSetMetadata>) distributionSetMetadataRepository.save(metadata); return (List<DistributionSetMetadata>) this.distributionSetMetadataRepository.save(metadata);
} }
/** /**
@@ -830,8 +811,8 @@ public class DistributionSetManagement {
findOne(metadata.getId()); findOne(metadata.getId());
// touch it to update the lock revision because we are modifying the // touch it to update the lock revision because we are modifying the
// DS indirectly // DS indirectly
entityManager.merge(metadata.getDistributionSet()).setLastModifiedAt(0L); this.entityManager.merge(metadata.getDistributionSet()).setLastModifiedAt(0L);
return distributionSetMetadataRepository.save(metadata); return this.distributionSetMetadataRepository.save(metadata);
} }
/** /**
@@ -844,7 +825,7 @@ public class DistributionSetManagement {
@Modifying @Modifying
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
public void deleteDistributionSetMetadata(@NotNull final DsMetadataCompositeKey id) { public void deleteDistributionSetMetadata(@NotNull final DsMetadataCompositeKey id) {
distributionSetMetadataRepository.delete(id); this.distributionSetMetadataRepository.delete(id);
} }
/** /**
@@ -861,14 +842,10 @@ public class DistributionSetManagement {
public Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId( public Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(
@NotNull final Long distributionSetId, @NotNull final Pageable pageable) { @NotNull final Long distributionSetId, @NotNull final Pageable pageable) {
return distributionSetMetadataRepository.findAll(new Specification<DistributionSetMetadata>() { return this.distributionSetMetadataRepository.findAll(
@Override (Specification<DistributionSetMetadata>) (root, query, cb) -> cb.equal(
public Predicate toPredicate(final Root<DistributionSetMetadata> root, final CriteriaQuery<?> query, root.get(DistributionSetMetadata_.distributionSet).get(DistributionSet_.id), distributionSetId),
final CriteriaBuilder cb) { pageable);
return cb.equal(root.get(DistributionSetMetadata_.distributionSet).get(DistributionSet_.id),
distributionSetId);
}
}, pageable);
} }
@@ -888,14 +865,14 @@ public class DistributionSetManagement {
public Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId( public Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(
@NotNull final Long distributionSetId, @NotNull final Specification<DistributionSetMetadata> spec, @NotNull final Long distributionSetId, @NotNull final Specification<DistributionSetMetadata> spec,
@NotNull final Pageable pageable) { @NotNull final Pageable pageable) {
return distributionSetMetadataRepository.findAll(new Specification<DistributionSetMetadata>() { return this.distributionSetMetadataRepository
@Override .findAll(
public Predicate toPredicate(final Root<DistributionSetMetadata> root, final CriteriaQuery<?> query, (Specification<DistributionSetMetadata>) (root, query,
final CriteriaBuilder cb) { cb) -> cb.and(
return cb.and(cb.equal(root.get(DistributionSetMetadata_.distributionSet).get(DistributionSet_.id), cb.equal(root.get(DistributionSetMetadata_.distributionSet)
distributionSetId), spec.toPredicate(root, query, cb)); .get(DistributionSet_.id), distributionSetId),
} spec.toPredicate(root, query, cb)),
}, pageable); pageable);
} }
/** /**
@@ -910,7 +887,7 @@ public class DistributionSetManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public DistributionSetMetadata findOne(@NotNull final DsMetadataCompositeKey id) { public DistributionSetMetadata findOne(@NotNull final DsMetadataCompositeKey id) {
final DistributionSetMetadata findOne = distributionSetMetadataRepository.findOne(id); final DistributionSetMetadata findOne = this.distributionSetMetadataRepository.findOne(id);
if (findOne == null) { if (findOne == null) {
throw new EntityNotFoundException("Metadata with key '" + id.getKey() + "' does not exist"); throw new EntityNotFoundException("Metadata with key '" + id.getKey() + "' does not exist");
} }
@@ -926,7 +903,7 @@ public class DistributionSetManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public DistributionSet findDistributionSetByAction(@NotNull final Action action) { public DistributionSet findDistributionSetByAction(@NotNull final Action action) {
return distributionSetRepository.findByAction(action); return this.distributionSetRepository.findByAction(action);
} }
/** /**
@@ -1001,7 +978,7 @@ public class DistributionSetManagement {
private void checkDistributionSetSoftwareModulesIsAllowedToModify(final DistributionSet distributionSet, private void checkDistributionSetSoftwareModulesIsAllowedToModify(final DistributionSet distributionSet,
final Set<SoftwareModule> softwareModules) { final Set<SoftwareModule> softwareModules) {
if (!new HashSet<SoftwareModule>(distributionSet.getModules()).equals(softwareModules) if (!new HashSet<SoftwareModule>(distributionSet.getModules()).equals(softwareModules)
&& actionRepository.countByDistributionSet(distributionSet) > 0) { && this.actionRepository.countByDistributionSet(distributionSet) > 0) {
throw new EntityLockedException( throw new EntityLockedException(
String.format("distribution set %s:%s is already assigned to targets and cannot be changed", String.format("distribution set %s:%s is already assigned to targets and cannot be changed",
distributionSet.getName(), distributionSet.getVersion())); distributionSet.getName(), distributionSet.getVersion()));
@@ -1009,7 +986,7 @@ public class DistributionSetManagement {
} }
private void checkDistributionSetSoftwareModulesIsAllowedToModify(final DistributionSet distributionSet) { private void checkDistributionSetSoftwareModulesIsAllowedToModify(final DistributionSet distributionSet) {
if (actionRepository.countByDistributionSet(distributionSet) > 0) { if (this.actionRepository.countByDistributionSet(distributionSet) > 0) {
throw new EntityLockedException( throw new EntityLockedException(
String.format("distribution set %s:%s is already assigned to targets and cannot be changed", String.format("distribution set %s:%s is already assigned to targets and cannot be changed",
distributionSet.getName(), distributionSet.getVersion())); distributionSet.getName(), distributionSet.getVersion()));
@@ -1042,25 +1019,16 @@ public class DistributionSetManagement {
*/ */
private Page<DistributionSet> findByCriteriaAPI(@NotNull final Pageable pageable, private Page<DistributionSet> findByCriteriaAPI(@NotNull final Pageable pageable,
final List<Specification<DistributionSet>> specList) { final List<Specification<DistributionSet>> specList) {
Specifications<DistributionSet> specs = null;
if (!specList.isEmpty()) { if (specList == null || specList.isEmpty()) {
specs = Specifications.where(specList.get(0)); return this.distributionSetRepository.findAll(pageable);
}
if (specList.size() > 1) {
for (final Specification<DistributionSet> s : specList.subList(1, specList.size())) {
specs = specs.and(s);
}
} }
if (specs == null) { return this.distributionSetRepository.findAll(SpecificationsBuilder.combineWithAnd(specList), pageable);
return distributionSetRepository.findAll(pageable);
} else {
return distributionSetRepository.findAll(specs, pageable);
}
} }
private void checkAndThrowAlreadyIfDistributionSetMetadataExists(final DsMetadataCompositeKey metadataId) { private void checkAndThrowAlreadyIfDistributionSetMetadataExists(final DsMetadataCompositeKey metadataId) {
if (distributionSetMetadataRepository.exists(metadataId)) { if (this.distributionSetMetadataRepository.exists(metadataId)) {
throw new EntityAlreadyExistsException( throw new EntityAlreadyExistsException(
"Metadata entry with key '" + metadataId.getKey() + "' already exists"); "Metadata entry with key '" + metadataId.getKey() + "' already exists");
} }
@@ -1089,13 +1057,13 @@ public class DistributionSetManagement {
final List<DistributionSet> allDs = findDistributionSetListWithDetails(dsIds); final List<DistributionSet> allDs = findDistributionSetListWithDetails(dsIds);
allDs.forEach(ds -> ds.getTags().add(tag)); allDs.forEach(ds -> ds.getTags().add(tag));
final List<DistributionSet> save = distributionSetRepository.save(allDs); final List<DistributionSet> save = this.distributionSetRepository.save(allDs);
afterCommit.afterCommit(() -> { this.afterCommit.afterCommit(() -> {
final DistributionSetTagAssigmentResult result = new DistributionSetTagAssigmentResult(0, save.size(), 0, final DistributionSetTagAssigmentResult result = new DistributionSetTagAssigmentResult(0, save.size(), 0,
save, Collections.emptyList(), tag); save, Collections.emptyList(), tag);
eventBus.post(new DistributionSetTagAssigmentResultEvent(result)); this.eventBus.post(new DistributionSetTagAssigmentResultEvent(result));
}); });
return save; return save;
@@ -1139,6 +1107,6 @@ public class DistributionSetManagement {
private List<DistributionSet> unAssignTag(final Collection<DistributionSet> distributionSets, private List<DistributionSet> unAssignTag(final Collection<DistributionSet> distributionSets,
final DistributionSetTag tag) { final DistributionSetTag tag) {
distributionSets.forEach(ds -> ds.getTags().remove(tag)); distributionSets.forEach(ds -> ds.getTags().remove(tag));
return distributionSetRepository.save(distributionSets); return this.distributionSetRepository.save(distributionSets);
} }
} }

View File

@@ -99,7 +99,7 @@ public class ReportManagement {
@Cacheable("targetStatus") @Cacheable("targetStatus")
public DataReportSeries<TargetUpdateStatus> targetStatus() { public DataReportSeries<TargetUpdateStatus> targetStatus() {
final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
final CriteriaQuery<Object[]> query = cb.createQuery(Object[].class); final CriteriaQuery<Object[]> query = cb.createQuery(Object[].class);
final Root<Target> targetRoot = query.from(Target.class); final Root<Target> targetRoot = query.from(Target.class);
final Join<Target, TargetInfo> targetInfo = targetRoot.join(Target_.targetInfo); final Join<Target, TargetInfo> targetInfo = targetRoot.join(Target_.targetInfo);
@@ -111,7 +111,7 @@ public class ReportManagement {
// | col1 | col2 | // | col1 | col2 |
// | U_STATUS | COUNT | // | U_STATUS | COUNT |
final List<Object[]> resultList = entityManager.createQuery(multiselect).getResultList(); final List<Object[]> resultList = this.entityManager.createQuery(multiselect).getResultList();
final List<DataReportSeriesItem<TargetUpdateStatus>> reportSeriesItems = resultList.stream() final List<DataReportSeriesItem<TargetUpdateStatus>> reportSeriesItems = resultList.stream()
.map(r -> new DataReportSeriesItem<TargetUpdateStatus>((TargetUpdateStatus) r[0], (Long) r[1])) .map(r -> new DataReportSeriesItem<TargetUpdateStatus>((TargetUpdateStatus) r[0], (Long) r[1]))
@@ -140,7 +140,7 @@ public class ReportManagement {
public List<InnerOuterDataReportSeries<String>> distributionUsageAssigned(final int topXEntries) { public List<InnerOuterDataReportSeries<String>> distributionUsageAssigned(final int topXEntries) {
// top X entries distribution usage // top X entries distribution usage
final CriteriaBuilder cbTopX = entityManager.getCriteriaBuilder(); final CriteriaBuilder cbTopX = this.entityManager.getCriteriaBuilder();
final CriteriaQuery<Object[]> queryTopX = cbTopX.createQuery(Object[].class); final CriteriaQuery<Object[]> queryTopX = cbTopX.createQuery(Object[].class);
final Root<DistributionSet> rootTopX = queryTopX.from(DistributionSet.class); final Root<DistributionSet> rootTopX = queryTopX.from(DistributionSet.class);
final ListJoin<DistributionSet, Target> joinTopX = rootTopX.join(DistributionSet_.assignedToTargets, final ListJoin<DistributionSet, Target> joinTopX = rootTopX.join(DistributionSet_.assignedToTargets,
@@ -154,7 +154,7 @@ public class ReportManagement {
.orderBy(cbTopX.desc(countColumn), cbTopX.asc(rootTopX.get(DistributionSet_.name))); .orderBy(cbTopX.desc(countColumn), cbTopX.asc(rootTopX.get(DistributionSet_.name)));
// | col1 | col2 | col3 | // | col1 | col2 | col3 |
// | NAME | VER | COUNT | // | NAME | VER | COUNT |
final List<Object[]> resultListTop = entityManager.createQuery(groupBy).getResultList(); final List<Object[]> resultListTop = this.entityManager.createQuery(groupBy).getResultList();
// end of top X entries distribution usage // end of top X entries distribution usage
return mapDistirbutionUsageResultToDataReport(topXEntries, resultListTop); return mapDistirbutionUsageResultToDataReport(topXEntries, resultListTop);
@@ -180,7 +180,7 @@ public class ReportManagement {
@Cacheable("distributionUsageInstalled") @Cacheable("distributionUsageInstalled")
public List<InnerOuterDataReportSeries<String>> distributionUsageInstalled(final int topXEntries) { public List<InnerOuterDataReportSeries<String>> distributionUsageInstalled(final int topXEntries) {
// top X entries distribution usage // top X entries distribution usage
final CriteriaBuilder cbTopX = entityManager.getCriteriaBuilder(); final CriteriaBuilder cbTopX = this.entityManager.getCriteriaBuilder();
final CriteriaQuery<Object[]> queryTopX = cbTopX.createQuery(Object[].class); final CriteriaQuery<Object[]> queryTopX = cbTopX.createQuery(Object[].class);
final Root<DistributionSet> rootTopX = queryTopX.from(DistributionSet.class); final Root<DistributionSet> rootTopX = queryTopX.from(DistributionSet.class);
final ListJoin<DistributionSet, TargetInfo> joinTopX = rootTopX.join(DistributionSet_.installedAtTargets, final ListJoin<DistributionSet, TargetInfo> joinTopX = rootTopX.join(DistributionSet_.installedAtTargets,
@@ -194,7 +194,7 @@ public class ReportManagement {
.orderBy(cbTopX.desc(countColumn), cbTopX.asc(rootTopX.get(DistributionSet_.name))); .orderBy(cbTopX.desc(countColumn), cbTopX.asc(rootTopX.get(DistributionSet_.name)));
// | col1 | col2 | col3 | // | col1 | col2 | col3 |
// | NAME | VER | COUNT | // | NAME | VER | COUNT |
final List<Object[]> resultListTop = entityManager.createQuery(groupBy).getResultList(); final List<Object[]> resultListTop = this.entityManager.createQuery(groupBy).getResultList();
// end of top X entries distribution usage // end of top X entries distribution usage
return mapDistirbutionUsageResultToDataReport(topXEntries, resultListTop); return mapDistirbutionUsageResultToDataReport(topXEntries, resultListTop);
@@ -213,9 +213,9 @@ public class ReportManagement {
* count * count
*/ */
@Cacheable("targetsCreatedOverPeriod") @Cacheable("targetsCreatedOverPeriod")
public <T> DataReportSeries<T> targetsCreatedOverPeriod(final DateType<T> dateType, final LocalDateTime from, public <T extends Serializable> DataReportSeries<T> targetsCreatedOverPeriod(final DateType<T> dateType,
final LocalDateTime to) { final LocalDateTime from, final LocalDateTime to) {
final Query createNativeQuery = entityManager final Query createNativeQuery = this.entityManager
.createNativeQuery(getTargetsCreatedQueryTemplate(dateType, from, to)); .createNativeQuery(getTargetsCreatedQueryTemplate(dateType, from, to));
final List<Object[]> resultList = createNativeQuery.getResultList(); final List<Object[]> resultList = createNativeQuery.getResultList();
@@ -223,22 +223,21 @@ public class ReportManagement {
.map(r -> new DataReportSeriesItem<>(dateType.format((String) r[0]), ((Number) r[1]).longValue())) .map(r -> new DataReportSeriesItem<>(dateType.format((String) r[0]), ((Number) r[1]).longValue()))
.collect(Collectors.toList()); .collect(Collectors.toList());
final DataReportSeries<T> report = new DataReportSeries<>("CreatedTargets", reportItems); return new DataReportSeries<>("CreatedTargets", reportItems);
return report;
} }
private String getTargetsCreatedQueryTemplate(final DateType<?> dateType, final LocalDateTime from, private String getTargetsCreatedQueryTemplate(final DateType<?> dateType, final LocalDateTime from,
final LocalDateTime to) { final LocalDateTime to) {
switch (databaseType) { switch (this.databaseType) {
case H2_DB_TYPE: case H2_DB_TYPE:
return String.format(H2_TARGET_CREATED_SQL_TEMPLATE, dateTimeFormatToSqlFormat(dateType), return String.format(H2_TARGET_CREATED_SQL_TEMPLATE, dateTimeFormatToSqlFormat(dateType),
dateTimeFormatToSqlFormat(dateType), from.format(DATE_FORMAT), dateTimeFormatToSqlFormat(dateType), dateTimeFormatToSqlFormat(dateType), from.format(DATE_FORMAT), dateTimeFormatToSqlFormat(dateType),
to.format(DATE_FORMAT), dateTimeFormatToSqlFormat(dateType), tenantAware.getCurrentTenant(), to.format(DATE_FORMAT), dateTimeFormatToSqlFormat(dateType), this.tenantAware.getCurrentTenant(),
dateTimeFormatToSqlFormat(dateType)); dateTimeFormatToSqlFormat(dateType));
case MYSQL_DB_TYPE: case MYSQL_DB_TYPE:
return String.format(MYSQL_TARGET_CREATED_SQL_TEMPLATE, dateTimeFormatToSqlFormat(dateType), return String.format(MYSQL_TARGET_CREATED_SQL_TEMPLATE, dateTimeFormatToSqlFormat(dateType),
dateTimeFormatToSqlFormat(dateType), from.toString(), dateTimeFormatToSqlFormat(dateType), dateTimeFormatToSqlFormat(dateType), from.toString(), dateTimeFormatToSqlFormat(dateType),
to.toString(), dateTimeFormatToSqlFormat(dateType), tenantAware.getCurrentTenant(), to.toString(), dateTimeFormatToSqlFormat(dateType), this.tenantAware.getCurrentTenant(),
dateTimeFormatToSqlFormat(dateType)); dateTimeFormatToSqlFormat(dateType));
default: default:
return null; return null;
@@ -247,16 +246,16 @@ public class ReportManagement {
private String getFeedbackReceivedQueryTemplate(final DateType<?> dateType, final LocalDateTime from, private String getFeedbackReceivedQueryTemplate(final DateType<?> dateType, final LocalDateTime from,
final LocalDateTime to) { final LocalDateTime to) {
switch (databaseType) { switch (this.databaseType) {
case H2_DB_TYPE: case H2_DB_TYPE:
return String.format(H2_CONTROLLER_FRRDBACK_SQL_TEMPLATE, dateTimeFormatToSqlFormat(dateType), return String.format(H2_CONTROLLER_FRRDBACK_SQL_TEMPLATE, dateTimeFormatToSqlFormat(dateType),
dateTimeFormatToSqlFormat(dateType), from.format(DATE_FORMAT), dateTimeFormatToSqlFormat(dateType), dateTimeFormatToSqlFormat(dateType), from.format(DATE_FORMAT), dateTimeFormatToSqlFormat(dateType),
to.format(DATE_FORMAT), dateTimeFormatToSqlFormat(dateType), tenantAware.getCurrentTenant(), to.format(DATE_FORMAT), dateTimeFormatToSqlFormat(dateType), this.tenantAware.getCurrentTenant(),
dateTimeFormatToSqlFormat(dateType)); dateTimeFormatToSqlFormat(dateType));
case MYSQL_DB_TYPE: case MYSQL_DB_TYPE:
return String.format(MYSQL_CONTROLLER_FRRDBACK_SQL_TEMPLATE, dateTimeFormatToSqlFormat(dateType), return String.format(MYSQL_CONTROLLER_FRRDBACK_SQL_TEMPLATE, dateTimeFormatToSqlFormat(dateType),
dateTimeFormatToSqlFormat(dateType), from.toString(), dateTimeFormatToSqlFormat(dateType), dateTimeFormatToSqlFormat(dateType), from.toString(), dateTimeFormatToSqlFormat(dateType),
to.toString(), dateTimeFormatToSqlFormat(dateType), tenantAware.getCurrentTenant(), to.toString(), dateTimeFormatToSqlFormat(dateType), this.tenantAware.getCurrentTenant(),
dateTimeFormatToSqlFormat(dateType)); dateTimeFormatToSqlFormat(dateType));
default: default:
return null; return null;
@@ -276,9 +275,9 @@ public class ReportManagement {
* count * count
*/ */
@Cacheable("feedbackReceivedOverTime") @Cacheable("feedbackReceivedOverTime")
public <T> DataReportSeries<T> feedbackReceivedOverTime(final DateType<T> dateType, final LocalDateTime from, public <T extends Serializable> DataReportSeries<T> feedbackReceivedOverTime(final DateType<T> dateType,
final LocalDateTime to) { final LocalDateTime from, final LocalDateTime to) {
final Query createNativeQuery = entityManager final Query createNativeQuery = this.entityManager
.createNativeQuery(getFeedbackReceivedQueryTemplate(dateType, from, to)); .createNativeQuery(getFeedbackReceivedQueryTemplate(dateType, from, to));
final List<Object[]> resultList = createNativeQuery.getResultList(); final List<Object[]> resultList = createNativeQuery.getResultList();
@@ -286,8 +285,7 @@ public class ReportManagement {
.map(r -> new DataReportSeriesItem<>(dateType.format((String) r[0]), ((Number) r[1]).longValue())) .map(r -> new DataReportSeriesItem<>(dateType.format((String) r[0]), ((Number) r[1]).longValue()))
.collect(Collectors.toList()); .collect(Collectors.toList());
final DataReportSeries<T> report = new DataReportSeries<>("FeedbackRecieved", reportItems); return new DataReportSeries<>("FeedbackRecieved", reportItems);
return report;
} }
/** /**
@@ -313,30 +311,30 @@ public class ReportManagement {
final LocalDateTime beforeMonth = now.minusMonths(1); final LocalDateTime beforeMonth = now.minusMonths(1);
final LocalDateTime beforeYear = now.minusYears(1); final LocalDateTime beforeYear = now.minusYears(1);
final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
final List<DataReportSeriesItem<SeriesTime>> resultList = new ArrayList<>(); final List<DataReportSeriesItem<SeriesTime>> resultList = new ArrayList<>();
// hours // hours
resultList.add(new DataReportSeriesItem<SeriesTime>(SeriesTime.HOUR, resultList.add(new DataReportSeriesItem<SeriesTime>(SeriesTime.HOUR, this.entityManager
entityManager.createQuery(createCountSelectTargetsLastPoll(cb, beforeHour, now)).getSingleResult())); .createQuery(createCountSelectTargetsLastPoll(cb, beforeHour, now)).getSingleResult()));
// days // days
resultList.add(new DataReportSeriesItem<SeriesTime>(SeriesTime.DAY, entityManager resultList.add(new DataReportSeriesItem<SeriesTime>(SeriesTime.DAY, this.entityManager
.createQuery(createCountSelectTargetsLastPoll(cb, beforeDay, beforeHour)).getSingleResult())); .createQuery(createCountSelectTargetsLastPoll(cb, beforeDay, beforeHour)).getSingleResult()));
// weeks // weeks
resultList.add(new DataReportSeriesItem<SeriesTime>(SeriesTime.WEEK, entityManager resultList.add(new DataReportSeriesItem<SeriesTime>(SeriesTime.WEEK, this.entityManager
.createQuery(createCountSelectTargetsLastPoll(cb, beforeWeek, beforeDay)).getSingleResult())); .createQuery(createCountSelectTargetsLastPoll(cb, beforeWeek, beforeDay)).getSingleResult()));
// months // months
resultList.add(new DataReportSeriesItem<SeriesTime>(SeriesTime.MONTH, entityManager resultList.add(new DataReportSeriesItem<SeriesTime>(SeriesTime.MONTH, this.entityManager
.createQuery(createCountSelectTargetsLastPoll(cb, beforeMonth, beforeWeek)).getSingleResult())); .createQuery(createCountSelectTargetsLastPoll(cb, beforeMonth, beforeWeek)).getSingleResult()));
// years // years
resultList.add(new DataReportSeriesItem<SeriesTime>(SeriesTime.YEAR, entityManager resultList.add(new DataReportSeriesItem<SeriesTime>(SeriesTime.YEAR, this.entityManager
.createQuery(createCountSelectTargetsLastPoll(cb, beforeYear, beforeMonth)).getSingleResult())); .createQuery(createCountSelectTargetsLastPoll(cb, beforeYear, beforeMonth)).getSingleResult()));
// years // years
resultList.add(new DataReportSeriesItem<SeriesTime>(SeriesTime.MORE_THAN_YEAR, resultList.add(new DataReportSeriesItem<SeriesTime>(SeriesTime.MORE_THAN_YEAR, this.entityManager
entityManager.createQuery(createCountSelectTargetsLastPoll(cb, null, beforeYear)).getSingleResult())); .createQuery(createCountSelectTargetsLastPoll(cb, null, beforeYear)).getSingleResult()));
// never // never
resultList.add(new DataReportSeriesItem<SeriesTime>(SeriesTime.NEVER, resultList.add(new DataReportSeriesItem<SeriesTime>(SeriesTime.NEVER,
entityManager.createQuery(createCountSelectTargetsLastPoll(cb, null, null)).getSingleResult())); this.entityManager.createQuery(createCountSelectTargetsLastPoll(cb, null, null)).getSingleResult()));
return new DataReportSeries<>("TargetLastPoll", resultList); return new DataReportSeries<>("TargetLastPoll", resultList);
} }
@@ -417,23 +415,23 @@ public class ReportManagement {
final List<InnerOuter> outer; final List<InnerOuter> outer;
private InnerOuter(final DSName idName) { private InnerOuter(final DSName idName) {
name = idName; this.name = idName;
outer = new ArrayList<>(); this.outer = new ArrayList<>();
} }
private InnerOuter(final DSName idName, final long count) { private InnerOuter(final DSName idName, final long count) {
name = idName; this.name = idName;
this.count = count; this.count = count;
outer = new ArrayList<>(); this.outer = new ArrayList<>();
} }
private void addOuter(final DSName idName, final long count) { private void addOuter(final DSName idName, final long count) {
outer.add(new InnerOuter(idName, count)); this.outer.add(new InnerOuter(idName, count));
this.count += count; this.count += count;
} }
private DataReportSeriesItem<String> toItem() { private DataReportSeriesItem<String> toItem() {
return new DataReportSeriesItem<String>(name.getName() != null ? name.getName() : "misc", count); return new DataReportSeriesItem<>(this.name.getName() != null ? this.name.getName() : "misc", this.count);
} }
} }
@@ -462,7 +460,7 @@ public class ReportManagement {
* @return the name * @return the name
*/ */
private String getName() { private String getName() {
return name; return this.name;
} }
/* /*
@@ -474,7 +472,7 @@ public class ReportManagement {
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + (name == null ? 0 : name.hashCode()); result = prime * result + (this.name == null ? 0 : this.name.hashCode());
return result; return result;
} }
@@ -496,11 +494,11 @@ public class ReportManagement {
return false; return false;
} }
final DSName other = (DSName) obj; final DSName other = (DSName) obj;
if (name == null) { if (this.name == null) {
if (other.name != null) { if (other.name != null) {
return false; return false;
} }
} else if (!name.equals(other.name)) { } else if (!this.name.equals(other.name)) {
return false; return false;
} }
return true; return true;
@@ -513,12 +511,12 @@ public class ReportManagement {
*/ */
@Override @Override
public String toString() { public String toString() {
return "DSName [name=" + name + "]"; return "DSName [name=" + this.name + "]";
} }
} }
private String dateTimeFormatToSqlFormat(final DateType<?> datatype) { private String dateTimeFormatToSqlFormat(final DateType<?> datatype) {
switch (databaseType) { switch (this.databaseType) {
case H2_DB_TYPE: case H2_DB_TYPE:
return datatype.h2Format(); return datatype.h2Format();
case MYSQL_DB_TYPE: case MYSQL_DB_TYPE:

View File

@@ -40,6 +40,7 @@ import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.model.SoftwareModule_; import org.eclipse.hawkbit.repository.model.SoftwareModule_;
import org.eclipse.hawkbit.repository.model.SwMetadataCompositeKey; import org.eclipse.hawkbit.repository.model.SwMetadataCompositeKey;
import org.eclipse.hawkbit.repository.specifications.SoftwareModuleSpecification; import org.eclipse.hawkbit.repository.specifications.SoftwareModuleSpecification;
import org.eclipse.hawkbit.repository.specifications.SpecificationsBuilder;
import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.AuditorAware; 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.Slice;
import org.springframework.data.domain.SliceImpl; import org.springframework.data.domain.SliceImpl;
import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Modifying;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -117,7 +117,7 @@ public class SoftwareManagement {
public SoftwareModule updateSoftwareModule(@NotNull final SoftwareModule sm) { public SoftwareModule updateSoftwareModule(@NotNull final SoftwareModule sm) {
checkNotNull(sm.getId()); checkNotNull(sm.getId());
final SoftwareModule module = softwareModuleRepository.findOne(sm.getId()); final SoftwareModule module = this.softwareModuleRepository.findOne(sm.getId());
if (null == sm.getDescription() || !sm.getDescription().equals(module.getDescription())) { if (null == sm.getDescription() || !sm.getDescription().equals(module.getDescription())) {
module.setDescription(sm.getDescription()); module.setDescription(sm.getDescription());
@@ -125,7 +125,7 @@ public class SoftwareManagement {
if (null == sm.getVendor() || !sm.getVendor().equals(module.getVendor())) { if (null == sm.getVendor() || !sm.getVendor().equals(module.getVendor())) {
module.setVendor(sm.getVendor()); module.setVendor(sm.getVendor());
} }
return softwareModuleRepository.save(module); return this.softwareModuleRepository.save(module);
} }
/** /**
@@ -143,7 +143,7 @@ public class SoftwareManagement {
public SoftwareModuleType updateSoftwareModuleType(@NotNull final SoftwareModuleType sm) { public SoftwareModuleType updateSoftwareModuleType(@NotNull final SoftwareModuleType sm) {
checkNotNull(sm.getId()); checkNotNull(sm.getId());
final SoftwareModuleType type = softwareModuleTypeRepository.findOne(sm.getId()); final SoftwareModuleType type = this.softwareModuleTypeRepository.findOne(sm.getId());
if (sm.getDescription() != null && !sm.getDescription().equals(type.getDescription())) { if (sm.getDescription() != null && !sm.getDescription().equals(type.getDescription())) {
type.setDescription(sm.getDescription()); type.setDescription(sm.getDescription());
@@ -151,7 +151,7 @@ public class SoftwareManagement {
if (sm.getColour() != null && !sm.getColour().equals(type.getColour())) { if (sm.getColour() != null && !sm.getColour().equals(type.getColour())) {
type.setColour(sm.getColour()); type.setColour(sm.getColour());
} }
return softwareModuleTypeRepository.save(type); return this.softwareModuleTypeRepository.save(type);
} }
/** /**
@@ -169,7 +169,7 @@ public class SoftwareManagement {
if (null != swModule.getId()) { if (null != swModule.getId()) {
throw new EntityAlreadyExistsException(); throw new EntityAlreadyExistsException();
} }
return softwareModuleRepository.save(swModule); return this.softwareModuleRepository.save(swModule);
} }
/** /**
@@ -191,7 +191,7 @@ public class SoftwareManagement {
} }
}); });
return softwareModuleRepository.save(swModules); return this.softwareModuleRepository.save(swModules);
} }
@@ -209,7 +209,7 @@ public class SoftwareManagement {
public Slice<SoftwareModule> findSoftwareModulesByType(@NotNull final Pageable pageable, public Slice<SoftwareModule> findSoftwareModulesByType(@NotNull final Pageable pageable,
@NotNull final SoftwareModuleType type) { @NotNull final SoftwareModuleType type) {
final List<Specification<SoftwareModule>> specList = new ArrayList<Specification<SoftwareModule>>(); final List<Specification<SoftwareModule>> specList = new ArrayList<>();
Specification<SoftwareModule> spec = SoftwareModuleSpecification.equalType(type); Specification<SoftwareModule> spec = SoftwareModuleSpecification.equalType(type);
specList.add(spec); specList.add(spec);
@@ -230,7 +230,7 @@ public class SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Long countSoftwareModulesByType(@NotNull final SoftwareModuleType type) { public Long countSoftwareModulesByType(@NotNull final SoftwareModuleType type) {
final List<Specification<SoftwareModule>> specList = new ArrayList<Specification<SoftwareModule>>(); final List<Specification<SoftwareModule>> specList = new ArrayList<>();
Specification<SoftwareModule> spec = SoftwareModuleSpecification.equalType(type); Specification<SoftwareModule> spec = SoftwareModuleSpecification.equalType(type);
specList.add(spec); specList.add(spec);
@@ -252,7 +252,7 @@ public class SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER) + SpringEvalExpressions.IS_CONTROLLER)
public SoftwareModule findSoftwareModuleById(@NotNull final Long id) { public SoftwareModule findSoftwareModuleById(@NotNull final Long id) {
return artifactManagement.findSoftwareModuleById(id); return this.artifactManagement.findSoftwareModuleById(id);
} }
/** /**
@@ -268,7 +268,7 @@ public class SoftwareManagement {
public List<SoftwareModule> findSoftwareModuleByNameAndVersion(@NotEmpty final String name, public List<SoftwareModule> findSoftwareModuleByNameAndVersion(@NotEmpty final String name,
@NotEmpty final String version) { @NotEmpty final String version) {
return softwareModuleRepository.findByNameAndVersion(name, version); return this.softwareModuleRepository.findByNameAndVersion(name, version);
} }
/** /**
@@ -286,36 +286,22 @@ public class SoftwareManagement {
} }
private boolean isUnassigned(final SoftwareModule bsmMerged) { private boolean isUnassigned(final SoftwareModule bsmMerged) {
return distributionSetRepository.findByModules(bsmMerged).isEmpty(); return this.distributionSetRepository.findByModules(bsmMerged).isEmpty();
} }
private Slice<SoftwareModule> findSwModuleByCriteriaAPI(@NotNull final Pageable pageable, private Slice<SoftwareModule> findSwModuleByCriteriaAPI(@NotNull final Pageable pageable,
@NotEmpty final List<Specification<SoftwareModule>> specList) { @NotEmpty final List<Specification<SoftwareModule>> specList) {
return this.criteriaNoCountDao.findAll(SpecificationsBuilder.combineWithAnd(specList), pageable,
Specifications<SoftwareModule> specs = Specifications.where(specList.get(0)); SoftwareModule.class);
if (specList.size() > 1) {
for (final Specification<SoftwareModule> s : specList.subList(1, specList.size())) {
specs = specs.and(s);
}
}
return criteriaNoCountDao.findAll(specs, pageable, SoftwareModule.class);
} }
private Long countSwModuleByCriteriaAPI(@NotEmpty final List<Specification<SoftwareModule>> specList) { private Long countSwModuleByCriteriaAPI(@NotEmpty final List<Specification<SoftwareModule>> specList) {
Specifications<SoftwareModule> specs = Specifications.where(specList.get(0)); return this.softwareModuleRepository.count(SpecificationsBuilder.combineWithAnd(specList));
if (specList.size() > 1) {
for (final Specification<SoftwareModule> s : specList.subList(1, specList.size())) {
specs = specs.and(s);
}
}
return softwareModuleRepository.count(specs);
} }
private void deleteGridFsArtifacts(final SoftwareModule swModule) { private void deleteGridFsArtifacts(final SoftwareModule swModule) {
for (final LocalArtifact localArtifact : swModule.getLocalArtifacts()) { for (final LocalArtifact localArtifact : swModule.getLocalArtifacts()) {
artifactManagement.deleteGridFsArtifact(localArtifact); this.artifactManagement.deleteGridFsArtifact(localArtifact);
} }
} }
@@ -329,7 +315,7 @@ public class SoftwareManagement {
@Transactional @Transactional
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
public void deleteSoftwareModules(@NotNull final Iterable<Long> ids) { public void deleteSoftwareModules(@NotNull final Iterable<Long> ids) {
final List<SoftwareModule> swModulesToDelete = softwareModuleRepository.findByIdIn(ids); final List<SoftwareModule> swModulesToDelete = this.softwareModuleRepository.findByIdIn(ids);
final Set<Long> assignedModuleIds = new HashSet<>(); final Set<Long> assignedModuleIds = new HashSet<>();
swModulesToDelete.forEach(swModule -> { swModulesToDelete.forEach(swModule -> {
@@ -338,7 +324,7 @@ public class SoftwareManagement {
if (isUnassigned(swModule)) { if (isUnassigned(swModule)) {
softwareModuleRepository.delete(swModule); this.softwareModuleRepository.delete(swModule);
} else { } else {
@@ -348,10 +334,10 @@ public class SoftwareManagement {
if (!assignedModuleIds.isEmpty()) { if (!assignedModuleIds.isEmpty()) {
String currentUser = null; String currentUser = null;
if (auditorProvider != null) { if (this.auditorProvider != null) {
currentUser = auditorProvider.getCurrentAuditor(); currentUser = this.auditorProvider.getCurrentAuditor();
} }
softwareModuleRepository.deleteSoftwareModule(System.currentTimeMillis(), currentUser, this.softwareModuleRepository.deleteSoftwareModule(System.currentTimeMillis(), currentUser,
assignedModuleIds.toArray(new Long[0])); assignedModuleIds.toArray(new Long[0]));
} }
} }
@@ -366,20 +352,16 @@ public class SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Slice<SoftwareModule> findSoftwareModulesAll(@NotNull final Pageable pageable) { public Slice<SoftwareModule> findSoftwareModulesAll(@NotNull final Pageable pageable) {
final List<Specification<SoftwareModule>> specList = new ArrayList<Specification<SoftwareModule>>(); final List<Specification<SoftwareModule>> specList = new ArrayList<>();
Specification<SoftwareModule> spec = SoftwareModuleSpecification.isDeletedFalse(); Specification<SoftwareModule> spec = SoftwareModuleSpecification.isDeletedFalse();
specList.add(spec); specList.add(spec);
spec = new Specification<SoftwareModule>() { spec = (root, query, cb) -> {
@Override if (!query.getResultType().isAssignableFrom(Long.class)) {
public Predicate toPredicate(final Root<SoftwareModule> root, final CriteriaQuery<?> query, root.fetch(SoftwareModule_.type);
final CriteriaBuilder cb) {
if (!query.getResultType().isAssignableFrom(Long.class)) {
root.fetch(SoftwareModule_.type);
}
return cb.conjunction();
} }
return cb.conjunction();
}; };
specList.add(spec); specList.add(spec);
@@ -396,7 +378,7 @@ public class SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Long countSoftwareModulesAll() { public Long countSoftwareModulesAll() {
final List<Specification<SoftwareModule>> specList = new ArrayList<Specification<SoftwareModule>>(); final List<Specification<SoftwareModule>> specList = new ArrayList<>();
final Specification<SoftwareModule> spec = SoftwareModuleSpecification.isDeletedFalse(); final Specification<SoftwareModule> spec = SoftwareModuleSpecification.isDeletedFalse();
specList.add(spec); specList.add(spec);
@@ -416,7 +398,7 @@ public class SoftwareManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public SoftwareModule findSoftwareModuleWithDetails(@NotNull final Long id) { public SoftwareModule findSoftwareModuleWithDetails(@NotNull final Long id) {
return artifactManagement.findSoftwareModuleWithDetails(id); return this.artifactManagement.findSoftwareModuleWithDetails(id);
} }
/** /**
@@ -431,7 +413,7 @@ public class SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Page<SoftwareModule> findSoftwareModulesByPredicate(@NotNull final Specification<SoftwareModule> spec, public Page<SoftwareModule> findSoftwareModulesByPredicate(@NotNull final Specification<SoftwareModule> spec,
@NotNull final Pageable pageable) { @NotNull final Pageable pageable) {
return softwareModuleRepository.findAll(spec, pageable); return this.softwareModuleRepository.findAll(spec, pageable);
} }
/** /**
@@ -446,7 +428,7 @@ public class SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Page<SoftwareModuleType> findSoftwareModuleTypesByPredicate( public Page<SoftwareModuleType> findSoftwareModuleTypesByPredicate(
@NotNull final Specification<SoftwareModuleType> spec, @NotNull final Pageable pageable) { @NotNull final Specification<SoftwareModuleType> spec, @NotNull final Pageable pageable) {
return softwareModuleTypeRepository.findAll(spec, pageable); return this.softwareModuleTypeRepository.findAll(spec, pageable);
} }
/** /**
@@ -459,7 +441,7 @@ public class SoftwareManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public List<SoftwareModule> findSoftwareModulesById(@NotEmpty final List<Long> ids) { public List<SoftwareModule> findSoftwareModulesById(@NotEmpty final List<Long> ids) {
return softwareModuleRepository.findByIdIn(ids); return this.softwareModuleRepository.findByIdIn(ids);
} }
/** /**
@@ -479,7 +461,7 @@ public class SoftwareManagement {
public Slice<SoftwareModule> findSoftwareModuleByFilters(@NotNull final Pageable pageable, final String searchText, public Slice<SoftwareModule> findSoftwareModuleByFilters(@NotNull final Pageable pageable, final String searchText,
final SoftwareModuleType type) { final SoftwareModuleType type) {
final List<Specification<SoftwareModule>> specList = new ArrayList<Specification<SoftwareModule>>(); final List<Specification<SoftwareModule>> specList = new ArrayList<>();
Specification<SoftwareModule> spec = SoftwareModuleSpecification.isDeletedFalse(); Specification<SoftwareModule> spec = SoftwareModuleSpecification.isDeletedFalse();
specList.add(spec); specList.add(spec);
@@ -494,15 +476,11 @@ public class SoftwareManagement {
specList.add(spec); specList.add(spec);
} }
spec = new Specification<SoftwareModule>() { spec = (root, query, cb) -> {
@Override if (!query.getResultType().isAssignableFrom(Long.class)) {
public Predicate toPredicate(final Root<SoftwareModule> root, final CriteriaQuery<?> query, root.fetch(SoftwareModule_.type);
final CriteriaBuilder cb) {
if (!query.getResultType().isAssignableFrom(Long.class)) {
root.fetch(SoftwareModule_.type);
}
return cb.conjunction();
} }
return cb.conjunction();
}; };
specList.add(spec); specList.add(spec);
@@ -531,7 +509,7 @@ public class SoftwareManagement {
final List<CustomSoftwareModule> resultList = new ArrayList<>(); final List<CustomSoftwareModule> resultList = new ArrayList<>();
final int pageSize = pageable.getPageSize(); final int pageSize = pageable.getPageSize();
final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
// get the assigned software modules // get the assigned software modules
final CriteriaQuery<SoftwareModule> assignedQuery = cb.createQuery(SoftwareModule.class); final CriteriaQuery<SoftwareModule> assignedQuery = cb.createQuery(SoftwareModule.class);
@@ -551,7 +529,8 @@ public class SoftwareManagement {
// don't page the assigned query on database, we need all assigned // don't page the assigned query on database, we need all assigned
// software modules to filter // software modules to filter
// them out in the unassigned query // them out in the unassigned query
final List<SoftwareModule> assignedSoftwareModules = entityManager.createQuery(assignedQuery).getResultList(); final List<SoftwareModule> assignedSoftwareModules = this.entityManager.createQuery(assignedQuery)
.getResultList();
// map result // map result
if (pageable.getOffset() < assignedSoftwareModules.size()) { if (pageable.getOffset() < assignedSoftwareModules.size()) {
assignedSoftwareModules assignedSoftwareModules
@@ -581,7 +560,7 @@ public class SoftwareManagement {
unassignedQuery.where(unassignedSpec); unassignedQuery.where(unassignedSpec);
unassignedQuery.orderBy(cb.asc(unassignedRoot.get(SoftwareModule_.name)), unassignedQuery.orderBy(cb.asc(unassignedRoot.get(SoftwareModule_.name)),
cb.asc(unassignedRoot.get(SoftwareModule_.version))); cb.asc(unassignedRoot.get(SoftwareModule_.version)));
final List<SoftwareModule> unassignedSoftwareModules = entityManager.createQuery(unassignedQuery) final List<SoftwareModule> unassignedSoftwareModules = this.entityManager.createQuery(unassignedQuery)
.setFirstResult(Math.max(0, pageable.getOffset() - assignedSoftwareModules.size())) .setFirstResult(Math.max(0, pageable.getOffset() - assignedSoftwareModules.size()))
.setMaxResults(pageSize).getResultList(); .setMaxResults(pageSize).getResultList();
// map result // map result
@@ -592,7 +571,7 @@ public class SoftwareManagement {
private List<Specification<SoftwareModule>> buildSpecificationList(final String searchText, private List<Specification<SoftwareModule>> buildSpecificationList(final String searchText,
final SoftwareModuleType type) { final SoftwareModuleType type) {
final List<Specification<SoftwareModule>> specList = new ArrayList<Specification<SoftwareModule>>(); final List<Specification<SoftwareModule>> specList = new ArrayList<>();
if (!Strings.isNullOrEmpty(searchText)) { if (!Strings.isNullOrEmpty(searchText)) {
specList.add(SoftwareModuleSpecification.likeNameOrVersion(searchText)); specList.add(SoftwareModuleSpecification.likeNameOrVersion(searchText));
} }
@@ -631,7 +610,7 @@ public class SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Long countSoftwareModuleByFilters(final String searchText, final SoftwareModuleType type) { public Long countSoftwareModuleByFilters(final String searchText, final SoftwareModuleType type) {
final List<Specification<SoftwareModule>> specList = new ArrayList<Specification<SoftwareModule>>(); final List<Specification<SoftwareModule>> specList = new ArrayList<>();
Specification<SoftwareModule> spec = SoftwareModuleSpecification.isDeletedFalse(); Specification<SoftwareModule> spec = SoftwareModuleSpecification.isDeletedFalse();
specList.add(spec); specList.add(spec);
@@ -656,7 +635,7 @@ public class SoftwareManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Page<SoftwareModuleType> findSoftwareModuleTypesAll(@NotNull final Pageable pageable) { public Page<SoftwareModuleType> findSoftwareModuleTypesAll(@NotNull final Pageable pageable) {
return softwareModuleTypeRepository.findByDeleted(pageable, false); return this.softwareModuleTypeRepository.findByDeleted(pageable, false);
} }
/** /**
@@ -664,7 +643,7 @@ public class SoftwareManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Long countSoftwareModuleTypesAll() { public Long countSoftwareModuleTypesAll() {
return softwareModuleTypeRepository.countByDeleted(false); return this.softwareModuleTypeRepository.countByDeleted(false);
} }
/** /**
@@ -676,7 +655,7 @@ public class SoftwareManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public SoftwareModuleType findSoftwareModuleTypeByKey(@NotNull final String key) { public SoftwareModuleType findSoftwareModuleTypeByKey(@NotNull final String key) {
return softwareModuleTypeRepository.findByKey(key); return this.softwareModuleTypeRepository.findByKey(key);
} }
/** /**
@@ -688,7 +667,7 @@ public class SoftwareManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public SoftwareModuleType findSoftwareModuleTypeById(@NotNull final Long id) { public SoftwareModuleType findSoftwareModuleTypeById(@NotNull final Long id) {
return softwareModuleTypeRepository.findOne(id); return this.softwareModuleTypeRepository.findOne(id);
} }
/** /**
@@ -700,7 +679,7 @@ public class SoftwareManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public SoftwareModuleType findSoftwareModuleTypeByName(@NotNull final String name) { public SoftwareModuleType findSoftwareModuleTypeByName(@NotNull final String name) {
return softwareModuleTypeRepository.findByName(name); return this.softwareModuleTypeRepository.findByName(name);
} }
/** /**
@@ -718,7 +697,7 @@ public class SoftwareManagement {
throw new EntityAlreadyExistsException("Given type contains an Id!"); throw new EntityAlreadyExistsException("Given type contains an Id!");
} }
return softwareModuleTypeRepository.save(type); return this.softwareModuleTypeRepository.save(type);
} }
/** /**
@@ -746,13 +725,13 @@ public class SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
public void deleteSoftwareModuleType(@NotNull final SoftwareModuleType type) { public void deleteSoftwareModuleType(@NotNull final SoftwareModuleType type) {
if (softwareModuleRepository.countByType(type) > 0 if (this.softwareModuleRepository.countByType(type) > 0
|| distributionSetTypeRepository.countByElementsSmType(type) > 0) { || this.distributionSetTypeRepository.countByElementsSmType(type) > 0) {
final SoftwareModuleType toDelete = entityManager.merge(type); final SoftwareModuleType toDelete = this.entityManager.merge(type);
toDelete.setDeleted(true); toDelete.setDeleted(true);
softwareModuleTypeRepository.save(toDelete); this.softwareModuleTypeRepository.save(toDelete);
} else { } else {
softwareModuleTypeRepository.delete(type.getId()); this.softwareModuleTypeRepository.delete(type.getId());
} }
} }
@@ -767,7 +746,7 @@ public class SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Page<SoftwareModule> findSoftwareModuleByAssignedTo(@NotNull final Pageable pageable, public Page<SoftwareModule> findSoftwareModuleByAssignedTo(@NotNull final Pageable pageable,
@NotNull final DistributionSet set) { @NotNull final DistributionSet set) {
return softwareModuleRepository.findByAssignedTo(pageable, set); return this.softwareModuleRepository.findByAssignedTo(pageable, set);
} }
/** /**
@@ -783,7 +762,7 @@ public class SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Page<SoftwareModule> findSoftwareModuleByAssignedToAndType(@NotNull final Pageable pageable, public Page<SoftwareModule> findSoftwareModuleByAssignedToAndType(@NotNull final Pageable pageable,
@NotNull final DistributionSet set, @NotNull final SoftwareModuleType type) { @NotNull final DistributionSet set, @NotNull final SoftwareModuleType type) {
return softwareModuleRepository.findByAssignedToAndType(pageable, set, type); return this.softwareModuleRepository.findByAssignedToAndType(pageable, set, type);
} }
/** /**
@@ -800,15 +779,15 @@ public class SoftwareManagement {
@Modifying @Modifying
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
public SoftwareModuleMetadata createSoftwareModuleMetadata(@NotNull final SoftwareModuleMetadata metadata) { public SoftwareModuleMetadata createSoftwareModuleMetadata(@NotNull final SoftwareModuleMetadata metadata) {
if (softwareModuleMetadataRepository.exists(metadata.getId())) { if (this.softwareModuleMetadataRepository.exists(metadata.getId())) {
throwMetadataKeyAlreadyExists(metadata.getId().getKey()); throwMetadataKeyAlreadyExists(metadata.getId().getKey());
} }
// merge base software module so optLockRevision gets updated and audit // merge base software module so optLockRevision gets updated and audit
// log written because // log written because
// modifying metadata is modifying the base software module itself for // modifying metadata is modifying the base software module itself for
// auditing purposes. // auditing purposes.
entityManager.merge(metadata.getSoftwareModule()).setLastModifiedAt(-1L); this.entityManager.merge(metadata.getSoftwareModule()).setLastModifiedAt(-1L);
return softwareModuleMetadataRepository.save(metadata); return this.softwareModuleMetadataRepository.save(metadata);
} }
/** /**
@@ -829,8 +808,8 @@ public class SoftwareManagement {
for (final SoftwareModuleMetadata softwareModuleMetadata : metadata) { for (final SoftwareModuleMetadata softwareModuleMetadata : metadata) {
checkAndThrowAlreadyExistsIfSoftwareModuleMetadataExists(softwareModuleMetadata.getId()); checkAndThrowAlreadyExistsIfSoftwareModuleMetadataExists(softwareModuleMetadata.getId());
} }
metadata.forEach(m -> entityManager.merge(m.getSoftwareModule()).setLastModifiedAt(-1L)); metadata.forEach(m -> this.entityManager.merge(m.getSoftwareModule()).setLastModifiedAt(-1L));
return softwareModuleMetadataRepository.save(metadata); return this.softwareModuleMetadataRepository.save(metadata);
} }
/** /**
@@ -852,8 +831,8 @@ public class SoftwareManagement {
// touch it to update the lock revision because we are modifying the // touch it to update the lock revision because we are modifying the
// software module // software module
// indirectly // indirectly
entityManager.merge(metadata.getSoftwareModule()).setLastModifiedAt(-1L); this.entityManager.merge(metadata.getSoftwareModule()).setLastModifiedAt(-1L);
return softwareModuleMetadataRepository.save(metadata); return this.softwareModuleMetadataRepository.save(metadata);
} }
/** /**
@@ -866,7 +845,7 @@ public class SoftwareManagement {
@Modifying @Modifying
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
public void deleteSoftwareModuleMetadata(@NotNull final SwMetadataCompositeKey id) { public void deleteSoftwareModuleMetadata(@NotNull final SwMetadataCompositeKey id) {
softwareModuleMetadataRepository.delete(id); this.softwareModuleMetadataRepository.delete(id);
} }
/** /**
@@ -882,7 +861,7 @@ public class SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(@NotNull final Long swId, public Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(@NotNull final Long swId,
@NotNull final Pageable pageable) { @NotNull final Pageable pageable) {
return softwareModuleMetadataRepository.findBySoftwareModuleId(swId, pageable); return this.softwareModuleMetadataRepository.findBySoftwareModuleId(swId, pageable);
} }
/** /**
@@ -900,15 +879,14 @@ public class SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(final Long softwareModuleId, public Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(final Long softwareModuleId,
@NotNull final Specification<SoftwareModuleMetadata> spec, @NotNull final Pageable pageable) { @NotNull final Specification<SoftwareModuleMetadata> spec, @NotNull final Pageable pageable) {
return softwareModuleMetadataRepository.findAll(new Specification<SoftwareModuleMetadata>() { return this.softwareModuleMetadataRepository
@Override .findAll(
public Predicate toPredicate(final Root<SoftwareModuleMetadata> root, final CriteriaQuery<?> query, (Specification<SoftwareModuleMetadata>) (root, query,
final CriteriaBuilder cb) { cb) -> cb.and(
cb.equal(root.get(SoftwareModuleMetadata_.softwareModule)
return cb.and(cb.equal(root.get(SoftwareModuleMetadata_.softwareModule).get(SoftwareModule_.id), .get(SoftwareModule_.id), softwareModuleId),
softwareModuleId), spec.toPredicate(root, query, cb)); spec.toPredicate(root, query, cb)),
} pageable);
}, pageable);
} }
/** /**
@@ -923,7 +901,7 @@ public class SoftwareManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
public SoftwareModuleMetadata findOne(@NotNull final SwMetadataCompositeKey id) { public SoftwareModuleMetadata findOne(@NotNull final SwMetadataCompositeKey id) {
final SoftwareModuleMetadata findOne = softwareModuleMetadataRepository.findOne(id); final SoftwareModuleMetadata findOne = this.softwareModuleMetadataRepository.findOne(id);
if (findOne == null) { if (findOne == null) {
throw new EntityNotFoundException("Metadata with key '" + id.getKey() + "' does not exist"); throw new EntityNotFoundException("Metadata with key '" + id.getKey() + "' does not exist");
} }
@@ -931,7 +909,7 @@ public class SoftwareManagement {
} }
private void checkAndThrowAlreadyExistsIfSoftwareModuleMetadataExists(final SwMetadataCompositeKey metadataId) { private void checkAndThrowAlreadyExistsIfSoftwareModuleMetadataExists(final SwMetadataCompositeKey metadataId) {
if (softwareModuleMetadataRepository.exists(metadataId)) { if (this.softwareModuleMetadataRepository.exists(metadataId)) {
throw new EntityAlreadyExistsException( throw new EntityAlreadyExistsException(
"Metadata entry with key '" + metadataId.getKey() + "' already exists"); "Metadata entry with key '" + metadataId.getKey() + "' already exists");
} }

View File

@@ -77,13 +77,13 @@ public class Rollout extends NamedEntity {
private int rolloutGroupsCreated = 0; private int rolloutGroupsCreated = 0;
@Transient @Transient
private TotalTargetCountStatus totalTargetCountStatus; private transient TotalTargetCountStatus totalTargetCountStatus;
/** /**
* @return the distributionSet * @return the distributionSet
*/ */
public DistributionSet getDistributionSet() { public DistributionSet getDistributionSet() {
return distributionSet; return this.distributionSet;
} }
/** /**
@@ -98,7 +98,7 @@ public class Rollout extends NamedEntity {
* @return the rolloutGroups * @return the rolloutGroups
*/ */
public List<RolloutGroup> getRolloutGroups() { public List<RolloutGroup> getRolloutGroups() {
return rolloutGroups; return this.rolloutGroups;
} }
/** /**
@@ -113,7 +113,7 @@ public class Rollout extends NamedEntity {
* @return the targetFilterQuery * @return the targetFilterQuery
*/ */
public String getTargetFilterQuery() { public String getTargetFilterQuery() {
return targetFilterQuery; return this.targetFilterQuery;
} }
/** /**
@@ -128,7 +128,7 @@ public class Rollout extends NamedEntity {
* @return the status * @return the status
*/ */
public RolloutStatus getStatus() { public RolloutStatus getStatus() {
return status; return this.status;
} }
/** /**
@@ -143,7 +143,7 @@ public class Rollout extends NamedEntity {
* @return the lastCheck * @return the lastCheck
*/ */
public long getLastCheck() { public long getLastCheck() {
return lastCheck; return this.lastCheck;
} }
/** /**
@@ -158,7 +158,7 @@ public class Rollout extends NamedEntity {
* @return the actionType * @return the actionType
*/ */
public ActionType getActionType() { public ActionType getActionType() {
return actionType; return this.actionType;
} }
/** /**
@@ -173,7 +173,7 @@ public class Rollout extends NamedEntity {
* @return the forcedTime * @return the forcedTime
*/ */
public long getForcedTime() { public long getForcedTime() {
return forcedTime; return this.forcedTime;
} }
/** /**
@@ -188,7 +188,7 @@ public class Rollout extends NamedEntity {
* @return the totalTargets * @return the totalTargets
*/ */
public long getTotalTargets() { public long getTotalTargets() {
return totalTargets; return this.totalTargets;
} }
/** /**
@@ -203,7 +203,7 @@ public class Rollout extends NamedEntity {
* @return the rolloutGroupsTotal * @return the rolloutGroupsTotal
*/ */
public int getRolloutGroupsTotal() { public int getRolloutGroupsTotal() {
return rolloutGroupsTotal; return this.rolloutGroupsTotal;
} }
/** /**
@@ -218,7 +218,7 @@ public class Rollout extends NamedEntity {
* @return the rolloutGroupsCreated * @return the rolloutGroupsCreated
*/ */
public int getRolloutGroupsCreated() { public int getRolloutGroupsCreated() {
return rolloutGroupsCreated; return this.rolloutGroupsCreated;
} }
/** /**
@@ -233,10 +233,10 @@ public class Rollout extends NamedEntity {
* @return the totalTargetCountStatus * @return the totalTargetCountStatus
*/ */
public TotalTargetCountStatus getTotalTargetCountStatus() { public TotalTargetCountStatus getTotalTargetCountStatus() {
if (totalTargetCountStatus == null) { if (this.totalTargetCountStatus == null) {
this.totalTargetCountStatus = new TotalTargetCountStatus(totalTargets); this.totalTargetCountStatus = new TotalTargetCountStatus(this.totalTargets);
} }
return totalTargetCountStatus; return this.totalTargetCountStatus;
} }
/** /**
@@ -249,9 +249,9 @@ public class Rollout extends NamedEntity {
@Override @Override
public String toString() { public String toString() {
return "Rollout [rolloutGroups=" + rolloutGroups + ", targetFilterQuery=" + targetFilterQuery return "Rollout [rolloutGroups=" + this.rolloutGroups + ", targetFilterQuery=" + this.targetFilterQuery
+ ", distributionSet=" + distributionSet + ", status=" + status + ", lastCheck=" + lastCheck + ", distributionSet=" + this.distributionSet + ", status=" + this.status + ", lastCheck="
+ ", getName()=" + getName() + ", getId()=" + getId() + "]"; + this.lastCheck + ", getName()=" + getName() + ", getId()=" + getId() + "]";
} }
/** /**
@@ -259,7 +259,7 @@ public class Rollout extends NamedEntity {
* @author Michael Hirsch * @author Michael Hirsch
* *
*/ */
public static enum RolloutStatus { public enum RolloutStatus {
/** /**
* Rollouts is beeing created. * Rollouts is beeing created.

View File

@@ -8,6 +8,7 @@
*/ */
package org.eclipse.hawkbit.repository.model; package org.eclipse.hawkbit.repository.model;
import java.io.Serializable;
import java.util.List; import java.util.List;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
@@ -30,16 +31,18 @@ import javax.persistence.Table;
@IdClass(RolloutTargetGroupId.class) @IdClass(RolloutTargetGroupId.class)
@Entity @Entity
@Table(name = "sp_rollouttargetgroup") @Table(name = "sp_rollouttargetgroup")
public class RolloutTargetGroup { public class RolloutTargetGroup implements Serializable {
private static final long serialVersionUID = 1L;
@Id @Id
@ManyToOne(targetEntity = RolloutGroup.class, fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }) @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; private RolloutGroup rolloutGroup;
@Id @Id
@ManyToOne(targetEntity = Target.class, fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }) @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; private Target target;
@OneToMany(targetEntity = Action.class, fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }) @OneToMany(targetEntity = Action.class, fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST })
@@ -60,6 +63,6 @@ public class RolloutTargetGroup {
} }
public RolloutTargetGroupId getId() { public RolloutTargetGroupId getId() {
return new RolloutTargetGroupId(rolloutGroup, target); return new RolloutTargetGroupId(this.rolloutGroup, this.target);
} }
} }

View File

@@ -9,7 +9,7 @@
package org.eclipse.hawkbit.repository.model; package org.eclipse.hawkbit.repository.model;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.EnumMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -27,7 +27,7 @@ public class TotalTargetCountStatus {
SCHEDULED, RUNNING, ERROR, FINISHED, CANCELLED, NOTSTARTED SCHEDULED, RUNNING, ERROR, FINISHED, CANCELLED, NOTSTARTED
} }
private final Map<Status, Long> statusTotalCountMap = new HashMap<>(); private final Map<Status, Long> statusTotalCountMap = new EnumMap<>(Status.class);
private final Long totalTargetCount; private final Long totalTargetCount;
/** /**
@@ -60,7 +60,7 @@ public class TotalTargetCountStatus {
* @return the statusTotalCountMap the state map * @return the statusTotalCountMap the state map
*/ */
public Map<Status, Long> getStatusTotalCountMap() { public Map<Status, Long> getStatusTotalCountMap() {
return statusTotalCountMap; return this.statusTotalCountMap;
} }
/** /**
@@ -71,7 +71,7 @@ public class TotalTargetCountStatus {
* @return the current target count cannot be <null> * @return the current target count cannot be <null>
*/ */
public Long getTotalTargetCountByStatus(final Status status) { public Long getTotalTargetCountByStatus(final Status status) {
final Long count = statusTotalCountMap.get(status); final Long count = this.statusTotalCountMap.get(status);
return count == null ? 0L : count; return count == null ? 0L : count;
} }
@@ -87,39 +87,39 @@ public class TotalTargetCountStatus {
private final void mapActionStatusToTotalTargetCountStatus( private final void mapActionStatusToTotalTargetCountStatus(
final List<TotalTargetCountActionStatus> targetCountActionStatus) { final List<TotalTargetCountActionStatus> targetCountActionStatus) {
if (targetCountActionStatus == null) { if (targetCountActionStatus == null) {
statusTotalCountMap.put(TotalTargetCountStatus.Status.NOTSTARTED, totalTargetCount); this.statusTotalCountMap.put(TotalTargetCountStatus.Status.NOTSTARTED, this.totalTargetCount);
return; return;
} }
statusTotalCountMap.put(Status.RUNNING, 0L); this.statusTotalCountMap.put(Status.RUNNING, 0L);
Long notStartedTargetCount = totalTargetCount; Long notStartedTargetCount = this.totalTargetCount;
for (final TotalTargetCountActionStatus item : targetCountActionStatus) { for (final TotalTargetCountActionStatus item : targetCountActionStatus) {
switch (item.getStatus()) { switch (item.getStatus()) {
case SCHEDULED: case SCHEDULED:
statusTotalCountMap.put(Status.SCHEDULED, item.getCount()); this.statusTotalCountMap.put(Status.SCHEDULED, item.getCount());
break; break;
case ERROR: case ERROR:
statusTotalCountMap.put(Status.ERROR, item.getCount()); this.statusTotalCountMap.put(Status.ERROR, item.getCount());
break; break;
case FINISHED: case FINISHED:
statusTotalCountMap.put(Status.FINISHED, item.getCount()); this.statusTotalCountMap.put(Status.FINISHED, item.getCount());
break; break;
case RETRIEVED: case RETRIEVED:
case RUNNING: case RUNNING:
case WARNING: case WARNING:
case DOWNLOAD: case DOWNLOAD:
case CANCELING: case CANCELING:
final Long runningItemsCount = statusTotalCountMap.get(Status.RUNNING) + item.getCount(); final Long runningItemsCount = this.statusTotalCountMap.get(Status.RUNNING) + item.getCount();
statusTotalCountMap.put(Status.RUNNING, runningItemsCount); this.statusTotalCountMap.put(Status.RUNNING, runningItemsCount);
break; break;
case CANCELED: case CANCELED:
statusTotalCountMap.put(Status.CANCELLED, item.getCount()); this.statusTotalCountMap.put(Status.CANCELLED, item.getCount());
break; break;
default: default:
throw new IllegalArgumentException("State " + item.getStatus() + "is not valid"); throw new IllegalArgumentException("State " + item.getStatus() + "is not valid");
} }
notStartedTargetCount -= item.getCount(); notStartedTargetCount -= item.getCount();
} }
statusTotalCountMap.put(TotalTargetCountStatus.Status.NOTSTARTED, notStartedTargetCount); this.statusTotalCountMap.put(TotalTargetCountStatus.Status.NOTSTARTED, notStartedTargetCount);
} }
} }

View File

@@ -16,7 +16,19 @@ import org.eclipse.hawkbit.repository.model.RolloutGroup;
*/ */
public interface RolloutGroupConditionEvaluator { 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); boolean eval(Rollout rollout, RolloutGroup rolloutGroup, final String expression);
} }

View File

@@ -23,30 +23,15 @@ import org.springframework.stereotype.Component;
@Component("thresholdRolloutGroupErrorCondition") @Component("thresholdRolloutGroupErrorCondition")
public class ThresholdRolloutGroupErrorCondition implements RolloutGroupConditionEvaluator { public class ThresholdRolloutGroupErrorCondition implements RolloutGroupConditionEvaluator {
private static Logger logger = LoggerFactory.getLogger(ThresholdRolloutGroupErrorCondition.class); private static final Logger LOGGER = LoggerFactory.getLogger(ThresholdRolloutGroupErrorCondition.class);
@Autowired @Autowired
private ActionRepository actionRepository; 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 @Override
public boolean eval(final Rollout rollout, final RolloutGroup rolloutGroup, final String expression) { public boolean eval(final Rollout rollout, final RolloutGroup rolloutGroup, final String expression) {
final Long totalGroup = actionRepository.countByRolloutAndRolloutGroup(rollout, rolloutGroup); final Long totalGroup = this.actionRepository.countByRolloutAndRolloutGroup(rollout, rolloutGroup);
final Long error = actionRepository.countByRolloutIdAndRolloutGroupIdAndStatus(rollout.getId(), final Long error = this.actionRepository.countByRolloutIdAndRolloutGroupIdAndStatus(rollout.getId(),
rolloutGroup.getId(), Action.Status.ERROR); rolloutGroup.getId(), Action.Status.ERROR);
try { try {
final Integer threshold = Integer.valueOf(expression); final Integer threshold = Integer.valueOf(expression);
@@ -60,7 +45,7 @@ public class ThresholdRolloutGroupErrorCondition implements RolloutGroupConditio
// calculate threshold // calculate threshold
return ((float) error / (float) totalGroup) > ((float) threshold / 100F); return ((float) error / (float) totalGroup) > ((float) threshold / 100F);
} catch (final NumberFormatException e) { } catch (final NumberFormatException e) {
logger.error("Cannot evaluate condition expression " + expression, e); LOGGER.error("Cannot evaluate condition expression " + expression, e);
return false; return false;
} }
} }

View File

@@ -12,6 +12,8 @@ import org.eclipse.hawkbit.repository.ActionRepository;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.RolloutGroup; 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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -20,39 +22,31 @@ import org.springframework.stereotype.Component;
*/ */
@Component("thresholdRolloutGroupSuccessCondition") @Component("thresholdRolloutGroupSuccessCondition")
public class ThresholdRolloutGroupSuccessCondition implements RolloutGroupConditionEvaluator { public class ThresholdRolloutGroupSuccessCondition implements RolloutGroupConditionEvaluator {
private static final Logger LOGGER = LoggerFactory.getLogger(ThresholdRolloutGroupSuccessCondition.class);
@Autowired @Autowired
private ActionRepository actionRepository; 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 @Override
public boolean eval(final Rollout rollout, final RolloutGroup rolloutGroup, final String expression) { public boolean eval(final Rollout rollout, final RolloutGroup rolloutGroup, final String expression) {
final Long totalGroup = rolloutGroup.getTotalTargets(); 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); rolloutGroup.getId(), Action.Status.FINISHED);
final Integer threshold = Integer.valueOf(expression); try {
final Integer threshold = Integer.valueOf(expression);
if (totalGroup == 0) { if (totalGroup == 0) {
// in case e.g. targets has been deleted we don't have any actions // in case e.g. targets has been deleted we don't have any
// left for this group, so the group is finished // actions
return true; // 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);
} }
} }

View File

@@ -75,7 +75,7 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener {
private SpringViewProvider viewProvider; private SpringViewProvider viewProvider;
@Autowired @Autowired
private ApplicationContext context; private transient ApplicationContext context;
@Autowired @Autowired
private I18N i18n; private I18N i18n;
@@ -89,7 +89,7 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener {
private ErrorView errorview; private ErrorView errorview;
@Autowired @Autowired
protected EventBus.SessionEventBus eventBus; protected transient EventBus.SessionEventBus eventBus;
/** /**
* An {@link com.google.common.eventbus.EventBus} subscriber which * An {@link com.google.common.eventbus.EventBus} subscriber which
@@ -103,21 +103,28 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener {
@AllowConcurrentEvents @AllowConcurrentEvents
public void dispatch(final org.eclipse.hawkbit.eventbus.event.Event event) { public void dispatch(final org.eclipse.hawkbit.eventbus.event.Event event) {
final VaadinSession session = getSession(); final VaadinSession session = getSession();
if (session != null && session.getState() == State.OPEN) { if (session == null || session.getState() != State.OPEN) {
final WrappedSession wrappedSession = session.getSession(); return;
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);
}
}
}
} }
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(this.eventBus, session, userContext, event));
} finally {
SecurityContextHolder.setContext(oldContext);
}
} }
protected boolean eventSecurityCheck(final SecurityContext userContext, protected boolean eventSecurityCheck(final SecurityContext userContext,
@@ -149,7 +156,7 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener {
protected void init(final VaadinRequest vaadinRequest) { protected void init(final VaadinRequest vaadinRequest) {
LOG.info("ManagementUI init starts uiid - {}", getUI().getUIId()); LOG.info("ManagementUI init starts uiid - {}", getUI().getUIId());
addDetachListener(this); addDetachListener(this);
SpringContextHelper.setContext(context); SpringContextHelper.setContext(this.context);
Responsive.makeResponsive(this); Responsive.makeResponsive(this);
addStyleName(ValoTheme.UI_WITH_MENU); addStyleName(ValoTheme.UI_WITH_MENU);
@@ -158,25 +165,25 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener {
final HorizontalLayout rootLayout = new HorizontalLayout(); final HorizontalLayout rootLayout = new HorizontalLayout();
rootLayout.setSizeFull(); rootLayout.setSizeFull();
dashboardMenu.init(); this.dashboardMenu.init();
dashboardMenu.setResponsive(Boolean.TRUE); this.dashboardMenu.setResponsive(Boolean.TRUE);
final VerticalLayout contentVerticalLayout = new VerticalLayout(); final VerticalLayout contentVerticalLayout = new VerticalLayout();
contentVerticalLayout.addComponent(buildHeader()); contentVerticalLayout.addComponent(buildHeader());
contentVerticalLayout.setSizeFull(); contentVerticalLayout.setSizeFull();
rootLayout.addComponent(dashboardMenu); rootLayout.addComponent(this.dashboardMenu);
rootLayout.addComponent(contentVerticalLayout); rootLayout.addComponent(contentVerticalLayout);
content = new HorizontalLayout(); this.content = new HorizontalLayout();
contentVerticalLayout.addComponent(content); contentVerticalLayout.addComponent(this.content);
content.setStyleName("view-content"); this.content.setStyleName("view-content");
content.setSizeFull(); this.content.setSizeFull();
rootLayout.setExpandRatio(contentVerticalLayout, 1.0f); rootLayout.setExpandRatio(contentVerticalLayout, 1.0f);
contentVerticalLayout.setStyleName("main-content"); contentVerticalLayout.setStyleName("main-content");
contentVerticalLayout.setExpandRatio(content, 1.0F); contentVerticalLayout.setExpandRatio(this.content, 1.0F);
setContent(rootLayout); setContent(rootLayout);
final Resource resource = context final Resource resource = this.context
.getResource("classpath:/VAADIN/themes/" + UI.getCurrent().getTheme() + "/layouts/footer.html"); .getResource("classpath:/VAADIN/themes/" + UI.getCurrent().getTheme() + "/layouts/footer.html");
try { try {
final CustomLayout customLayout = new CustomLayout(resource.getInputStream()); final CustomLayout customLayout = new CustomLayout(resource.getInputStream());
@@ -185,7 +192,7 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener {
} catch (final IOException ex) { } catch (final IOException ex) {
LOG.error("Footer file is missing", ex); LOG.error("Footer file is missing", ex);
} }
final Navigator navigator = new Navigator(this, content); final Navigator navigator = new Navigator(this, this.content);
navigator.addViewChangeListener(new ViewChangeListener() { navigator.addViewChangeListener(new ViewChangeListener() {
@Override @Override
public boolean beforeViewChange(final ViewChangeEvent event) { public boolean beforeViewChange(final ViewChangeEvent event) {
@@ -194,17 +201,17 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener {
@Override @Override
public void afterViewChange(final ViewChangeEvent event) { public void afterViewChange(final ViewChangeEvent event) {
final DashboardMenuItem view = dashboardMenu.getByViewName(event.getViewName()); final DashboardMenuItem view = HawkbitUI.this.dashboardMenu.getByViewName(event.getViewName());
dashboardMenu.postViewChange(new PostViewChangeEvent(view)); HawkbitUI.this.dashboardMenu.postViewChange(new PostViewChangeEvent(view));
if (view == null) { if (view == null) {
content.setCaption(null); HawkbitUI.this.content.setCaption(null);
return; return;
} }
content.setCaption(view.getDashboardCaptionLong()); HawkbitUI.this.content.setCaption(view.getDashboardCaptionLong());
} }
}); });
navigator.setErrorView(errorview); navigator.setErrorView(this.errorview);
navigator.addProvider(new ManagementViewProvider()); navigator.addProvider(new ManagementViewProvider());
setNavigator(navigator); setNavigator(navigator);
navigator.addView(EMPTY_VIEW, new Navigator.EmptyView()); navigator.addView(EMPTY_VIEW, new Navigator.EmptyView());
@@ -214,7 +221,7 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener {
setLocale(new Locale(locale)); setLocale(new Locale(locale));
UI.getCurrent().setErrorHandler(new SPUIErrorHandler()); UI.getCurrent().setErrorHandler(new SPUIErrorHandler());
LOG.info("Current locale of the application is : {}", i18n.getLocale()); LOG.info("Current locale of the application is : {}", this.i18n.getLocale());
} }
private Component buildHeader() { private Component buildHeader() {
@@ -269,20 +276,20 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener {
@Override @Override
public String getViewName(final String viewAndParameters) { public String getViewName(final String viewAndParameters) {
return viewProvider.getViewName(getStartView(viewAndParameters)); return HawkbitUI.this.viewProvider.getViewName(getStartView(viewAndParameters));
} }
@Override @Override
public View getView(final String viewName) { public View getView(final String viewName) {
return viewProvider.getView(getStartView(viewName)); return HawkbitUI.this.viewProvider.getView(getStartView(viewName));
} }
private String getStartView(final String viewName) { private String getStartView(final String viewName) {
final DashboardMenuItem view = dashboardMenu.getByViewName(viewName); final DashboardMenuItem view = HawkbitUI.this.dashboardMenu.getByViewName(viewName);
if ("".equals(viewName) && !dashboardMenu.isAccessibleViewsEmpty()) { if ("".equals(viewName) && !HawkbitUI.this.dashboardMenu.isAccessibleViewsEmpty()) {
return dashboardMenu.getInitialViewName(); return HawkbitUI.this.dashboardMenu.getInitialViewName();
} }
if (view == null || dashboardMenu.isAccessDenied(viewName)) { if (view == null || HawkbitUI.this.dashboardMenu.isAccessDenied(viewName)) {
return " "; return " ";
} }
return viewName; return viewName;

View File

@@ -90,12 +90,12 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind
*/ */
@Override @Override
protected Map<String, ConfirmationTab> getConfimrationTabs() { protected Map<String, ConfirmationTab> getConfimrationTabs() {
final Map<String, ConfirmationTab> tabs = new HashMap<String, ConfirmationTab>(); final Map<String, ConfirmationTab> tabs = new HashMap<>();
if (!artifactUploadState.getDeleteSofwareModules().isEmpty()) { if (!this.artifactUploadState.getDeleteSofwareModules().isEmpty()) {
tabs.put(i18n.get("caption.delete.swmodule.accordion.tab"), createSMDeleteConfirmationTab()); tabs.put(this.i18n.get("caption.delete.swmodule.accordion.tab"), createSMDeleteConfirmationTab());
} }
if (!artifactUploadState.getSelectedDeleteSWModuleTypes().isEmpty()) { if (!this.artifactUploadState.getSelectedDeleteSWModuleTypes().isEmpty()) {
tabs.put(i18n.get("caption.delete.sw.module.type.accordion.tab"), createSMtypeDeleteConfirmationTab()); tabs.put(this.i18n.get("caption.delete.sw.module.type.accordion.tab"), createSMtypeDeleteConfirmationTab());
} }
return tabs; return tabs;
} }
@@ -105,10 +105,10 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind
tab.getConfirmAll().setId(SPUIComponetIdProvider.SW_DELETE_ALL); tab.getConfirmAll().setId(SPUIComponetIdProvider.SW_DELETE_ALL);
tab.getConfirmAll().setIcon(FontAwesome.TRASH_O); tab.getConfirmAll().setIcon(FontAwesome.TRASH_O);
tab.getConfirmAll().setCaption(i18n.get("button.delete.all")); tab.getConfirmAll().setCaption(this.i18n.get("button.delete.all"));
tab.getConfirmAll().addClickListener(event -> deleteSMAll(tab)); tab.getConfirmAll().addClickListener(event -> deleteSMAll(tab));
tab.getDiscardAll().setCaption(i18n.get("button.discard.all")); tab.getDiscardAll().setCaption(this.i18n.get("button.discard.all"));
tab.getDiscardAll().addClickListener(event -> discardSMAll(tab)); tab.getDiscardAll().addClickListener(event -> discardSMAll(tab));
// Add items container to the table. // Add items container to the table.
@@ -131,8 +131,8 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind
if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) {
visibleColumnIds.add(SW_MODULE_NAME_MSG); visibleColumnIds.add(SW_MODULE_NAME_MSG);
visibleColumnIds.add(SW_DISCARD_CHGS); visibleColumnIds.add(SW_DISCARD_CHGS);
visibleColumnLabels.add(i18n.get("upload.swModuleTable.header")); visibleColumnLabels.add(this.i18n.get("upload.swModuleTable.header"));
visibleColumnLabels.add(i18n.get("header.second.deletetarget.table")); visibleColumnLabels.add(this.i18n.get("header.second.deletetarget.table"));
} }
tab.getTable().setVisibleColumns(visibleColumnIds.toArray()); tab.getTable().setVisibleColumns(visibleColumnIds.toArray());
tab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0])); tab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0]));
@@ -153,12 +153,11 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind
final IndexedContainer swcontactContainer = new IndexedContainer(); final IndexedContainer swcontactContainer = new IndexedContainer();
swcontactContainer.addContainerProperty("SWModuleId", String.class, ""); swcontactContainer.addContainerProperty("SWModuleId", String.class, "");
swcontactContainer.addContainerProperty(SW_MODULE_NAME_MSG, String.class, ""); swcontactContainer.addContainerProperty(SW_MODULE_NAME_MSG, String.class, "");
Item item = null; for (final Long swModuleID : this.artifactUploadState.getDeleteSofwareModules().keySet()) {
for (final Long swModuleID : artifactUploadState.getDeleteSofwareModules().keySet()) { final Item item = swcontactContainer.addItem(swModuleID);
item = swcontactContainer.addItem(swModuleID);
item.getItemProperty("SWModuleId").setValue(swModuleID.toString()); item.getItemProperty("SWModuleId").setValue(swModuleID.toString());
item.getItemProperty(SW_MODULE_NAME_MSG) item.getItemProperty(SW_MODULE_NAME_MSG)
.setValue(artifactUploadState.getDeleteSofwareModules().get(swModuleID)); .setValue(this.artifactUploadState.getDeleteSofwareModules().get(swModuleID));
} }
return swcontactContainer; return swcontactContainer;
} }
@@ -166,56 +165,56 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind
private void discardSoftwareDelete(final Button.ClickEvent event, final Object itemId, final ConfirmationTab tab) { private void discardSoftwareDelete(final Button.ClickEvent event, final Object itemId, final ConfirmationTab tab) {
final Long swmoduleId = (Long) ((Button) event.getComponent()).getData(); final Long swmoduleId = (Long) ((Button) event.getComponent()).getData();
if (null != artifactUploadState.getDeleteSofwareModules() if (null != this.artifactUploadState.getDeleteSofwareModules()
&& !artifactUploadState.getDeleteSofwareModules().isEmpty() && !this.artifactUploadState.getDeleteSofwareModules().isEmpty()
&& artifactUploadState.getDeleteSofwareModules().containsKey(swmoduleId)) { && this.artifactUploadState.getDeleteSofwareModules().containsKey(swmoduleId)) {
artifactUploadState.getDeleteSofwareModules().remove(swmoduleId); this.artifactUploadState.getDeleteSofwareModules().remove(swmoduleId);
} }
tab.getTable().getContainerDataSource().removeItem(itemId); tab.getTable().getContainerDataSource().removeItem(itemId);
final int deleteCount = tab.getTable().size(); final int deleteCount = tab.getTable().size();
if (0 == deleteCount) { if (0 == deleteCount) {
removeCurrentTab(tab); removeCurrentTab(tab);
eventBus.publish(this, UploadArtifactUIEvent.DISCARD_ALL_DELETE_SOFTWARE); this.eventBus.publish(this, UploadArtifactUIEvent.DISCARD_ALL_DELETE_SOFTWARE);
} else { } else {
eventBus.publish(this, UploadArtifactUIEvent.DISCARD_DELETE_SOFTWARE); this.eventBus.publish(this, UploadArtifactUIEvent.DISCARD_DELETE_SOFTWARE);
} }
} }
private void deleteSMAll(final ConfirmationTab tab) { private void deleteSMAll(final ConfirmationTab tab) {
final Set<Long> swmoduleIds = artifactUploadState.getDeleteSofwareModules().keySet(); final Set<Long> swmoduleIds = this.artifactUploadState.getDeleteSofwareModules().keySet();
softwareManagement.deleteSoftwareModules(swmoduleIds); this.softwareManagement.deleteSoftwareModules(swmoduleIds);
addToConsolitatedMsg(FontAwesome.TRASH_O.getHtml() + SPUILabelDefinitions.HTML_SPACE addToConsolitatedMsg(FontAwesome.TRASH_O.getHtml() + SPUILabelDefinitions.HTML_SPACE
+ i18n.get("message.swModule.deleted", artifactUploadState.getDeleteSofwareModules().size())); + this.i18n.get("message.swModule.deleted", this.artifactUploadState.getDeleteSofwareModules().size()));
/* /*
* Check if any information / files pending to upload for the deleted * Check if any information / files pending to upload for the deleted
* software modules. If so, then delete the files from the upload list. * software modules. If so, then delete the files from the upload list.
*/ */
final List<CustomFile> tobeRemoved = new ArrayList<>(); final List<CustomFile> tobeRemoved = new ArrayList<>();
for (final Long id : swmoduleIds) { for (final Long id : swmoduleIds) {
final String deleteSoftwareNameVersion = artifactUploadState.getDeleteSofwareModules().get(id); final String deleteSoftwareNameVersion = this.artifactUploadState.getDeleteSofwareModules().get(id);
for (final CustomFile customFile : artifactUploadState.getFileSelected()) { for (final CustomFile customFile : this.artifactUploadState.getFileSelected()) {
final String swNameVersion = HawkbitCommonUtil.getFormattedNameVersion( final String swNameVersion = HawkbitCommonUtil.getFormattedNameVersion(
customFile.getBaseSoftwareModuleName(), customFile.getBaseSoftwareModuleVersion()); customFile.getBaseSoftwareModuleName(), customFile.getBaseSoftwareModuleVersion());
if (HawkbitCommonUtil.bothSame(deleteSoftwareNameVersion, swNameVersion)) { if (deleteSoftwareNameVersion != null && deleteSoftwareNameVersion.equals(swNameVersion)) {
tobeRemoved.add(customFile); tobeRemoved.add(customFile);
} }
} }
} }
if (!tobeRemoved.isEmpty()) { if (!tobeRemoved.isEmpty()) {
artifactUploadState.getFileSelected().removeAll(tobeRemoved); this.artifactUploadState.getFileSelected().removeAll(tobeRemoved);
} }
artifactUploadState.getDeleteSofwareModules().clear(); this.artifactUploadState.getDeleteSofwareModules().clear();
removeCurrentTab(tab); removeCurrentTab(tab);
setActionMessage(i18n.get("message.software.delete.success")); setActionMessage(this.i18n.get("message.software.delete.success"));
eventBus.publish(this, UploadArtifactUIEvent.DELETED_ALL_SOFWARE); this.eventBus.publish(this, UploadArtifactUIEvent.DELETED_ALL_SOFWARE);
} }
private void discardSMAll(final ConfirmationTab tab) { private void discardSMAll(final ConfirmationTab tab) {
removeCurrentTab(tab); removeCurrentTab(tab);
artifactUploadState.getDeleteSofwareModules().clear(); this.artifactUploadState.getDeleteSofwareModules().clear();
setActionMessage(i18n.get("message.software.discard.success")); setActionMessage(this.i18n.get("message.software.discard.success"));
eventBus.publish(this, UploadArtifactUIEvent.DISCARD_ALL_DELETE_SOFTWARE); this.eventBus.publish(this, UploadArtifactUIEvent.DISCARD_ALL_DELETE_SOFTWARE);
} }
private ConfirmationTab createSMtypeDeleteConfirmationTab() { private ConfirmationTab createSMtypeDeleteConfirmationTab() {
@@ -223,10 +222,10 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind
tab.getConfirmAll().setId(SPUIComponetIdProvider.SAVE_DELETE_SW_MODULE_TYPE); tab.getConfirmAll().setId(SPUIComponetIdProvider.SAVE_DELETE_SW_MODULE_TYPE);
tab.getConfirmAll().setIcon(FontAwesome.TRASH_O); tab.getConfirmAll().setIcon(FontAwesome.TRASH_O);
tab.getConfirmAll().setCaption(i18n.get("button.delete.all")); tab.getConfirmAll().setCaption(this.i18n.get("button.delete.all"));
tab.getConfirmAll().addClickListener(event -> deleteSMtypeAll(tab)); tab.getConfirmAll().addClickListener(event -> deleteSMtypeAll(tab));
tab.getDiscardAll().setCaption(i18n.get("button.discard.all")); tab.getDiscardAll().setCaption(this.i18n.get("button.discard.all"));
tab.getDiscardAll().addClickListener(event -> discardSMtypeAll(tab)); tab.getDiscardAll().addClickListener(event -> discardSMtypeAll(tab));
// Add items container to the table. // Add items container to the table.
@@ -252,8 +251,8 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind
if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) {
visibleColumnIds.add(SW_MODULE_TYPE_NAME); visibleColumnIds.add(SW_MODULE_TYPE_NAME);
visibleColumnIds.add(DISCARD); visibleColumnIds.add(DISCARD);
visibleColumnLabels.add(i18n.get("header.first.delete.swmodule.type.table")); visibleColumnLabels.add(this.i18n.get("header.first.delete.swmodule.type.table"));
visibleColumnLabels.add(i18n.get("header.second.delete.swmodule.type.table")); visibleColumnLabels.add(this.i18n.get("header.second.delete.swmodule.type.table"));
} }
tab.getTable().setVisibleColumns(visibleColumnIds.toArray()); tab.getTable().setVisibleColumns(visibleColumnIds.toArray());
@@ -271,7 +270,7 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind
private Container getSWModuleTypeTableContainer() { private Container getSWModuleTypeTableContainer() {
final IndexedContainer contactContainer = new IndexedContainer(); final IndexedContainer contactContainer = new IndexedContainer();
contactContainer.addContainerProperty(SW_MODULE_TYPE_NAME, String.class, ""); contactContainer.addContainerProperty(SW_MODULE_TYPE_NAME, String.class, "");
for (final String swModuleTypeName : artifactUploadState.getSelectedDeleteSWModuleTypes()) { for (final String swModuleTypeName : this.artifactUploadState.getSelectedDeleteSWModuleTypes()) {
final Item saveTblitem = contactContainer.addItem(swModuleTypeName); final Item saveTblitem = contactContainer.addItem(swModuleTypeName);
saveTblitem.getItemProperty(SW_MODULE_TYPE_NAME).setValue(swModuleTypeName); saveTblitem.getItemProperty(SW_MODULE_TYPE_NAME).setValue(swModuleTypeName);
} }
@@ -280,40 +279,40 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind
private void discardSoftwareTypeDelete(final String discardSWModuleType, final Object itemId, private void discardSoftwareTypeDelete(final String discardSWModuleType, final Object itemId,
final ConfirmationTab tab) { final ConfirmationTab tab) {
if (null != artifactUploadState.getSelectedDeleteSWModuleTypes() if (null != this.artifactUploadState.getSelectedDeleteSWModuleTypes()
&& !artifactUploadState.getSelectedDeleteSWModuleTypes().isEmpty() && !this.artifactUploadState.getSelectedDeleteSWModuleTypes().isEmpty()
&& artifactUploadState.getSelectedDeleteSWModuleTypes().contains(discardSWModuleType)) { && this.artifactUploadState.getSelectedDeleteSWModuleTypes().contains(discardSWModuleType)) {
artifactUploadState.getSelectedDeleteSWModuleTypes().remove(discardSWModuleType); this.artifactUploadState.getSelectedDeleteSWModuleTypes().remove(discardSWModuleType);
} }
tab.getTable().getContainerDataSource().removeItem(itemId); tab.getTable().getContainerDataSource().removeItem(itemId);
final int deleteCount = tab.getTable().size(); final int deleteCount = tab.getTable().size();
if (0 == deleteCount) { if (0 == deleteCount) {
removeCurrentTab(tab); removeCurrentTab(tab);
eventBus.publish(this, UploadArtifactUIEvent.DISCARD_ALL_DELETE_SOFTWARE_TYPE); this.eventBus.publish(this, UploadArtifactUIEvent.DISCARD_ALL_DELETE_SOFTWARE_TYPE);
} else { } else {
eventBus.publish(this, UploadArtifactUIEvent.DISCARD_DELETE_SOFTWARE_TYPE); this.eventBus.publish(this, UploadArtifactUIEvent.DISCARD_DELETE_SOFTWARE_TYPE);
} }
} }
private void deleteSMtypeAll(final ConfirmationTab tab) { private void deleteSMtypeAll(final ConfirmationTab tab) {
final int deleteSWModuleTypeCount = artifactUploadState.getSelectedDeleteSWModuleTypes().size(); final int deleteSWModuleTypeCount = this.artifactUploadState.getSelectedDeleteSWModuleTypes().size();
for (final String swModuleTypeName : artifactUploadState.getSelectedDeleteSWModuleTypes()) { for (final String swModuleTypeName : this.artifactUploadState.getSelectedDeleteSWModuleTypes()) {
softwareManagement this.softwareManagement
.deleteSoftwareModuleType(softwareManagement.findSoftwareModuleTypeByName(swModuleTypeName)); .deleteSoftwareModuleType(this.softwareManagement.findSoftwareModuleTypeByName(swModuleTypeName));
} }
addToConsolitatedMsg(FontAwesome.TASKS.getHtml() + SPUILabelDefinitions.HTML_SPACE addToConsolitatedMsg(FontAwesome.TASKS.getHtml() + SPUILabelDefinitions.HTML_SPACE
+ i18n.get("message.sw.module.type.delete", new Object[] { deleteSWModuleTypeCount })); + this.i18n.get("message.sw.module.type.delete", new Object[] { deleteSWModuleTypeCount }));
artifactUploadState.getSelectedDeleteSWModuleTypes().clear(); this.artifactUploadState.getSelectedDeleteSWModuleTypes().clear();
removeCurrentTab(tab); removeCurrentTab(tab);
setActionMessage(i18n.get("message.software.type.delete.success")); setActionMessage(this.i18n.get("message.software.type.delete.success"));
eventBus.publish(this, UploadArtifactUIEvent.DELETED_ALL_SOFWARE_TYPE); this.eventBus.publish(this, UploadArtifactUIEvent.DELETED_ALL_SOFWARE_TYPE);
} }
private void discardSMtypeAll(final ConfirmationTab tab) { private void discardSMtypeAll(final ConfirmationTab tab) {
removeCurrentTab(tab); removeCurrentTab(tab);
artifactUploadState.getSelectedDeleteSWModuleTypes().clear(); this.artifactUploadState.getSelectedDeleteSWModuleTypes().clear();
setActionMessage(i18n.get("message.software.type.discard.success")); setActionMessage(this.i18n.get("message.software.type.discard.success"));
eventBus.publish(this, UploadArtifactUIEvent.DISCARD_ALL_DELETE_SOFTWARE_TYPE); this.eventBus.publish(this, UploadArtifactUIEvent.DISCARD_ALL_DELETE_SOFTWARE_TYPE);
} }
} }

View File

@@ -38,13 +38,13 @@ public class ArtifactUploadState implements Serializable {
private final Map<Long, String> deleteSofwareModules = new HashMap<>(); private final Map<Long, String> deleteSofwareModules = new HashMap<>();
private final Set<CustomFile> fileSelected = new HashSet<CustomFile>(); private final Set<CustomFile> fileSelected = new HashSet<>();
private Long selectedBaseSwModuleId; private Long selectedBaseSwModuleId;
private SoftwareModule selectedBaseSoftwareModule; private SoftwareModule selectedBaseSoftwareModule;
private final Map<String, SoftwareModule> baseSwModuleList = new HashMap<String, SoftwareModule>(); private final Map<String, SoftwareModule> baseSwModuleList = new HashMap<>();
private Set<Long> selectedSoftwareModules = Collections.emptySet(); private Set<Long> selectedSoftwareModules = Collections.emptySet();
@@ -64,21 +64,21 @@ public class ArtifactUploadState implements Serializable {
* @return * @return
*/ */
public SoftwareModuleFilters getSoftwareModuleFilters() { public SoftwareModuleFilters getSoftwareModuleFilters() {
return softwareModuleFilters; return this.softwareModuleFilters;
} }
/** /**
* @return the selectedSofwareModules * @return the selectedSofwareModules
*/ */
public Map<Long, String> getDeleteSofwareModules() { public Map<Long, String> getDeleteSofwareModules() {
return deleteSofwareModules; return this.deleteSofwareModules;
} }
/** /**
* @return the fileSelected * @return the fileSelected
*/ */
public Set<CustomFile> getFileSelected() { public Set<CustomFile> getFileSelected() {
return fileSelected; return this.fileSelected;
} }
/** /**
@@ -116,14 +116,14 @@ public class ArtifactUploadState implements Serializable {
* @return the baseSwModuleList * @return the baseSwModuleList
*/ */
public Map<String, SoftwareModule> getBaseSwModuleList() { public Map<String, SoftwareModule> getBaseSwModuleList() {
return baseSwModuleList; return this.baseSwModuleList;
} }
/** /**
* @return the selectedSoftwareModules * @return the selectedSoftwareModules
*/ */
public Set<Long> getSelectedSoftwareModules() { public Set<Long> getSelectedSoftwareModules() {
return selectedSoftwareModules; return this.selectedSoftwareModules;
} }
/** /**
@@ -138,7 +138,7 @@ public class ArtifactUploadState implements Serializable {
* @return the swTypeFilterClosed * @return the swTypeFilterClosed
*/ */
public boolean isSwTypeFilterClosed() { public boolean isSwTypeFilterClosed() {
return swTypeFilterClosed; return this.swTypeFilterClosed;
} }
/** /**
@@ -153,7 +153,7 @@ public class ArtifactUploadState implements Serializable {
* @return the isSwModuleTableMaximized * @return the isSwModuleTableMaximized
*/ */
public boolean isSwModuleTableMaximized() { public boolean isSwModuleTableMaximized() {
return isSwModuleTableMaximized; return this.isSwModuleTableMaximized;
} }
/** /**
@@ -165,14 +165,14 @@ public class ArtifactUploadState implements Serializable {
} }
public Set<String> getSelectedDeleteSWModuleTypes() { public Set<String> getSelectedDeleteSWModuleTypes() {
return selectedDeleteSWModuleTypes; return this.selectedDeleteSWModuleTypes;
} }
/** /**
* @return the isArtifactDetailsMaximized * @return the isArtifactDetailsMaximized
*/ */
public boolean isArtifactDetailsMaximized() { public boolean isArtifactDetailsMaximized() {
return isArtifactDetailsMaximized; return this.isArtifactDetailsMaximized;
} }
/** /**
@@ -187,7 +187,7 @@ public class ArtifactUploadState implements Serializable {
* @return the noDataAvilableSoftwareModule * @return the noDataAvilableSoftwareModule
*/ */
public boolean isNoDataAvilableSoftwareModule() { public boolean isNoDataAvilableSoftwareModule() {
return noDataAvilableSoftwareModule; return this.noDataAvilableSoftwareModule;
} }
/** /**

View File

@@ -10,8 +10,6 @@ package org.eclipse.hawkbit.ui.artifacts.state;
import java.io.Serializable; import java.io.Serializable;
import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil;
/** /**
* Custom file to hold details of uploaded file. * Custom file to hold details of uploaded file.
* *
@@ -98,7 +96,7 @@ public class CustomFile implements Serializable {
} }
public String getBaseSoftwareModuleName() { public String getBaseSoftwareModuleName() {
return baseSoftwareModuleName; return this.baseSoftwareModuleName;
} }
public void setBaseSoftwareModuleName(final String baseSoftwareModuleName) { public void setBaseSoftwareModuleName(final String baseSoftwareModuleName) {
@@ -106,7 +104,7 @@ public class CustomFile implements Serializable {
} }
public String getBaseSoftwareModuleVersion() { public String getBaseSoftwareModuleVersion() {
return baseSoftwareModuleVersion; return this.baseSoftwareModuleVersion;
} }
public void setBaseSoftwareModuleVersion(final String baseSoftwareModuleVersion) { public void setBaseSoftwareModuleVersion(final String baseSoftwareModuleVersion) {
@@ -114,11 +112,11 @@ public class CustomFile implements Serializable {
} }
public String getFileName() { public String getFileName() {
return fileName; return this.fileName;
} }
public long getFileSize() { public long getFileSize() {
return fileSize; return this.fileSize;
} }
public void setFileSize(final long fileSize) { public void setFileSize(final long fileSize) {
@@ -126,7 +124,7 @@ public class CustomFile implements Serializable {
} }
public String getFilePath() { public String getFilePath() {
return filePath; return this.filePath;
} }
public void setFilePath(final String filePath) { public void setFilePath(final String filePath) {
@@ -134,7 +132,7 @@ public class CustomFile implements Serializable {
} }
public String getMimeType() { public String getMimeType() {
return mimeType; return this.mimeType;
} }
/** /**
@@ -142,7 +140,7 @@ public class CustomFile implements Serializable {
* @return the isValid * @return the isValid
*/ */
public Boolean getIsValid() { public Boolean getIsValid() {
return isValid; return this.isValid;
} }
/** /**
@@ -165,39 +163,54 @@ public class CustomFile implements Serializable {
* @return the failureReason * @return the failureReason
*/ */
public String getFailureReason() { public String getFailureReason() {
return failureReason; return this.failureReason;
} }
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override @Override
public int hashCode() { // NOSONAR - as this is generated public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + (fileName == null ? 0 : fileName.hashCode()); result = prime * result + ((this.baseSoftwareModuleName == null) ? 0 : this.baseSoftwareModuleName.hashCode());
result = prime * result
+ ((this.baseSoftwareModuleVersion == null) ? 0 : this.baseSoftwareModuleVersion.hashCode());
result = prime * result + ((this.fileName == null) ? 0 : this.fileName.hashCode());
return result; return result;
} }
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override @Override
public boolean equals(final Object obj) { public boolean equals(final Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (!(obj instanceof CustomFile)) { if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false; return false;
} }
final CustomFile other = (CustomFile) obj; final CustomFile other = (CustomFile) obj;
return HawkbitCommonUtil.bothSame(fileName, other.fileName) if (this.baseSoftwareModuleName == null) {
&& HawkbitCommonUtil.bothSame(baseSoftwareModuleName, other.baseSoftwareModuleName) if (other.baseSoftwareModuleName != null) {
&& HawkbitCommonUtil.bothSame(baseSoftwareModuleVersion, other.baseSoftwareModuleVersion); return false;
}
} else if (!this.baseSoftwareModuleName.equals(other.baseSoftwareModuleName)) {
return false;
}
if (this.baseSoftwareModuleVersion == null) {
if (other.baseSoftwareModuleVersion != null) {
return false;
}
} else if (!this.baseSoftwareModuleVersion.equals(other.baseSoftwareModuleVersion)) {
return false;
}
if (this.fileName == null) {
if (other.fileName != null) {
return false;
}
} else if (!this.fileName.equals(other.fileName)) {
return false;
}
return true;
} }
} }

View File

@@ -8,8 +8,6 @@
*/ */
package org.eclipse.hawkbit.ui.common.filterlayout; package org.eclipse.hawkbit.ui.common.filterlayout;
import java.util.Optional;
import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions;
import com.vaadin.ui.Button; import com.vaadin.ui.Button;
@@ -26,7 +24,7 @@ public abstract class AbstractFilterSingleButtonClick extends AbstractFilterButt
private static final long serialVersionUID = 478874092615793581L; private static final long serialVersionUID = 478874092615793581L;
private Optional<Button> alreadyClickedButton = Optional.empty(); private Button alreadyClickedButton;
/* /*
* (non-Javadoc) * (non-Javadoc)
@@ -40,18 +38,18 @@ public abstract class AbstractFilterSingleButtonClick extends AbstractFilterButt
if (isButtonUnClicked(clickedButton)) { if (isButtonUnClicked(clickedButton)) {
/* If same button clicked */ /* If same button clicked */
clickedButton.removeStyleName(SPUIStyleDefinitions.SP_FILTER_BTN_CLICKED_STYLE); clickedButton.removeStyleName(SPUIStyleDefinitions.SP_FILTER_BTN_CLICKED_STYLE);
alreadyClickedButton = Optional.empty(); this.alreadyClickedButton = null;
filterUnClicked(clickedButton); filterUnClicked(clickedButton);
} else if (alreadyClickedButton.isPresent()) { } else if (this.alreadyClickedButton != null) {
/* If button clicked and some other button is already clicked */ /* If button clicked and some other button is already clicked */
alreadyClickedButton.get().removeStyleName(SPUIStyleDefinitions.SP_FILTER_BTN_CLICKED_STYLE); this.alreadyClickedButton.removeStyleName(SPUIStyleDefinitions.SP_FILTER_BTN_CLICKED_STYLE);
clickedButton.addStyleName(SPUIStyleDefinitions.SP_FILTER_BTN_CLICKED_STYLE); clickedButton.addStyleName(SPUIStyleDefinitions.SP_FILTER_BTN_CLICKED_STYLE);
alreadyClickedButton = Optional.of(clickedButton); this.alreadyClickedButton = clickedButton;
filterClicked(clickedButton); filterClicked(clickedButton);
} else { } else {
/* If button clicked and not other button is clicked currently */ /* If button clicked and not other button is clicked currently */
clickedButton.addStyleName(SPUIStyleDefinitions.SP_FILTER_BTN_CLICKED_STYLE); clickedButton.addStyleName(SPUIStyleDefinitions.SP_FILTER_BTN_CLICKED_STYLE);
alreadyClickedButton = Optional.of(clickedButton); this.alreadyClickedButton = clickedButton;
filterClicked(clickedButton); filterClicked(clickedButton);
} }
} }
@@ -61,7 +59,7 @@ public abstract class AbstractFilterSingleButtonClick extends AbstractFilterButt
* @return * @return
*/ */
private boolean isButtonUnClicked(final Button clickedButton) { private boolean isButtonUnClicked(final Button clickedButton) {
return alreadyClickedButton.isPresent() && alreadyClickedButton.get().equals(clickedButton); return this.alreadyClickedButton != null && this.alreadyClickedButton.equals(clickedButton);
} }
/* /*
@@ -72,10 +70,8 @@ public abstract class AbstractFilterSingleButtonClick extends AbstractFilterButt
*/ */
@Override @Override
protected void setDefaultClickedButton(final Button button) { protected void setDefaultClickedButton(final Button button) {
if (button == null) { this.alreadyClickedButton = button;
alreadyClickedButton = Optional.empty(); if (button != null) {
} else {
alreadyClickedButton = Optional.of(button);
button.addStyleName(SPUIStyleDefinitions.SP_FILTER_BTN_CLICKED_STYLE); button.addStyleName(SPUIStyleDefinitions.SP_FILTER_BTN_CLICKED_STYLE);
} }
} }
@@ -83,15 +79,15 @@ public abstract class AbstractFilterSingleButtonClick extends AbstractFilterButt
/** /**
* @return the alreadyClickedButton * @return the alreadyClickedButton
*/ */
public Optional<Button> getAlreadyClickedButton() { public Button getAlreadyClickedButton() {
return alreadyClickedButton; return this.alreadyClickedButton;
} }
/** /**
* @param alreadyClickedButton * @param alreadyClickedButton
* the alreadyClickedButton to set * the alreadyClickedButton to set
*/ */
public void setAlreadyClickedButton(final Optional<Button> alreadyClickedButton) { public void setAlreadyClickedButton(final Button alreadyClickedButton) {
this.alreadyClickedButton = alreadyClickedButton; this.alreadyClickedButton = alreadyClickedButton;
} }

View File

@@ -47,9 +47,9 @@ public abstract class AbstractTagToken implements Serializable {
protected IndexedContainer container; protected IndexedContainer container;
protected final Map<Long, TagData> tagDetails = new HashMap<Long, TagData>(); protected final Map<Long, TagData> tagDetails = new HashMap<>();
protected final Map<Long, TagData> tokensAdded = new HashMap<Long, TagData>(); protected final Map<Long, TagData> tokensAdded = new HashMap<>();
protected CssLayout tokenLayout = new CssLayout(); protected CssLayout tokenLayout = new CssLayout();
@@ -63,16 +63,16 @@ public abstract class AbstractTagToken implements Serializable {
private void createTokenField() { private void createTokenField() {
final Container tokenContainer = createContainer(); final Container tokenContainer = createContainer();
tokenField = createTokenField(tokenContainer); this.tokenField = createTokenField(tokenContainer);
tokenField.setContainerDataSource(tokenContainer); this.tokenField.setContainerDataSource(tokenContainer);
tokenField.setNewTokensAllowed(false); this.tokenField.setNewTokensAllowed(false);
tokenField.setFilteringMode(FilteringMode.CONTAINS); this.tokenField.setFilteringMode(FilteringMode.CONTAINS);
tokenField.setInputPrompt(getTokenInputPrompt()); this.tokenField.setInputPrompt(getTokenInputPrompt());
tokenField.setTokenInsertPosition(InsertPosition.AFTER); this.tokenField.setTokenInsertPosition(InsertPosition.AFTER);
tokenField.setImmediate(true); this.tokenField.setImmediate(true);
tokenField.addStyleName(ValoTheme.COMBOBOX_TINY); this.tokenField.addStyleName(ValoTheme.COMBOBOX_TINY);
tokenField.setSizeFull(); this.tokenField.setSizeFull();
tokenField.setTokenCaptionPropertyId("name"); this.tokenField.setTokenCaptionPropertyId("name");
} }
protected void repopulateToken() { protected void repopulateToken() {
@@ -81,26 +81,26 @@ public abstract class AbstractTagToken implements Serializable {
} }
private Container createContainer() { private Container createContainer() {
container = new IndexedContainer(); this.container = new IndexedContainer();
container.addContainerProperty("name", String.class, ""); this.container.addContainerProperty("name", String.class, "");
container.addContainerProperty("id", Long.class, ""); this.container.addContainerProperty("id", Long.class, "");
container.addContainerProperty(COLOR_PROPERTY, String.class, ""); this.container.addContainerProperty(COLOR_PROPERTY, String.class, "");
return container; return this.container;
} }
protected void addNewToken(final Long tagId) { protected void addNewToken(final Long tagId) {
tokenField.addToken(tagId); this.tokenField.addToken(tagId);
removeTagAssignedFromCombo(tagId); removeTagAssignedFromCombo(tagId);
} }
private void removeTagAssignedFromCombo(final Long tagId) { private void removeTagAssignedFromCombo(final Long tagId) {
tokensAdded.put(tagId, new TagData(tagId, getTagName(tagId), getColor(tagId))); this.tokensAdded.put(tagId, new TagData(tagId, getTagName(tagId), getColor(tagId)));
container.removeItem(tagId); this.container.removeItem(tagId);
} }
protected void setContainerPropertValues(final Long tagId, final String tagName, final String tagColor) { protected void setContainerPropertValues(final Long tagId, final String tagName, final String tagColor) {
tagDetails.put(tagId, new TagData(tagId, tagName, tagColor)); this.tagDetails.put(tagId, new TagData(tagId, tagName, tagColor));
final Item item = container.addItem(tagId); final Item item = this.container.addItem(tagId);
item.getItemProperty("id").setValue(tagId); item.getItemProperty("id").setValue(tagId);
updateItem(tagName, tagColor, item); updateItem(tagName, tagColor, item);
} }
@@ -112,12 +112,12 @@ public abstract class AbstractTagToken implements Serializable {
protected void checkIfTagAssignedIsAllowed() { protected void checkIfTagAssignedIsAllowed() {
if (!isToggleTagAssignmentAllowed()) { if (!isToggleTagAssignmentAllowed()) {
tokenField.addStyleName("hideTokenFieldcombo"); this.tokenField.addStyleName("hideTokenFieldcombo");
} }
} }
private TokenField createTokenField(final Container tokenContainer) { private TokenField createTokenField(final Container tokenContainer) {
return new CustomTokenField(tokenLayout, tokenContainer); return new CustomTokenField(this.tokenLayout, tokenContainer);
} }
class CustomTokenField extends TokenField { class CustomTokenField extends TokenField {
@@ -166,12 +166,12 @@ public abstract class AbstractTagToken implements Serializable {
} }
private Property getItemNameProperty(final Object tokenId) { private Property getItemNameProperty(final Object tokenId) {
final Item item = tokenField.getContainerDataSource().getItem(tokenId); final Item item = this.tokenField.getContainerDataSource().getItem(tokenId);
return item.getItemProperty("name"); return item.getItemProperty("name");
} }
private String getColor(final Object tokenId) { private String getColor(final Object tokenId) {
final Item item = tokenField.getContainerDataSource().getItem(tokenId); final Item item = this.tokenField.getContainerDataSource().getItem(tokenId);
if (item.getItemProperty(COLOR_PROPERTY).getValue() != null) { if (item.getItemProperty(COLOR_PROPERTY).getValue() != null) {
return (String) item.getItemProperty(COLOR_PROPERTY).getValue(); return (String) item.getItemProperty(COLOR_PROPERTY).getValue();
} else { } else {
@@ -180,23 +180,23 @@ public abstract class AbstractTagToken implements Serializable {
} }
private String getTagName(final Object tokenId) { private String getTagName(final Object tokenId) {
final Item item = tokenField.getContainerDataSource().getItem(tokenId); final Item item = this.tokenField.getContainerDataSource().getItem(tokenId);
return (String) item.getItemProperty("name").getValue(); return (String) item.getItemProperty("name").getValue();
} }
private void tokenClick(final Object tokenId) { private void tokenClick(final Object tokenId) {
final Item item = tokenField.getContainerDataSource().addItem(tokenId); final Item item = this.tokenField.getContainerDataSource().addItem(tokenId);
item.getItemProperty("name").setValue(tagDetails.get(tokenId).getName()); item.getItemProperty("name").setValue(this.tagDetails.get(tokenId).getName());
item.getItemProperty(COLOR_PROPERTY).setValue(tagDetails.get(tokenId).getColor()); item.getItemProperty(COLOR_PROPERTY).setValue(this.tagDetails.get(tokenId).getColor());
unassignTag(tagDetails.get(tokenId).getName()); unassignTag(this.tagDetails.get(tokenId).getName());
} }
protected void removePreviouslyAddedTokens() { protected void removePreviouslyAddedTokens() {
tokensAdded.keySet().forEach(previouslyAddedToken -> tokenField.removeToken(previouslyAddedToken)); this.tokensAdded.keySet().forEach(previouslyAddedToken -> this.tokenField.removeToken(previouslyAddedToken));
} }
protected Long getTagIdByTagName(final String tagName) { protected Long getTagIdByTagName(final String tagName) {
final Optional<Map.Entry<Long, TagData>> mapEntry = tagDetails.entrySet().stream() final Optional<Map.Entry<Long, TagData>> mapEntry = this.tagDetails.entrySet().stream()
.filter(entry -> entry.getValue().getName().equals(tagName)).findFirst(); .filter(entry -> entry.getValue().getName().equals(tagName)).findFirst();
if (mapEntry.isPresent()) { if (mapEntry.isPresent()) {
return mapEntry.get().getKey(); return mapEntry.get().getKey();
@@ -205,13 +205,13 @@ public abstract class AbstractTagToken implements Serializable {
} }
protected void removeTokenItem(final Long tokenId, final String name) { protected void removeTokenItem(final Long tokenId, final String name) {
tokenField.removeToken(tokenId); this.tokenField.removeToken(tokenId);
setContainerPropertValues(tokenId, name, tokensAdded.get(tokenId).getColor()); setContainerPropertValues(tokenId, name, this.tokensAdded.get(tokenId).getColor());
} }
protected void removeTagFromCombo(final Long deletedTagId) { protected void removeTagFromCombo(final Long deletedTagId) {
if (deletedTagId != null) { if (deletedTagId != null) {
container.removeItem(deletedTagId); this.container.removeItem(deletedTagId);
} }
} }
@@ -230,14 +230,16 @@ public abstract class AbstractTagToken implements Serializable {
protected abstract void populateContainer(); protected abstract void populateContainer();
public TokenField getTokenField() { public TokenField getTokenField() {
return tokenField; return this.tokenField;
} }
/** /**
* Tag details. * Tag details.
* *
*/ */
public static class TagData { public static class TagData implements Serializable {
private static final long serialVersionUID = 1L;
private String name; private String name;
@@ -262,7 +264,7 @@ public abstract class AbstractTagToken implements Serializable {
* @return the name * @return the name
*/ */
public String getName() { public String getName() {
return name; return this.name;
} }
/** /**
@@ -277,7 +279,7 @@ public abstract class AbstractTagToken implements Serializable {
* @return the id * @return the id
*/ */
public Long getId() { public Long getId() {
return id; return this.id;
} }
/** /**
@@ -292,7 +294,7 @@ public abstract class AbstractTagToken implements Serializable {
* @return the color * @return the color
*/ */
public String getColor() { public String getColor() {
return color; return this.color;
} }
/** /**

View File

@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.ui.distributions.dstable; package org.eclipse.hawkbit.ui.distributions.dstable;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@@ -113,16 +114,17 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
@Override @Override
@PostConstruct @PostConstruct
protected void init() { protected void init() {
softwareModuleTable = new SoftwareModuleDetailsTable(); this.softwareModuleTable = new SoftwareModuleDetailsTable();
softwareModuleTable.init(i18n, true, permissionChecker, distributionSetManagement, eventBus, manageDistUIState); this.softwareModuleTable.init(this.i18n, true, this.permissionChecker, this.distributionSetManagement,
this.eventBus, this.manageDistUIState);
super.init(); super.init();
ui = UI.getCurrent(); this.ui = UI.getCurrent();
eventBus.subscribe(this); this.eventBus.subscribe(this);
} }
protected VerticalLayout createTagsLayout() { protected VerticalLayout createTagsLayout() {
tagsLayout = getTabLayout(); this.tagsLayout = getTabLayout();
return tagsLayout; return this.tagsLayout;
} }
private void populateDetailsWidget(final DistributionSet ds) { private void populateDetailsWidget(final DistributionSet ds) {
@@ -146,19 +148,20 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
} }
private void populteModule(final DistributionSet distributionSet) { private void populteModule(final DistributionSet distributionSet) {
softwareModuleTable.populateModule(distributionSet); this.softwareModuleTable.populateModule(distributionSet);
showUnsavedAssignment(); showUnsavedAssignment();
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void showUnsavedAssignment() { private void showUnsavedAssignment() {
Item item; Item item;
final Map<DistributionSetIdName, Set<SoftwareModuleIdName>> assignedList = manageDistUIState.getAssignedList(); final Map<DistributionSetIdName, HashSet<SoftwareModuleIdName>> assignedList = this.manageDistUIState
final Long selectedDistId = manageDistUIState.getLastSelectedDistribution().isPresent() .getAssignedList();
? manageDistUIState.getLastSelectedDistribution().get().getId() : null; final Long selectedDistId = this.manageDistUIState.getLastSelectedDistribution().isPresent()
? this.manageDistUIState.getLastSelectedDistribution().get().getId() : null;
Set<SoftwareModuleIdName> softwareModuleIdNameList = null; Set<SoftwareModuleIdName> softwareModuleIdNameList = null;
for (final Map.Entry<DistributionSetIdName, Set<SoftwareModuleIdName>> entry : assignedList.entrySet()) { for (final Map.Entry<DistributionSetIdName, HashSet<SoftwareModuleIdName>> entry : assignedList.entrySet()) {
if (entry.getKey().getId().equals(selectedDistId)) { if (entry.getKey().getId().equals(selectedDistId)) {
softwareModuleIdNameList = entry.getValue(); softwareModuleIdNameList = entry.getValue();
break; break;
@@ -167,22 +170,22 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
if (null != softwareModuleIdNameList) { if (null != softwareModuleIdNameList) {
for (final SoftwareModuleIdName swIdName : softwareModuleIdNameList) { for (final SoftwareModuleIdName swIdName : softwareModuleIdNameList) {
final SoftwareModule softwareModule = softwareManagement.findSoftwareModuleById(swIdName.getId()); final SoftwareModule softwareModule = this.softwareManagement.findSoftwareModuleById(swIdName.getId());
if (assignedSWModule.containsKey(softwareModule.getType().getName())) { if (this.assignedSWModule.containsKey(softwareModule.getType().getName())) {
assignedSWModule.get(softwareModule.getType().getName()).append("</br>").append("<I>") this.assignedSWModule.get(softwareModule.getType().getName()).append("</br>").append("<I>")
.append(getUnsavedAssigedSwModule(softwareModule.getName(), softwareModule.getVersion())) .append(getUnsavedAssigedSwModule(softwareModule.getName(), softwareModule.getVersion()))
.append("<I>"); .append("<I>");
} else { } else {
assignedSWModule.put(softwareModule.getType().getName(), this.assignedSWModule.put(softwareModule.getType().getName(),
new StringBuilder().append("<I>").append( new StringBuilder().append("<I>").append(
getUnsavedAssigedSwModule(softwareModule.getName(), softwareModule.getVersion())) getUnsavedAssigedSwModule(softwareModule.getName(), softwareModule.getVersion()))
.append("<I>")); .append("<I>"));
} }
} }
for (final Map.Entry<String, StringBuilder> entry : assignedSWModule.entrySet()) { for (final Map.Entry<String, StringBuilder> entry : this.assignedSWModule.entrySet()) {
item = softwareModuleTable.getContainerDataSource().getItem(entry.getKey()); item = this.softwareModuleTable.getContainerDataSource().getItem(entry.getKey());
if (item != null) { if (item != null) {
item.getItemProperty(SOFT_MODULE) item.getItemProperty(SOFT_MODULE)
.setValue(HawkbitCommonUtil.getFormatedLabel(entry.getValue().toString())); .setValue(HawkbitCommonUtil.getFormatedLabel(entry.getValue().toString()));
@@ -198,8 +201,8 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
* @param entry * @param entry
*/ */
private void assignSoftModuleButton(final Item item, final Map.Entry<String, StringBuilder> entry) { private void assignSoftModuleButton(final Item item, final Map.Entry<String, StringBuilder> entry) {
if (permissionChecker.hasUpdateDistributionPermission() && distributionSetManagement if (this.permissionChecker.hasUpdateDistributionPermission() && this.distributionSetManagement
.findDistributionSetById(manageDistUIState.getLastSelectedDistribution().get().getId()) .findDistributionSetById(this.manageDistUIState.getLastSelectedDistribution().get().getId())
.getAssignedTargets().isEmpty()) { .getAssignedTargets().isEmpty()) {
final Button reassignSoftModule = SPUIComponentProvider.getButton(entry.getKey(), "", "", "", true, final Button reassignSoftModule = SPUIComponentProvider.getButton(entry.getKey(), "", "", "", true,
FontAwesome.TIMES, SPUIButtonStyleSmallNoBorder.class); FontAwesome.TIMES, SPUIButtonStyleSmallNoBorder.class);
@@ -215,8 +218,8 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void updateSoftwareModule(final SoftwareModule module) { private void updateSoftwareModule(final SoftwareModule module) {
softwareModuleTable.getContainerDataSource().getItemIds(); this.softwareModuleTable.getContainerDataSource().getItemIds();
if (assignedSWModule.containsKey(module.getType().getName())) { if (this.assignedSWModule.containsKey(module.getType().getName())) {
/* /*
* If software module type is software, means multiple softwares can * If software module type is software, means multiple softwares can
* assigned to that type. Hence if multipe softwares belongs to same * assigned to that type. Hence if multipe softwares belongs to same
@@ -224,7 +227,7 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
*/ */
if (module.getType().getMaxAssignments() == Integer.MAX_VALUE) { if (module.getType().getMaxAssignments() == Integer.MAX_VALUE) {
assignedSWModule.get(module.getType().getName()).append("</br>").append("<I>") this.assignedSWModule.get(module.getType().getName()).append("</br>").append("<I>")
.append(getUnsavedAssigedSwModule(module.getName(), module.getVersion())).append("</I>"); .append(getUnsavedAssigedSwModule(module.getName(), module.getVersion())).append("</I>");
} }
@@ -234,17 +237,17 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
* same type is dropped, then override with previous one. * same type is dropped, then override with previous one.
*/ */
if (module.getType().getMaxAssignments() == 1) { if (module.getType().getMaxAssignments() == 1) {
assignedSWModule.put(module.getType().getName(), new StringBuilder().append("<I>") this.assignedSWModule.put(module.getType().getName(), new StringBuilder().append("<I>")
.append(getUnsavedAssigedSwModule(module.getName(), module.getVersion())).append("</I>")); .append(getUnsavedAssigedSwModule(module.getName(), module.getVersion())).append("</I>"));
} }
} else { } else {
assignedSWModule.put(module.getType().getName(), new StringBuilder().append("<I>") this.assignedSWModule.put(module.getType().getName(), new StringBuilder().append("<I>")
.append(getUnsavedAssigedSwModule(module.getName(), module.getVersion())).append("</I>")); .append(getUnsavedAssigedSwModule(module.getName(), module.getVersion())).append("</I>"));
} }
for (final Map.Entry<String, StringBuilder> entry : assignedSWModule.entrySet()) { for (final Map.Entry<String, StringBuilder> entry : this.assignedSWModule.entrySet()) {
final Item item = softwareModuleTable.getContainerDataSource().getItem(entry.getKey()); final Item item = this.softwareModuleTable.getContainerDataSource().getItem(entry.getKey());
if (item != null) { if (item != null) {
item.getItemProperty(SOFT_MODULE) item.getItemProperty(SOFT_MODULE)
.setValue(HawkbitCommonUtil.getFormatedLabel(entry.getValue().toString())); .setValue(HawkbitCommonUtil.getFormatedLabel(entry.getValue().toString()));
@@ -257,23 +260,23 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
private VerticalLayout createSoftwareModuleTab() { private VerticalLayout createSoftwareModuleTab() {
final VerticalLayout softwareLayout = getTabLayout(); final VerticalLayout softwareLayout = getTabLayout();
softwareLayout.setSizeFull(); softwareLayout.setSizeFull();
softwareLayout.addComponent(softwareModuleTable); softwareLayout.addComponent(this.softwareModuleTable);
return softwareLayout; return softwareLayout;
} }
private void populateTags(final DistributionSet ds) { private void populateTags(final DistributionSet ds) {
tagsLayout.removeAllComponents(); this.tagsLayout.removeAllComponents();
if (null != ds) { if (null != ds) {
tagsLayout.addComponent(distributionTagToken.getTokenField()); this.tagsLayout.addComponent(this.distributionTagToken.getTokenField());
} }
} }
private void populateLog(final DistributionSet ds) { private void populateLog(final DistributionSet ds) {
if (null != ds) { if (null != ds) {
updateLogLayout(getLogLayout(), ds.getLastModifiedAt(), ds.getLastModifiedBy(), ds.getCreatedAt(), updateLogLayout(getLogLayout(), ds.getLastModifiedAt(), ds.getLastModifiedBy(), ds.getCreatedAt(),
ds.getCreatedBy(), i18n); ds.getCreatedBy(), this.i18n);
} else { } else {
updateLogLayout(getLogLayout(), null, HawkbitCommonUtil.SP_STRING_EMPTY, null, null, i18n); updateLogLayout(getLogLayout(), null, HawkbitCommonUtil.SP_STRING_EMPTY, null, null, this.i18n);
} }
} }
@@ -287,9 +290,9 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
private void populateDescription(final DistributionSet ds) { private void populateDescription(final DistributionSet ds) {
if (ds != null) { if (ds != null) {
updateDescriptionLayout(i18n.get("label.description"), ds.getDescription()); updateDescriptionLayout(this.i18n.get("label.description"), ds.getDescription());
} else { } else {
updateDescriptionLayout(i18n.get("label.description"), null); updateDescriptionLayout(this.i18n.get("label.description"), null);
} }
} }
@@ -298,21 +301,21 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
detailsTabLayout.removeAllComponents(); detailsTabLayout.removeAllComponents();
if (type != null) { if (type != null) {
final Label typeLabel = SPUIComponentProvider.createNameValueLabel(i18n.get("label.dist.details.type"), final Label typeLabel = SPUIComponentProvider.createNameValueLabel(this.i18n.get("label.dist.details.type"),
type); type);
typeLabel.setId(SPUIComponetIdProvider.DETAILS_TYPE_LABEL_ID); typeLabel.setId(SPUIComponetIdProvider.DETAILS_TYPE_LABEL_ID);
detailsTabLayout.addComponent(typeLabel); detailsTabLayout.addComponent(typeLabel);
} }
if (isMigrationRequired != null) { if (isMigrationRequired != null) {
detailsTabLayout.addComponent( detailsTabLayout.addComponent(SPUIComponentProvider.createNameValueLabel(
SPUIComponentProvider.createNameValueLabel(i18n.get("checkbox.dist.migration.required"), this.i18n.get("checkbox.dist.migration.required"),
isMigrationRequired.equals(Boolean.TRUE) ? i18n.get("label.yes") : i18n.get("label.no"))); isMigrationRequired.equals(Boolean.TRUE) ? this.i18n.get("label.yes") : this.i18n.get("label.no")));
} }
} }
public Long getDsId() { public Long getDsId() {
return dsId; return this.dsId;
} }
public void setDsId(final Long dsId) { public void setDsId(final Long dsId) {
@@ -327,9 +330,9 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
*/ */
@Override @Override
protected void onEdit(final ClickEvent event) { protected void onEdit(final ClickEvent event) {
final Window newDistWindow = distributionAddUpdateWindowLayout.getWindow(); final Window newDistWindow = this.distributionAddUpdateWindowLayout.getWindow();
distributionAddUpdateWindowLayout.populateValuesOfDistribution(getDsId()); this.distributionAddUpdateWindowLayout.populateValuesOfDistribution(getDsId());
newDistWindow.setCaption(i18n.get("caption.update.dist")); newDistWindow.setCaption(this.i18n.get("caption.update.dist"));
UI.getCurrent().addWindow(newDistWindow); UI.getCurrent().addWindow(newDistWindow);
newDistWindow.setVisible(Boolean.TRUE); newDistWindow.setVisible(Boolean.TRUE);
} }
@@ -353,8 +356,8 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
*/ */
@Override @Override
protected Boolean onLoadIsTableRowSelected() { protected Boolean onLoadIsTableRowSelected() {
return manageDistUIState.getSelectedDistributions().isPresent() return this.manageDistUIState.getSelectedDistributions().isPresent()
&& !manageDistUIState.getSelectedDistributions().get().isEmpty(); && !this.manageDistUIState.getSelectedDistributions().get().isEmpty();
} }
/* /*
@@ -365,7 +368,7 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
*/ */
@Override @Override
protected Boolean onLoadIsTableMaximized() { protected Boolean onLoadIsTableMaximized() {
return manageDistUIState.isDsTableMaximized(); return this.manageDistUIState.isDsTableMaximized();
} }
/* /*
@@ -376,7 +379,7 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
*/ */
@Override @Override
protected void populateDetailsWidget() { protected void populateDetailsWidget() {
populateDetailsWidget(selectedDsModule); populateDetailsWidget(this.selectedDsModule);
} }
/* /*
@@ -387,7 +390,7 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
*/ */
@Override @Override
protected String getDefaultCaption() { protected String getDefaultCaption() {
return i18n.get("distribution.details.header"); return this.i18n.get("distribution.details.header");
} }
/* /*
@@ -398,11 +401,11 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
*/ */
@Override @Override
protected void addTabs(final TabSheet detailsTab) { protected void addTabs(final TabSheet detailsTab) {
detailsTab.addTab(createDetailsLayout(), i18n.get("caption.tab.details"), null); detailsTab.addTab(createDetailsLayout(), this.i18n.get("caption.tab.details"), null);
detailsTab.addTab(createDescriptionLayout(), i18n.get("caption.tab.description"), null); detailsTab.addTab(createDescriptionLayout(), this.i18n.get("caption.tab.description"), null);
detailsTab.addTab(createSoftwareModuleTab(), i18n.get("caption.softwares.distdetail.tab"), null); detailsTab.addTab(createSoftwareModuleTab(), this.i18n.get("caption.softwares.distdetail.tab"), null);
detailsTab.addTab(createTagsLayout(), i18n.get("caption.tags.tab"), null); detailsTab.addTab(createTagsLayout(), this.i18n.get("caption.tags.tab"), null);
detailsTab.addTab(createLogLayout(), i18n.get("caption.logs.tab"), null); detailsTab.addTab(createLogLayout(), this.i18n.get("caption.logs.tab"), null);
} }
/* /*
@@ -424,13 +427,13 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
*/ */
@Override @Override
protected Boolean hasEditPermission() { protected Boolean hasEditPermission() {
return permissionChecker.hasUpdateDistributionPermission(); return this.permissionChecker.hasUpdateDistributionPermission();
} }
@EventBusListenerMethod(scope = EventScope.SESSION) @EventBusListenerMethod(scope = EventScope.SESSION)
void onEvent(final SoftwareModuleEvent event) { void onEvent(final SoftwareModuleEvent event) {
if (event.getSoftwareModuleEventType() == SoftwareModuleEventType.ASSIGN_SOFTWARE_MODULE) { if (event.getSoftwareModuleEventType() == SoftwareModuleEventType.ASSIGN_SOFTWARE_MODULE) {
ui.access(() -> updateSoftwareModule(event.getSoftwareModule())); this.ui.access(() -> updateSoftwareModule(event.getSoftwareModule()));
} }
} }
@@ -439,37 +442,37 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
if (distributionTableEvent.getDistributionComponentEvent() == DistributionComponentEvent.ON_VALUE_CHANGE if (distributionTableEvent.getDistributionComponentEvent() == DistributionComponentEvent.ON_VALUE_CHANGE
|| distributionTableEvent || distributionTableEvent
.getDistributionComponentEvent() == DistributionComponentEvent.EDIT_DISTRIBUTION) { .getDistributionComponentEvent() == DistributionComponentEvent.EDIT_DISTRIBUTION) {
assignedSWModule.clear(); this.assignedSWModule.clear();
ui.access(() -> { this.ui.access(() -> {
/** /**
* distributionTableEvent.getDistributionSet() is null when * distributionTableEvent.getDistributionSet() is null when
* table has no data. * table has no data.
*/ */
if (distributionTableEvent.getDistributionSet() != null) { if (distributionTableEvent.getDistributionSet() != null) {
selectedDsModule = distributionTableEvent.getDistributionSet(); this.selectedDsModule = distributionTableEvent.getDistributionSet();
populateData(true); populateData(true);
} else { } else {
populateData(false); populateData(false);
} }
}); });
} else if (distributionTableEvent.getDistributionComponentEvent() == DistributionComponentEvent.MINIMIZED) { } else if (distributionTableEvent.getDistributionComponentEvent() == DistributionComponentEvent.MINIMIZED) {
ui.access(() -> showLayout()); this.ui.access(() -> showLayout());
} else if (distributionTableEvent.getDistributionComponentEvent() == DistributionComponentEvent.MAXIMIZED) { } else if (distributionTableEvent.getDistributionComponentEvent() == DistributionComponentEvent.MAXIMIZED) {
ui.access(() -> hideLayout()); this.ui.access(() -> hideLayout());
} }
} }
@EventBusListenerMethod(scope = EventScope.SESSION) @EventBusListenerMethod(scope = EventScope.SESSION)
void onEvent(final SoftwareModuleAssignmentDiscardEvent softwareModuleAssignmentDiscardEvent) { void onEvent(final SoftwareModuleAssignmentDiscardEvent softwareModuleAssignmentDiscardEvent) {
if (softwareModuleAssignmentDiscardEvent.getDistributionSetIdName() != null) { if (softwareModuleAssignmentDiscardEvent.getDistributionSetIdName() != null) {
ui.access(() -> { this.ui.access(() -> {
final DistributionSetIdName distIdName = softwareModuleAssignmentDiscardEvent final DistributionSetIdName distIdName = softwareModuleAssignmentDiscardEvent
.getDistributionSetIdName(); .getDistributionSetIdName();
if (distIdName.getId().equals(selectedDsModule.getId()) if (distIdName.getId().equals(this.selectedDsModule.getId())
&& distIdName.getName().equals(selectedDsModule.getName())) { && distIdName.getName().equals(this.selectedDsModule.getName())) {
selectedDsModule = distributionSetManagement this.selectedDsModule = this.distributionSetManagement
.findDistributionSetByIdWithDetails(selectedDsModule.getId()); .findDistributionSetByIdWithDetails(this.selectedDsModule.getId());
populteModule(selectedDsModule); populteModule(this.selectedDsModule);
} }
}); });
} }
@@ -479,10 +482,11 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
void onEvent(final SaveActionWindowEvent saveActionWindowEvent) { void onEvent(final SaveActionWindowEvent saveActionWindowEvent) {
if ((saveActionWindowEvent == SaveActionWindowEvent.SAVED_ASSIGNMENTS if ((saveActionWindowEvent == SaveActionWindowEvent.SAVED_ASSIGNMENTS
|| saveActionWindowEvent == SaveActionWindowEvent.DISCARD_ALL_ASSIGNMENTS) || saveActionWindowEvent == SaveActionWindowEvent.DISCARD_ALL_ASSIGNMENTS)
&& selectedDsModule != null) { && this.selectedDsModule != null) {
assignedSWModule.clear(); this.assignedSWModule.clear();
selectedDsModule = distributionSetManagement.findDistributionSetByIdWithDetails(selectedDsModule.getId()); this.selectedDsModule = this.distributionSetManagement
ui.access(() -> populteModule(selectedDsModule)); .findDistributionSetByIdWithDetails(this.selectedDsModule.getId());
this.ui.access(() -> populteModule(this.selectedDsModule));
} }
} }
@@ -491,7 +495,7 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
if (saveActionWindowEvent == SaveActionWindowEvent.DISCARD_ASSIGNMENT if (saveActionWindowEvent == SaveActionWindowEvent.DISCARD_ASSIGNMENT
|| saveActionWindowEvent == SaveActionWindowEvent.DISCARD_ALL_ASSIGNMENTS || saveActionWindowEvent == SaveActionWindowEvent.DISCARD_ALL_ASSIGNMENTS
|| saveActionWindowEvent == SaveActionWindowEvent.DELETE_ALL_SOFWARE) { || saveActionWindowEvent == SaveActionWindowEvent.DELETE_ALL_SOFWARE) {
assignedSWModule.clear(); this.assignedSWModule.clear();
showUnsavedAssignment(); showUnsavedAssignment();
} }
} }
@@ -502,7 +506,7 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout {
* It's good to do this, even though vaadin-spring will automatically * It's good to do this, even though vaadin-spring will automatically
* unsubscribe . * unsubscribe .
*/ */
eventBus.unsubscribe(this); this.eventBus.unsubscribe(this);
} }
/* /*

View File

@@ -124,7 +124,7 @@ public class DistributionSetTable extends AbstractTable {
super.init(); super.init();
addTableStyleGenerator(); addTableStyleGenerator();
setNoDataAvailable(); setNoDataAvailable();
eventBus.subscribe(this); this.eventBus.subscribe(this);
} }
@EventBusListenerMethod(scope = EventScope.SESSION) @EventBusListenerMethod(scope = EventScope.SESSION)
@@ -157,23 +157,20 @@ public class DistributionSetTable extends AbstractTable {
@Override @Override
protected Container createContainer() { protected Container createContainer() {
final Map<String, Object> queryConfiguration = new HashMap<String, Object>(); final Map<String, Object> queryConfiguration = new HashMap<>();
manageDistUIState.getManageDistFilters().getSearchText() this.manageDistUIState.getManageDistFilters().getSearchText()
.ifPresent(value -> queryConfiguration.put(SPUIDefinitions.FILTER_BY_TEXT, value)); .ifPresent(value -> queryConfiguration.put(SPUIDefinitions.FILTER_BY_TEXT, value));
if (null != manageDistUIState.getManageDistFilters().getClickedDistSetType()) { if (null != this.manageDistUIState.getManageDistFilters().getClickedDistSetType()) {
queryConfiguration.put(SPUIDefinitions.FILTER_BY_DISTRIBUTION_SET_TYPE, queryConfiguration.put(SPUIDefinitions.FILTER_BY_DISTRIBUTION_SET_TYPE,
manageDistUIState.getManageDistFilters().getClickedDistSetType()); this.manageDistUIState.getManageDistFilters().getClickedDistSetType());
} }
final BeanQueryFactory<ManageDistBeanQuery> distributionQF = new BeanQueryFactory<ManageDistBeanQuery>( final BeanQueryFactory<ManageDistBeanQuery> distributionQF = new BeanQueryFactory<>(ManageDistBeanQuery.class);
ManageDistBeanQuery.class);
distributionQF.setQueryConfiguration(queryConfiguration); distributionQF.setQueryConfiguration(queryConfiguration);
final LazyQueryContainer distContainer = new LazyQueryContainer( return new LazyQueryContainer(
new LazyQueryDefinition(true, SPUIDefinitions.PAGE_SIZE, SPUILabelDefinitions.VAR_DIST_ID_NAME), new LazyQueryDefinition(true, SPUIDefinitions.PAGE_SIZE, SPUILabelDefinitions.VAR_DIST_ID_NAME),
distributionQF); distributionQF);
return distContainer;
} }
/* /*
@@ -210,8 +207,8 @@ public class DistributionSetTable extends AbstractTable {
*/ */
@Override @Override
protected boolean isFirstRowSelectedOnLoad() { protected boolean isFirstRowSelectedOnLoad() {
return !manageDistUIState.getSelectedDistributions().isPresent() return !this.manageDistUIState.getSelectedDistributions().isPresent()
|| manageDistUIState.getSelectedDistributions().get().isEmpty(); || this.manageDistUIState.getSelectedDistributions().get().isEmpty();
} }
/* /*
@@ -221,8 +218,8 @@ public class DistributionSetTable extends AbstractTable {
*/ */
@Override @Override
protected Object getItemIdToSelect() { protected Object getItemIdToSelect() {
if (manageDistUIState.getSelectedDistributions().isPresent()) { if (this.manageDistUIState.getSelectedDistributions().isPresent()) {
return manageDistUIState.getSelectedDistributions().get(); return this.manageDistUIState.getSelectedDistributions().get();
} }
return null; return null;
} }
@@ -235,7 +232,7 @@ public class DistributionSetTable extends AbstractTable {
*/ */
@Override @Override
protected void onValueChange() { protected void onValueChange() {
eventBus.publish(this, DragEvent.HIDE_DROP_HINT); this.eventBus.publish(this, DragEvent.HIDE_DROP_HINT);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Set<DistributionSetIdName> values = (Set<DistributionSetIdName>) getValue(); final Set<DistributionSetIdName> values = (Set<DistributionSetIdName>) getValue();
DistributionSetIdName value = null; DistributionSetIdName value = null;
@@ -250,20 +247,20 @@ public class DistributionSetTable extends AbstractTable {
* getValue returns null. * getValue returns null.
*/ */
if (null != value) { if (null != value) {
manageDistUIState.setSelectedDistributions(values); this.manageDistUIState.setSelectedDistributions(values);
manageDistUIState.setLastSelectedDistribution(value); this.manageDistUIState.setLastSelectedDistribution(value);
final DistributionSet lastSelectedDistSet = distributionSetManagement final DistributionSet lastSelectedDistSet = this.distributionSetManagement
.findDistributionSetByIdWithDetails(value.getId()); .findDistributionSetByIdWithDetails(value.getId());
eventBus.publish(this, this.eventBus.publish(this,
new DistributionTableEvent(DistributionComponentEvent.ON_VALUE_CHANGE, lastSelectedDistSet)); new DistributionTableEvent(DistributionComponentEvent.ON_VALUE_CHANGE, lastSelectedDistSet));
} }
} else { } else {
manageDistUIState.setSelectedDistributions(null); this.manageDistUIState.setSelectedDistributions(null);
manageDistUIState.setLastSelectedDistribution(null); this.manageDistUIState.setLastSelectedDistribution(null);
eventBus.publish(this, new DistributionTableEvent(DistributionComponentEvent.ON_VALUE_CHANGE, null)); this.eventBus.publish(this, new DistributionTableEvent(DistributionComponentEvent.ON_VALUE_CHANGE, null));
} }
eventBus.publish(this, DistributionsUIEvent.ORDER_BY_DISTRIBUTION); this.eventBus.publish(this, DistributionsUIEvent.ORDER_BY_DISTRIBUTION);
} }
@@ -275,7 +272,7 @@ public class DistributionSetTable extends AbstractTable {
*/ */
@Override @Override
protected boolean isMaximized() { protected boolean isMaximized() {
return manageDistUIState.isDsTableMaximized(); return this.manageDistUIState.isDsTableMaximized();
} }
/* /*
@@ -286,7 +283,7 @@ public class DistributionSetTable extends AbstractTable {
*/ */
@Override @Override
protected List<TableColumn> getTableVisibleColumns() { protected List<TableColumn> getTableVisibleColumns() {
return HawkbitCommonUtil.getTableVisibleColumns(isMaximized(), false, i18n); return HawkbitCommonUtil.getTableVisibleColumns(isMaximized(), false, this.i18n);
} }
/* /*
@@ -301,7 +298,7 @@ public class DistributionSetTable extends AbstractTable {
@Override @Override
public AcceptCriterion getAcceptCriterion() { public AcceptCriterion getAcceptCriterion() {
return distributionsViewAcceptCriteria; return DistributionSetTable.this.distributionsViewAcceptCriteria;
} }
@Override @Override
@@ -317,7 +314,7 @@ public class DistributionSetTable extends AbstractTable {
final TableTransferable transferable = (TableTransferable) event.getTransferable(); final TableTransferable transferable = (TableTransferable) event.getTransferable();
final Table source = transferable.getSourceComponent(); final Table source = transferable.getSourceComponent();
final Set<Long> softwareModuleSelected = (Set<Long>) source.getValue(); final Set<Long> softwareModuleSelected = (Set<Long>) source.getValue();
final Set<Long> softwareModulesIdList = new HashSet<Long>(); final Set<Long> softwareModulesIdList = new HashSet<>();
if (!softwareModuleSelected.contains(transferable.getData("itemId"))) { if (!softwareModuleSelected.contains(transferable.getData("itemId"))) {
softwareModulesIdList.add((Long) transferable.getData("itemId")); softwareModulesIdList.add((Long) transferable.getData("itemId"));
@@ -345,12 +342,12 @@ public class DistributionSetTable extends AbstractTable {
final String distVersion = (String) item.getItemProperty("version").getValue(); final String distVersion = (String) item.getItemProperty("version").getValue();
final DistributionSetIdName distributionSetIdName = new DistributionSetIdName(distId, distName, distVersion); final DistributionSetIdName distributionSetIdName = new DistributionSetIdName(distId, distName, distVersion);
final Map<Long, Set<SoftwareModuleIdName>> map; final HashMap<Long, HashSet<SoftwareModuleIdName>> map;
if (manageDistUIState.getConsolidatedDistSoftwarewList().containsKey(distributionSetIdName)) { if (this.manageDistUIState.getConsolidatedDistSoftwarewList().containsKey(distributionSetIdName)) {
map = manageDistUIState.getConsolidatedDistSoftwarewList().get(distributionSetIdName); map = this.manageDistUIState.getConsolidatedDistSoftwarewList().get(distributionSetIdName);
} else { } else {
map = new HashMap<Long, Set<SoftwareModuleIdName>>(); map = new HashMap<>();
manageDistUIState.getConsolidatedDistSoftwarewList().put(distributionSetIdName, map); this.manageDistUIState.getConsolidatedDistSoftwarewList().put(distributionSetIdName, map);
} }
for (final Long softwareModuleId : softwareModulesIdList) { for (final Long softwareModuleId : softwareModulesIdList) {
@@ -358,7 +355,7 @@ public class DistributionSetTable extends AbstractTable {
final String name = (String) softwareItem.getItemProperty(SPUILabelDefinitions.VAR_NAME).getValue(); final String name = (String) softwareItem.getItemProperty(SPUILabelDefinitions.VAR_NAME).getValue();
final String swVersion = (String) softwareItem.getItemProperty(SPUILabelDefinitions.VAR_VERSION).getValue(); final String swVersion = (String) softwareItem.getItemProperty(SPUILabelDefinitions.VAR_VERSION).getValue();
final SoftwareModule softwareModule = softwareManagement.findSoftwareModuleById(softwareModuleId); final SoftwareModule softwareModule = this.softwareManagement.findSoftwareModuleById(softwareModuleId);
if (validSoftwareModule(distId, softwareModule)) { if (validSoftwareModule(distId, softwareModule)) {
final SoftwareModuleIdName softwareModuleIdName = new SoftwareModuleIdName(softwareModuleId, final SoftwareModuleIdName softwareModuleIdName = new SoftwareModuleIdName(softwareModuleId,
name.concat(":" + swVersion)); name.concat(":" + swVersion));
@@ -382,7 +379,8 @@ public class DistributionSetTable extends AbstractTable {
} }
} }
final Set<SoftwareModuleIdName> softwareModules = new HashSet<SoftwareModuleIdName>(); // hashset is seriablizable
final HashSet<SoftwareModuleIdName> softwareModules = new HashSet<>();
map.keySet().forEach(typeId -> softwareModules.addAll(map.get(typeId))); map.keySet().forEach(typeId -> softwareModules.addAll(map.get(typeId)));
updateDropedDetails(distributionSetIdName, softwareModules); updateDropedDetails(distributionSetIdName, softwareModules);
@@ -393,9 +391,9 @@ public class DistributionSetTable extends AbstractTable {
* @param softwareModule * @param softwareModule
*/ */
private void publishAssignEvent(final Long distId, final SoftwareModule softwareModule) { private void publishAssignEvent(final Long distId, final SoftwareModule softwareModule) {
if (manageDistUIState.getLastSelectedDistribution().isPresent() if (this.manageDistUIState.getLastSelectedDistribution().isPresent()
&& manageDistUIState.getLastSelectedDistribution().get().getId().equals(distId)) { && this.manageDistUIState.getLastSelectedDistribution().get().getId().equals(distId)) {
eventBus.publish(this, this.eventBus.publish(this,
new SoftwareModuleEvent(SoftwareModuleEventType.ASSIGN_SOFTWARE_MODULE, softwareModule)); new SoftwareModuleEvent(SoftwareModuleEventType.ASSIGN_SOFTWARE_MODULE, softwareModule));
} }
} }
@@ -405,8 +403,8 @@ public class DistributionSetTable extends AbstractTable {
* @param softwareModule * @param softwareModule
* @param softwareModuleIdName * @param softwareModuleIdName
*/ */
private void handleFirmwareCase(final Map<Long, Set<SoftwareModuleIdName>> map, final SoftwareModule softwareModule, private void handleFirmwareCase(final Map<Long, HashSet<SoftwareModuleIdName>> map,
final SoftwareModuleIdName softwareModuleIdName) { final SoftwareModule softwareModule, final SoftwareModuleIdName softwareModuleIdName) {
if (softwareModule.getType().getMaxAssignments() == 1) { if (softwareModule.getType().getMaxAssignments() == 1) {
if (!map.containsKey(softwareModule.getType().getId())) { if (!map.containsKey(softwareModule.getType().getId())) {
map.put(softwareModule.getType().getId(), new HashSet<SoftwareModuleIdName>()); map.put(softwareModule.getType().getId(), new HashSet<SoftwareModuleIdName>());
@@ -423,8 +421,8 @@ public class DistributionSetTable extends AbstractTable {
* @param softwareModule * @param softwareModule
* @param softwareModuleIdName * @param softwareModuleIdName
*/ */
private void handleSoftwareCase(final Map<Long, Set<SoftwareModuleIdName>> map, final SoftwareModule softwareModule, private void handleSoftwareCase(final Map<Long, HashSet<SoftwareModuleIdName>> map,
final SoftwareModuleIdName softwareModuleIdName) { final SoftwareModule softwareModule, final SoftwareModuleIdName softwareModuleIdName) {
if (softwareModule.getType().getMaxAssignments() == Integer.MAX_VALUE) { if (softwareModule.getType().getMaxAssignments() == Integer.MAX_VALUE) {
if (!map.containsKey(softwareModule.getType().getId())) { if (!map.containsKey(softwareModule.getType().getId())) {
map.put(softwareModule.getType().getId(), new HashSet<SoftwareModuleIdName>()); map.put(softwareModule.getType().getId(), new HashSet<SoftwareModuleIdName>());
@@ -434,43 +432,43 @@ public class DistributionSetTable extends AbstractTable {
} }
private void updateDropedDetails(final DistributionSetIdName distributionSetIdName, private void updateDropedDetails(final DistributionSetIdName distributionSetIdName,
final Set<SoftwareModuleIdName> softwareModules) { final HashSet<SoftwareModuleIdName> softwareModules) {
LOG.debug("Adding a log to check if distributionSetIdName is null : {} ", distributionSetIdName); LOG.debug("Adding a log to check if distributionSetIdName is null : {} ", distributionSetIdName);
manageDistUIState.getAssignedList().put(distributionSetIdName, softwareModules); this.manageDistUIState.getAssignedList().put(distributionSetIdName, softwareModules);
eventBus.publish(this, DistributionsUIEvent.UPDATE_COUNT); this.eventBus.publish(this, DistributionsUIEvent.UPDATE_COUNT);
eventBus.publish(this, DragEvent.HIDE_DROP_HINT); this.eventBus.publish(this, DragEvent.HIDE_DROP_HINT);
} }
private boolean validSoftwareModule(final Long distId, final SoftwareModule sm) { private boolean validSoftwareModule(final Long distId, final SoftwareModule sm) {
if (!isSoftwareModuleDragged(distId, sm)) { if (!isSoftwareModuleDragged(distId, sm)) {
return false; return false;
} }
final DistributionSet ds = distributionSetManagement.findDistributionSetByIdWithDetails(distId); final DistributionSet ds = this.distributionSetManagement.findDistributionSetByIdWithDetails(distId);
if (!validateSoftwareModule(sm, ds)) { if (!validateSoftwareModule(sm, ds)) {
return false; return false;
} }
try { try {
distributionSetManagement.checkDistributionSetAlreadyUse(ds); this.distributionSetManagement.checkDistributionSetAlreadyUse(ds);
} catch (final EntityLockedException exception) { } catch (final EntityLockedException exception) {
LOG.error("Unable to update distribution : ", exception); LOG.error("Unable to update distribution : ", exception);
notification.displayValidationError(exception.getMessage()); this.notification.displayValidationError(exception.getMessage());
return false; return false;
} }
return true; return true;
} }
private boolean validateSoftwareModule(final SoftwareModule sm, final DistributionSet ds) { private boolean validateSoftwareModule(final SoftwareModule sm, final DistributionSet ds) {
if (targetManagement.countTargetByFilters(null, null, ds.getId(), Boolean.FALSE, new String[] {}) > 0) { if (this.targetManagement.countTargetByFilters(null, null, ds.getId(), Boolean.FALSE, new String[] {}) > 0) {
/* Distribution is already assigned */ /* Distribution is already assigned */
notification.displayValidationError(i18n.get("message.dist.inuse", this.notification.displayValidationError(this.i18n.get("message.dist.inuse",
HawkbitCommonUtil.concatStrings(":", ds.getName(), ds.getVersion()))); HawkbitCommonUtil.concatStrings(":", ds.getName(), ds.getVersion())));
return false; return false;
} }
if (ds.getModules().contains(sm)) { if (ds.getModules().contains(sm)) {
/* Already has software module */ /* Already has software module */
notification.displayValidationError(i18n.get("message.software.dist.already.assigned", this.notification.displayValidationError(this.i18n.get("message.software.dist.already.assigned",
HawkbitCommonUtil.concatStrings(":", ds.getName(), ds.getVersion()), HawkbitCommonUtil.concatStrings(":", ds.getName(), ds.getVersion()),
HawkbitCommonUtil.concatStrings(":", sm.getName(), sm.getVersion()))); HawkbitCommonUtil.concatStrings(":", sm.getName(), sm.getVersion())));
return false; return false;
@@ -478,7 +476,7 @@ public class DistributionSetTable extends AbstractTable {
if (!ds.getType().containsModuleType(sm.getType())) { if (!ds.getType().containsModuleType(sm.getType())) {
/* Invalid type of the software module */ /* Invalid type of the software module */
notification.displayValidationError(i18n.get("message.software.dist.type.notallowed", this.notification.displayValidationError(this.i18n.get("message.software.dist.type.notallowed",
HawkbitCommonUtil.concatStrings(":", sm.getName(), sm.getVersion()), HawkbitCommonUtil.concatStrings(":", sm.getName(), sm.getVersion()),
HawkbitCommonUtil.concatStrings(":", ds.getName(), ds.getVersion()))); HawkbitCommonUtil.concatStrings(":", ds.getName(), ds.getVersion())));
return false; return false;
@@ -487,20 +485,20 @@ public class DistributionSetTable extends AbstractTable {
} }
private boolean isSoftwareModuleDragged(final Long distId, final SoftwareModule sm) { private boolean isSoftwareModuleDragged(final Long distId, final SoftwareModule sm) {
for (final Entry<DistributionSetIdName, Set<SoftwareModuleIdName>> entry : manageDistUIState.getAssignedList() for (final Entry<DistributionSetIdName, HashSet<SoftwareModuleIdName>> entry : this.manageDistUIState
.entrySet()) { .getAssignedList().entrySet()) {
if (distId.equals(entry.getKey().getId())) { if (!distId.equals(entry.getKey().getId())) {
final Set<SoftwareModuleIdName> swModuleIdNames = entry.getValue(); continue;
for (final SoftwareModuleIdName swModuleIdName : swModuleIdNames) {
if ((sm.getName().concat(":" + sm.getVersion())).equals(swModuleIdName.getName())) {
notification.displayValidationError(i18n.get("message.software.already.dragged",
HawkbitCommonUtil.concatStrings(":", sm.getName(), sm.getVersion())));
return false;
}
}
} }
final Set<SoftwareModuleIdName> swModuleIdNames = entry.getValue();
for (final SoftwareModuleIdName swModuleIdName : swModuleIdNames) {
if ((sm.getName().concat(":" + sm.getVersion())).equals(swModuleIdName.getName())) {
this.notification.displayValidationError(this.i18n.get("message.software.already.dragged",
HawkbitCommonUtil.concatStrings(":", sm.getName(), sm.getVersion())));
return false;
}
}
} }
return true; return true;
} }
@@ -513,19 +511,19 @@ public class DistributionSetTable extends AbstractTable {
* @return boolean as flag * @return boolean as flag
*/ */
private Boolean doValidation(final DragAndDropEvent dragEvent) { private Boolean doValidation(final DragAndDropEvent dragEvent) {
if (!permissionChecker.hasUpdateDistributionPermission()) { if (!this.permissionChecker.hasUpdateDistributionPermission()) {
notification.displayValidationError(i18n.get("message.permission.insufficient")); this.notification.displayValidationError(this.i18n.get("message.permission.insufficient"));
return false; return false;
} else { } else {
final Component compsource = dragEvent.getTransferable().getSourceComponent(); final Component compsource = dragEvent.getTransferable().getSourceComponent();
final Table source = (Table) compsource; final Table source = (Table) compsource;
if (compsource instanceof Table) { if (compsource instanceof Table) {
if (!source.getId().equals(SPUIComponetIdProvider.UPLOAD_SOFTWARE_MODULE_TABLE)) { if (!source.getId().equals(SPUIComponetIdProvider.UPLOAD_SOFTWARE_MODULE_TABLE)) {
notification.displayValidationError(i18n.get("message.action.not.allowed")); this.notification.displayValidationError(this.i18n.get("message.action.not.allowed"));
return false; return false;
} }
} else { } else {
notification.displayValidationError(i18n.get("message.action.not.allowed")); this.notification.displayValidationError(this.i18n.get("message.action.not.allowed"));
return false; return false;
} }
} }
@@ -557,28 +555,25 @@ public class DistributionSetTable extends AbstractTable {
item.getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE) item.getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE)
.setValue(SPDateTimeUtil.getFormattedDate(distributionSet.getLastModifiedAt())); .setValue(SPDateTimeUtil.getFormattedDate(distributionSet.getLastModifiedAt()));
item.getItemProperty(SPUILabelDefinitions.VAR_IS_DISTRIBUTION_COMPLETE).setValue(distributionSet.isComplete()); item.getItemProperty(SPUILabelDefinitions.VAR_IS_DISTRIBUTION_COMPLETE).setValue(distributionSet.isComplete());
if (manageDistUIState.getSelectedDistributions().isPresent()) { if (this.manageDistUIState.getSelectedDistributions().isPresent()) {
manageDistUIState.getSelectedDistributions().get().stream().forEach(dsNameId -> unselect(dsNameId)); this.manageDistUIState.getSelectedDistributions().get().stream().forEach(dsNameId -> unselect(dsNameId));
} }
select(distributionSet.getDistributionSetIdName()); select(distributionSet.getDistributionSetIdName());
} }
private void addTableStyleGenerator() { private void addTableStyleGenerator() {
setCellStyleGenerator(new Table.CellStyleGenerator() { setCellStyleGenerator((source, itemId, propertyId) -> {
@Override if (propertyId == null) {
public String getStyle(final Table source, final Object itemId, final Object propertyId) { // Styling for row
if (propertyId == null) { final Item item = getItem(itemId);
// Styling for row final Boolean isComplete = (Boolean) item
final Item item = getItem(itemId); .getItemProperty(SPUILabelDefinitions.VAR_IS_DISTRIBUTION_COMPLETE).getValue();
final Boolean isComplete = (Boolean) item if (!isComplete) {
.getItemProperty(SPUILabelDefinitions.VAR_IS_DISTRIBUTION_COMPLETE).getValue(); return SPUIDefinitions.DISABLE_DISTRIBUTION;
if (!isComplete) {
return SPUIDefinitions.DISABLE_DISTRIBUTION;
}
return null;
} else {
return null;
} }
return null;
} else {
return null;
} }
}); });
} }
@@ -622,15 +617,15 @@ public class DistributionSetTable extends AbstractTable {
* It's good manners to do this, even though vaadin-spring will * It's good manners to do this, even though vaadin-spring will
* automatically unsubscribe when this UI is garbage collected. * automatically unsubscribe when this UI is garbage collected.
*/ */
eventBus.unsubscribe(this); this.eventBus.unsubscribe(this);
} }
private void setNoDataAvailable() { private void setNoDataAvailable() {
final int containerSize = getContainerDataSource().size(); final int containerSize = getContainerDataSource().size();
if (containerSize == 0) { if (containerSize == 0) {
manageDistUIState.setNoDataAvailableDist(true); this.manageDistUIState.setNoDataAvailableDist(true);
} else { } else {
manageDistUIState.setNoDataAvailableDist(false); this.manageDistUIState.setNoDataAvailableDist(false);
} }
} }
} }

View File

@@ -98,10 +98,11 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
* @see * @see
* org.eclipse.hawkbit.server.ui.common.footer.DeleteActionsLayout#init() * org.eclipse.hawkbit.server.ui.common.footer.DeleteActionsLayout#init()
*/ */
@Override
@PostConstruct @PostConstruct
protected void init() { protected void init() {
super.init(); super.init();
eventBus.subscribe(this); this.eventBus.subscribe(this);
} }
@PreDestroy @PreDestroy
@@ -110,7 +111,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
* It's good manners to do this, even though vaadin-spring will * It's good manners to do this, even though vaadin-spring will
* automatically unsubscribe when this UI is garbage collected. * automatically unsubscribe when this UI is garbage collected.
*/ */
eventBus.unsubscribe(this); this.eventBus.unsubscribe(this);
} }
@EventBusListenerMethod(scope = EventScope.SESSION) @EventBusListenerMethod(scope = EventScope.SESSION)
@@ -128,9 +129,9 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
UI.getCurrent().access(() -> { UI.getCurrent().access(() -> {
if (!hasUnsavedActions()) { if (!hasUnsavedActions()) {
closeUnsavedActionsWindow(); closeUnsavedActionsWindow();
final String message = distConfirmationWindowLayout.getConsolidatedMessage(); final String message = this.distConfirmationWindowLayout.getConsolidatedMessage();
if (message != null && message.length() > 0) { if (message != null && message.length() > 0) {
notification.displaySuccess(message); this.notification.displaySuccess(message);
} }
} }
updateDSActionCount(); updateDSActionCount();
@@ -147,7 +148,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
*/ */
@Override @Override
protected boolean hasDeletePermission() { protected boolean hasDeletePermission() {
return permChecker.hasDeleteDistributionPermission(); return this.permChecker.hasDeleteDistributionPermission();
} }
@@ -161,7 +162,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
@Override @Override
protected boolean hasUpdatePermission() { protected boolean hasUpdatePermission() {
return permChecker.hasUpdateDistributionPermission(); return this.permChecker.hasUpdateDistributionPermission();
} }
/* /*
@@ -173,7 +174,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
*/ */
@Override @Override
protected String getDeleteAreaLabel() { protected String getDeleteAreaLabel() {
return i18n.get("label.components.drop.area"); return this.i18n.get("label.components.drop.area");
} }
/* /*
@@ -199,7 +200,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
@Override @Override
protected AcceptCriterion getDeleteLayoutAcceptCriteria() { protected AcceptCriterion getDeleteLayoutAcceptCriteria() {
return distributionsViewAcceptCriteria; return this.distributionsViewAcceptCriteria;
} }
/* /*
@@ -227,7 +228,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
processDeleteSWType(sourceComponent.getId()); processDeleteSWType(sourceComponent.getId());
} }
eventBus.publish(this, DragEvent.HIDE_DROP_HINT); this.eventBus.publish(this, DragEvent.HIDE_DROP_HINT);
hideDropHints(); hideDropHints();
} }
@@ -236,12 +237,12 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
final String distTypeName = HawkbitCommonUtil.removePrefix(distTypeId, final String distTypeName = HawkbitCommonUtil.removePrefix(distTypeId,
SPUIDefinitions.DISTRIBUTION_SET_TYPE_ID_PREFIXS); SPUIDefinitions.DISTRIBUTION_SET_TYPE_ID_PREFIXS);
if (isDsTypeSelected(distTypeName)) { if (isDsTypeSelected(distTypeName)) {
notification this.notification.displayValidationError(
.displayValidationError(i18n.get("message.dist.type.check.delete", new Object[] { distTypeName })); this.i18n.get("message.dist.type.check.delete", new Object[] { distTypeName }));
} else if (isDefaultDsType(distTypeName)) { } else if (isDefaultDsType(distTypeName)) {
notification.displayValidationError(i18n.get("message.cannot.delete.default.dstype")); this.notification.displayValidationError(this.i18n.get("message.cannot.delete.default.dstype"));
} else { } else {
manageDistUIState.getSelectedDeleteDistSetTypes().add(distTypeName); this.manageDistUIState.getSelectedDeleteDistSetTypes().add(distTypeName);
updateDSActionCount(); updateDSActionCount();
} }
} }
@@ -253,7 +254,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
* @return true if ds type is selected * @return true if ds type is selected
*/ */
private boolean isDsTypeSelected(final String distTypeName) { private boolean isDsTypeSelected(final String distTypeName) {
return null != manageDistUIState.getManageDistFilters().getClickedDistSetType() && manageDistUIState return null != this.manageDistUIState.getManageDistFilters().getClickedDistSetType() && this.manageDistUIState
.getManageDistFilters().getClickedDistSetType().getName().equalsIgnoreCase(distTypeName); .getManageDistFilters().getClickedDistSetType().getName().equalsIgnoreCase(distTypeName);
} }
@@ -261,13 +262,13 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
final String swModuleTypeName = HawkbitCommonUtil.removePrefix(swTypeId, final String swModuleTypeName = HawkbitCommonUtil.removePrefix(swTypeId,
SPUIDefinitions.SOFTWARE_MODULE_TAG_ID_PREFIXS); SPUIDefinitions.SOFTWARE_MODULE_TAG_ID_PREFIXS);
if (manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType().isPresent() if (this.manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType().isPresent()
&& manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType().get().getName() && this.manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType().get().getName()
.equalsIgnoreCase(swModuleTypeName)) { .equalsIgnoreCase(swModuleTypeName)) {
notification.displayValidationError( this.notification.displayValidationError(
i18n.get("message.swmodule.type.check.delete", new Object[] { swModuleTypeName })); this.i18n.get("message.swmodule.type.check.delete", new Object[] { swModuleTypeName }));
} else { } else {
manageDistUIState.getSelectedDeleteSWModuleTypes().add(swModuleTypeName); this.manageDistUIState.getSelectedDeleteSWModuleTypes().add(swModuleTypeName);
updateDSActionCount(); updateDSActionCount();
} }
@@ -276,7 +277,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
private void addInDeleteDistributionList(final Table sourceTable, final TableTransferable transferable) { private void addInDeleteDistributionList(final Table sourceTable, final TableTransferable transferable) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Set<DistributionSetIdName> distSelected = (Set<DistributionSetIdName>) sourceTable.getValue(); final Set<DistributionSetIdName> distSelected = (Set<DistributionSetIdName>) sourceTable.getValue();
final Set<DistributionSetIdName> distributionIdNameSet = new HashSet<DistributionSetIdName>(); final Set<DistributionSetIdName> distributionIdNameSet = new HashSet<>();
if (!distSelected.contains(transferable.getData(SPUIDefinitions.ITEMID))) { if (!distSelected.contains(transferable.getData(SPUIDefinitions.ITEMID))) {
distributionIdNameSet.add((DistributionSetIdName) transferable.getData(SPUIDefinitions.ITEMID)); distributionIdNameSet.add((DistributionSetIdName) transferable.getData(SPUIDefinitions.ITEMID));
} else { } else {
@@ -287,9 +288,9 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
* the deleted list (or) some distributions are already in the deleted * the deleted list (or) some distributions are already in the deleted
* distribution list. * distribution list.
*/ */
final int existingDeletedDistributionsSize = manageDistUIState.getDeletedDistributionList().size(); final int existingDeletedDistributionsSize = this.manageDistUIState.getDeletedDistributionList().size();
manageDistUIState.getDeletedDistributionList().addAll(distributionIdNameSet); this.manageDistUIState.getDeletedDistributionList().addAll(distributionIdNameSet);
final int newDeletedDistributionsSize = manageDistUIState.getDeletedDistributionList().size(); final int newDeletedDistributionsSize = this.manageDistUIState.getDeletedDistributionList().size();
if (newDeletedDistributionsSize == existingDeletedDistributionsSize) { if (newDeletedDistributionsSize == existingDeletedDistributionsSize) {
/* /*
* No new distributions are added, all distributions dropped now are * No new distributions are added, all distributions dropped now are
@@ -297,7 +298,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
* message accordingly. * message accordingly.
*/ */
uiNotification.displayValidationError(i18n.get("message.targets.already.deleted")); this.uiNotification.displayValidationError(this.i18n.get("message.targets.already.deleted"));
} else if (newDeletedDistributionsSize - existingDeletedDistributionsSize != distributionIdNameSet.size()) { } else if (newDeletedDistributionsSize - existingDeletedDistributionsSize != distributionIdNameSet.size()) {
/* /*
* Not the all distributions dropped now are added to the delete * Not the all distributions dropped now are added to the delete
@@ -305,7 +306,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
* delete list. Hence display warning message accordingly. * delete list. Hence display warning message accordingly.
*/ */
uiNotification.displayValidationError(i18n.get("message.dist.deleted.pending")); this.uiNotification.displayValidationError(this.i18n.get("message.dist.deleted.pending"));
} }
} }
@@ -314,7 +315,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Set<Long> swModuleSelected = (Set<Long>) sourceTable.getValue(); final Set<Long> swModuleSelected = (Set<Long>) sourceTable.getValue();
final Set<Long> swModuleIdNameSet = new HashSet<Long>(); final Set<Long> swModuleIdNameSet = new HashSet<>();
if (!swModuleSelected.contains(transferable.getData(SPUIDefinitions.ITEMID))) { if (!swModuleSelected.contains(transferable.getData(SPUIDefinitions.ITEMID))) {
swModuleIdNameSet.add((Long) transferable.getData(SPUIDefinitions.ITEMID)); swModuleIdNameSet.add((Long) transferable.getData(SPUIDefinitions.ITEMID));
} else { } else {
@@ -323,7 +324,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
swModuleIdNameSet.forEach(id -> { swModuleIdNameSet.forEach(id -> {
final String swModuleName = (String) sourceTable.getContainerDataSource().getItem(id) final String swModuleName = (String) sourceTable.getContainerDataSource().getItem(id)
.getItemProperty(SPUILabelDefinitions.NAME_VERSION).getValue(); .getItemProperty(SPUILabelDefinitions.NAME_VERSION).getValue();
manageDistUIState.getDeleteSofwareModulesList().put(id, swModuleName); this.manageDistUIState.getDeleteSofwareModulesList().put(id, swModuleName);
}); });
} }
@@ -331,14 +332,14 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
* Update the software module delete count. * Update the software module delete count.
*/ */
private void updateDSActionCount() { private void updateDSActionCount() {
int count = manageDistUIState.getSelectedDeleteDistSetTypes().size() int count = this.manageDistUIState.getSelectedDeleteDistSetTypes().size()
+ manageDistUIState.getSelectedDeleteSWModuleTypes().size() + this.manageDistUIState.getSelectedDeleteSWModuleTypes().size()
+ manageDistUIState.getDeleteSofwareModulesList().size() + this.manageDistUIState.getDeleteSofwareModulesList().size()
+ manageDistUIState.getDeletedDistributionList().size(); + this.manageDistUIState.getDeletedDistributionList().size();
for (final Entry<DistributionSetIdName, Set<SoftwareModuleIdName>> mapEntry : manageDistUIState for (final Entry<DistributionSetIdName, HashSet<SoftwareModuleIdName>> mapEntry : this.manageDistUIState
.getAssignedList().entrySet()) { .getAssignedList().entrySet()) {
count += manageDistUIState.getAssignedList().get(mapEntry.getKey()).size(); count += this.manageDistUIState.getAssignedList().get(mapEntry.getKey()).size();
} }
updateActionsCount(count); updateActionsCount(count);
} }
@@ -357,22 +358,12 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
} }
/**
*
* @param source
* @return true if it is distribution table
*/
private boolean isDistributionTable(final Component source) { private boolean isDistributionTable(final Component source) {
return HawkbitCommonUtil.bothSame(source.getId(), SPUIComponetIdProvider.DIST_TABLE_ID); return SPUIComponetIdProvider.DIST_TABLE_ID.equals(source.getId());
} }
/**
*
* @param source
* @return true if it is SoftwareModule table
*/
private boolean isSoftwareModuleTable(final Component source) { private boolean isSoftwareModuleTable(final Component source) {
return HawkbitCommonUtil.bothSame(source.getId(), SPUIComponetIdProvider.UPLOAD_SOFTWARE_MODULE_TABLE); return SPUIComponetIdProvider.UPLOAD_SOFTWARE_MODULE_TABLE.equals(source.getId());
} }
/* /*
@@ -384,7 +375,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
*/ */
@Override @Override
protected String getNoActionsButtonLabel() { protected String getNoActionsButtonLabel() {
return i18n.get("button.no.actions"); return this.i18n.get("button.no.actions");
} }
/* /*
@@ -397,7 +388,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
@Override @Override
protected String getActionsButtonLabel() { protected String getActionsButtonLabel() {
return i18n.get("button.actions"); return this.i18n.get("button.actions");
} }
@@ -423,7 +414,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
*/ */
@Override @Override
protected String getUnsavedActionsWindowCaption() { protected String getUnsavedActionsWindowCaption() {
return i18n.get("caption.save.window"); return this.i18n.get("caption.save.window");
} }
/* /*
@@ -435,9 +426,9 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
*/ */
@Override @Override
protected void unsavedActionsWindowClosed() { protected void unsavedActionsWindowClosed() {
final String message = distConfirmationWindowLayout.getConsolidatedMessage(); final String message = this.distConfirmationWindowLayout.getConsolidatedMessage();
if (message != null && message.length() > 0) { if (message != null && message.length() > 0) {
notification.displaySuccess(message); this.notification.displaySuccess(message);
} }
} }
@@ -451,8 +442,8 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
*/ */
@Override @Override
protected Component getUnsavedActionsWindowContent() { protected Component getUnsavedActionsWindowContent() {
distConfirmationWindowLayout.init(); this.distConfirmationWindowLayout.init();
return distConfirmationWindowLayout; return this.distConfirmationWindowLayout;
} }
/* /*
@@ -466,12 +457,12 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
protected boolean hasUnsavedActions() { protected boolean hasUnsavedActions() {
boolean unSavedActionsTypes = false; boolean unSavedActionsTypes = false;
boolean unSavedActionsTables = false; boolean unSavedActionsTables = false;
if (!manageDistUIState.getSelectedDeleteDistSetTypes().isEmpty() if (!this.manageDistUIState.getSelectedDeleteDistSetTypes().isEmpty()
|| !manageDistUIState.getSelectedDeleteSWModuleTypes().isEmpty()) { || !this.manageDistUIState.getSelectedDeleteSWModuleTypes().isEmpty()) {
unSavedActionsTypes = true; unSavedActionsTypes = true;
} else if (!manageDistUIState.getDeleteSofwareModulesList().isEmpty() } else if (!this.manageDistUIState.getDeleteSofwareModulesList().isEmpty()
|| !manageDistUIState.getDeletedDistributionList().isEmpty() || !this.manageDistUIState.getDeletedDistributionList().isEmpty()
|| !manageDistUIState.getAssignedList().isEmpty()) { || !this.manageDistUIState.getAssignedList().isEmpty()) {
unSavedActionsTables = true; unSavedActionsTables = true;
} }
@@ -526,7 +517,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
} }
private DistributionSetType getCurrentDistributionSetType() { private DistributionSetType getCurrentDistributionSetType() {
return systemManagement.getTenantMetadata().getDefaultDsType(); return this.systemManagement.getTenantMetadata().getDefaultDsType();
} }
/** /**

View File

@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.ui.distributions.footer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@@ -113,31 +114,32 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
*/ */
@Override @Override
protected Map<String, ConfirmationTab> getConfimrationTabs() { protected Map<String, ConfirmationTab> getConfimrationTabs() {
final Map<String, ConfirmationTab> tabs = new HashMap<String, ConfirmationTab>(); final Map<String, ConfirmationTab> tabs = new HashMap<>();
/* Create tab for SW Modules delete */ /* Create tab for SW Modules delete */
if (!manageDistUIState.getDeleteSofwareModulesList().isEmpty()) { if (!this.manageDistUIState.getDeleteSofwareModulesList().isEmpty()) {
tabs.put(i18n.get("caption.delete.swmodule.accordion.tab"), createSMDeleteConfirmationTab()); tabs.put(this.i18n.get("caption.delete.swmodule.accordion.tab"), createSMDeleteConfirmationTab());
} }
/* Create tab for SW Module Type delete */ /* Create tab for SW Module Type delete */
if (!manageDistUIState.getSelectedDeleteSWModuleTypes().isEmpty()) { if (!this.manageDistUIState.getSelectedDeleteSWModuleTypes().isEmpty()) {
tabs.put(i18n.get("caption.delete.sw.module.type.accordion.tab"), createSMtypeDeleteConfirmationTab()); tabs.put(this.i18n.get("caption.delete.sw.module.type.accordion.tab"), createSMtypeDeleteConfirmationTab());
} }
/* Create tab for Distributions delete */ /* Create tab for Distributions delete */
if (!manageDistUIState.getDeletedDistributionList().isEmpty()) { if (!this.manageDistUIState.getDeletedDistributionList().isEmpty()) {
tabs.put(i18n.get("caption.delete.dist.accordion.tab"), createDistDeleteConfirmationTab()); tabs.put(this.i18n.get("caption.delete.dist.accordion.tab"), createDistDeleteConfirmationTab());
} }
/* Create tab for Distribution Set Types delete */ /* Create tab for Distribution Set Types delete */
if (!manageDistUIState.getSelectedDeleteDistSetTypes().isEmpty()) { if (!this.manageDistUIState.getSelectedDeleteDistSetTypes().isEmpty()) {
tabs.put(i18n.get("caption.delete.dist.set.type.accordion.tab"), createDistSetTypeDeleteConfirmationTab()); tabs.put(this.i18n.get("caption.delete.dist.set.type.accordion.tab"),
createDistSetTypeDeleteConfirmationTab());
} }
/* Create tab for Assign Software Module */ /* Create tab for Assign Software Module */
if (!manageDistUIState.getAssignedList().isEmpty()) { if (!this.manageDistUIState.getAssignedList().isEmpty()) {
tabs.put(i18n.get("caption.assign.dist.accordion.tab"), createAssignSWModuleConfirmationTab()); tabs.put(this.i18n.get("caption.assign.dist.accordion.tab"), createAssignSWModuleConfirmationTab());
} }
return tabs; return tabs;
@@ -149,10 +151,10 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
tab.getConfirmAll().setId(SPUIComponetIdProvider.SW_DELETE_ALL); tab.getConfirmAll().setId(SPUIComponetIdProvider.SW_DELETE_ALL);
tab.getConfirmAll().setIcon(FontAwesome.TRASH_O); tab.getConfirmAll().setIcon(FontAwesome.TRASH_O);
tab.getConfirmAll().setCaption(i18n.get(SPUILabelDefinitions.BUTTON_DELETE_ALL)); tab.getConfirmAll().setCaption(this.i18n.get(SPUILabelDefinitions.BUTTON_DELETE_ALL));
tab.getConfirmAll().addClickListener(event -> deleteSMAll(tab)); tab.getConfirmAll().addClickListener(event -> deleteSMAll(tab));
tab.getDiscardAll().setCaption(i18n.get(SPUILabelDefinitions.BUTTON_DISCARD_ALL)); tab.getDiscardAll().setCaption(this.i18n.get(SPUILabelDefinitions.BUTTON_DISCARD_ALL));
tab.getDiscardAll().addClickListener(event -> discardSMAll(tab)); tab.getDiscardAll().addClickListener(event -> discardSMAll(tab));
/* Add items container to the table. */ /* Add items container to the table. */
@@ -175,8 +177,8 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) {
visibleColumnIds.add(SW_MODULE_NAME_MSG); visibleColumnIds.add(SW_MODULE_NAME_MSG);
visibleColumnIds.add(SW_DISCARD_CHGS); visibleColumnIds.add(SW_DISCARD_CHGS);
visibleColumnLabels.add(i18n.get("upload.swModuleTable.header")); visibleColumnLabels.add(this.i18n.get("upload.swModuleTable.header"));
visibleColumnLabels.add(i18n.get("header.second.deletetarget.table")); visibleColumnLabels.add(this.i18n.get("header.second.deletetarget.table"));
} }
tab.getTable().setVisibleColumns(visibleColumnIds.toArray()); tab.getTable().setVisibleColumns(visibleColumnIds.toArray());
tab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0])); tab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0]));
@@ -188,44 +190,46 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
} }
private void deleteSMAll(final ConfirmationTab tab) { private void deleteSMAll(final ConfirmationTab tab) {
final Set<Long> swmoduleIds = manageDistUIState.getDeleteSofwareModulesList().keySet(); final Set<Long> swmoduleIds = this.manageDistUIState.getDeleteSofwareModulesList().keySet();
if (null != manageDistUIState.getAssignedList() && !manageDistUIState.getAssignedList().isEmpty()) {
for (final Entry<DistributionSetIdName, Set<SoftwareModuleIdName>> entryAssignSM : manageDistUIState
.getAssignedList().entrySet()) {
for (final Entry<Long, String> entryDeleteSM : manageDistUIState.getDeleteSofwareModulesList()
.entrySet()) {
final SoftwareModuleIdName smIdName = new SoftwareModuleIdName(entryDeleteSM.getKey(),
entryDeleteSM.getValue());
if (entryAssignSM.getValue().contains(smIdName)) {
entryAssignSM.getValue().remove(smIdName);
assignmnetTab.getTable().removeItem(HawkbitCommonUtil.concatStrings("|||",
entryAssignSM.getKey().getId().toString(), smIdName.getId().toString()));
}
if (entryAssignSM.getValue().isEmpty()) {
manageDistUIState.getAssignedList().remove(entryAssignSM.getKey());
}
}
}
if (this.manageDistUIState.getAssignedList() == null || this.manageDistUIState.getAssignedList().isEmpty()) {
removeAssignedSoftwareModules();
} }
softwareManagement.deleteSoftwareModules(swmoduleIds); this.softwareManagement.deleteSoftwareModules(swmoduleIds);
addToConsolitatedMsg(FontAwesome.TRASH_O.getHtml() + SPUILabelDefinitions.HTML_SPACE addToConsolitatedMsg(FontAwesome.TRASH_O.getHtml() + SPUILabelDefinitions.HTML_SPACE
+ i18n.get("message.swModule.deleted", swmoduleIds.size())); + this.i18n.get("message.swModule.deleted", swmoduleIds.size()));
manageDistUIState.getDeleteSofwareModulesList().clear(); this.manageDistUIState.getDeleteSofwareModulesList().clear();
removeCurrentTab(tab); removeCurrentTab(tab);
setActionMessage(i18n.get("message.software.delete.success")); setActionMessage(this.i18n.get("message.software.delete.success"));
eventBus.publish(this, SaveActionWindowEvent.DELETE_ALL_SOFWARE); this.eventBus.publish(this, SaveActionWindowEvent.DELETE_ALL_SOFWARE);
}
private void removeAssignedSoftwareModules() {
for (final Entry<DistributionSetIdName, HashSet<SoftwareModuleIdName>> entryAssignSM : this.manageDistUIState
.getAssignedList().entrySet()) {
for (final Entry<Long, String> entryDeleteSM : this.manageDistUIState.getDeleteSofwareModulesList()
.entrySet()) {
final SoftwareModuleIdName smIdName = new SoftwareModuleIdName(entryDeleteSM.getKey(),
entryDeleteSM.getValue());
if (entryAssignSM.getValue().contains(smIdName)) {
entryAssignSM.getValue().remove(smIdName);
this.assignmnetTab.getTable().removeItem(HawkbitCommonUtil.concatStrings("|||",
entryAssignSM.getKey().getId().toString(), smIdName.getId().toString()));
}
if (entryAssignSM.getValue().isEmpty()) {
this.manageDistUIState.getAssignedList().remove(entryAssignSM.getKey());
}
}
}
} }
private void discardSMAll(final ConfirmationTab tab) { private void discardSMAll(final ConfirmationTab tab) {
removeCurrentTab(tab); removeCurrentTab(tab);
manageDistUIState.getDeleteSofwareModulesList().clear(); this.manageDistUIState.getDeleteSofwareModulesList().clear();
setActionMessage(i18n.get("message.software.discard.success")); setActionMessage(this.i18n.get("message.software.discard.success"));
eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_SOFTWARE); this.eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_SOFTWARE);
} }
/** /**
@@ -238,30 +242,29 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
final IndexedContainer swcontactContainer = new IndexedContainer(); final IndexedContainer swcontactContainer = new IndexedContainer();
swcontactContainer.addContainerProperty("SWModuleId", String.class, ""); swcontactContainer.addContainerProperty("SWModuleId", String.class, "");
swcontactContainer.addContainerProperty(SW_MODULE_NAME_MSG, String.class, ""); swcontactContainer.addContainerProperty(SW_MODULE_NAME_MSG, String.class, "");
Item item = null; for (final Long swModuleID : this.manageDistUIState.getDeleteSofwareModulesList().keySet()) {
for (final Long swModuleID : manageDistUIState.getDeleteSofwareModulesList().keySet()) { final Item item = swcontactContainer.addItem(swModuleID);
item = swcontactContainer.addItem(swModuleID);
item.getItemProperty("SWModuleId").setValue(swModuleID.toString()); item.getItemProperty("SWModuleId").setValue(swModuleID.toString());
item.getItemProperty(SW_MODULE_NAME_MSG) item.getItemProperty(SW_MODULE_NAME_MSG)
.setValue(manageDistUIState.getDeleteSofwareModulesList().get(swModuleID)); .setValue(this.manageDistUIState.getDeleteSofwareModulesList().get(swModuleID));
} }
return swcontactContainer; return swcontactContainer;
} }
private void discardSoftwareDelete(final Button.ClickEvent event, final Object itemId, final ConfirmationTab tab) { private void discardSoftwareDelete(final Button.ClickEvent event, final Object itemId, final ConfirmationTab tab) {
final Long swmoduleId = (Long) ((Button) event.getComponent()).getData(); final Long swmoduleId = (Long) ((Button) event.getComponent()).getData();
if (null != manageDistUIState.getDeleteSofwareModulesList() if (null != this.manageDistUIState.getDeleteSofwareModulesList()
&& !manageDistUIState.getDeleteSofwareModulesList().isEmpty() && !this.manageDistUIState.getDeleteSofwareModulesList().isEmpty()
&& manageDistUIState.getDeleteSofwareModulesList().containsKey(swmoduleId)) { && this.manageDistUIState.getDeleteSofwareModulesList().containsKey(swmoduleId)) {
manageDistUIState.getDeleteSofwareModulesList().remove(swmoduleId); this.manageDistUIState.getDeleteSofwareModulesList().remove(swmoduleId);
} }
tab.getTable().getContainerDataSource().removeItem(itemId); tab.getTable().getContainerDataSource().removeItem(itemId);
final int deleteCount = tab.getTable().size(); final int deleteCount = tab.getTable().size();
if (0 == deleteCount) { if (0 == deleteCount) {
removeCurrentTab(tab); removeCurrentTab(tab);
eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_SOFTWARE); this.eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_SOFTWARE);
} else { } else {
eventBus.publish(this, SaveActionWindowEvent.DISCARD_DELETE_SOFTWARE); this.eventBus.publish(this, SaveActionWindowEvent.DISCARD_DELETE_SOFTWARE);
} }
} }
@@ -270,10 +273,10 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
tab.getConfirmAll().setId(SPUIComponetIdProvider.SAVE_DELETE_SW_MODULE_TYPE); tab.getConfirmAll().setId(SPUIComponetIdProvider.SAVE_DELETE_SW_MODULE_TYPE);
tab.getConfirmAll().setIcon(FontAwesome.TRASH_O); tab.getConfirmAll().setIcon(FontAwesome.TRASH_O);
tab.getConfirmAll().setCaption(i18n.get(SPUILabelDefinitions.BUTTON_DELETE_ALL)); tab.getConfirmAll().setCaption(this.i18n.get(SPUILabelDefinitions.BUTTON_DELETE_ALL));
tab.getConfirmAll().addClickListener(event -> deleteSMtypeAll(tab)); tab.getConfirmAll().addClickListener(event -> deleteSMtypeAll(tab));
tab.getDiscardAll().setCaption(i18n.get(SPUILabelDefinitions.BUTTON_DISCARD_ALL)); tab.getDiscardAll().setCaption(this.i18n.get(SPUILabelDefinitions.BUTTON_DISCARD_ALL));
tab.getDiscardAll().setId(SPUIComponetIdProvider.DISCARD_SW_MODULE_TYPE); tab.getDiscardAll().setId(SPUIComponetIdProvider.DISCARD_SW_MODULE_TYPE);
tab.getDiscardAll().addClickListener(event -> discardSMtypeAll(tab)); tab.getDiscardAll().addClickListener(event -> discardSMtypeAll(tab));
@@ -300,8 +303,8 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) {
visibleColumnIds.add(SW_MODULE_TYPE_NAME); visibleColumnIds.add(SW_MODULE_TYPE_NAME);
visibleColumnIds.add(DISCARD); visibleColumnIds.add(DISCARD);
visibleColumnLabels.add(i18n.get("header.first.delete.swmodule.type.table")); visibleColumnLabels.add(this.i18n.get("header.first.delete.swmodule.type.table"));
visibleColumnLabels.add(i18n.get("header.second.delete.swmodule.type.table")); visibleColumnLabels.add(this.i18n.get("header.second.delete.swmodule.type.table"));
} }
tab.getTable().setVisibleColumns(visibleColumnIds.toArray()); tab.getTable().setVisibleColumns(visibleColumnIds.toArray());
@@ -314,32 +317,32 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
} }
private void deleteSMtypeAll(final ConfirmationTab tab) { private void deleteSMtypeAll(final ConfirmationTab tab) {
final int deleteSWModuleTypeCount = manageDistUIState.getSelectedDeleteSWModuleTypes().size(); final int deleteSWModuleTypeCount = this.manageDistUIState.getSelectedDeleteSWModuleTypes().size();
for (final String swModuleTypeName : manageDistUIState.getSelectedDeleteSWModuleTypes()) { for (final String swModuleTypeName : this.manageDistUIState.getSelectedDeleteSWModuleTypes()) {
softwareManagement this.softwareManagement
.deleteSoftwareModuleType(softwareManagement.findSoftwareModuleTypeByName(swModuleTypeName)); .deleteSoftwareModuleType(this.softwareManagement.findSoftwareModuleTypeByName(swModuleTypeName));
} }
addToConsolitatedMsg(FontAwesome.TASKS.getHtml() + SPUILabelDefinitions.HTML_SPACE addToConsolitatedMsg(FontAwesome.TASKS.getHtml() + SPUILabelDefinitions.HTML_SPACE
+ i18n.get("message.sw.module.type.delete", new Object[] { deleteSWModuleTypeCount })); + this.i18n.get("message.sw.module.type.delete", new Object[] { deleteSWModuleTypeCount }));
manageDistUIState.getSelectedDeleteSWModuleTypes().clear(); this.manageDistUIState.getSelectedDeleteSWModuleTypes().clear();
removeCurrentTab(tab); removeCurrentTab(tab);
setActionMessage(i18n.get("message.software.type.delete.success")); setActionMessage(this.i18n.get("message.software.type.delete.success"));
eventBus.publish(this, SaveActionWindowEvent.SAVED_DELETE_SW_MODULE_TYPES); this.eventBus.publish(this, SaveActionWindowEvent.SAVED_DELETE_SW_MODULE_TYPES);
} }
private void discardSMtypeAll(final ConfirmationTab tab) { private void discardSMtypeAll(final ConfirmationTab tab) {
removeCurrentTab(tab); removeCurrentTab(tab);
manageDistUIState.getSelectedDeleteSWModuleTypes().clear(); this.manageDistUIState.getSelectedDeleteSWModuleTypes().clear();
setActionMessage(i18n.get("message.software.type.discard.success")); setActionMessage(this.i18n.get("message.software.type.discard.success"));
eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_DELETE_SW_MODULE_TYPES); this.eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_DELETE_SW_MODULE_TYPES);
} }
private Container getSWModuleTypeTableContainer() { private Container getSWModuleTypeTableContainer() {
final IndexedContainer contactContainer = new IndexedContainer(); final IndexedContainer contactContainer = new IndexedContainer();
contactContainer.addContainerProperty(SW_MODULE_TYPE_NAME, String.class, ""); contactContainer.addContainerProperty(SW_MODULE_TYPE_NAME, String.class, "");
for (final String swModuleTypeName : manageDistUIState.getSelectedDeleteSWModuleTypes()) { for (final String swModuleTypeName : this.manageDistUIState.getSelectedDeleteSWModuleTypes()) {
final Item saveTblitem = contactContainer.addItem(swModuleTypeName); final Item saveTblitem = contactContainer.addItem(swModuleTypeName);
saveTblitem.getItemProperty(SW_MODULE_TYPE_NAME).setValue(swModuleTypeName); saveTblitem.getItemProperty(SW_MODULE_TYPE_NAME).setValue(swModuleTypeName);
@@ -350,18 +353,18 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
private void discardSoftwareTypeDelete(final String discardSWModuleType, final Object itemId, private void discardSoftwareTypeDelete(final String discardSWModuleType, final Object itemId,
final ConfirmationTab tab) { final ConfirmationTab tab) {
if (null != manageDistUIState.getSelectedDeleteSWModuleTypes() if (null != this.manageDistUIState.getSelectedDeleteSWModuleTypes()
&& !manageDistUIState.getSelectedDeleteSWModuleTypes().isEmpty() && !this.manageDistUIState.getSelectedDeleteSWModuleTypes().isEmpty()
&& manageDistUIState.getSelectedDeleteSWModuleTypes().contains(discardSWModuleType)) { && this.manageDistUIState.getSelectedDeleteSWModuleTypes().contains(discardSWModuleType)) {
manageDistUIState.getSelectedDeleteSWModuleTypes().remove(discardSWModuleType); this.manageDistUIState.getSelectedDeleteSWModuleTypes().remove(discardSWModuleType);
} }
tab.getTable().getContainerDataSource().removeItem(itemId); tab.getTable().getContainerDataSource().removeItem(itemId);
final int deleteCount = tab.getTable().size(); final int deleteCount = tab.getTable().size();
if (0 == deleteCount) { if (0 == deleteCount) {
removeCurrentTab(tab); removeCurrentTab(tab);
eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_DELETE_SW_MODULE_TYPES); this.eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_DELETE_SW_MODULE_TYPES);
} else { } else {
eventBus.publish(this, SaveActionWindowEvent.DISCARD_DELETE_SW_MODULE_TYPE); this.eventBus.publish(this, SaveActionWindowEvent.DISCARD_DELETE_SW_MODULE_TYPE);
} }
} }
@@ -371,10 +374,10 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
tab.getConfirmAll().setId(SPUIComponetIdProvider.DIST_DELETE_ALL); tab.getConfirmAll().setId(SPUIComponetIdProvider.DIST_DELETE_ALL);
tab.getConfirmAll().setIcon(FontAwesome.TRASH_O); tab.getConfirmAll().setIcon(FontAwesome.TRASH_O);
tab.getConfirmAll().setCaption(i18n.get(SPUILabelDefinitions.BUTTON_DELETE_ALL)); tab.getConfirmAll().setCaption(this.i18n.get(SPUILabelDefinitions.BUTTON_DELETE_ALL));
tab.getConfirmAll().addClickListener(event -> deleteDistAll(tab)); tab.getConfirmAll().addClickListener(event -> deleteDistAll(tab));
tab.getDiscardAll().setCaption(i18n.get(SPUILabelDefinitions.BUTTON_DISCARD_ALL)); tab.getDiscardAll().setCaption(this.i18n.get(SPUILabelDefinitions.BUTTON_DISCARD_ALL));
tab.getDiscardAll().addClickListener(event -> discardDistAll(tab)); tab.getDiscardAll().addClickListener(event -> discardDistAll(tab));
/* Add items container to the table. */ /* Add items container to the table. */
@@ -397,8 +400,8 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) {
visibleColumnIds.add(DIST_NAME); visibleColumnIds.add(DIST_NAME);
visibleColumnIds.add(DISCARD); visibleColumnIds.add(DISCARD);
visibleColumnLabels.add(i18n.get("header.one.deletedist.table")); visibleColumnLabels.add(this.i18n.get("header.one.deletedist.table"));
visibleColumnLabels.add(i18n.get("header.second.deletedist.table")); visibleColumnLabels.add(this.i18n.get("header.second.deletedist.table"));
} }
tab.getTable().setVisibleColumns(visibleColumnIds.toArray()); tab.getTable().setVisibleColumns(visibleColumnIds.toArray());
tab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0])); tab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0]));
@@ -411,12 +414,12 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
/* Delete Distributions. */ /* Delete Distributions. */
private void deleteDistAll(final ConfirmationTab tab) { private void deleteDistAll(final ConfirmationTab tab) {
final Long[] deletedIds = manageDistUIState.getDeletedDistributionList().stream().map(idName -> idName.getId()) final Long[] deletedIds = this.manageDistUIState.getDeletedDistributionList().stream()
.toArray(Long[]::new); .map(idName -> idName.getId()).toArray(Long[]::new);
if (null != manageDistUIState.getAssignedList() && !manageDistUIState.getAssignedList().isEmpty()) { if (null != this.manageDistUIState.getAssignedList() && !this.manageDistUIState.getAssignedList().isEmpty()) {
manageDistUIState.getDeletedDistributionList().forEach(distSetName -> { this.manageDistUIState.getDeletedDistributionList().forEach(distSetName -> {
if (manageDistUIState.getAssignedList().containsKey(distSetName)) { if (this.manageDistUIState.getAssignedList().containsKey(distSetName)) {
manageDistUIState.getAssignedList().remove(distSetName); this.manageDistUIState.getAssignedList().remove(distSetName);
} }
@@ -424,23 +427,23 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
} }
dsManagement.deleteDistributionSet(deletedIds); this.dsManagement.deleteDistributionSet(deletedIds);
addToConsolitatedMsg(FontAwesome.TRASH_O.getHtml() + SPUILabelDefinitions.HTML_SPACE addToConsolitatedMsg(FontAwesome.TRASH_O.getHtml() + SPUILabelDefinitions.HTML_SPACE
+ i18n.get("message.dist.deleted", deletedIds.length)); + this.i18n.get("message.dist.deleted", deletedIds.length));
manageDistUIState.getDeletedDistributionList() this.manageDistUIState.getDeletedDistributionList()
.forEach(deletedIdname -> manageDistUIState.getAssignedList().remove(deletedIdname)); .forEach(deletedIdname -> this.manageDistUIState.getAssignedList().remove(deletedIdname));
removeCurrentTab(tab); removeCurrentTab(tab);
manageDistUIState.getDeletedDistributionList().clear(); this.manageDistUIState.getDeletedDistributionList().clear();
eventBus.publish(this, SaveActionWindowEvent.DELETED_DISTRIBUTIONS); this.eventBus.publish(this, SaveActionWindowEvent.DELETED_DISTRIBUTIONS);
} }
private void discardDistAll(final ConfirmationTab tab) { private void discardDistAll(final ConfirmationTab tab) {
removeCurrentTab(tab); removeCurrentTab(tab);
manageDistUIState.getDeletedDistributionList().clear(); this.manageDistUIState.getDeletedDistributionList().clear();
setActionMessage(i18n.get("message.dist.discard.success")); setActionMessage(this.i18n.get("message.dist.discard.success"));
eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_DISTRIBUTIONS); this.eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_DISTRIBUTIONS);
} }
@@ -449,7 +452,7 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
contactContainer.addContainerProperty(DIST_ID_NAME, DistributionSetIdName.class, ""); contactContainer.addContainerProperty(DIST_ID_NAME, DistributionSetIdName.class, "");
contactContainer.addContainerProperty(DIST_NAME, String.class, ""); contactContainer.addContainerProperty(DIST_NAME, String.class, "");
Item item; Item item;
for (final DistributionSetIdName distIdName : manageDistUIState.getDeletedDistributionList()) { for (final DistributionSetIdName distIdName : this.manageDistUIState.getDeletedDistributionList()) {
item = contactContainer.addItem(distIdName); item = contactContainer.addItem(distIdName);
item.getItemProperty(DIST_NAME).setValue(distIdName.getName().concat(":" + distIdName.getVersion())); item.getItemProperty(DIST_NAME).setValue(distIdName.getName().concat(":" + distIdName.getVersion()));
} }
@@ -460,18 +463,18 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
private void discardDistDelete(final Button.ClickEvent event, final Object itemId, final ConfirmationTab tab) { private void discardDistDelete(final Button.ClickEvent event, final Object itemId, final ConfirmationTab tab) {
final DistributionSetIdName distId = (DistributionSetIdName) ((Button) event.getComponent()).getData(); final DistributionSetIdName distId = (DistributionSetIdName) ((Button) event.getComponent()).getData();
if (null != manageDistUIState.getDeletedDistributionList() if (null != this.manageDistUIState.getDeletedDistributionList()
&& !manageDistUIState.getDeletedDistributionList().isEmpty() && !this.manageDistUIState.getDeletedDistributionList().isEmpty()
&& manageDistUIState.getDeletedDistributionList().contains(distId)) { && this.manageDistUIState.getDeletedDistributionList().contains(distId)) {
manageDistUIState.getDeletedDistributionList().remove(distId); this.manageDistUIState.getDeletedDistributionList().remove(distId);
} }
tab.getTable().getContainerDataSource().removeItem(itemId); tab.getTable().getContainerDataSource().removeItem(itemId);
final int deleteCount = tab.getTable().size(); final int deleteCount = tab.getTable().size();
if (0 == deleteCount) { if (0 == deleteCount) {
removeCurrentTab(tab); removeCurrentTab(tab);
eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_DISTRIBUTIONS); this.eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_DISTRIBUTIONS);
} else { } else {
eventBus.publish(this, SaveActionWindowEvent.DISCARD_DEL_DISTRIBUTION); this.eventBus.publish(this, SaveActionWindowEvent.DISCARD_DEL_DISTRIBUTION);
} }
} }
@@ -482,10 +485,10 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
tab.getConfirmAll().setId(SPUIComponetIdProvider.SAVE_DELETE_DIST_SET_TYPE); tab.getConfirmAll().setId(SPUIComponetIdProvider.SAVE_DELETE_DIST_SET_TYPE);
tab.getConfirmAll().setIcon(FontAwesome.TRASH_O); tab.getConfirmAll().setIcon(FontAwesome.TRASH_O);
tab.getConfirmAll().setCaption(i18n.get(SPUILabelDefinitions.BUTTON_DELETE_ALL)); tab.getConfirmAll().setCaption(this.i18n.get(SPUILabelDefinitions.BUTTON_DELETE_ALL));
tab.getConfirmAll().addClickListener(event -> deleteDistSetTypeAll(tab)); tab.getConfirmAll().addClickListener(event -> deleteDistSetTypeAll(tab));
tab.getDiscardAll().setCaption(i18n.get(SPUILabelDefinitions.BUTTON_DISCARD_ALL)); tab.getDiscardAll().setCaption(this.i18n.get(SPUILabelDefinitions.BUTTON_DISCARD_ALL));
tab.getDiscardAll().setId(SPUIComponetIdProvider.DISCARD_DIST_SET_TYPE); tab.getDiscardAll().setId(SPUIComponetIdProvider.DISCARD_DIST_SET_TYPE);
tab.getDiscardAll().addClickListener(event -> discardDistSetTypeAll(tab)); tab.getDiscardAll().addClickListener(event -> discardDistSetTypeAll(tab));
@@ -512,8 +515,8 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) {
visibleColumnIds.add(DIST_SET_NAME); visibleColumnIds.add(DIST_SET_NAME);
visibleColumnIds.add(DISCARD); visibleColumnIds.add(DISCARD);
visibleColumnLabels.add(i18n.get("header.first.delete.dist.type.table")); visibleColumnLabels.add(this.i18n.get("header.first.delete.dist.type.table"));
visibleColumnLabels.add(i18n.get("header.second.delete.dist.type.table")); visibleColumnLabels.add(this.i18n.get("header.second.delete.dist.type.table"));
} }
tab.getTable().setVisibleColumns(visibleColumnIds.toArray()); tab.getTable().setVisibleColumns(visibleColumnIds.toArray());
@@ -527,31 +530,32 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
private void deleteDistSetTypeAll(final ConfirmationTab tab) { private void deleteDistSetTypeAll(final ConfirmationTab tab) {
final int deleteDistTypeCount = manageDistUIState.getSelectedDeleteDistSetTypes().size(); final int deleteDistTypeCount = this.manageDistUIState.getSelectedDeleteDistSetTypes().size();
for (final String deleteDistTypeName : manageDistUIState.getSelectedDeleteDistSetTypes()) { for (final String deleteDistTypeName : this.manageDistUIState.getSelectedDeleteDistSetTypes()) {
dsManagement.deleteDistributionSetType(dsManagement.findDistributionSetTypeByName(deleteDistTypeName)); this.dsManagement
.deleteDistributionSetType(this.dsManagement.findDistributionSetTypeByName(deleteDistTypeName));
} }
addToConsolitatedMsg(FontAwesome.TASKS.getHtml() + SPUILabelDefinitions.HTML_SPACE addToConsolitatedMsg(FontAwesome.TASKS.getHtml() + SPUILabelDefinitions.HTML_SPACE
+ i18n.get("message.dist.type.delete", new Object[] { deleteDistTypeCount })); + this.i18n.get("message.dist.type.delete", new Object[] { deleteDistTypeCount }));
manageDistUIState.getSelectedDeleteDistSetTypes().clear(); this.manageDistUIState.getSelectedDeleteDistSetTypes().clear();
removeCurrentTab(tab); removeCurrentTab(tab);
setActionMessage(i18n.get("message.dist.set.type.deleted.success")); setActionMessage(this.i18n.get("message.dist.set.type.deleted.success"));
eventBus.publish(this, SaveActionWindowEvent.SAVED_DELETE_DIST_SET_TYPES); this.eventBus.publish(this, SaveActionWindowEvent.SAVED_DELETE_DIST_SET_TYPES);
} }
private void discardDistSetTypeAll(final ConfirmationTab tab) { private void discardDistSetTypeAll(final ConfirmationTab tab) {
removeCurrentTab(tab); removeCurrentTab(tab);
manageDistUIState.getSelectedDeleteDistSetTypes().clear(); this.manageDistUIState.getSelectedDeleteDistSetTypes().clear();
setActionMessage(i18n.get("message.dist.type.discard.success")); setActionMessage(this.i18n.get("message.dist.type.discard.success"));
eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_DELETE_DIST_SET_TYPES); this.eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_DELETE_DIST_SET_TYPES);
} }
private IndexedContainer getDistSetTypeTableContainer() { private IndexedContainer getDistSetTypeTableContainer() {
final IndexedContainer contactContainer = new IndexedContainer(); final IndexedContainer contactContainer = new IndexedContainer();
contactContainer.addContainerProperty(DIST_SET_NAME, String.class, ""); contactContainer.addContainerProperty(DIST_SET_NAME, String.class, "");
for (final String distTypeMName : manageDistUIState.getSelectedDeleteDistSetTypes()) { for (final String distTypeMName : this.manageDistUIState.getSelectedDeleteDistSetTypes()) {
final Item saveTblitem = contactContainer.addItem(distTypeMName); final Item saveTblitem = contactContainer.addItem(distTypeMName);
saveTblitem.getItemProperty(DIST_SET_NAME).setValue(distTypeMName); saveTblitem.getItemProperty(DIST_SET_NAME).setValue(distTypeMName);
@@ -563,40 +567,40 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
private void discardDistTypeDelete(final String discardDSType, final Object itemId, final ConfirmationTab tab) { private void discardDistTypeDelete(final String discardDSType, final Object itemId, final ConfirmationTab tab) {
if (null != manageDistUIState.getSelectedDeleteDistSetTypes() if (null != this.manageDistUIState.getSelectedDeleteDistSetTypes()
&& !manageDistUIState.getSelectedDeleteDistSetTypes().isEmpty() && !this.manageDistUIState.getSelectedDeleteDistSetTypes().isEmpty()
&& manageDistUIState.getSelectedDeleteDistSetTypes().contains(discardDSType)) { && this.manageDistUIState.getSelectedDeleteDistSetTypes().contains(discardDSType)) {
manageDistUIState.getSelectedDeleteDistSetTypes().remove(discardDSType); this.manageDistUIState.getSelectedDeleteDistSetTypes().remove(discardDSType);
} }
tab.getTable().getContainerDataSource().removeItem(itemId); tab.getTable().getContainerDataSource().removeItem(itemId);
final int deleteCount = tab.getTable().size(); final int deleteCount = tab.getTable().size();
if (0 == deleteCount) { if (0 == deleteCount) {
removeCurrentTab(tab); removeCurrentTab(tab);
eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_DELETE_DIST_SET_TYPES); this.eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_DELETE_DIST_SET_TYPES);
} else { } else {
eventBus.publish(this, SaveActionWindowEvent.DISCARD_DELETE_DIST_SET_TYPE); this.eventBus.publish(this, SaveActionWindowEvent.DISCARD_DELETE_DIST_SET_TYPE);
} }
} }
/* For Assign software modules */ /* For Assign software modules */
private ConfirmationTab createAssignSWModuleConfirmationTab() { private ConfirmationTab createAssignSWModuleConfirmationTab() {
assignmnetTab = new ConfirmationTab(); this.assignmnetTab = new ConfirmationTab();
assignmnetTab.getConfirmAll().setId(SPUIComponetIdProvider.SAVE_ASSIGNMENT); this.assignmnetTab.getConfirmAll().setId(SPUIComponetIdProvider.SAVE_ASSIGNMENT);
assignmnetTab.getConfirmAll().setIcon(FontAwesome.SAVE); this.assignmnetTab.getConfirmAll().setIcon(FontAwesome.SAVE);
assignmnetTab.getConfirmAll().setCaption(i18n.get("button.assign.all")); this.assignmnetTab.getConfirmAll().setCaption(this.i18n.get("button.assign.all"));
assignmnetTab.getConfirmAll().addClickListener(event -> saveAllAssignments(assignmnetTab)); this.assignmnetTab.getConfirmAll().addClickListener(event -> saveAllAssignments(this.assignmnetTab));
assignmnetTab.getDiscardAll().setCaption(i18n.get(SPUILabelDefinitions.BUTTON_DISCARD_ALL)); this.assignmnetTab.getDiscardAll().setCaption(this.i18n.get(SPUILabelDefinitions.BUTTON_DISCARD_ALL));
assignmnetTab.getDiscardAll().setId(SPUIComponetIdProvider.DISCARD_ASSIGNMENT); this.assignmnetTab.getDiscardAll().setId(SPUIComponetIdProvider.DISCARD_ASSIGNMENT);
assignmnetTab.getDiscardAll().addClickListener(event -> discardAllSWAssignments(assignmnetTab)); this.assignmnetTab.getDiscardAll().addClickListener(event -> discardAllSWAssignments(this.assignmnetTab));
// Add items container to the table. // Add items container to the table.
assignmnetTab.getTable().setContainerDataSource(getSWAssignmentsTableContainer()); this.assignmnetTab.getTable().setContainerDataSource(getSWAssignmentsTableContainer());
// Add the discard action column // Add the discard action column
assignmnetTab.getTable().addGeneratedColumn(DISCARD, (source, itemId, columnId) -> { this.assignmnetTab.getTable().addGeneratedColumn(DISCARD, (source, itemId, columnId) -> {
final StringBuilder style = new StringBuilder(ValoTheme.BUTTON_TINY); final StringBuilder style = new StringBuilder(ValoTheme.BUTTON_TINY);
style.append(' '); style.append(' ');
style.append(SPUIStyleDefinitions.REDICON); style.append(SPUIStyleDefinitions.REDICON);
@@ -605,7 +609,7 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
deleteIcon.setData(itemId); deleteIcon.setData(itemId);
deleteIcon.setImmediate(true); deleteIcon.setImmediate(true);
deleteIcon.addClickListener(event -> discardSWAssignment((String) ((Button) event.getComponent()).getData(), deleteIcon.addClickListener(event -> discardSWAssignment((String) ((Button) event.getComponent()).getData(),
itemId, assignmnetTab)); itemId, this.assignmnetTab));
return deleteIcon; return deleteIcon;
}); });
@@ -616,19 +620,19 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
visibleColumnIds.add(DIST_NAME); visibleColumnIds.add(DIST_NAME);
visibleColumnIds.add(SOFTWARE_MODULE_NAME); visibleColumnIds.add(SOFTWARE_MODULE_NAME);
visibleColumnIds.add(DISCARD); visibleColumnIds.add(DISCARD);
visibleColumnLabels.add(i18n.get("header.dist.first.assignment.table")); visibleColumnLabels.add(this.i18n.get("header.dist.first.assignment.table"));
visibleColumnLabels.add(i18n.get("header.dist.second.assignment.table")); visibleColumnLabels.add(this.i18n.get("header.dist.second.assignment.table"));
visibleColumnLabels.add(i18n.get("header.third.assignment.table")); visibleColumnLabels.add(this.i18n.get("header.third.assignment.table"));
} }
assignmnetTab.getTable().setVisibleColumns(visibleColumnIds.toArray()); this.assignmnetTab.getTable().setVisibleColumns(visibleColumnIds.toArray());
assignmnetTab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0])); this.assignmnetTab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0]));
assignmnetTab.getTable().setColumnExpandRatio(DIST_NAME, 2); this.assignmnetTab.getTable().setColumnExpandRatio(DIST_NAME, 2);
assignmnetTab.getTable().setColumnExpandRatio(SOFTWARE_MODULE_NAME, 2); this.assignmnetTab.getTable().setColumnExpandRatio(SOFTWARE_MODULE_NAME, 2);
assignmnetTab.getTable().setColumnExpandRatio(DISCARD, SPUIDefinitions.DISCARD_COLUMN_WIDTH); this.assignmnetTab.getTable().setColumnExpandRatio(DISCARD, SPUIDefinitions.DISCARD_COLUMN_WIDTH);
assignmnetTab.getTable().setColumnAlignment(DISCARD, Align.CENTER); this.assignmnetTab.getTable().setColumnAlignment(DISCARD, Align.CENTER);
return assignmnetTab; return this.assignmnetTab;
} }
@@ -640,7 +644,8 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
contactContainer.addContainerProperty(DIST_ID_NAME, DistributionSetIdName.class, ""); contactContainer.addContainerProperty(DIST_ID_NAME, DistributionSetIdName.class, "");
contactContainer.addContainerProperty(SOFTWARE_MODULE_ID_NAME, SoftwareModuleIdName.class, ""); contactContainer.addContainerProperty(SOFTWARE_MODULE_ID_NAME, SoftwareModuleIdName.class, "");
final Map<DistributionSetIdName, Set<SoftwareModuleIdName>> assignedList = manageDistUIState.getAssignedList(); final Map<DistributionSetIdName, HashSet<SoftwareModuleIdName>> assignedList = this.manageDistUIState
.getAssignedList();
assignedList.forEach((distIdname, softIdNameSet) -> softIdNameSet.forEach(softIdName -> { assignedList.forEach((distIdname, softIdNameSet) -> softIdNameSet.forEach(softIdName -> {
final String itemId = HawkbitCommonUtil.concatStrings("|||", distIdname.getId().toString(), final String itemId = HawkbitCommonUtil.concatStrings("|||", distIdname.getId().toString(),
@@ -658,38 +663,38 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
} }
private void saveAllAssignments(final ConfirmationTab tab) { private void saveAllAssignments(final ConfirmationTab tab) {
manageDistUIState.getAssignedList().forEach((distIdName, softIdNameSet) -> { this.manageDistUIState.getAssignedList().forEach((distIdName, softIdNameSet) -> {
final DistributionSet ds = dsManagement.findDistributionSetByIdWithDetails(distIdName.getId()); final DistributionSet ds = this.dsManagement.findDistributionSetByIdWithDetails(distIdName.getId());
final List<Long> softIds = softIdNameSet.stream().map(softIdName -> softIdName.getId()) final List<Long> softIds = softIdNameSet.stream().map(softIdName -> softIdName.getId())
.collect(Collectors.toList()); .collect(Collectors.toList());
final List<SoftwareModule> softwareModules = softwareManagement.findSoftwareModulesById(softIds); final List<SoftwareModule> softwareModules = this.softwareManagement.findSoftwareModulesById(softIds);
softwareModules.forEach(ds::addModule); softwareModules.forEach(ds::addModule);
dsManagement.updateDistributionSet(ds); this.dsManagement.updateDistributionSet(ds);
}); });
int count = 0; int count = 0;
for (final Entry<DistributionSetIdName, Set<SoftwareModuleIdName>> entry : manageDistUIState.getAssignedList() for (final Entry<DistributionSetIdName, HashSet<SoftwareModuleIdName>> entry : this.manageDistUIState
.entrySet()) { .getAssignedList().entrySet()) {
count += entry.getValue().size(); count += entry.getValue().size();
} }
addToConsolitatedMsg(FontAwesome.TASKS.getHtml() + SPUILabelDefinitions.HTML_SPACE addToConsolitatedMsg(FontAwesome.TASKS.getHtml() + SPUILabelDefinitions.HTML_SPACE
+ i18n.get("message.software.assignment", new Object[] { count })); + this.i18n.get("message.software.assignment", new Object[] { count }));
manageDistUIState.getAssignedList().clear(); this.manageDistUIState.getAssignedList().clear();
manageDistUIState.getConsolidatedDistSoftwarewList().clear(); this.manageDistUIState.getConsolidatedDistSoftwarewList().clear();
removeCurrentTab(tab); removeCurrentTab(tab);
eventBus.publish(this, SaveActionWindowEvent.SAVED_ASSIGNMENTS); this.eventBus.publish(this, SaveActionWindowEvent.SAVED_ASSIGNMENTS);
} }
private void discardAllSWAssignments(final ConfirmationTab tab) { private void discardAllSWAssignments(final ConfirmationTab tab) {
removeCurrentTab(tab); removeCurrentTab(tab);
manageDistUIState.getAssignedList().clear(); this.manageDistUIState.getAssignedList().clear();
manageDistUIState.getConsolidatedDistSoftwarewList().clear(); this.manageDistUIState.getConsolidatedDistSoftwarewList().clear();
setActionMessage(i18n.get("message.assign.discard.success")); setActionMessage(this.i18n.get("message.assign.discard.success"));
eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_ASSIGNMENTS); this.eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_ASSIGNMENTS);
} }
private void discardSWAssignment(final String discardSW, final Object itemId, final ConfirmationTab tab) { private void discardSWAssignment(final String discardSW, final Object itemId, final ConfirmationTab tab) {
@@ -700,23 +705,23 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW
final SoftwareModuleIdName discardSoftIdName = (SoftwareModuleIdName) rowitem final SoftwareModuleIdName discardSoftIdName = (SoftwareModuleIdName) rowitem
.getItemProperty(SOFTWARE_MODULE_ID_NAME).getValue(); .getItemProperty(SOFTWARE_MODULE_ID_NAME).getValue();
final Set<SoftwareModuleIdName> softIdNameSet = manageDistUIState.getAssignedList().get(discardDistIdName); final Set<SoftwareModuleIdName> softIdNameSet = this.manageDistUIState.getAssignedList().get(discardDistIdName);
manageDistUIState.getAssignedList().get(discardDistIdName).remove(discardSoftIdName); this.manageDistUIState.getAssignedList().get(discardDistIdName).remove(discardSoftIdName);
softIdNameSet.remove(discardSoftIdName); softIdNameSet.remove(discardSoftIdName);
tab.getTable().getContainerDataSource().removeItem(itemId); tab.getTable().getContainerDataSource().removeItem(itemId);
if (softIdNameSet.isEmpty()) { if (softIdNameSet.isEmpty()) {
manageDistUIState.getAssignedList().remove(discardDistIdName); this.manageDistUIState.getAssignedList().remove(discardDistIdName);
} }
final Map<Long, Set<SoftwareModuleIdName>> map = manageDistUIState.getConsolidatedDistSoftwarewList() final Map<Long, HashSet<SoftwareModuleIdName>> map = this.manageDistUIState.getConsolidatedDistSoftwarewList()
.get(discardDistIdName); .get(discardDistIdName);
map.keySet().forEach(typeId -> map.get(typeId).remove(discardSoftIdName)); map.keySet().forEach(typeId -> map.get(typeId).remove(discardSoftIdName));
final int assigCount = tab.getTable().getContainerDataSource().size(); final int assigCount = tab.getTable().getContainerDataSource().size();
if (0 == assigCount) { if (0 == assigCount) {
removeCurrentTab(tab); removeCurrentTab(tab);
eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_ASSIGNMENTS); this.eventBus.publish(this, SaveActionWindowEvent.DISCARD_ALL_ASSIGNMENTS);
} else { } else {
eventBus.publish(this, SaveActionWindowEvent.DISCARD_ASSIGNMENT); this.eventBus.publish(this, SaveActionWindowEvent.DISCARD_ASSIGNMENT);
} }
} }

View File

@@ -40,11 +40,11 @@ public class ManageDistUIState implements Serializable {
@Autowired @Autowired
private ManageSoftwareModuleFilters softwareModuleFilters; private ManageSoftwareModuleFilters softwareModuleFilters;
private final Map<DistributionSetIdName, Set<SoftwareModuleIdName>> assignedList = new HashMap<DistributionSetIdName, Set<SoftwareModuleIdName>>(); private final Map<DistributionSetIdName, HashSet<SoftwareModuleIdName>> assignedList = new HashMap<>();
private final Set<DistributionSetIdName> deletedDistributionList = new HashSet<DistributionSetIdName>(); private final Set<DistributionSetIdName> deletedDistributionList = new HashSet<>();
private Set<DistributionSetIdName> selectedDistributions = new HashSet<DistributionSetIdName>(); private Set<DistributionSetIdName> selectedDistributions = new HashSet<>();
private DistributionSetIdName lastSelectedDistribution; private DistributionSetIdName lastSelectedDistribution;
@@ -66,9 +66,9 @@ public class ManageDistUIState implements Serializable {
private boolean isDsTableMaximized = Boolean.FALSE; private boolean isDsTableMaximized = Boolean.FALSE;
private final Map<String, SoftwareModuleIdName> assignedSoftwareModuleDetails = new HashMap<String, SoftwareModuleIdName>(); private final Map<String, SoftwareModuleIdName> assignedSoftwareModuleDetails = new HashMap<>();
private final Map<DistributionSetIdName, Map<Long, Set<SoftwareModuleIdName>>> consolidatedDistSoftwarewList = new HashMap<DistributionSetIdName, Map<Long, Set<SoftwareModuleIdName>>>(); private final Map<DistributionSetIdName, HashMap<Long, HashSet<SoftwareModuleIdName>>> consolidatedDistSoftwarewList = new HashMap<>();
private boolean noDataAvilableSwModule = Boolean.FALSE; private boolean noDataAvilableSwModule = Boolean.FALSE;
@@ -78,36 +78,37 @@ public class ManageDistUIState implements Serializable {
* @return the manageDistFilters * @return the manageDistFilters
*/ */
public ManageDistFilters getManageDistFilters() { public ManageDistFilters getManageDistFilters() {
return manageDistFilters; return this.manageDistFilters;
} }
/** /**
* @return the deletedDistributionList * @return the deletedDistributionList
*/ */
public Set<DistributionSetIdName> getDeletedDistributionList() { public Set<DistributionSetIdName> getDeletedDistributionList() {
return deletedDistributionList; return this.deletedDistributionList;
} }
/** /**
* Need HashSet because the Set have to be serializable
* *
* @return the assignedList * @return the assignedList
*/ */
public Map<DistributionSetIdName, Set<SoftwareModuleIdName>> getAssignedList() { public Map<DistributionSetIdName, HashSet<SoftwareModuleIdName>> getAssignedList() {
return assignedList; return this.assignedList;
} }
/** /**
* @return the slectedDistributions * @return the slectedDistributions
*/ */
public Optional<Set<DistributionSetIdName>> getSelectedDistributions() { public Optional<Set<DistributionSetIdName>> getSelectedDistributions() {
return selectedDistributions == null ? Optional.empty() : Optional.of(selectedDistributions); return this.selectedDistributions == null ? Optional.empty() : Optional.of(this.selectedDistributions);
} }
/** /**
* @return the lastSelectedDistribution * @return the lastSelectedDistribution
*/ */
public Optional<DistributionSetIdName> getLastSelectedDistribution() { public Optional<DistributionSetIdName> getLastSelectedDistribution() {
return lastSelectedDistribution == null ? Optional.empty() : Optional.of(lastSelectedDistribution); return this.lastSelectedDistribution == null ? Optional.empty() : Optional.of(this.lastSelectedDistribution);
} }
/** /**
@@ -126,14 +127,14 @@ public class ManageDistUIState implements Serializable {
* @return the softwareModuleFilters * @return the softwareModuleFilters
*/ */
public ManageSoftwareModuleFilters getSoftwareModuleFilters() { public ManageSoftwareModuleFilters getSoftwareModuleFilters() {
return softwareModuleFilters; return this.softwareModuleFilters;
} }
/** /**
* @return the selectedSoftwareModules * @return the selectedSoftwareModules
*/ */
public Set<Long> getSelectedSoftwareModules() { public Set<Long> getSelectedSoftwareModules() {
return selectedSoftwareModules; return this.selectedSoftwareModules;
} }
/** /**
@@ -163,7 +164,7 @@ public class ManageDistUIState implements Serializable {
* @return the distTypeFilterClosed * @return the distTypeFilterClosed
*/ */
public boolean isDistTypeFilterClosed() { public boolean isDistTypeFilterClosed() {
return distTypeFilterClosed; return this.distTypeFilterClosed;
} }
/** /**
@@ -178,7 +179,7 @@ public class ManageDistUIState implements Serializable {
* @return the swTypeFilterClosed * @return the swTypeFilterClosed
*/ */
public boolean isSwTypeFilterClosed() { public boolean isSwTypeFilterClosed() {
return swTypeFilterClosed; return this.swTypeFilterClosed;
} }
/** /**
@@ -193,11 +194,11 @@ public class ManageDistUIState implements Serializable {
* @return the deleteSofwareModulesList * @return the deleteSofwareModulesList
*/ */
public Map<Long, String> getDeleteSofwareModulesList() { public Map<Long, String> getDeleteSofwareModulesList() {
return deleteSofwareModulesList; return this.deleteSofwareModulesList;
} }
public Set<String> getSelectedDeleteDistSetTypes() { public Set<String> getSelectedDeleteDistSetTypes() {
return selectedDeleteDistSetTypes; return this.selectedDeleteDistSetTypes;
} }
public void setSelectedDeleteDistSetTypes(final Set<String> selectedDeleteDistSetTypes) { public void setSelectedDeleteDistSetTypes(final Set<String> selectedDeleteDistSetTypes) {
@@ -205,7 +206,7 @@ public class ManageDistUIState implements Serializable {
} }
public Set<String> getSelectedDeleteSWModuleTypes() { public Set<String> getSelectedDeleteSWModuleTypes() {
return selectedDeleteSWModuleTypes; return this.selectedDeleteSWModuleTypes;
} }
public void setSelectedDeleteSWModuleTypes(final Set<String> selectedDeleteSWModuleTypes) { public void setSelectedDeleteSWModuleTypes(final Set<String> selectedDeleteSWModuleTypes) {
@@ -218,7 +219,7 @@ public class ManageDistUIState implements Serializable {
* @return boolean * @return boolean
*/ */
public boolean isDsTableMaximized() { public boolean isDsTableMaximized() {
return isDsTableMaximized; return this.isDsTableMaximized;
} }
/*** /***
@@ -231,14 +232,14 @@ public class ManageDistUIState implements Serializable {
} }
public Map<String, SoftwareModuleIdName> getAssignedSoftwareModuleDetails() { public Map<String, SoftwareModuleIdName> getAssignedSoftwareModuleDetails() {
return assignedSoftwareModuleDetails; return this.assignedSoftwareModuleDetails;
} }
/** /**
* @return the isSwModuleTableMaximized * @return the isSwModuleTableMaximized
*/ */
public boolean isSwModuleTableMaximized() { public boolean isSwModuleTableMaximized() {
return isSwModuleTableMaximized; return this.isSwModuleTableMaximized;
} }
/** /**
@@ -253,7 +254,7 @@ public class ManageDistUIState implements Serializable {
* @return the noDataAvilableSwModule * @return the noDataAvilableSwModule
*/ */
public boolean isNoDataAvilableSwModule() { public boolean isNoDataAvilableSwModule() {
return noDataAvilableSwModule; return this.noDataAvilableSwModule;
} }
/** /**
@@ -268,7 +269,7 @@ public class ManageDistUIState implements Serializable {
* @return the noDataAvailableDist * @return the noDataAvailableDist
*/ */
public boolean isNoDataAvailableDist() { public boolean isNoDataAvailableDist() {
return noDataAvailableDist; return this.noDataAvailableDist;
} }
/** /**
@@ -279,8 +280,13 @@ public class ManageDistUIState implements Serializable {
this.noDataAvailableDist = noDataAvailableDist; this.noDataAvailableDist = noDataAvailableDist;
} }
public Map<DistributionSetIdName, Map<Long, Set<SoftwareModuleIdName>>> getConsolidatedDistSoftwarewList() { /**
return consolidatedDistSoftwarewList; * Need HashSet because the Set have to be serializable
*
* @return map
*/
public Map<DistributionSetIdName, HashMap<Long, HashSet<SoftwareModuleIdName>>> getConsolidatedDistSoftwarewList() {
return this.consolidatedDistSoftwarewList;
} }
} }

View File

@@ -49,11 +49,11 @@ public class HawkbitLoginUI extends DefaultHawkbitUI {
private SpringViewProvider viewProvider; private SpringViewProvider viewProvider;
@Autowired @Autowired
private ApplicationContext context; private transient ApplicationContext context;
@Override @Override
protected void init(final VaadinRequest request) { protected void init(final VaadinRequest request) {
SpringContextHelper.setContext(context); SpringContextHelper.setContext(this.context);
final VerticalLayout rootLayout = new VerticalLayout(); final VerticalLayout rootLayout = new VerticalLayout();
final Component header = buildHeader(); final Component header = buildHeader();
@@ -69,7 +69,7 @@ public class HawkbitLoginUI extends DefaultHawkbitUI {
rootLayout.setExpandRatio(header, 1.0F); rootLayout.setExpandRatio(header, 1.0F);
rootLayout.setExpandRatio(content, 2.0F); rootLayout.setExpandRatio(content, 2.0F);
final Resource resource = context final Resource resource = this.context
.getResource("classpath:/VAADIN/themes/" + UI.getCurrent().getTheme() + "/layouts/footer.html"); .getResource("classpath:/VAADIN/themes/" + UI.getCurrent().getTheme() + "/layouts/footer.html");
try { try {
final CustomLayout customLayout = new CustomLayout(resource.getInputStream()); final CustomLayout customLayout = new CustomLayout(resource.getInputStream());
@@ -81,7 +81,7 @@ public class HawkbitLoginUI extends DefaultHawkbitUI {
setContent(rootLayout); setContent(rootLayout);
final Navigator navigator = new Navigator(this, content); final Navigator navigator = new Navigator(this, content);
navigator.addProvider(viewProvider); navigator.addProvider(this.viewProvider);
setNavigator(navigator); setNavigator(navigator);
} }

View File

@@ -79,10 +79,10 @@ public class ActionHistoryTable extends TreeTable implements Handler {
private I18N i18n; private I18N i18n;
@Autowired @Autowired
private DeploymentManagement deploymentManagement; private transient DeploymentManagement deploymentManagement;
@Autowired @Autowired
private EventBus.SessionEventBus eventBus; private transient EventBus.SessionEventBus eventBus;
@Autowired @Autowired
private UINotification notification; private UINotification notification;
@@ -106,21 +106,21 @@ public class ActionHistoryTable extends TreeTable implements Handler {
*/ */
@PostConstruct @PostConstruct
public void init() { public void init() {
actionCancel = new com.vaadin.event.Action(i18n.get("message.cancel.action")); this.actionCancel = new com.vaadin.event.Action(this.i18n.get("message.cancel.action"));
actionForceQuit = new com.vaadin.event.Action(i18n.get("message.forcequit.action")); this.actionForceQuit = new com.vaadin.event.Action(this.i18n.get("message.forcequit.action"));
actionForceQuit.setIcon(FontAwesome.WARNING); this.actionForceQuit.setIcon(FontAwesome.WARNING);
actionForce = new com.vaadin.event.Action(i18n.get("message.force.action")); this.actionForce = new com.vaadin.event.Action(this.i18n.get("message.force.action"));
initializeTableSettings(); initializeTableSettings();
buildComponent(); buildComponent();
restorePreviousState(); restorePreviousState();
setVisibleColumns(getVisbleColumns().toArray()); setVisibleColumns(getVisbleColumns().toArray());
eventBus.subscribe(this); this.eventBus.subscribe(this);
setPageLength(SPUIDefinitions.PAGE_SIZE); setPageLength(SPUIDefinitions.PAGE_SIZE);
} }
@PreDestroy @PreDestroy
void destroy() { void destroy() {
eventBus.unsubscribe(this); this.eventBus.unsubscribe(this);
} }
@EventBusListenerMethod(scope = EventScope.SESSION) @EventBusListenerMethod(scope = EventScope.SESSION)
@@ -140,7 +140,7 @@ public class ActionHistoryTable extends TreeTable implements Handler {
private void buildComponent() { private void buildComponent() {
// create an empty container // create an empty container
createContainer(); createContainer();
setContainerDataSource(hierarchicalContainer); setContainerDataSource(this.hierarchicalContainer);
addGeneratedColumns(); addGeneratedColumns();
setColumnExpandRatioForMinimisedTable(); setColumnExpandRatioForMinimisedTable();
} }
@@ -171,11 +171,11 @@ public class ActionHistoryTable extends TreeTable implements Handler {
// listeners for child // listeners for child
addExpandListener(event -> { addExpandListener(event -> {
expandParentActionRow(event.getItemId()); expandParentActionRow(event.getItemId());
managementUIState.getExpandParentActionRowId().add(event.getItemId()); this.managementUIState.getExpandParentActionRowId().add(event.getItemId());
}); });
addCollapseListener(event -> { addCollapseListener(event -> {
collapseParentActionRow(event.getItemId()); collapseParentActionRow(event.getItemId());
managementUIState.getExpandParentActionRowId().remove(event.getItemId()); this.managementUIState.getExpandParentActionRowId().remove(event.getItemId());
}); });
/* /*
* Add the cancel action handler for active actions. To be used to * Add the cancel action handler for active actions. To be used to
@@ -189,17 +189,20 @@ public class ActionHistoryTable extends TreeTable implements Handler {
*/ */
public void createContainer() { public void createContainer() {
/* Create HierarchicalContainer container */ /* Create HierarchicalContainer container */
hierarchicalContainer = new HierarchicalContainer(); this.hierarchicalContainer = new HierarchicalContainer();
hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTIVE_HIDDEN, String.class, null); this.hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTIVE_HIDDEN, String.class,
hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_FORCED, Action.class, null); null);
hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID_HIDDEN, Long.class, null); this.hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_FORCED, Action.class, null);
hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID, String.class, null); this.hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID_HIDDEN, Long.class,
hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_DIST, String.class, null); null);
hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_DATETIME, String.class, null); this.hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID, String.class, null);
hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_STATUS_HIDDEN, Action.Status.class, this.hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_DIST, String.class, null);
this.hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_DATETIME, String.class, null);
this.hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_STATUS_HIDDEN,
Action.Status.class, null);
this.hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_MSGS_HIDDEN, List.class, null);
this.hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_ROLLOUT_NAME, String.class,
null); null);
hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_MSGS_HIDDEN, List.class, null);
hierarchicalContainer.addContainerProperty(SPUIDefinitions.ACTION_HIS_TBL_ROLLOUT_NAME, String.class, null);
} }
/** /**
@@ -217,7 +220,7 @@ public class ActionHistoryTable extends TreeTable implements Handler {
visibleColumnIds.add(SPUIDefinitions.ACTION_HIS_TBL_DATETIME); visibleColumnIds.add(SPUIDefinitions.ACTION_HIS_TBL_DATETIME);
visibleColumnIds.add(SPUIDefinitions.ACTION_HIS_TBL_STATUS); visibleColumnIds.add(SPUIDefinitions.ACTION_HIS_TBL_STATUS);
visibleColumnIds.add(SPUIDefinitions.ACTION_HIS_TBL_FORCED); visibleColumnIds.add(SPUIDefinitions.ACTION_HIS_TBL_FORCED);
if (managementUIState.isActionHistoryMaximized()) { if (this.managementUIState.isActionHistoryMaximized()) {
visibleColumnIds.add(SPUIDefinitions.ACTION_HIS_TBL_ROLLOUT_NAME); visibleColumnIds.add(SPUIDefinitions.ACTION_HIS_TBL_ROLLOUT_NAME);
visibleColumnIds.add(SPUIDefinitions.ACTION_HIS_TBL_MSGS); visibleColumnIds.add(SPUIDefinitions.ACTION_HIS_TBL_MSGS);
visibleColumnIds.add(1, SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID); visibleColumnIds.add(1, SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID);
@@ -245,10 +248,10 @@ public class ActionHistoryTable extends TreeTable implements Handler {
} }
private void getcontainerData() { private void getcontainerData() {
hierarchicalContainer.removeAllItems(); this.hierarchicalContainer.removeAllItems();
/* service method to create action history for target */ /* service method to create action history for target */
final List<ActionWithStatusCount> actionHistory = deploymentManagement final List<ActionWithStatusCount> actionHistory = this.deploymentManagement
.findActionsWithStatusCountByTargetOrderByIdDesc(target); .findActionsWithStatusCountByTargetOrderByIdDesc(this.target);
addDetailsToContainer(actionHistory); addDetailsToContainer(actionHistory);
} }
@@ -273,16 +276,16 @@ public class ActionHistoryTable extends TreeTable implements Handler {
final Action action = actionWithStatusCount.getAction(); final Action action = actionWithStatusCount.getAction();
final Item item = hierarchicalContainer.addItem(actionWithStatusCount.getActionId()); final Item item = this.hierarchicalContainer.addItem(actionWithStatusCount.getActionId());
item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_STATUS_HIDDEN).setValue( item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_STATUS_HIDDEN)
actionWithStatusCount.getActionStatus()); .setValue(actionWithStatusCount.getActionStatus());
/* /*
* add action id. * add action id.
*/ */
item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID).setValue( item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID)
actionWithStatusCount.getActionId().toString()); .setValue(actionWithStatusCount.getActionId().toString());
/* /*
* add active/inactive status to the item which will be used in * add active/inactive status to the item which will be used in
* Column generator to generate respective icon * Column generator to generate respective icon
@@ -294,31 +297,31 @@ public class ActionHistoryTable extends TreeTable implements Handler {
* add action Id to the item which will be used for fetching child * add action Id to the item which will be used for fetching child
* items ( previous action status ) during expand * items ( previous action status ) during expand
*/ */
item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID_HIDDEN).setValue( item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID_HIDDEN)
actionWithStatusCount.getActionId()); .setValue(actionWithStatusCount.getActionId());
/* /*
* add distribution name to the item which will be displayed in the * add distribution name to the item which will be displayed in the
* table. The name should not exceed certain limit. * table. The name should not exceed certain limit.
*/ */
item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_DIST).setValue( item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_DIST).setValue(HawkbitCommonUtil
HawkbitCommonUtil.getFormattedText(actionWithStatusCount.getDsName() + ":" .getFormattedText(actionWithStatusCount.getDsName() + ":" + actionWithStatusCount.getDsVersion()));
+ actionWithStatusCount.getDsVersion()));
item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_FORCED).setValue(action); item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_FORCED).setValue(action);
/* Default no child */ /* Default no child */
((Hierarchical) hierarchicalContainer).setChildrenAllowed(actionWithStatusCount.getActionId(), false); ((Hierarchical) this.hierarchicalContainer).setChildrenAllowed(actionWithStatusCount.getActionId(), false);
item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_DATETIME) item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_DATETIME)
.setValue( .setValue(SPDateTimeUtil.getFormattedDate((actionWithStatusCount.getActionLastModifiedAt() != null)
SPDateTimeUtil.getFormattedDate((actionWithStatusCount.getActionLastModifiedAt() != null) ? actionWithStatusCount ? actionWithStatusCount.getActionLastModifiedAt()
.getActionLastModifiedAt() : actionWithStatusCount.getActionCreatedAt())); : actionWithStatusCount.getActionCreatedAt()));
item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ROLLOUT_NAME).setValue( item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ROLLOUT_NAME)
actionWithStatusCount.getRolloutName()); .setValue(actionWithStatusCount.getRolloutName());
if (actionWithStatusCount.getActionStatusCount() > 0) { if (actionWithStatusCount.getActionStatusCount() > 0) {
((Hierarchical) hierarchicalContainer).setChildrenAllowed(actionWithStatusCount.getActionId(), true); ((Hierarchical) this.hierarchicalContainer).setChildrenAllowed(actionWithStatusCount.getActionId(),
true);
} }
} }
} }
@@ -359,7 +362,7 @@ public class ActionHistoryTable extends TreeTable implements Handler {
* @return * @return
*/ */
private Component getForcedColumn(final Object itemId) { private Component getForcedColumn(final Object itemId) {
final Action actionWithActiveStatus = (Action) hierarchicalContainer.getItem(itemId) final Action actionWithActiveStatus = (Action) this.hierarchicalContainer.getItem(itemId)
.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_FORCED).getValue(); .getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_FORCED).getValue();
final Label actionLabel = SPUIComponentProvider.getLabel("", SPUILabelDefinitions.SP_LABEL_SIMPLE); final Label actionLabel = SPUIComponentProvider.getLabel("", SPUILabelDefinitions.SP_LABEL_SIMPLE);
actionLabel.setContentMode(ContentMode.HTML); actionLabel.setContentMode(ContentMode.HTML);
@@ -379,21 +382,21 @@ public class ActionHistoryTable extends TreeTable implements Handler {
* @return * @return
*/ */
private Component getActiveColumn(final Object itemId) { private Component getActiveColumn(final Object itemId) {
final Action.Status status = (Action.Status) hierarchicalContainer.getItem(itemId) final Action.Status status = (Action.Status) this.hierarchicalContainer.getItem(itemId)
.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_STATUS_HIDDEN).getValue(); .getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_STATUS_HIDDEN).getValue();
String activeValue; String activeValue;
if (status == Action.Status.SCHEDULED) { if (status == Action.Status.SCHEDULED) {
activeValue = Action.Status.SCHEDULED.toString().toLowerCase(); activeValue = Action.Status.SCHEDULED.toString().toLowerCase();
} else { } else {
activeValue = (String) hierarchicalContainer.getItem(itemId) activeValue = (String) this.hierarchicalContainer.getItem(itemId)
.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTIVE_HIDDEN).getValue(); .getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTIVE_HIDDEN).getValue();
} }
final String distName = (String) hierarchicalContainer.getItem(itemId) final String distName = (String) this.hierarchicalContainer.getItem(itemId)
.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_DIST).getValue(); .getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_DIST).getValue();
final Label activeStatusIcon = createActiveStatusLabel( final Label activeStatusIcon = createActiveStatusLabel(activeValue,
activeValue, (Action.Status) this.hierarchicalContainer.getItem(itemId)
(Action.Status) hierarchicalContainer.getItem(itemId) .getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_STATUS_HIDDEN)
.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_STATUS_HIDDEN).getValue() == Action.Status.ERROR); .getValue() == Action.Status.ERROR);
activeStatusIcon.setId(new StringJoiner(".").add(distName).add(itemId.toString()) activeStatusIcon.setId(new StringJoiner(".").add(distName).add(itemId.toString())
.add(SPUIDefinitions.ACTION_HIS_TBL_ACTIVE).add(activeValue).toString()); .add(SPUIDefinitions.ACTION_HIS_TBL_ACTIVE).add(activeValue).toString());
return activeStatusIcon; return activeStatusIcon;
@@ -404,7 +407,7 @@ public class ActionHistoryTable extends TreeTable implements Handler {
* @return * @return
*/ */
private Component getStatusColumn(final Object itemId) { private Component getStatusColumn(final Object itemId) {
final Action.Status status = (Action.Status) hierarchicalContainer.getItem(itemId) final Action.Status status = (Action.Status) this.hierarchicalContainer.getItem(itemId)
.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_STATUS_HIDDEN).getValue(); .getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_STATUS_HIDDEN).getValue();
return getStatusIcon(status); return getStatusIcon(status);
} }
@@ -419,17 +422,17 @@ public class ActionHistoryTable extends TreeTable implements Handler {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void expandParentActionRow(final Object parentRowIdx) { private void expandParentActionRow(final Object parentRowIdx) {
/* Get the item for which the expand is made */ /* Get the item for which the expand is made */
final Item item = hierarchicalContainer.getItem(parentRowIdx); final Item item = this.hierarchicalContainer.getItem(parentRowIdx);
if (null != item) { if (null != item) {
final Long actionId = (Long) item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID_HIDDEN) final Long actionId = (Long) item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID_HIDDEN)
.getValue(); .getValue();
final org.eclipse.hawkbit.repository.model.Action action = deploymentManagement final org.eclipse.hawkbit.repository.model.Action action = this.deploymentManagement
.findActionWithDetails(actionId); .findActionWithDetails(actionId);
final Pageable pageReq = new PageRequest(0, 1000); final Pageable pageReq = new PageRequest(0, 1000);
final Page<ActionStatus> actionStatusList = deploymentManagement final Page<ActionStatus> actionStatusList = this.deploymentManagement
.findActionStatusMessagesByActionInDescOrder(pageReq, action, .findActionStatusMessagesByActionInDescOrder(pageReq, action,
managementUIState.isActionHistoryMaximized()); this.managementUIState.isActionHistoryMaximized());
final List<ActionStatus> content = actionStatusList.getContent(); final List<ActionStatus> content = actionStatusList.getContent();
/* /*
* Since the recent action status and messages are already * Since the recent action status and messages are already
@@ -439,7 +442,7 @@ public class ActionHistoryTable extends TreeTable implements Handler {
int childIdx = 1; int childIdx = 1;
for (final ActionStatus actionStatus : content) { for (final ActionStatus actionStatus : content) {
final String childId = parentRowIdx + " -> " + childIdx; final String childId = parentRowIdx + " -> " + childIdx;
final Item childItem = hierarchicalContainer.addItem(childId); final Item childItem = this.hierarchicalContainer.addItem(childId);
if (null != childItem) { if (null != childItem) {
/* /*
* For better UI, no need to display active/inactive icon * For better UI, no need to display active/inactive icon
@@ -447,19 +450,19 @@ public class ActionHistoryTable extends TreeTable implements Handler {
*/ */
childItem.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTIVE_HIDDEN).setValue(""); childItem.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTIVE_HIDDEN).setValue("");
childItem.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_DIST).setValue( childItem.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_DIST)
HawkbitCommonUtil.getFormattedText(action.getDistributionSet().getName() + ":" .setValue(HawkbitCommonUtil.getFormattedText(action.getDistributionSet().getName() + ":"
+ action.getDistributionSet().getVersion())); + action.getDistributionSet().getVersion()));
childItem.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_DATETIME).setValue( childItem.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_DATETIME)
SPDateTimeUtil.getFormattedDate(actionStatus.getCreatedAt())); .setValue(SPDateTimeUtil.getFormattedDate(actionStatus.getCreatedAt()));
childItem.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_STATUS_HIDDEN).setValue( childItem.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_STATUS_HIDDEN)
actionStatus.getStatus()); .setValue(actionStatus.getStatus());
showOrHideMessage(childItem, actionStatus); showOrHideMessage(childItem, actionStatus);
/* No further child items allowed for the child items */ /* No further child items allowed for the child items */
((Hierarchical) hierarchicalContainer).setChildrenAllowed(childId, false); ((Hierarchical) this.hierarchicalContainer).setChildrenAllowed(childId, false);
/* Assign this childItem to the parent */ /* Assign this childItem to the parent */
((Hierarchical) hierarchicalContainer).setParent(childId, parentRowIdx); ((Hierarchical) this.hierarchicalContainer).setParent(childId, parentRowIdx);
childIdx++; childIdx++;
} }
@@ -475,12 +478,12 @@ public class ActionHistoryTable extends TreeTable implements Handler {
*/ */
public void collapseParentActionRow(final Object parentRowIdx) { public void collapseParentActionRow(final Object parentRowIdx) {
/* Remove all child items for the clear the memory. */ /* Remove all child items for the clear the memory. */
final Collection<?> children = ((Hierarchical) hierarchicalContainer).getChildren(parentRowIdx); final Collection<?> children = ((Hierarchical) this.hierarchicalContainer).getChildren(parentRowIdx);
if (children != null && !children.isEmpty()) { if (children != null && !children.isEmpty()) {
String ids = children.toString().substring(1); String ids = children.toString().substring(1);
ids = ids.substring(0, ids.length() - 1); ids = ids.substring(0, ids.length() - 1);
for (final String childId : ids.split(", ")) { for (final String childId : ids.split(", ")) {
((Hierarchical) hierarchicalContainer).removeItem(childId); ((Hierarchical) this.hierarchicalContainer).removeItem(childId);
} }
} }
} }
@@ -497,42 +500,42 @@ public class ActionHistoryTable extends TreeTable implements Handler {
final String statusIconPending = "statusIconPending"; final String statusIconPending = "statusIconPending";
label.setContentMode(ContentMode.HTML); label.setContentMode(ContentMode.HTML);
if (Action.Status.FINISHED == status) { if (Action.Status.FINISHED == status) {
label.setDescription(i18n.get("label.finished")); label.setDescription(this.i18n.get("label.finished"));
label.setStyleName(STATUS_ICON_GREEN); label.setStyleName(STATUS_ICON_GREEN);
label.setValue(FontAwesome.CHECK_CIRCLE.getHtml()); label.setValue(FontAwesome.CHECK_CIRCLE.getHtml());
} else if (Action.Status.ERROR == status) { } else if (Action.Status.ERROR == status) {
label.setDescription(i18n.get("label.error")); label.setDescription(this.i18n.get("label.error"));
label.setStyleName("statusIconRed"); label.setStyleName("statusIconRed");
label.setValue(FontAwesome.EXCLAMATION_CIRCLE.getHtml()); label.setValue(FontAwesome.EXCLAMATION_CIRCLE.getHtml());
} else if (Action.Status.WARNING == status) { } else if (Action.Status.WARNING == status) {
label.setStyleName("statusIconOrange"); label.setStyleName("statusIconOrange");
label.setDescription(i18n.get("label.warning")); label.setDescription(this.i18n.get("label.warning"));
label.setValue(FontAwesome.EXCLAMATION_CIRCLE.getHtml()); label.setValue(FontAwesome.EXCLAMATION_CIRCLE.getHtml());
} else if (Action.Status.RUNNING == status) { } else if (Action.Status.RUNNING == status) {
// dynamic spinner // dynamic spinner
label.setStyleName(statusIconPending); label.setStyleName(statusIconPending);
label.setDescription(i18n.get("label.running")); label.setDescription(this.i18n.get("label.running"));
label.setValue(FontAwesome.ADJUST.getHtml()); label.setValue(FontAwesome.ADJUST.getHtml());
} else if (Action.Status.CANCELING == status) { } else if (Action.Status.CANCELING == status) {
label.setStyleName(statusIconPending); label.setStyleName(statusIconPending);
label.setDescription(i18n.get("label.cancelling")); label.setDescription(this.i18n.get("label.cancelling"));
label.setValue(FontAwesome.TIMES_CIRCLE.getHtml()); label.setValue(FontAwesome.TIMES_CIRCLE.getHtml());
} else if (Action.Status.CANCELED == status) { } else if (Action.Status.CANCELED == status) {
label.setStyleName(statusIconPending); label.setStyleName(statusIconPending);
label.setDescription(i18n.get("label.cancelled")); label.setDescription(this.i18n.get("label.cancelled"));
label.setStyleName(STATUS_ICON_GREEN); label.setStyleName(STATUS_ICON_GREEN);
label.setValue(FontAwesome.TIMES_CIRCLE.getHtml()); label.setValue(FontAwesome.TIMES_CIRCLE.getHtml());
} else if (Action.Status.RETRIEVED == status) { } else if (Action.Status.RETRIEVED == status) {
label.setStyleName(statusIconPending); label.setStyleName(statusIconPending);
label.setDescription(i18n.get("label.retrieved")); label.setDescription(this.i18n.get("label.retrieved"));
label.setValue(FontAwesome.CIRCLE_O.getHtml()); label.setValue(FontAwesome.CIRCLE_O.getHtml());
} else if (Action.Status.DOWNLOAD == status) { } else if (Action.Status.DOWNLOAD == status) {
label.setStyleName(statusIconPending); label.setStyleName(statusIconPending);
label.setDescription(i18n.get("label.download")); label.setDescription(this.i18n.get("label.download"));
label.setValue(FontAwesome.CLOUD_DOWNLOAD.getHtml()); label.setValue(FontAwesome.CLOUD_DOWNLOAD.getHtml());
} else if (Action.Status.SCHEDULED == status) { } else if (Action.Status.SCHEDULED == status) {
label.setStyleName(statusIconPending); label.setStyleName(statusIconPending);
label.setDescription(i18n.get("label.scheduled")); label.setDescription(this.i18n.get("label.scheduled"));
label.setValue(FontAwesome.BULLSEYE.getHtml()); label.setValue(FontAwesome.BULLSEYE.getHtml());
} else { } else {
label.setDescription(""); label.setDescription("");
@@ -561,13 +564,11 @@ public class ActionHistoryTable extends TreeTable implements Handler {
if (actionWithActiveStatus.isHitAutoForceTime(currentTimeMillis)) { if (actionWithActiveStatus.isHitAutoForceTime(currentTimeMillis)) {
autoForceLabel.setDescription("autoforced"); autoForceLabel.setDescription("autoforced");
autoForceLabel.setStyleName(STATUS_ICON_GREEN); autoForceLabel.setStyleName(STATUS_ICON_GREEN);
autoForceLabel.setDescription("auto forced since " autoForceLabel.setDescription("auto forced since " + SPDateTimeUtil
+ SPDateTimeUtil.getDurationFormattedString(actionWithActiveStatus.getForcedTime(), .getDurationFormattedString(actionWithActiveStatus.getForcedTime(), currentTimeMillis, this.i18n));
currentTimeMillis, i18n));
} else { } else {
autoForceLabel.setDescription("auto forcing in " autoForceLabel.setDescription("auto forcing in " + SPDateTimeUtil
+ SPDateTimeUtil.getDurationFormattedString(currentTimeMillis, .getDurationFormattedString(currentTimeMillis, actionWithActiveStatus.getForcedTime(), this.i18n));
actionWithActiveStatus.getForcedTime(), i18n));
autoForceLabel.setStyleName("statusIconPending"); autoForceLabel.setStyleName("statusIconPending");
autoForceLabel.setValue(FontAwesome.HISTORY.getHtml()); autoForceLabel.setValue(FontAwesome.HISTORY.getHtml());
} }
@@ -609,7 +610,7 @@ public class ActionHistoryTable extends TreeTable implements Handler {
*/ */
private void createTableContentForMax() { private void createTableContentForMax() {
setColumnCollapsingAllowed(true); setColumnCollapsingAllowed(true);
if (!alreadyHasMessages) { if (!this.alreadyHasMessages) {
/* /*
* check to avoid DB call for fetching the messages again and again * check to avoid DB call for fetching the messages again and again
* if already available in container. * if already available in container.
@@ -617,7 +618,7 @@ public class ActionHistoryTable extends TreeTable implements Handler {
getcontainerData(); getcontainerData();
// to expand parent row , if already expanded. // to expand parent row , if already expanded.
expandParentRow(); expandParentRow();
alreadyHasMessages = true; this.alreadyHasMessages = true;
} }
addGeneratedColumn(SPUIDefinitions.ACTION_HIS_TBL_MSGS, new Table.ColumnGenerator() { addGeneratedColumn(SPUIDefinitions.ACTION_HIS_TBL_MSGS, new Table.ColumnGenerator() {
@@ -626,8 +627,8 @@ public class ActionHistoryTable extends TreeTable implements Handler {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public Component generateCell(final Table source, final Object itemId, final Object columnId) { public Component generateCell(final Table source, final Object itemId, final Object columnId) {
final List<String> messages = (List<String>) hierarchicalContainer.getItem(itemId) final List<String> messages = (List<String>) ActionHistoryTable.this.hierarchicalContainer
.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_MSGS_HIDDEN).getValue(); .getItem(itemId).getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_MSGS_HIDDEN).getValue();
return createMessagesBlock(messages); return createMessagesBlock(messages);
} }
}); });
@@ -671,7 +672,7 @@ public class ActionHistoryTable extends TreeTable implements Handler {
} }
} else { } else {
/* Messages are not available */ /* Messages are not available */
updateStatusMessages.append(i18n.get("message.no.available")); updateStatusMessages.append(this.i18n.get("message.no.available"));
} }
textArea.setValue(updateStatusMessages.toString()); textArea.setValue(updateStatusMessages.toString());
textArea.setReadOnly(Boolean.TRUE); textArea.setReadOnly(Boolean.TRUE);
@@ -690,7 +691,7 @@ public class ActionHistoryTable extends TreeTable implements Handler {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void showOrHideMessage(final Item childItem, final ActionStatus actionStatus) { private void showOrHideMessage(final Item childItem, final ActionStatus actionStatus) {
if (managementUIState.isActionHistoryMaximized()) { if (this.managementUIState.isActionHistoryMaximized()) {
childItem.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_MSGS_HIDDEN).setValue(actionStatus.getMessages()); childItem.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_MSGS_HIDDEN).setValue(actionStatus.getMessages());
} }
} }
@@ -700,7 +701,7 @@ public class ActionHistoryTable extends TreeTable implements Handler {
*/ */
private void normalActionHistoryTable() { private void normalActionHistoryTable() {
setColumnCollapsingAllowed(false); setColumnCollapsingAllowed(false);
managementUIState.setActionHistoryMaximized(false); this.managementUIState.setActionHistoryMaximized(false);
removeGeneratedColumn(SPUIDefinitions.ACTION_HIS_TBL_MSGS); removeGeneratedColumn(SPUIDefinitions.ACTION_HIS_TBL_MSGS);
setVisibleColumns(getVisbleColumns().toArray()); setVisibleColumns(getVisbleColumns().toArray());
setColumnExpandRatioForMinimisedTable(); setColumnExpandRatioForMinimisedTable();
@@ -709,15 +710,15 @@ public class ActionHistoryTable extends TreeTable implements Handler {
@Override @Override
public void handleAction(final com.vaadin.event.Action action, final Object sender, final Object target) { public void handleAction(final com.vaadin.event.Action action, final Object sender, final Object target) {
/* Get the actionId details of the cancel item or row */ /* Get the actionId details of the cancel item or row */
final Item item = hierarchicalContainer.getItem(target); final Item item = this.hierarchicalContainer.getItem(target);
final Long actionId = (Long) item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID_HIDDEN).getValue(); final Long actionId = (Long) item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID_HIDDEN).getValue();
if (action.equals(actionCancel)) { if (action.equals(this.actionCancel)) {
if (actionId != null) { if (actionId != null) {
confirmAndCancelAction(actionId); confirmAndCancelAction(actionId);
} }
} else if (action.equals(actionForce)) { } else if (action.equals(this.actionForce)) {
confirmAndForceAction(actionId); confirmAndForceAction(actionId);
} else if (action.equals(actionForceQuit)) { } else if (action.equals(this.actionForceQuit)) {
confirmAndForceQuitAction(actionId); confirmAndForceQuitAction(actionId);
} }
} }
@@ -727,18 +728,18 @@ public class ActionHistoryTable extends TreeTable implements Handler {
final List<com.vaadin.event.Action> actions = Lists.newArrayList(); final List<com.vaadin.event.Action> actions = Lists.newArrayList();
if (target != null) { if (target != null) {
/* Check if the row or item belongs to active action */ /* Check if the row or item belongs to active action */
final String activeValue = (String) hierarchicalContainer.getItem(target) final String activeValue = (String) this.hierarchicalContainer.getItem(target)
.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTIVE_HIDDEN).getValue(); .getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTIVE_HIDDEN).getValue();
if (SPUIDefinitions.ACTIVE.equals(activeValue)) { if (SPUIDefinitions.ACTIVE.equals(activeValue)) {
final Action actionWithActiveStatus = (Action) hierarchicalContainer.getItem(target) final Action actionWithActiveStatus = (Action) this.hierarchicalContainer.getItem(target)
.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_FORCED).getValue(); .getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_FORCED).getValue();
if (!actionWithActiveStatus.isForce()) { if (!actionWithActiveStatus.isForce()) {
actions.add(actionForce); actions.add(this.actionForce);
} }
if (!actionWithActiveStatus.isCancelingOrCanceled()) { if (!actionWithActiveStatus.isCancelingOrCanceled()) {
actions.add(actionCancel); actions.add(this.actionCancel);
} else { } else {
actions.add(actionForceQuit); actions.add(this.actionForceQuit);
} }
} }
@@ -754,11 +755,12 @@ public class ActionHistoryTable extends TreeTable implements Handler {
*/ */
private void confirmAndForceAction(final Long actionId) { private void confirmAndForceAction(final Long actionId) {
/* Display the confirmation */ /* Display the confirmation */
final ConfirmationDialog confirmDialog = new ConfirmationDialog(i18n.get("caption.force.action.confirmbox"), final ConfirmationDialog confirmDialog = new ConfirmationDialog(
i18n.get("message.force.action.confirm"), i18n.get("button.ok"), i18n.get("button.cancel"), ok -> { this.i18n.get("caption.force.action.confirmbox"), this.i18n.get("message.force.action.confirm"),
this.i18n.get("button.ok"), this.i18n.get("button.cancel"), ok -> {
if (ok) { if (ok) {
/* cancel the action */ /* cancel the action */
deploymentManagement.forceTargetAction(actionId); this.deploymentManagement.forceTargetAction(actionId);
/* /*
* Refresh the action history table to show latest * Refresh the action history table to show latest
@@ -766,8 +768,8 @@ public class ActionHistoryTable extends TreeTable implements Handler {
* Target Details * Target Details
*/ */
populateAndupdateTargetDetails(target); populateAndupdateTargetDetails(this.target);
notification.displaySuccess(i18n.get("message.force.action.success")); this.notification.displaySuccess(this.i18n.get("message.force.action.success"));
} }
}); });
UI.getCurrent().addWindow(confirmDialog.getWindow()); UI.getCurrent().addWindow(confirmDialog.getWindow());
@@ -777,8 +779,8 @@ public class ActionHistoryTable extends TreeTable implements Handler {
private void confirmAndForceQuitAction(final Long actionId) { private void confirmAndForceQuitAction(final Long actionId) {
/* Display the confirmation */ /* Display the confirmation */
final ConfirmationDialog confirmDialog = new ConfirmationDialog( final ConfirmationDialog confirmDialog = new ConfirmationDialog(
i18n.get("caption.forcequit.action.confirmbox"), i18n.get("message.forcequit.action.confirm"), this.i18n.get("caption.forcequit.action.confirmbox"), this.i18n.get("message.forcequit.action.confirm"),
i18n.get("button.ok"), i18n.get("button.cancel"), ok -> { this.i18n.get("button.ok"), this.i18n.get("button.cancel"), ok -> {
if (ok) { if (ok) {
final boolean cancelResult = forceQuitActiveAction(actionId); final boolean cancelResult = forceQuitActiveAction(actionId);
if (cancelResult) { if (cancelResult) {
@@ -787,13 +789,13 @@ public class ActionHistoryTable extends TreeTable implements Handler {
* change of the action cancellation and update the * change of the action cancellation and update the
* Target Details * Target Details
*/ */
populateAndupdateTargetDetails(target); populateAndupdateTargetDetails(this.target);
notification.displaySuccess(i18n.get("message.forcequit.action.success")); this.notification.displaySuccess(this.i18n.get("message.forcequit.action.success"));
} else { } else {
notification.displayValidationError(i18n.get("message.forcequit.action.failed")); this.notification.displayValidationError(this.i18n.get("message.forcequit.action.failed"));
} }
} }
}, FontAwesome.WARNING); } , FontAwesome.WARNING);
UI.getCurrent().addWindow(confirmDialog.getWindow()); UI.getCurrent().addWindow(confirmDialog.getWindow());
confirmDialog.getWindow().bringToFront(); confirmDialog.getWindow().bringToFront();
} }
@@ -805,8 +807,9 @@ public class ActionHistoryTable extends TreeTable implements Handler {
* as Id if the action needs to be cancelled. * as Id if the action needs to be cancelled.
*/ */
private void confirmAndCancelAction(final Long actionId) { private void confirmAndCancelAction(final Long actionId) {
final ConfirmationDialog confirmDialog = new ConfirmationDialog(i18n.get("caption.cancel.action.confirmbox"), final ConfirmationDialog confirmDialog = new ConfirmationDialog(
i18n.get("message.cancel.action.confirm"), i18n.get("button.ok"), i18n.get("button.cancel"), ok -> { this.i18n.get("caption.cancel.action.confirmbox"), this.i18n.get("message.cancel.action.confirm"),
this.i18n.get("button.ok"), this.i18n.get("button.cancel"), ok -> {
if (ok) { if (ok) {
final boolean cancelResult = cancelActiveAction(actionId); final boolean cancelResult = cancelActiveAction(actionId);
if (cancelResult) { if (cancelResult) {
@@ -815,10 +818,10 @@ public class ActionHistoryTable extends TreeTable implements Handler {
* change of the action cancellation and update the * change of the action cancellation and update the
* Target Details * Target Details
*/ */
populateAndupdateTargetDetails(target); populateAndupdateTargetDetails(this.target);
notification.displaySuccess(i18n.get("message.cancel.action.success")); this.notification.displaySuccess(this.i18n.get("message.cancel.action.success"));
} else { } else {
notification.displayValidationError(i18n.get("message.cancel.action.failed")); this.notification.displayValidationError(this.i18n.get("message.cancel.action.failed"));
} }
} }
}); });
@@ -836,9 +839,9 @@ public class ActionHistoryTable extends TreeTable implements Handler {
// service call to cancel the active action // service call to cancel the active action
private boolean cancelActiveAction(final Long actionId) { private boolean cancelActiveAction(final Long actionId) {
if (actionId != null) { if (actionId != null) {
final Action activeAction = deploymentManagement.findAction(actionId); final Action activeAction = this.deploymentManagement.findAction(actionId);
try { try {
deploymentManagement.cancelAction(activeAction, target); this.deploymentManagement.cancelAction(activeAction, this.target);
return true; return true;
} catch (final CancelActionNotAllowedException e) { } catch (final CancelActionNotAllowedException e) {
LOG.info("Cancel action not allowed exception :{}", e); LOG.info("Cancel action not allowed exception :{}", e);
@@ -851,9 +854,9 @@ public class ActionHistoryTable extends TreeTable implements Handler {
// service call to cancel the active action // service call to cancel the active action
private boolean forceQuitActiveAction(final Long actionId) { private boolean forceQuitActiveAction(final Long actionId) {
if (actionId != null) { if (actionId != null) {
final Action activeAction = deploymentManagement.findAction(actionId); final Action activeAction = this.deploymentManagement.findAction(actionId);
try { try {
deploymentManagement.forceQuitAction(activeAction, target); this.deploymentManagement.forceQuitAction(activeAction, this.target);
return true; return true;
} catch (final CancelActionNotAllowedException e) { } catch (final CancelActionNotAllowedException e) {
LOG.info("Force Cancel action not allowed exception :{}", e); LOG.info("Force Cancel action not allowed exception :{}", e);
@@ -868,7 +871,7 @@ public class ActionHistoryTable extends TreeTable implements Handler {
* Update the target status in the Target table and update the color * Update the target status in the Target table and update the color
* settings for DS in DS table. * settings for DS in DS table.
*/ */
eventBus.publish(this, new TargetTableEvent(TargetComponentEvent.EDIT_TARGET, target)); this.eventBus.publish(this, new TargetTableEvent(TargetComponentEvent.EDIT_TARGET, this.target));
updateDistributionTableStyle(); updateDistributionTableStyle();
} }
@@ -878,13 +881,13 @@ public class ActionHistoryTable extends TreeTable implements Handler {
*/ */
private void updateDistributionTableStyle() { private void updateDistributionTableStyle() {
if (managementUIState.getDistributionTableFilters().getPinnedTargetId().isPresent() if (this.managementUIState.getDistributionTableFilters().getPinnedTargetId().isPresent()
&& null != managementUIState.getDistributionTableFilters().getPinnedTargetId().get()) { && null != this.managementUIState.getDistributionTableFilters().getPinnedTargetId().get()) {
final String alreadyPinnedControllerId = managementUIState.getDistributionTableFilters() final String alreadyPinnedControllerId = this.managementUIState.getDistributionTableFilters()
.getPinnedTargetId().get(); .getPinnedTargetId().get();
// if the current target is pinned publish a pin event again // if the current target is pinned publish a pin event again
if (null != alreadyPinnedControllerId && alreadyPinnedControllerId.equals(target.getControllerId())) { if (null != alreadyPinnedControllerId && alreadyPinnedControllerId.equals(this.target.getControllerId())) {
eventBus.publish(this, PinUnpinEvent.PIN_TARGET); this.eventBus.publish(this, PinUnpinEvent.PIN_TARGET);
} }
} }
} }
@@ -907,15 +910,15 @@ public class ActionHistoryTable extends TreeTable implements Handler {
} }
private void restorePreviousState() { private void restorePreviousState() {
if (managementUIState.isActionHistoryMaximized()) { if (this.managementUIState.isActionHistoryMaximized()) {
createTableContentForMax(); createTableContentForMax();
} }
} }
private void expandParentRow() { private void expandParentRow() {
if (null != managementUIState.getExpandParentActionRowId() if (null != this.managementUIState.getExpandParentActionRowId()
&& !managementUIState.getExpandParentActionRowId().isEmpty()) { && !this.managementUIState.getExpandParentActionRowId().isEmpty()) {
for (final Object obj : managementUIState.getExpandParentActionRowId()) { for (final Object obj : this.managementUIState.getExpandParentActionRowId()) {
expandParentActionRow(obj); expandParentActionRow(obj);
} }
} }

View File

@@ -54,6 +54,7 @@ import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button; import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox; import com.vaadin.ui.CheckBox;
import com.vaadin.ui.ComboBox; import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label; import com.vaadin.ui.Label;
import com.vaadin.ui.TextArea; import com.vaadin.ui.TextArea;
@@ -109,7 +110,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
private String originalDistDescription; private String originalDistDescription;
private Boolean originalReqMigStep; private Boolean originalReqMigStep;
private String originalDistSetType; private String originalDistSetType;
private final List<Object> changedComponents = new ArrayList<Object>(); private final List<Component> changedComponents = new ArrayList<>();
private ValueChangeListener reqMigStepCheckboxListerner; private ValueChangeListener reqMigStepCheckboxListerner;
private TextChangeListener descTextAreaListener; private TextChangeListener descTextAreaListener;
private TextChangeListener distNameTextFieldListener; private TextChangeListener distNameTextFieldListener;
@@ -130,9 +131,9 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
final HorizontalLayout buttonsLayout = new HorizontalLayout(); final HorizontalLayout buttonsLayout = new HorizontalLayout();
buttonsLayout.setSizeFull(); buttonsLayout.setSizeFull();
buttonsLayout.setStyleName("dist-buttons-horz-layout"); buttonsLayout.setStyleName("dist-buttons-horz-layout");
buttonsLayout.addComponents(saveDistribution, discardDistribution); buttonsLayout.addComponents(this.saveDistribution, this.discardDistribution);
buttonsLayout.setComponentAlignment(saveDistribution, Alignment.BOTTOM_LEFT); buttonsLayout.setComponentAlignment(this.saveDistribution, Alignment.BOTTOM_LEFT);
buttonsLayout.setComponentAlignment(discardDistribution, Alignment.BOTTOM_RIGHT); buttonsLayout.setComponentAlignment(this.discardDistribution, Alignment.BOTTOM_RIGHT);
buttonsLayout.addStyleName("window-style"); buttonsLayout.addStyleName("window-style");
/* /*
@@ -142,11 +143,11 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
setSpacing(Boolean.TRUE); setSpacing(Boolean.TRUE);
addStyleName("lay-color"); addStyleName("lay-color");
setSizeUndefined(); setSizeUndefined();
addComponents(madatoryLabel, distsetTypeNameComboBox, distNameTextField, distVersionTextField, descTextArea, addComponents(this.madatoryLabel, this.distsetTypeNameComboBox, this.distNameTextField,
reqMigStepCheckbox); this.distVersionTextField, this.descTextArea, this.reqMigStepCheckbox);
addComponent(buttonsLayout); addComponent(buttonsLayout);
setComponentAlignment(madatoryLabel, Alignment.MIDDLE_LEFT); setComponentAlignment(this.madatoryLabel, Alignment.MIDDLE_LEFT);
} }
@@ -154,45 +155,45 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
* Create required UI components. * Create required UI components.
*/ */
private void createRequiredComponents() { private void createRequiredComponents() {
distNameTextField = SPUIComponentProvider.getTextField("", ValoTheme.TEXTFIELD_TINY, true, null, this.distNameTextField = SPUIComponentProvider.getTextField("", ValoTheme.TEXTFIELD_TINY, true, null,
i18n.get("textfield.name"), true, SPUILabelDefinitions.TEXT_FIELD_MAX_LENGTH); this.i18n.get("textfield.name"), true, SPUILabelDefinitions.TEXT_FIELD_MAX_LENGTH);
distNameTextField.setId(SPUIComponetIdProvider.DIST_ADD_NAME); this.distNameTextField.setId(SPUIComponetIdProvider.DIST_ADD_NAME);
distNameTextField.setNullRepresentation(""); this.distNameTextField.setNullRepresentation("");
distVersionTextField = SPUIComponentProvider.getTextField("", ValoTheme.TEXTFIELD_TINY, true, null, this.distVersionTextField = SPUIComponentProvider.getTextField("", ValoTheme.TEXTFIELD_TINY, true, null,
i18n.get("textfield.version"), true, SPUILabelDefinitions.TEXT_FIELD_MAX_LENGTH); this.i18n.get("textfield.version"), true, SPUILabelDefinitions.TEXT_FIELD_MAX_LENGTH);
distVersionTextField.setId(SPUIComponetIdProvider.DIST_ADD_VERSION); this.distVersionTextField.setId(SPUIComponetIdProvider.DIST_ADD_VERSION);
distVersionTextField.setNullRepresentation(""); this.distVersionTextField.setNullRepresentation("");
distsetTypeNameComboBox = SPUIComponentProvider.getComboBox("", "", null, "", false, "", this.distsetTypeNameComboBox = SPUIComponentProvider.getComboBox("", "", null, "", false, "",
i18n.get("label.combobox.type")); this.i18n.get("label.combobox.type"));
distsetTypeNameComboBox.setImmediate(true); this.distsetTypeNameComboBox.setImmediate(true);
distsetTypeNameComboBox.setNullSelectionAllowed(false); this.distsetTypeNameComboBox.setNullSelectionAllowed(false);
distsetTypeNameComboBox.setId(SPUIComponetIdProvider.DIST_ADD_DISTSETTYPE); this.distsetTypeNameComboBox.setId(SPUIComponetIdProvider.DIST_ADD_DISTSETTYPE);
descTextArea = SPUIComponentProvider.getTextArea("text-area-style", ValoTheme.TEXTAREA_TINY, false, null, this.descTextArea = SPUIComponentProvider.getTextArea("text-area-style", ValoTheme.TEXTAREA_TINY, false, null,
i18n.get("textfield.description"), SPUILabelDefinitions.TEXT_AREA_MAX_LENGTH); this.i18n.get("textfield.description"), SPUILabelDefinitions.TEXT_AREA_MAX_LENGTH);
descTextArea.setId(SPUIComponetIdProvider.DIST_ADD_DESC); this.descTextArea.setId(SPUIComponetIdProvider.DIST_ADD_DESC);
descTextArea.setNullRepresentation(""); this.descTextArea.setNullRepresentation("");
/* Label for mandatory symbol */ /* Label for mandatory symbol */
madatoryLabel = new Label(i18n.get("label.mandatory.field")); this.madatoryLabel = new Label(this.i18n.get("label.mandatory.field"));
madatoryLabel.setStyleName(SPUIStyleDefinitions.SP_TEXTFIELD_ERROR + " " + ValoTheme.LABEL_SMALL); this.madatoryLabel.setStyleName(SPUIStyleDefinitions.SP_TEXTFIELD_ERROR + " " + ValoTheme.LABEL_SMALL);
reqMigStepCheckbox = SPUIComponentProvider.getCheckBox(i18n.get("checkbox.dist.required.migration.step"), this.reqMigStepCheckbox = SPUIComponentProvider.getCheckBox(
"dist-checkbox-style", null, false, ""); this.i18n.get("checkbox.dist.required.migration.step"), "dist-checkbox-style", null, false, "");
reqMigStepCheckbox.addStyleName(ValoTheme.CHECKBOX_SMALL); this.reqMigStepCheckbox.addStyleName(ValoTheme.CHECKBOX_SMALL);
reqMigStepCheckbox.setId(SPUIComponetIdProvider.DIST_ADD_MIGRATION_CHECK); this.reqMigStepCheckbox.setId(SPUIComponetIdProvider.DIST_ADD_MIGRATION_CHECK);
/* save or update button */ /* save or update button */
saveDistribution = SPUIComponentProvider.getButton(SPUIComponetIdProvider.DIST_ADD_SAVE, "", "", "", true, this.saveDistribution = SPUIComponentProvider.getButton(SPUIComponetIdProvider.DIST_ADD_SAVE, "", "", "", true,
FontAwesome.SAVE, SPUIButtonStyleSmallNoBorder.class); FontAwesome.SAVE, SPUIButtonStyleSmallNoBorder.class);
saveDistribution.addClickListener(event -> saveDistribution()); this.saveDistribution.addClickListener(event -> saveDistribution());
/* close button */ /* close button */
discardDistribution = SPUIComponentProvider.getButton(SPUIComponetIdProvider.DIST_ADD_DISCARD, "", "", "", true, this.discardDistribution = SPUIComponentProvider.getButton(SPUIComponetIdProvider.DIST_ADD_DISCARD, "", "", "",
FontAwesome.TIMES, SPUIButtonStyleSmallNoBorder.class); true, FontAwesome.TIMES, SPUIButtonStyleSmallNoBorder.class);
discardDistribution.addClickListener(event -> discardDistribution()); this.discardDistribution.addClickListener(event -> discardDistribution());
} }
/** /**
@@ -201,8 +202,8 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
* @return * @return
*/ */
private LazyQueryContainer getDistSetTypeLazyQueryContainer() { private LazyQueryContainer getDistSetTypeLazyQueryContainer() {
final Map<String, Object> queryConfig = new HashMap<String, Object>(); final Map<String, Object> queryConfig = new HashMap<>();
final BeanQueryFactory<DistributionSetTypeBeanQuery> dtQF = new BeanQueryFactory<DistributionSetTypeBeanQuery>( final BeanQueryFactory<DistributionSetTypeBeanQuery> dtQF = new BeanQueryFactory<>(
DistributionSetTypeBeanQuery.class); DistributionSetTypeBeanQuery.class);
dtQF.setQueryConfiguration(queryConfig); dtQF.setQueryConfiguration(queryConfig);
@@ -215,22 +216,22 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
} }
private void enableSaveButton() { private void enableSaveButton() {
saveDistribution.setEnabled(true); this.saveDistribution.setEnabled(true);
} }
private DistributionSetType getDefaultDistributionSetType() { private DistributionSetType getDefaultDistributionSetType() {
final TenantMetaData tenantMetaData = tenantMetaDataRepository final TenantMetaData tenantMetaData = this.tenantMetaDataRepository
.findByTenantIgnoreCase(systemManagement.currentTenant()); .findByTenantIgnoreCase(this.systemManagement.currentTenant());
return tenantMetaData.getDefaultDsType(); return tenantMetaData.getDefaultDsType();
} }
private void disableSaveButton() { private void disableSaveButton() {
saveDistribution.setEnabled(false); this.saveDistribution.setEnabled(false);
} }
private void saveDistribution() { private void saveDistribution() {
/* add new or update target */ /* add new or update target */
if (editDistribution) { if (this.editDistribution) {
updateDistribution(); updateDistribution();
} else { } else {
addNewDistribution(); addNewDistribution();
@@ -242,71 +243,73 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
* Update Distribution. * Update Distribution.
*/ */
private void updateDistribution() { private void updateDistribution() {
final String name = HawkbitCommonUtil.trimAndNullIfEmpty(distNameTextField.getValue()); final String name = HawkbitCommonUtil.trimAndNullIfEmpty(this.distNameTextField.getValue());
final String version = HawkbitCommonUtil.trimAndNullIfEmpty(distVersionTextField.getValue()); final String version = HawkbitCommonUtil.trimAndNullIfEmpty(this.distVersionTextField.getValue());
final String distSetTypeName = HawkbitCommonUtil final String distSetTypeName = HawkbitCommonUtil
.trimAndNullIfEmpty((String) distsetTypeNameComboBox.getValue()); .trimAndNullIfEmpty((String) this.distsetTypeNameComboBox.getValue());
if (mandatoryCheck(name, version, distSetTypeName) && duplicateCheck(name, version)) { if (mandatoryCheck(name, version, distSetTypeName) && duplicateCheck(name, version)) {
final DistributionSet currentDS = distributionSetManagement.findDistributionSetByIdWithDetails(editDistId); final DistributionSet currentDS = this.distributionSetManagement
final String desc = HawkbitCommonUtil.trimAndNullIfEmpty(descTextArea.getValue()); .findDistributionSetByIdWithDetails(this.editDistId);
final boolean isMigStepReq = reqMigStepCheckbox.getValue(); final String desc = HawkbitCommonUtil.trimAndNullIfEmpty(this.descTextArea.getValue());
final boolean isMigStepReq = this.reqMigStepCheckbox.getValue();
/* identify the changes */ /* identify the changes */
setDistributionValues(currentDS, name, version, distSetTypeName, desc, isMigStepReq); setDistributionValues(currentDS, name, version, distSetTypeName, desc, isMigStepReq);
try { try {
distributionSetManagement.updateDistributionSet(currentDS); this.distributionSetManagement.updateDistributionSet(currentDS);
notificationMessage.displaySuccess(i18n.get("message.new.dist.save.success", this.notificationMessage.displaySuccess(this.i18n.get("message.new.dist.save.success",
new Object[] { currentDS.getName(), currentDS.getVersion() })); new Object[] { currentDS.getName(), currentDS.getVersion() }));
// update table row+details layout // update table row+details layout
eventBus.publish(this, this.eventBus.publish(this,
new DistributionTableEvent(DistributionComponentEvent.EDIT_DISTRIBUTION, currentDS)); new DistributionTableEvent(DistributionComponentEvent.EDIT_DISTRIBUTION, currentDS));
} catch (final EntityAlreadyExistsException entityAlreadyExistsException) { } catch (final EntityAlreadyExistsException entityAlreadyExistsException) {
LOG.error("Update distribution failed {}", entityAlreadyExistsException); LOG.error("Update distribution failed {}", entityAlreadyExistsException);
notificationMessage.displayValidationError( this.notificationMessage.displayValidationError(this.i18n.get("message.distribution.no.update",
i18n.get("message.distribution.no.update", currentDS.getName() + ":" + currentDS.getVersion())); currentDS.getName() + ":" + currentDS.getVersion()));
} }
closeThisWindow(); closeThisWindow();
} }
} }
private void addListeners() { private void addListeners() {
reqMigStepCheckboxListerner = event -> checkValueChanged(originalReqMigStep, event); this.reqMigStepCheckboxListerner = event -> checkValueChanged(this.originalReqMigStep, event);
descTextAreaListener = event -> checkValueChanged(originalDistDescription, event); this.descTextAreaListener = event -> checkValueChanged(this.originalDistDescription, event);
distNameTextFieldListener = event -> checkValueChanged(originalDistName, event); this.distNameTextFieldListener = event -> checkValueChanged(this.originalDistName, event);
distVersionTextFieldListener = event -> checkValueChanged(originalDistVersion, event); this.distVersionTextFieldListener = event -> checkValueChanged(this.originalDistVersion, event);
distsetTypeNameComboBoxListener = event -> checkValueChanged(originalDistSetType, event); this.distsetTypeNameComboBoxListener = event -> checkValueChanged(this.originalDistSetType, event);
reqMigStepCheckbox.addValueChangeListener(reqMigStepCheckboxListerner); this.reqMigStepCheckbox.addValueChangeListener(this.reqMigStepCheckboxListerner);
descTextArea.addTextChangeListener(descTextAreaListener); this.descTextArea.addTextChangeListener(this.descTextAreaListener);
distNameTextField.addTextChangeListener(distNameTextFieldListener); this.distNameTextField.addTextChangeListener(this.distNameTextFieldListener);
distVersionTextField.addTextChangeListener(distVersionTextFieldListener); this.distVersionTextField.addTextChangeListener(this.distVersionTextFieldListener);
distsetTypeNameComboBox.addValueChangeListener(distsetTypeNameComboBoxListener); this.distsetTypeNameComboBox.addValueChangeListener(this.distsetTypeNameComboBoxListener);
} }
/** /**
* Add new Distribution set. * Add new Distribution set.
*/ */
private void addNewDistribution() { private void addNewDistribution() {
editDistribution = Boolean.FALSE; this.editDistribution = Boolean.FALSE;
final String name = HawkbitCommonUtil.trimAndNullIfEmpty(distNameTextField.getValue()); final String name = HawkbitCommonUtil.trimAndNullIfEmpty(this.distNameTextField.getValue());
final String version = HawkbitCommonUtil.trimAndNullIfEmpty(distVersionTextField.getValue()); final String version = HawkbitCommonUtil.trimAndNullIfEmpty(this.distVersionTextField.getValue());
final String distSetTypeName = HawkbitCommonUtil final String distSetTypeName = HawkbitCommonUtil
.trimAndNullIfEmpty((String) distsetTypeNameComboBox.getValue()); .trimAndNullIfEmpty((String) this.distsetTypeNameComboBox.getValue());
if (mandatoryCheck(name, version, distSetTypeName) && duplicateCheck(name, version)) { if (mandatoryCheck(name, version, distSetTypeName) && duplicateCheck(name, version)) {
final String desc = HawkbitCommonUtil.trimAndNullIfEmpty(descTextArea.getValue()); final String desc = HawkbitCommonUtil.trimAndNullIfEmpty(this.descTextArea.getValue());
final boolean isMigStepReq = reqMigStepCheckbox.getValue(); final boolean isMigStepReq = this.reqMigStepCheckbox.getValue();
DistributionSet newDist = new DistributionSet(); DistributionSet newDist = new DistributionSet();
setDistributionValues(newDist, name, version, distSetTypeName, desc, isMigStepReq); setDistributionValues(newDist, name, version, distSetTypeName, desc, isMigStepReq);
newDist = distributionSetManagement.createDistributionSet(newDist); newDist = this.distributionSetManagement.createDistributionSet(newDist);
notificationMessage.displaySuccess(i18n.get("message.new.dist.save.success", this.notificationMessage.displaySuccess(this.i18n.get("message.new.dist.save.success",
new Object[] { newDist.getName(), newDist.getVersion() })); new Object[] { newDist.getName(), newDist.getVersion() }));
/* close the window */ /* close the window */
closeThisWindow(); closeThisWindow();
eventBus.publish(this, new DistributionTableEvent(DistributionComponentEvent.ADD_DISTRIBUTION, newDist)); this.eventBus.publish(this,
new DistributionTableEvent(DistributionComponentEvent.ADD_DISTRIBUTION, newDist));
} }
} }
@@ -314,8 +317,8 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
* Close window. * Close window.
*/ */
private void closeThisWindow() { private void closeThisWindow() {
addDistributionWindow.close(); this.addDistributionWindow.close();
UI.getCurrent().removeWindow(addDistributionWindow); UI.getCurrent().removeWindow(this.addDistributionWindow);
} }
/** /**
@@ -336,7 +339,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
final String distSetTypeName, final String desc, final boolean isMigStepReq) { final String distSetTypeName, final String desc, final boolean isMigStepReq) {
distributionSet.setName(name); distributionSet.setName(name);
distributionSet.setVersion(version); distributionSet.setVersion(version);
distributionSet.setType(distributionSetManagement.findDistributionSetTypeByName(distSetTypeName)); distributionSet.setType(this.distributionSetManagement.findDistributionSetTypeByName(distSetTypeName));
distributionSet.setDescription(desc != null ? desc : ""); distributionSet.setDescription(desc != null ? desc : "");
distributionSet.setRequiredMigrationStep(isMigStepReq); distributionSet.setRequiredMigrationStep(isMigStepReq);
} }
@@ -351,18 +354,20 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
* @return * @return
*/ */
private boolean duplicateCheck(final String name, final String version) { private boolean duplicateCheck(final String name, final String version) {
final DistributionSet existingDs = distributionSetManagement.findDistributionSetByNameAndVersion(name, version); final DistributionSet existingDs = this.distributionSetManagement.findDistributionSetByNameAndVersion(name,
version);
/* /*
* Distribution should not exists with the same name & version. Display * Distribution should not exists with the same name & version. Display
* error message, when the "existingDs" is not null and it is add window * error message, when the "existingDs" is not null and it is add window
* (or) when the "existingDs" is not null and it is edit window and the * (or) when the "existingDs" is not null and it is edit window and the
* distribution Id of the edit window is different then the "existingDs" * distribution Id of the edit window is different then the "existingDs"
*/ */
if (existingDs != null && (!editDistribution || editDistribution && !existingDs.getId().equals(editDistId))) { if (existingDs != null
distNameTextField.addStyleName("v-textfield-error"); && (!this.editDistribution || this.editDistribution && !existingDs.getId().equals(this.editDistId))) {
distVersionTextField.addStyleName("v-textfield-error"); this.distNameTextField.addStyleName("v-textfield-error");
notificationMessage.displayValidationError( this.distVersionTextField.addStyleName("v-textfield-error");
i18n.get("message.duplicate.dist", new Object[] { existingDs.getName(), existingDs.getVersion() })); this.notificationMessage.displayValidationError(this.i18n.get("message.duplicate.dist",
new Object[] { existingDs.getName(), existingDs.getVersion() }));
return false; return false;
} else { } else {
@@ -389,16 +394,16 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
if (name == null || version == null || distSetTypeName == null) { if (name == null || version == null || distSetTypeName == null) {
if (name == null) { if (name == null) {
distNameTextField.addStyleName(SPUIStyleDefinitions.SP_TEXTFIELD_ERROR); this.distNameTextField.addStyleName(SPUIStyleDefinitions.SP_TEXTFIELD_ERROR);
} }
if (version == null) { if (version == null) {
distVersionTextField.addStyleName(SPUIStyleDefinitions.SP_TEXTFIELD_ERROR); this.distVersionTextField.addStyleName(SPUIStyleDefinitions.SP_TEXTFIELD_ERROR);
} }
if (distSetTypeName == null) { if (distSetTypeName == null) {
distsetTypeNameComboBox.addStyleName(SPUIStyleDefinitions.SP_COMBOFIELD_ERROR); this.distsetTypeNameComboBox.addStyleName(SPUIStyleDefinitions.SP_COMBOFIELD_ERROR);
} }
notificationMessage.displayValidationError(i18n.get("message.mandatory.check")); this.notificationMessage.displayValidationError(this.i18n.get("message.mandatory.check"));
return false; return false;
} }
@@ -407,7 +412,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
private void discardDistribution() { private void discardDistribution() {
/* Just close this window */ /* Just close this window */
distsetTypeNameComboBox.removeValueChangeListener(distsetTypeNameComboBoxListener); this.distsetTypeNameComboBox.removeValueChangeListener(this.distsetTypeNameComboBoxListener);
closeThisWindow(); closeThisWindow();
} }
@@ -415,17 +420,17 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
* clear all the fields. * clear all the fields.
*/ */
public void resetComponents() { public void resetComponents() {
editDistribution = Boolean.FALSE; this.editDistribution = Boolean.FALSE;
distNameTextField.clear(); this.distNameTextField.clear();
distNameTextField.removeStyleName(SPUIStyleDefinitions.SP_TEXTFIELD_ERROR); this.distNameTextField.removeStyleName(SPUIStyleDefinitions.SP_TEXTFIELD_ERROR);
distVersionTextField.clear(); this.distVersionTextField.clear();
distVersionTextField.removeStyleName(SPUIStyleDefinitions.SP_TEXTFIELD_ERROR); this.distVersionTextField.removeStyleName(SPUIStyleDefinitions.SP_TEXTFIELD_ERROR);
distsetTypeNameComboBox.removeStyleName(SPUIStyleDefinitions.SP_COMBOFIELD_ERROR); this.distsetTypeNameComboBox.removeStyleName(SPUIStyleDefinitions.SP_COMBOFIELD_ERROR);
descTextArea.clear(); this.descTextArea.clear();
reqMigStepCheckbox.clear(); this.reqMigStepCheckbox.clear();
saveDistribution.setEnabled(true); this.saveDistribution.setEnabled(true);
removeListeners(); removeListeners();
changedComponents.clear(); this.changedComponents.clear();
} }
private void populateRequiredComponents() { private void populateRequiredComponents() {
@@ -433,10 +438,10 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
} }
private void removeListeners() { private void removeListeners() {
reqMigStepCheckbox.removeValueChangeListener(reqMigStepCheckboxListerner); this.reqMigStepCheckbox.removeValueChangeListener(this.reqMigStepCheckboxListerner);
descTextArea.removeTextChangeListener(descTextAreaListener); this.descTextArea.removeTextChangeListener(this.descTextAreaListener);
distNameTextField.removeTextChangeListener(distNameTextFieldListener); this.distNameTextField.removeTextChangeListener(this.distNameTextFieldListener);
distVersionTextField.removeTextChangeListener(distVersionTextFieldListener); this.distVersionTextField.removeTextChangeListener(this.distVersionTextFieldListener);
} }
public void setOriginalDistName(final String originalDistName) { public void setOriginalDistName(final String originalDistName) {
@@ -452,41 +457,41 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
} }
private void checkValueChanged(final String originalValue, final TextChangeEvent event) { private void checkValueChanged(final String originalValue, final TextChangeEvent event) {
if (editDistribution) { if (this.editDistribution) {
final String newValue = event.getText(); final String newValue = event.getText();
if (!originalValue.equalsIgnoreCase(newValue)) { if (!originalValue.equalsIgnoreCase(newValue)) {
changedComponents.add(event.getComponent()); this.changedComponents.add(event.getComponent());
} else { } else {
changedComponents.remove(event.getComponent()); this.changedComponents.remove(event.getComponent());
} }
enableDisableSaveButton(); enableDisableSaveButton();
} }
} }
private void checkValueChanged(final Boolean originalValue, final ValueChangeEvent event) { private void checkValueChanged(final Boolean originalValue, final ValueChangeEvent event) {
if (editDistribution) { if (this.editDistribution) {
if (!originalValue.equals(event.getProperty().getValue())) { if (!originalValue.equals(event.getProperty().getValue())) {
changedComponents.add(reqMigStepCheckbox); this.changedComponents.add(this.reqMigStepCheckbox);
} else { } else {
changedComponents.remove(reqMigStepCheckbox); this.changedComponents.remove(this.reqMigStepCheckbox);
} }
enableDisableSaveButton(); enableDisableSaveButton();
} }
} }
private void checkValueChanged(final String originalValue, final ValueChangeEvent event) { private void checkValueChanged(final String originalValue, final ValueChangeEvent event) {
if (editDistribution) { if (this.editDistribution) {
if (!originalValue.equals(event.getProperty().getValue())) { if (!originalValue.equals(event.getProperty().getValue())) {
changedComponents.add(distsetTypeNameComboBox); this.changedComponents.add(this.distsetTypeNameComboBox);
} else { } else {
changedComponents.remove(distsetTypeNameComboBox); this.changedComponents.remove(this.distsetTypeNameComboBox);
} }
enableDisableSaveButton(); enableDisableSaveButton();
} }
} }
private void enableDisableSaveButton() { private void enableDisableSaveButton() {
if (changedComponents.isEmpty()) { if (this.changedComponents.isEmpty()) {
disableSaveButton(); disableSaveButton();
} else { } else {
enableSaveButton(); enableSaveButton();
@@ -504,19 +509,19 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
*/ */
public void populateValuesOfDistribution(final Long editDistId) { public void populateValuesOfDistribution(final Long editDistId) {
this.editDistId = editDistId; this.editDistId = editDistId;
editDistribution = Boolean.TRUE; this.editDistribution = Boolean.TRUE;
saveDistribution.setEnabled(false); this.saveDistribution.setEnabled(false);
final DistributionSet distSet = distributionSetManagement.findDistributionSetByIdWithDetails(editDistId); final DistributionSet distSet = this.distributionSetManagement.findDistributionSetByIdWithDetails(editDistId);
if (distSet != null) { if (distSet != null) {
distNameTextField.setValue(distSet.getName()); this.distNameTextField.setValue(distSet.getName());
distVersionTextField.setValue(distSet.getVersion()); this.distVersionTextField.setValue(distSet.getVersion());
if (distSet.getType().isDeleted()) { if (distSet.getType().isDeleted()) {
distsetTypeNameComboBox.addItem(distSet.getType().getName()); this.distsetTypeNameComboBox.addItem(distSet.getType().getName());
} }
distsetTypeNameComboBox.setValue(distSet.getType().getName()); this.distsetTypeNameComboBox.setValue(distSet.getType().getName());
reqMigStepCheckbox.setValue(distSet.isRequiredMigrationStep()); this.reqMigStepCheckbox.setValue(distSet.isRequiredMigrationStep());
if (distSet.getDescription() != null) { if (distSet.getDescription() != null) {
descTextArea.setValue(distSet.getDescription()); this.descTextArea.setValue(distSet.getDescription());
} }
setOriginalDistName(distSet.getName()); setOriginalDistName(distSet.getName());
setOriginalDistVersion(distSet.getVersion()); setOriginalDistVersion(distSet.getVersion());
@@ -528,22 +533,22 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout {
} }
public Window getWindow() { public Window getWindow() {
eventBus.publish(this, DragEvent.HIDE_DROP_HINT); this.eventBus.publish(this, DragEvent.HIDE_DROP_HINT);
populateRequiredComponents(); populateRequiredComponents();
resetComponents(); resetComponents();
addDistributionWindow = SPUIComponentProvider.getWindow(i18n.get("caption.add.new.dist"), null, this.addDistributionWindow = SPUIComponentProvider.getWindow(this.i18n.get("caption.add.new.dist"), null,
SPUIDefinitions.CREATE_UPDATE_WINDOW); SPUIDefinitions.CREATE_UPDATE_WINDOW);
addDistributionWindow.setContent(this); this.addDistributionWindow.setContent(this);
return addDistributionWindow; return this.addDistributionWindow;
} }
/** /**
* Populate DistributionSet Type name combo. * Populate DistributionSet Type name combo.
*/ */
public void populateDistSetTypeNameCombo() { public void populateDistSetTypeNameCombo() {
distsetTypeNameComboBox.setContainerDataSource(getDistSetTypeLazyQueryContainer()); this.distsetTypeNameComboBox.setContainerDataSource(getDistSetTypeLazyQueryContainer());
distsetTypeNameComboBox.setItemCaptionPropertyId(SPUILabelDefinitions.VAR_NAME); this.distsetTypeNameComboBox.setItemCaptionPropertyId(SPUILabelDefinitions.VAR_NAME);
distsetTypeNameComboBox.setValue(getDefaultDistributionSetType().getName()); this.distsetTypeNameComboBox.setValue(getDefaultDistributionSetType().getName());
} }
/** /**

View File

@@ -8,7 +8,6 @@
*/ */
package org.eclipse.hawkbit.ui.management.footer; package org.eclipse.hawkbit.ui.management.footer;
import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil;
import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider;
import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions;
@@ -69,7 +68,7 @@ public final class DeleteActionsLayoutHelper {
* @return true if it component is target table * @return true if it component is target table
*/ */
public static boolean isTargetTable(final Component source) { public static boolean isTargetTable(final Component source) {
return HawkbitCommonUtil.bothSame(source.getId(), SPUIComponetIdProvider.TARGET_TABLE_ID); return SPUIComponetIdProvider.TARGET_TABLE_ID.equalsIgnoreCase(source.getId());
} }
/** /**
@@ -80,7 +79,7 @@ public final class DeleteActionsLayoutHelper {
* @return true if it component is distribution table * @return true if it component is distribution table
*/ */
public static boolean isDistributionTable(final Component source) { public static boolean isDistributionTable(final Component source) {
return HawkbitCommonUtil.bothSame(source.getId(), SPUIComponetIdProvider.DIST_TABLE_ID); return SPUIComponetIdProvider.DIST_TABLE_ID.equalsIgnoreCase(source.getId());
} }
/** /**

View File

@@ -35,17 +35,19 @@ public class ManagementUIState implements Serializable {
private static final long serialVersionUID = 7301409196969723794L; private static final long serialVersionUID = 7301409196969723794L;
private final transient Set<Object> expandParentActionRowId = new HashSet<>();
@Autowired @Autowired
private DistributionTableFilters distributionTableFilters; private DistributionTableFilters distributionTableFilters;
@Autowired @Autowired
private TargetTableFilters targetTableFilters; private TargetTableFilters targetTableFilters;
private final Map<TargetIdName, DistributionSetIdName> assignedList = new HashMap<TargetIdName, DistributionSetIdName>(); private final Map<TargetIdName, DistributionSetIdName> assignedList = new HashMap<>();
private final Set<DistributionSetIdName> deletedDistributionList = new HashSet<DistributionSetIdName>(); private final Set<DistributionSetIdName> deletedDistributionList = new HashSet<>();
private final Set<TargetIdName> deletedTargetList = new HashSet<TargetIdName>(); private final Set<TargetIdName> deletedTargetList = new HashSet<>();
private Boolean targetTagLayoutVisible = Boolean.TRUE; private Boolean targetTagLayoutVisible = Boolean.TRUE;
@@ -79,9 +81,7 @@ public class ManagementUIState implements Serializable {
private boolean noDataAvailableDistribution = Boolean.FALSE; private boolean noDataAvailableDistribution = Boolean.FALSE;
private final Set<String> canceledTargetName = new HashSet<String>(); private final Set<String> canceledTargetName = new HashSet<>();
private final Set<Object> expandParentActionRowId = new HashSet<Object>();
private boolean customFilterSelected; private boolean customFilterSelected;
@@ -91,7 +91,7 @@ public class ManagementUIState implements Serializable {
* @return the bulkUploadWindowMinimised * @return the bulkUploadWindowMinimised
*/ */
public boolean isBulkUploadWindowMinimised() { public boolean isBulkUploadWindowMinimised() {
return bulkUploadWindowMinimised; return this.bulkUploadWindowMinimised;
} }
/** /**
@@ -106,7 +106,7 @@ public class ManagementUIState implements Serializable {
* @return the isCustomFilterSelected * @return the isCustomFilterSelected
*/ */
public boolean isCustomFilterSelected() { public boolean isCustomFilterSelected() {
return customFilterSelected; return this.customFilterSelected;
} }
/** /**
@@ -118,11 +118,11 @@ public class ManagementUIState implements Serializable {
} }
public Set<Object> getExpandParentActionRowId() { public Set<Object> getExpandParentActionRowId() {
return expandParentActionRowId; return this.expandParentActionRowId;
} }
public Set<String> getCanceledTargetName() { public Set<String> getCanceledTargetName() {
return canceledTargetName; return this.canceledTargetName;
} }
public void setDistTagLayoutVisible(final Boolean distTagLayoutVisible) { public void setDistTagLayoutVisible(final Boolean distTagLayoutVisible) {
@@ -130,7 +130,7 @@ public class ManagementUIState implements Serializable {
} }
public Boolean getDistTagLayoutVisible() { public Boolean getDistTagLayoutVisible() {
return distTagLayoutVisible; return this.distTagLayoutVisible;
} }
public void setTargetTagLayoutVisible(final Boolean targetTagVisible) { public void setTargetTagLayoutVisible(final Boolean targetTagVisible) {
@@ -138,31 +138,31 @@ public class ManagementUIState implements Serializable {
} }
public Boolean getTargetTagLayoutVisible() { public Boolean getTargetTagLayoutVisible() {
return targetTagLayoutVisible; return this.targetTagLayoutVisible;
} }
public TargetTableFilters getTargetTableFilters() { public TargetTableFilters getTargetTableFilters() {
return targetTableFilters; return this.targetTableFilters;
} }
public DistributionTableFilters getDistributionTableFilters() { public DistributionTableFilters getDistributionTableFilters() {
return distributionTableFilters; return this.distributionTableFilters;
} }
public Map<TargetIdName, DistributionSetIdName> getAssignedList() { public Map<TargetIdName, DistributionSetIdName> getAssignedList() {
return assignedList; return this.assignedList;
} }
public Set<DistributionSetIdName> getDeletedDistributionList() { public Set<DistributionSetIdName> getDeletedDistributionList() {
return deletedDistributionList; return this.deletedDistributionList;
} }
public Set<TargetIdName> getDeletedTargetList() { public Set<TargetIdName> getDeletedTargetList() {
return deletedTargetList; return this.deletedTargetList;
} }
public TargetIdName getLastSelectedTargetIdName() { public TargetIdName getLastSelectedTargetIdName() {
return lastSelectedTargetIdName; return this.lastSelectedTargetIdName;
} }
public void setLastSelectedTargetIdName(final TargetIdName lastSelectedTargetIdName) { public void setLastSelectedTargetIdName(final TargetIdName lastSelectedTargetIdName) {
@@ -170,7 +170,7 @@ public class ManagementUIState implements Serializable {
} }
public Optional<Set<TargetIdName>> getSelectedTargetIdName() { public Optional<Set<TargetIdName>> getSelectedTargetIdName() {
return selectedTargetIdName == null ? Optional.empty() : Optional.of(selectedTargetIdName); return this.selectedTargetIdName == null ? Optional.empty() : Optional.of(this.selectedTargetIdName);
} }
public void setSelectedTargetIdName(final Set<TargetIdName> selectedTargetIdName) { public void setSelectedTargetIdName(final Set<TargetIdName> selectedTargetIdName) {
@@ -181,7 +181,7 @@ public class ManagementUIState implements Serializable {
* @return the targetTagFilterClosed * @return the targetTagFilterClosed
*/ */
public boolean isTargetTagFilterClosed() { public boolean isTargetTagFilterClosed() {
return targetTagFilterClosed; return this.targetTagFilterClosed;
} }
/** /**
@@ -196,7 +196,7 @@ public class ManagementUIState implements Serializable {
* @return the distTagFilterClosed * @return the distTagFilterClosed
*/ */
public boolean isDistTagFilterClosed() { public boolean isDistTagFilterClosed() {
return distTagFilterClosed; return this.distTagFilterClosed;
} }
/** /**
@@ -211,7 +211,7 @@ public class ManagementUIState implements Serializable {
* @return the targetsTruncated * @return the targetsTruncated
*/ */
public Long getTargetsTruncated() { public Long getTargetsTruncated() {
return targetsTruncated; return this.targetsTruncated;
} }
/** /**
@@ -226,7 +226,7 @@ public class ManagementUIState implements Serializable {
* @return the targetsCountAll * @return the targetsCountAll
*/ */
public long getTargetsCountAll() { public long getTargetsCountAll() {
return targetsCountAll.get(); return this.targetsCountAll.get();
} }
/** /**
@@ -255,7 +255,7 @@ public class ManagementUIState implements Serializable {
} }
public boolean isDsTableMaximized() { public boolean isDsTableMaximized() {
return isDsTableMaximized; return this.isDsTableMaximized;
} }
public void setDsTableMaximized(final boolean isDsTableMaximized) { public void setDsTableMaximized(final boolean isDsTableMaximized) {
@@ -263,7 +263,7 @@ public class ManagementUIState implements Serializable {
} }
public DistributionSetIdName getLastSelectedDsIdName() { public DistributionSetIdName getLastSelectedDsIdName() {
return lastSelectedDsIdName; return this.lastSelectedDsIdName;
} }
public void setLastSelectedDsIdName(final DistributionSetIdName lastSelectedDsIdName) { public void setLastSelectedDsIdName(final DistributionSetIdName lastSelectedDsIdName) {
@@ -275,14 +275,14 @@ public class ManagementUIState implements Serializable {
} }
public Optional<Set<DistributionSetIdName>> getSelectedDsIdName() { public Optional<Set<DistributionSetIdName>> getSelectedDsIdName() {
return selectedDsIdName == null ? Optional.empty() : Optional.of(selectedDsIdName); return this.selectedDsIdName == null ? Optional.empty() : Optional.of(this.selectedDsIdName);
} }
/** /**
* @return the isTargetTableMaximized * @return the isTargetTableMaximized
*/ */
public boolean isTargetTableMaximized() { public boolean isTargetTableMaximized() {
return isTargetTableMaximized; return this.isTargetTableMaximized;
} }
/** /**
@@ -297,7 +297,7 @@ public class ManagementUIState implements Serializable {
* @return the isActionHistoryMaximized * @return the isActionHistoryMaximized
*/ */
public boolean isActionHistoryMaximized() { public boolean isActionHistoryMaximized() {
return isActionHistoryMaximized; return this.isActionHistoryMaximized;
} }
/** /**
@@ -312,7 +312,7 @@ public class ManagementUIState implements Serializable {
* @return the noDataAvilableTarget * @return the noDataAvilableTarget
*/ */
public boolean isNoDataAvilableTarget() { public boolean isNoDataAvilableTarget() {
return noDataAvilableTarget; return this.noDataAvilableTarget;
} }
/** /**
@@ -327,7 +327,7 @@ public class ManagementUIState implements Serializable {
* @return the noDataAvailableDistribution * @return the noDataAvailableDistribution
*/ */
public boolean isNoDataAvailableDistribution() { public boolean isNoDataAvailableDistribution() {
return noDataAvailableDistribution; return this.noDataAvailableDistribution;
} }
/** /**

View File

@@ -56,12 +56,7 @@ import com.vaadin.ui.components.colorpicker.ColorSelector;
import com.vaadin.ui.themes.ValoTheme; import com.vaadin.ui.themes.ValoTheme;
/** /**
*
* Abstract class for create/update target tag layout. * Abstract class for create/update target tag layout.
*
*
*
*
*/ */
public abstract class CreateUpdateTagLayout extends CustomComponent implements ColorChangeListener, ColorSelector { public abstract class CreateUpdateTagLayout extends CustomComponent implements ColorChangeListener, ColorSelector {
private static final long serialVersionUID = 4229177824620576456L; private static final long serialVersionUID = 4229177824620576456L;
@@ -78,7 +73,7 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C
protected I18N i18n; protected I18N i18n;
@Autowired @Autowired
protected TagManagement tagManagement; protected transient TagManagement tagManagement;
@Autowired @Autowired
protected transient EventBus.SessionEventBus eventBus; protected transient EventBus.SessionEventBus eventBus;
@@ -155,126 +150,126 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C
createRequiredComponents(); createRequiredComponents();
addListeners(); addListeners();
buildLayout(); buildLayout();
eventBus.subscribe(this); this.eventBus.subscribe(this);
} }
@PreDestroy @PreDestroy
void destroy() { void destroy() {
eventBus.unsubscribe(this); this.eventBus.unsubscribe(this);
} }
private void createRequiredComponents() { private void createRequiredComponents() {
createTagNw = i18n.get("label.create.tag"); this.createTagNw = this.i18n.get("label.create.tag");
updateTagNw = i18n.get("label.update.tag"); this.updateTagNw = this.i18n.get("label.update.tag");
createTag = SPUIComponentProvider.getLabel(createTagNw, null); this.createTag = SPUIComponentProvider.getLabel(this.createTagNw, null);
updateTag = SPUIComponentProvider.getLabel(i18n.get("label.update.tag"), null); this.updateTag = SPUIComponentProvider.getLabel(this.i18n.get("label.update.tag"), null);
comboLabel = SPUIComponentProvider.getLabel(i18n.get("label.choose.tag"), null); this.comboLabel = SPUIComponentProvider.getLabel(this.i18n.get("label.choose.tag"), null);
madatoryLabel = getMandatoryLabel(); this.madatoryLabel = getMandatoryLabel();
colorLabel = SPUIComponentProvider.getLabel(i18n.get("label.choose.tag.color"), null); this.colorLabel = SPUIComponentProvider.getLabel(this.i18n.get("label.choose.tag.color"), null);
colorLabel.addStyleName(SPUIDefinitions.COLOR_LABEL_STYLE); this.colorLabel.addStyleName(SPUIDefinitions.COLOR_LABEL_STYLE);
tagName = SPUIComponentProvider.getTextField("", ValoTheme.TEXTFIELD_TINY + " " + SPUIDefinitions.TAG_NAME, this.tagName = SPUIComponentProvider.getTextField("", ValoTheme.TEXTFIELD_TINY + " " + SPUIDefinitions.TAG_NAME,
true, "", i18n.get("textfield.name"), true, SPUILabelDefinitions.TEXT_FIELD_MAX_LENGTH); true, "", this.i18n.get("textfield.name"), true, SPUILabelDefinitions.TEXT_FIELD_MAX_LENGTH);
tagName.setId(SPUIDefinitions.NEW_TARGET_TAG_NAME); this.tagName.setId(SPUIDefinitions.NEW_TARGET_TAG_NAME);
tagDesc = SPUIComponentProvider.getTextArea("", ValoTheme.TEXTFIELD_TINY + " " + SPUIDefinitions.TAG_DESC, this.tagDesc = SPUIComponentProvider.getTextArea("", ValoTheme.TEXTFIELD_TINY + " " + SPUIDefinitions.TAG_DESC,
false, "", i18n.get("textfield.description"), SPUILabelDefinitions.TEXT_AREA_MAX_LENGTH); false, "", this.i18n.get("textfield.description"), SPUILabelDefinitions.TEXT_AREA_MAX_LENGTH);
tagDesc.setId(SPUIDefinitions.NEW_TARGET_TAG_DESC); this.tagDesc.setId(SPUIDefinitions.NEW_TARGET_TAG_DESC);
tagDesc.setImmediate(true); this.tagDesc.setImmediate(true);
tagDesc.setNullRepresentation(""); this.tagDesc.setNullRepresentation("");
tagNameComboBox = SPUIComponentProvider.getComboBox("", "", null, null, false, "", this.tagNameComboBox = SPUIComponentProvider.getComboBox("", "", null, null, false, "",
i18n.get("label.combobox.tag")); this.i18n.get("label.combobox.tag"));
tagNameComboBox.addStyleName(SPUIDefinitions.FILTER_TYPE_COMBO_STYLE); this.tagNameComboBox.addStyleName(SPUIDefinitions.FILTER_TYPE_COMBO_STYLE);
tagNameComboBox.setImmediate(true); this.tagNameComboBox.setImmediate(true);
saveTag = SPUIComponentProvider.getButton(SPUIDefinitions.NEW_TARGET_TAG_SAVE, "", "", "", true, this.saveTag = SPUIComponentProvider.getButton(SPUIDefinitions.NEW_TARGET_TAG_SAVE, "", "", "", true,
FontAwesome.SAVE, SPUIButtonStyleSmallNoBorder.class); FontAwesome.SAVE, SPUIButtonStyleSmallNoBorder.class);
saveTag.addStyleName(ValoTheme.BUTTON_BORDERLESS); this.saveTag.addStyleName(ValoTheme.BUTTON_BORDERLESS);
discardTag = SPUIComponentProvider.getButton(SPUIDefinitions.NEW_TARGET_TAG_DISRACD, "", "", this.discardTag = SPUIComponentProvider.getButton(SPUIDefinitions.NEW_TARGET_TAG_DISRACD, "", "",
"discard-button-style", true, FontAwesome.TIMES, SPUIButtonStyleSmallNoBorder.class); "discard-button-style", true, FontAwesome.TIMES, SPUIButtonStyleSmallNoBorder.class);
discardTag.addStyleName(ValoTheme.BUTTON_BORDERLESS); this.discardTag.addStyleName(ValoTheme.BUTTON_BORDERLESS);
tagColorPreviewBtn = new Button(); this.tagColorPreviewBtn = new Button();
tagColorPreviewBtn.setId(SPUIComponetIdProvider.TAG_COLOR_PREVIEW_ID); this.tagColorPreviewBtn.setId(SPUIComponetIdProvider.TAG_COLOR_PREVIEW_ID);
getPreviewButtonColor(DEFAULT_COLOR); getPreviewButtonColor(DEFAULT_COLOR);
tagColorPreviewBtn.setStyleName(TAG_DYNAMIC_STYLE); this.tagColorPreviewBtn.setStyleName(TAG_DYNAMIC_STYLE);
selectors = new HashSet<ColorSelector>(); this.selectors = new HashSet<>();
selectedColor = new Color(44, 151, 32); this.selectedColor = new Color(44, 151, 32);
selPreview = new SpColorPickerPreview(selectedColor); this.selPreview = new SpColorPickerPreview(this.selectedColor);
colorSelect = new ColorPickerGradient("rgb-gradient", rgbConverter); this.colorSelect = new ColorPickerGradient("rgb-gradient", this.rgbConverter);
colorSelect.setColor(selectedColor); this.colorSelect.setColor(this.selectedColor);
colorSelect.setWidth("220px"); this.colorSelect.setWidth("220px");
redSlider = createRGBSlider("", "red"); this.redSlider = createRGBSlider("", "red");
greenSlider = createRGBSlider("", "green"); this.greenSlider = createRGBSlider("", "green");
blueSlider = createRGBSlider("", "blue"); this.blueSlider = createRGBSlider("", "blue");
setRgbSliderValues(selectedColor); setRgbSliderValues(this.selectedColor);
createOptionGroup(); createOptionGroup();
} }
private void buildLayout() { private void buildLayout() {
comboLayout = new VerticalLayout(); this.comboLayout = new VerticalLayout();
sliders = new VerticalLayout(); this.sliders = new VerticalLayout();
sliders.addComponents(redSlider, greenSlider, blueSlider); this.sliders.addComponents(this.redSlider, this.greenSlider, this.blueSlider);
selectors.add(colorSelect); this.selectors.add(this.colorSelect);
colorPickerLayout = new VerticalLayout(); this.colorPickerLayout = new VerticalLayout();
colorPickerLayout.setStyleName("rgb-vertical-layout"); this.colorPickerLayout.setStyleName("rgb-vertical-layout");
colorPickerLayout.addComponent(selPreview); this.colorPickerLayout.addComponent(this.selPreview);
colorPickerLayout.addComponent(colorSelect); this.colorPickerLayout.addComponent(this.colorSelect);
fieldLayout = new VerticalLayout(); this.fieldLayout = new VerticalLayout();
fieldLayout.setSpacing(false); this.fieldLayout.setSpacing(false);
fieldLayout.setMargin(false); this.fieldLayout.setMargin(false);
fieldLayout.setWidth("100%"); this.fieldLayout.setWidth("100%");
fieldLayout.setHeight(null); this.fieldLayout.setHeight(null);
fieldLayout.addComponent(optiongroup); this.fieldLayout.addComponent(this.optiongroup);
fieldLayout.addComponent(comboLayout); this.fieldLayout.addComponent(this.comboLayout);
fieldLayout.addComponent(madatoryLabel); this.fieldLayout.addComponent(this.madatoryLabel);
fieldLayout.addComponent(tagName); this.fieldLayout.addComponent(this.tagName);
fieldLayout.addComponent(tagDesc); this.fieldLayout.addComponent(this.tagDesc);
final HorizontalLayout colorLabelLayout = new HorizontalLayout(); final HorizontalLayout colorLabelLayout = new HorizontalLayout();
colorLabelLayout.addComponents(colorLabel, tagColorPreviewBtn); colorLabelLayout.addComponents(this.colorLabel, this.tagColorPreviewBtn);
fieldLayout.addComponent(colorLabelLayout); this.fieldLayout.addComponent(colorLabelLayout);
final HorizontalLayout buttonLayout = new HorizontalLayout(); final HorizontalLayout buttonLayout = new HorizontalLayout();
buttonLayout.addComponent(saveTag); buttonLayout.addComponent(this.saveTag);
buttonLayout.addComponent(discardTag); buttonLayout.addComponent(this.discardTag);
buttonLayout.setComponentAlignment(discardTag, Alignment.BOTTOM_RIGHT); buttonLayout.setComponentAlignment(this.discardTag, Alignment.BOTTOM_RIGHT);
buttonLayout.setComponentAlignment(saveTag, Alignment.BOTTOM_LEFT); buttonLayout.setComponentAlignment(this.saveTag, Alignment.BOTTOM_LEFT);
buttonLayout.addStyleName("window-style"); buttonLayout.addStyleName("window-style");
buttonLayout.setWidth("152px"); buttonLayout.setWidth("152px");
final VerticalLayout fieldButtonLayout = new VerticalLayout(); final VerticalLayout fieldButtonLayout = new VerticalLayout();
fieldButtonLayout.addComponent(fieldLayout); fieldButtonLayout.addComponent(this.fieldLayout);
fieldButtonLayout.addComponent(buttonLayout); fieldButtonLayout.addComponent(buttonLayout);
fieldButtonLayout.setComponentAlignment(buttonLayout, Alignment.BOTTOM_CENTER); fieldButtonLayout.setComponentAlignment(buttonLayout, Alignment.BOTTOM_CENTER);
mainLayout = new HorizontalLayout(); this.mainLayout = new HorizontalLayout();
mainLayout.addComponent(fieldButtonLayout); this.mainLayout.addComponent(fieldButtonLayout);
setCompositionRoot(mainLayout); setCompositionRoot(this.mainLayout);
} }
private void addListeners() { private void addListeners() {
saveTag.addClickListener(event -> save(event)); this.saveTag.addClickListener(event -> save(event));
discardTag.addClickListener(event -> discard(event)); this.discardTag.addClickListener(event -> discard(event));
colorSelect.addColorChangeListener(this); this.colorSelect.addColorChangeListener(this);
selPreview.addColorChangeListener(this); this.selPreview.addColorChangeListener(this);
tagColorPreviewBtn.addClickListener(event -> previewButtonClicked()); this.tagColorPreviewBtn.addClickListener(event -> previewButtonClicked());
optiongroup.addValueChangeListener(event -> optionValueChanged(event)); this.optiongroup.addValueChangeListener(event -> optionValueChanged(event));
tagNameComboBox.addValueChangeListener(event -> tagNameChosen(event)); this.tagNameComboBox.addValueChangeListener(event -> tagNameChosen(event));
slidersValueChangeListeners(); slidersValueChangeListeners();
} }
@@ -283,35 +278,40 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C
* on target tag if already selected. * on target tag if already selected.
*/ */
private void previewButtonClicked() { private void previewButtonClicked() {
if (!tagPreviewBtnClicked) { if (!this.tagPreviewBtnClicked) {
final String selectedOption = (String) optiongroup.getValue(); setColor();
if (null != selectedOption && selectedOption.equalsIgnoreCase(updateTagNw)) { this.selPreview.setColor(this.selectedColor);
if (null != tagNameComboBox.getValue()) { this.fieldLayout.addComponent(this.sliders);
this.mainLayout.addComponent(this.colorPickerLayout);
final TargetTag targetTagSelected = tagManagement this.mainLayout.setComponentAlignment(this.colorPickerLayout, Alignment.BOTTOM_CENTER);
.findTargetTag(tagNameComboBox.getValue().toString());
if (null != targetTagSelected) {
selectedColor = targetTagSelected.getColour() != null
? rgbToColorConverter(targetTagSelected.getColour())
: rgbToColorConverter(DEFAULT_COLOR);
} else {
final DistributionSetTag distTag = tagManagement
.findDistributionSetTag(tagNameComboBox.getValue().toString());
selectedColor = distTag.getColour() != null ? rgbToColorConverter(distTag.getColour())
: rgbToColorConverter(DEFAULT_COLOR);
}
} else {
selectedColor = rgbToColorConverter(DEFAULT_COLOR);
}
}
selPreview.setColor(selectedColor);
fieldLayout.addComponent(sliders);
mainLayout.addComponent(colorPickerLayout);
mainLayout.setComponentAlignment(colorPickerLayout, Alignment.BOTTOM_CENTER);
} }
tagPreviewBtnClicked = !tagPreviewBtnClicked; this.tagPreviewBtnClicked = !this.tagPreviewBtnClicked;
}
private void setColor() {
final String selectedOption = (String) this.optiongroup.getValue();
if (selectedOption == null || !selectedOption.equalsIgnoreCase(this.updateTagNw)) {
return;
}
if (this.tagNameComboBox.getValue() == null) {
this.selectedColor = rgbToColorConverter(DEFAULT_COLOR);
return;
}
final TargetTag targetTagSelected = this.tagManagement
.findTargetTag(this.tagNameComboBox.getValue().toString());
if (targetTagSelected == null) {
final DistributionSetTag distTag = this.tagManagement
.findDistributionSetTag(this.tagNameComboBox.getValue().toString());
this.selectedColor = distTag.getColour() != null ? rgbToColorConverter(distTag.getColour())
: rgbToColorConverter(DEFAULT_COLOR);
} else {
this.selectedColor = targetTagSelected.getColour() != null
? rgbToColorConverter(targetTagSelected.getColour()) : rgbToColorConverter(DEFAULT_COLOR);
}
} }
/** /**
@@ -322,24 +322,24 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C
* @return Color * @return Color
*/ */
protected Color rgbToColorConverter(final String value) { protected Color rgbToColorConverter(final String value) {
if (value.startsWith("rgb")) { if (!value.startsWith("rgb")) {
// RGB color format rgb/rgba(255,255,255,0.1) return null;
final String[] colors = value.substring(value.indexOf('(') + 1, value.length() - 1).split(","); }
final int red = Integer.parseInt(colors[0]); // RGB color format rgb/rgba(255,255,255,0.1)
final int green = Integer.parseInt(colors[1]); final String[] colors = value.substring(value.indexOf('(') + 1, value.length() - 1).split(",");
final int blue = Integer.parseInt(colors[2]); final int red = Integer.parseInt(colors[0]);
if (colors.length > 3) { final int green = Integer.parseInt(colors[1]);
final int alpha = (int) (Double.parseDouble(colors[3]) * 255d); final int blue = Integer.parseInt(colors[2]);
return new Color(red, green, blue, alpha); if (colors.length > 3) {
} else { final int alpha = (int) (Double.parseDouble(colors[3]) * 255d);
return new Color(red, green, blue); return new Color(red, green, blue, alpha);
} } else {
return new Color(red, green, blue);
} }
return null;
} }
private Label getMandatoryLabel() { private Label getMandatoryLabel() {
final Label label = new Label(i18n.get("label.mandatory.field")); final Label label = new Label(this.i18n.get("label.mandatory.field"));
label.setStyleName(SPUIStyleDefinitions.SP_TEXTFIELD_ERROR + " " + ValoTheme.LABEL_SMALL); label.setStyleName(SPUIStyleDefinitions.SP_TEXTFIELD_ERROR + " " + ValoTheme.LABEL_SMALL);
return label; return label;
} }
@@ -354,16 +354,16 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C
} }
private void resetTagNameField() { private void resetTagNameField() {
tagName.setEnabled(false); this.tagName.setEnabled(false);
tagName.clear(); this.tagName.clear();
tagDesc.clear(); this.tagDesc.clear();
restoreComponentStyles(); restoreComponentStyles();
fieldLayout.removeComponent(sliders); this.fieldLayout.removeComponent(this.sliders);
mainLayout.removeComponent(colorPickerLayout); this.mainLayout.removeComponent(this.colorPickerLayout);
selectedColor = new Color(44, 151, 32); this.selectedColor = new Color(44, 151, 32);
selPreview.setColor(selectedColor); this.selPreview.setColor(this.selectedColor);
tagPreviewBtnClicked = false; this.tagPreviewBtnClicked = false;
} }
@@ -375,30 +375,30 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C
*/ */
private void optionValueChanged(final ValueChangeEvent event) { private void optionValueChanged(final ValueChangeEvent event) {
if ("Update Tag".equals(event.getProperty().getValue())) { if ("Update Tag".equals(event.getProperty().getValue())) {
tagName.clear(); this.tagName.clear();
tagDesc.clear(); this.tagDesc.clear();
tagName.setEnabled(false); this.tagName.setEnabled(false);
populateTagNameCombo(); populateTagNameCombo();
// show target name combo // show target name combo
comboLayout.addComponent(comboLabel); this.comboLayout.addComponent(this.comboLabel);
comboLayout.addComponent(tagNameComboBox); this.comboLayout.addComponent(this.tagNameComboBox);
} else { } else {
tagName.setEnabled(true); this.tagName.setEnabled(true);
tagName.clear(); this.tagName.clear();
tagDesc.clear(); this.tagDesc.clear();
// hide target name combo // hide target name combo
comboLayout.removeComponent(comboLabel); this.comboLayout.removeComponent(this.comboLabel);
comboLayout.removeComponent(tagNameComboBox); this.comboLayout.removeComponent(this.tagNameComboBox);
} }
// close the color picker layout // close the color picker layout
tagPreviewBtnClicked = false; this.tagPreviewBtnClicked = false;
// reset the selected color - Set defualt color // reset the selected color - Set defualt color
restoreComponentStyles(); restoreComponentStyles();
getPreviewButtonColor(DEFAULT_COLOR); getPreviewButtonColor(DEFAULT_COLOR);
selPreview.setColor(rgbToColorConverter(DEFAULT_COLOR)); this.selPreview.setColor(rgbToColorConverter(DEFAULT_COLOR));
// remove the sliders and color picker layout // remove the sliders and color picker layout
fieldLayout.removeComponent(sliders); this.fieldLayout.removeComponent(this.sliders);
mainLayout.removeComponent(colorPickerLayout); this.mainLayout.removeComponent(this.colorPickerLayout);
} }
@@ -406,23 +406,23 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C
* reset the components. * reset the components.
*/ */
protected void reset() { protected void reset() {
tagName.setEnabled(true); this.tagName.setEnabled(true);
tagName.clear(); this.tagName.clear();
tagDesc.clear(); this.tagDesc.clear();
restoreComponentStyles(); restoreComponentStyles();
// hide target name combo // hide target name combo
comboLayout.removeComponent(comboLabel); this.comboLayout.removeComponent(this.comboLabel);
comboLayout.removeComponent(tagNameComboBox); this.comboLayout.removeComponent(this.tagNameComboBox);
fieldLayout.removeComponent(sliders); this.fieldLayout.removeComponent(this.sliders);
mainLayout.removeComponent(colorPickerLayout); this.mainLayout.removeComponent(this.colorPickerLayout);
optiongroup.select(createTagNw); this.optiongroup.select(this.createTagNw);
// Default green color // Default green color
selectedColor = new Color(44, 151, 32); this.selectedColor = new Color(44, 151, 32);
selPreview.setColor(selectedColor); this.selPreview.setColor(this.selectedColor);
tagPreviewBtnClicked = false; this.tagPreviewBtnClicked = false;
} }
/** /**
@@ -432,14 +432,15 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C
@Override @Override
public void colorChanged(final ColorChangeEvent event) { public void colorChanged(final ColorChangeEvent event) {
setColor(event.getColor()); setColor(event.getColor());
for (final ColorSelector select : selectors) { for (final ColorSelector select : this.selectors) {
if (!event.getSource().equals(select) && select.equals(this) && !select.getColor().equals(selectedColor)) { if (!event.getSource().equals(select) && select.equals(this)
select.setColor(selectedColor); && !select.getColor().equals(this.selectedColor)) {
select.setColor(this.selectedColor);
} }
} }
setRgbSliderValues(selectedColor); setRgbSliderValues(this.selectedColor);
getPreviewButtonColor(event.getColor().getCSS()); getPreviewButtonColor(event.getColor().getCSS());
createDynamicStyleForComponents(tagName, tagDesc, event.getColor().getCSS()); createDynamicStyleForComponents(this.tagName, this.tagDesc, event.getColor().getCSS());
} }
/** /**
@@ -465,11 +466,11 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C
private void setRgbSliderValues(final Color color) { private void setRgbSliderValues(final Color color) {
try { try {
final double redColorValue = color.getRed(); final double redColorValue = color.getRed();
redSlider.setValue(new Double(redColorValue)); this.redSlider.setValue(new Double(redColorValue));
final double blueColorValue = color.getBlue(); final double blueColorValue = color.getBlue();
blueSlider.setValue(new Double(blueColorValue)); this.blueSlider.setValue(new Double(blueColorValue));
final double greenColorValue = color.getGreen(); final double greenColorValue = color.getGreen();
greenSlider.setValue(new Double(greenColorValue)); this.greenSlider.setValue(new Double(greenColorValue));
} catch (final ValueOutOfBoundsException e) { } catch (final ValueOutOfBoundsException e) {
LOG.error("Unable to set RGB color value to " + color.getRed() + "," + color.getGreen() + "," LOG.error("Unable to set RGB color value to " + color.getRed() + "," + color.getGreen() + ","
+ color.getBlue(), e); + color.getBlue(), e);
@@ -496,10 +497,10 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C
* reset the tag name and tag description component border color. * reset the tag name and tag description component border color.
*/ */
private void restoreComponentStyles() { private void restoreComponentStyles() {
tagName.removeStyleName(TAG_NAME_DYNAMIC_STYLE); this.tagName.removeStyleName(TAG_NAME_DYNAMIC_STYLE);
tagDesc.removeStyleName(TAG_DESC_DYNAMIC_STYLE); this.tagDesc.removeStyleName(TAG_DESC_DYNAMIC_STYLE);
tagName.addStyleName(SPUIDefinitions.TAG_NAME); this.tagName.addStyleName(SPUIDefinitions.TAG_NAME);
tagDesc.addStyleName(SPUIDefinitions.TAG_DESC); this.tagDesc.addStyleName(SPUIDefinitions.TAG_DESC);
getPreviewButtonColor(DEFAULT_COLOR); getPreviewButtonColor(DEFAULT_COLOR);
} }
@@ -524,12 +525,12 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C
if (color == null) { if (color == null) {
return; return;
} }
selectedColor = color; this.selectedColor = color;
selPreview.setColor(selectedColor); this.selPreview.setColor(this.selectedColor);
final String colorPickedPreview = selPreview.getColor().getCSS(); final String colorPickedPreview = this.selPreview.getColor().getCSS();
if (tagName.isEnabled() && null != colorSelect) { if (this.tagName.isEnabled() && null != this.colorSelect) {
createDynamicStyleForComponents(tagName, tagDesc, colorPickedPreview); createDynamicStyleForComponents(this.tagName, this.tagDesc, colorPickedPreview);
colorSelect.setColor(selPreview.getColor()); this.colorSelect.setColor(this.selPreview.getColor());
} }
} }
@@ -537,33 +538,36 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C
* Value change listeners implementations of sliders. * Value change listeners implementations of sliders.
*/ */
private void slidersValueChangeListeners() { private void slidersValueChangeListeners() {
redSlider.addValueChangeListener(new ValueChangeListener() { this.redSlider.addValueChangeListener(new ValueChangeListener() {
private static final long serialVersionUID = -8336732888800920839L; private static final long serialVersionUID = -8336732888800920839L;
@Override @Override
public void valueChange(final ValueChangeEvent event) { public void valueChange(final ValueChangeEvent event) {
final double red = (Double) event.getProperty().getValue(); final double red = (Double) event.getProperty().getValue();
final Color newColor = new Color((int) red, selectedColor.getGreen(), selectedColor.getBlue()); final Color newColor = new Color((int) red, CreateUpdateTagLayout.this.selectedColor.getGreen(),
CreateUpdateTagLayout.this.selectedColor.getBlue());
setColorToComponents(newColor); setColorToComponents(newColor);
} }
}); });
greenSlider.addValueChangeListener(new ValueChangeListener() { this.greenSlider.addValueChangeListener(new ValueChangeListener() {
private static final long serialVersionUID = 1236358037766775663L; private static final long serialVersionUID = 1236358037766775663L;
@Override @Override
public void valueChange(final ValueChangeEvent event) { public void valueChange(final ValueChangeEvent event) {
final double green = (Double) event.getProperty().getValue(); final double green = (Double) event.getProperty().getValue();
final Color newColor = new Color(selectedColor.getRed(), (int) green, selectedColor.getBlue()); final Color newColor = new Color(CreateUpdateTagLayout.this.selectedColor.getRed(), (int) green,
CreateUpdateTagLayout.this.selectedColor.getBlue());
setColorToComponents(newColor); setColorToComponents(newColor);
} }
}); });
blueSlider.addValueChangeListener(new ValueChangeListener() { this.blueSlider.addValueChangeListener(new ValueChangeListener() {
private static final long serialVersionUID = 8466370763686043947L; private static final long serialVersionUID = 8466370763686043947L;
@Override @Override
public void valueChange(final ValueChangeEvent event) { public void valueChange(final ValueChangeEvent event) {
final double blue = (Double) event.getProperty().getValue(); final double blue = (Double) event.getProperty().getValue();
final Color newColor = new Color(selectedColor.getRed(), selectedColor.getGreen(), (int) blue); final Color newColor = new Color(CreateUpdateTagLayout.this.selectedColor.getRed(),
CreateUpdateTagLayout.this.selectedColor.getGreen(), (int) blue);
setColorToComponents(newColor); setColorToComponents(newColor);
} }
}); });
@@ -571,9 +575,9 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C
private void setColorToComponents(final Color newColor) { private void setColorToComponents(final Color newColor) {
setColor(newColor); setColor(newColor);
colorSelect.setColor(newColor); this.colorSelect.setColor(newColor);
getPreviewButtonColor(newColor.getCSS()); getPreviewButtonColor(newColor.getCSS());
createDynamicStyleForComponents(tagName, tagDesc, newColor.getCSS()); createDynamicStyleForComponents(this.tagName, this.tagDesc, newColor.getCSS());
} }
@Override @Override

View File

@@ -9,7 +9,6 @@
package org.eclipse.hawkbit.ui.management.targettag; package org.eclipse.hawkbit.ui.management.targettag;
import java.io.Serializable; import java.io.Serializable;
import java.util.Optional;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
@@ -54,8 +53,8 @@ public class CustomTargetTagFilterButtonClick extends AbstractFilterSingleButton
*/ */
@Override @Override
protected void filterUnClicked(final Button clickedButton) { protected void filterUnClicked(final Button clickedButton) {
managementUIState.getTargetTableFilters().setTargetFilterQuery(null); this.managementUIState.getTargetTableFilters().setTargetFilterQuery(null);
eventBus.publish(this, TargetFilterEvent.REMOVE_FILTER_BY_TARGET_FILTER_QUERY); this.eventBus.publish(this, TargetFilterEvent.REMOVE_FILTER_BY_TARGET_FILTER_QUERY);
} }
/* /*
@@ -66,10 +65,10 @@ public class CustomTargetTagFilterButtonClick extends AbstractFilterSingleButton
*/ */
@Override @Override
protected void filterClicked(final Button clickedButton) { protected void filterClicked(final Button clickedButton) {
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement final TargetFilterQuery targetFilterQuery = this.targetFilterQueryManagement
.findTargetFilterQueryById((Long) clickedButton.getData()); .findTargetFilterQueryById((Long) clickedButton.getData());
managementUIState.getTargetTableFilters().setTargetFilterQuery(targetFilterQuery); this.managementUIState.getTargetTableFilters().setTargetFilterQuery(targetFilterQuery);
eventBus.publish(this, TargetFilterEvent.FILTER_BY_TARGET_FILTER_QUERY); this.eventBus.publish(this, TargetFilterEvent.FILTER_BY_TARGET_FILTER_QUERY);
} }
protected void processButtonClick(final ClickEvent event) { protected void processButtonClick(final ClickEvent event) {
@@ -77,12 +76,12 @@ public class CustomTargetTagFilterButtonClick extends AbstractFilterSingleButton
} }
protected void clearAppliedTargetFilterQuery() { protected void clearAppliedTargetFilterQuery() {
if (getAlreadyClickedButton().isPresent()) { if (getAlreadyClickedButton() != null) {
getAlreadyClickedButton().get().removeStyleName(SPUIStyleDefinitions.SP_FILTER_BTN_CLICKED_STYLE); getAlreadyClickedButton().removeStyleName(SPUIStyleDefinitions.SP_FILTER_BTN_CLICKED_STYLE);
setAlreadyClickedButton(Optional.empty()); setAlreadyClickedButton(null);
} }
managementUIState.getTargetTableFilters().setTargetFilterQuery(null); this.managementUIState.getTargetTableFilters().setTargetFilterQuery(null);
eventBus.publish(this, TargetFilterEvent.REMOVE_FILTER_BY_TARGET_FILTER_QUERY); this.eventBus.publish(this, TargetFilterEvent.REMOVE_FILTER_BY_TARGET_FILTER_QUERY);
} }
protected void setDefaultButtonClicked(final Button button) { protected void setDefaultButtonClicked(final Button button) {

View File

@@ -8,6 +8,8 @@
*/ */
package org.eclipse.hawkbit.ui.tenantconfiguration.authentication; package org.eclipse.hawkbit.ui.tenantconfiguration.authentication;
import java.io.Serializable;
import com.vaadin.ui.Component; import com.vaadin.ui.Component;
/** /**
@@ -62,7 +64,8 @@ public interface TenantConfigurationItem extends Component {
* *
* *
*/ */
interface TenantConfigurationChangeListener { @FunctionalInterface
interface TenantConfigurationChangeListener extends Serializable {
/** /**
* called to notify about configuration has been changed. * called to notify about configuration has been changed.
*/ */

View File

@@ -263,14 +263,13 @@ public final class HawkbitCommonUtil {
public static String concatStrings(final String delimiter, final String... texts) { public static String concatStrings(final String delimiter, final String... texts) {
final String delim = delimiter == null ? SP_STRING_EMPTY : delimiter; final String delim = delimiter == null ? SP_STRING_EMPTY : delimiter;
final StringBuilder conCatStrBldr = new StringBuilder(); final StringBuilder conCatStrBldr = new StringBuilder();
String conCatedStr = null;
if (null != texts) { if (null != texts) {
for (final String text : texts) { for (final String text : texts) {
conCatStrBldr.append(delim); conCatStrBldr.append(delim);
conCatStrBldr.append(text); conCatStrBldr.append(text);
} }
} }
conCatedStr = conCatStrBldr.toString(); final String conCatedStr = conCatStrBldr.toString();
return delim.length() > 0 && conCatedStr.startsWith(delim) ? conCatedStr.substring(1) : conCatedStr; return delim.length() > 0 && conCatedStr.startsWith(delim) ? conCatedStr.substring(1) : conCatedStr;
} }
@@ -343,31 +342,6 @@ public final class HawkbitCommonUtil {
return labelId.toString(); return labelId.toString();
} }
/**
* Check if two objects are same or not.
*
* @param obj1
* as reference
* @param obj2
* as reference
* @return true if both obj1 & obj2 are null (or) if the .equals() method
* return true. false if only either one of obj1 & obj2 is null (or)
* if .equals() method return false.
*/
public static boolean bothSame(final Object obj1, final Object obj2) {
boolean result = false;
if (obj1 == null && obj2 == null) {
result = true;
} else if (obj1 == null && obj2 != null) {
result = false;
} else if (obj1 != null && obj2 == null) {
result = false;
} else {
result = obj2.equals(obj1);
}
return result;
}
/** /**
* Get label with software module name and description. * Get label with software module name and description.
* *
@@ -982,12 +956,10 @@ public final class HawkbitCommonUtil {
* @return instance of {@link LazyQueryContainer}. * @return instance of {@link LazyQueryContainer}.
*/ */
public static LazyQueryContainer createLazyQueryContainer( public static LazyQueryContainer createLazyQueryContainer(
final BeanQueryFactory<? extends AbstractBeanQuery> queryFactory) { final BeanQueryFactory<? extends AbstractBeanQuery<?>> queryFactory) {
final Map<String, Object> queryConfig = new HashMap<String, Object>(); final Map<String, Object> queryConfig = new HashMap<>();
queryFactory.setQueryConfiguration(queryConfig); queryFactory.setQueryConfiguration(queryConfig);
final LazyQueryContainer typeContainer = new LazyQueryContainer( return new LazyQueryContainer(new LazyQueryDefinition(true, 20, SPUILabelDefinitions.VAR_NAME), queryFactory);
new LazyQueryDefinition(true, 20, SPUILabelDefinitions.VAR_NAME), queryFactory);
return typeContainer;
} }
/** /**
@@ -998,12 +970,10 @@ public final class HawkbitCommonUtil {
* @return LazyQueryContainer * @return LazyQueryContainer
*/ */
public static LazyQueryContainer createDSLazyQueryContainer( public static LazyQueryContainer createDSLazyQueryContainer(
final BeanQueryFactory<? extends AbstractBeanQuery> queryFactory) { final BeanQueryFactory<? extends AbstractBeanQuery<?>> queryFactory) {
final Map<String, Object> queryConfig = new HashMap<String, Object>(); final Map<String, Object> queryConfig = new HashMap<>();
queryFactory.setQueryConfiguration(queryConfig); queryFactory.setQueryConfiguration(queryConfig);
final LazyQueryContainer typeContainer = new LazyQueryContainer(new LazyQueryDefinition(true, 20, "tagIdName"), return new LazyQueryContainer(new LazyQueryDefinition(true, 20, "tagIdName"), queryFactory);
queryFactory);
return typeContainer;
} }
/** /**
@@ -1037,7 +1007,7 @@ public final class HawkbitCommonUtil {
*/ */
public static List<TableColumn> getTableVisibleColumns(final Boolean isMaximized, final Boolean isShowPinColumn, public static List<TableColumn> getTableVisibleColumns(final Boolean isMaximized, final Boolean isShowPinColumn,
final I18N i18n) { final I18N i18n) {
final List<TableColumn> columnList = new ArrayList<TableColumn>(); final List<TableColumn> columnList = new ArrayList<>();
if (isMaximized) { if (isMaximized) {
columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.get(HEADER_NAME), 0.2f)); columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.get(HEADER_NAME), 0.2f));
columnList.add(new TableColumn(SPUILabelDefinitions.VAR_VERSION, i18n.get(HEADER_VERSION), 0.1f)); columnList.add(new TableColumn(SPUILabelDefinitions.VAR_VERSION, i18n.get(HEADER_VERSION), 0.1f));