Minor code improvements

Signed-off-by: Dominic Schabel dominic.schabel@bosch-si.com
This commit is contained in:
Dominic Schabel
2016-08-15 11:30:21 +02:00
parent 7f156f05a4
commit 3accac9ade
50 changed files with 639 additions and 696 deletions

View File

@@ -8,9 +8,12 @@
*/ */
package org.eclipse.hawkbit.simulator; package org.eclipse.hawkbit.simulator;
import static java.util.concurrent.Executors.newScheduledThreadPool;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream;
import java.security.DigestOutputStream; import java.security.DigestOutputStream;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.KeyStoreException; import java.security.KeyStoreException;
@@ -20,7 +23,6 @@ import java.security.SecureRandom;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -56,9 +58,10 @@ import com.google.common.io.ByteStreams;
*/ */
@Service @Service
public class DeviceSimulatorUpdater { public class DeviceSimulatorUpdater {
private static final Logger LOGGER = LoggerFactory.getLogger(DeviceSimulatorUpdater.class); private static final Logger LOGGER = LoggerFactory.getLogger(DeviceSimulatorUpdater.class);
private static final ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(8); private static final ScheduledExecutorService threadPool = newScheduledThreadPool(8);
@Autowired @Autowired
private SpSenderService spSenderService; private SpSenderService spSenderService;
@@ -118,14 +121,9 @@ public class DeviceSimulatorUpdater {
} }
private static final class DeviceSimulatorUpdateThread implements Runnable { private static final class DeviceSimulatorUpdateThread implements Runnable {
/**
*
*/
private static final String BUT_GOT_LOG_MESSAGE = " but got: "; private static final String BUT_GOT_LOG_MESSAGE = " but got: ";
/**
*
*/
private static final String DOWNLOAD_LOG_MESSAGE = "Download "; private static final String DOWNLOAD_LOG_MESSAGE = "Download ";
private static final int MINIMUM_TOKENLENGTH_FOR_HINT = 6; private static final int MINIMUM_TOKENLENGTH_FOR_HINT = 6;
@@ -279,13 +277,17 @@ public class DeviceSimulatorUpdater {
private static long getOverallRead(final CloseableHttpResponse response, final MessageDigest md) private static long getOverallRead(final CloseableHttpResponse response, final MessageDigest md)
throws IOException { throws IOException {
long overallread; long overallread;
try (final BufferedOutputStream bdos = new BufferedOutputStream(
new DigestOutputStream(ByteStreams.nullOutputStream(), md))) { try (final OutputStream os = ByteStreams.nullOutputStream();
final BufferedOutputStream bos = new BufferedOutputStream(new DigestOutputStream(os, md))) {
try (BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent())) { try (BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent())) {
overallread = ByteStreams.copy(bis, bdos); overallread = ByteStreams.copy(bis, bos);
} }
} }
return overallread; return overallread;
} }

View File

@@ -16,7 +16,6 @@ import java.util.Map;
* An interface for declaring the name of the field described in the database * An interface for declaring the name of the field described in the database
* which is used as string representation of the field, e.g. for sorting the * which is used as string representation of the field, e.g. for sorting the
* fields over REST. * fields over REST.
*
*/ */
public interface FieldNameProvider { public interface FieldNameProvider {
/** /**
@@ -38,7 +37,22 @@ public interface FieldNameProvider {
* @return <true> contains <false> contains not * @return <true> contains <false> contains not
*/ */
default boolean containsSubEntityAttribute(final String propertyField) { default boolean containsSubEntityAttribute(final String propertyField) {
return FieldNameProvider.containsSubEntityAttribute(propertyField, getSubEntityAttributes());
final List<String> subEntityAttributes = getSubEntityAttributes();
if (subEntityAttributes.contains(propertyField)) {
return true;
}
for (final String attribute : subEntityAttributes) {
final String[] graph = attribute.split("\\" + SUB_ATTRIBUTE_SEPERATOR);
for (final String subAttribute : graph) {
if (subAttribute.equalsIgnoreCase(propertyField)) {
return true;
}
}
}
return false;
} }
/** /**
@@ -75,31 +89,4 @@ public interface FieldNameProvider {
default boolean isMap() { default boolean isMap() {
return getKeyFieldName() != null; return getKeyFieldName() != null;
} }
/**
* Check if a sub attribute exists.
*
* @param propertyField
* the sub property field.
* @param subEntityAttribues
* the list of available properties
* @return <true> property exists <false> not exists
*/
static boolean containsSubEntityAttribute(final String propertyField, final List<String> subEntityAttribues) {
if (subEntityAttribues.contains(propertyField)) {
return true;
}
for (final String attribute : subEntityAttribues) {
final String[] graph = attribute.split("\\" + SUB_ATTRIBUTE_SEPERATOR);
for (final String subAttribute : graph) {
if (subAttribute.equalsIgnoreCase(propertyField)) {
return true;
}
}
}
return false;
}
} }

View File

@@ -8,8 +8,9 @@ import java.util.Map;
/** /**
* {@link Map} with attributes of SP Target. * {@link Map} with attributes of SP Target.
*
*/ */
public class MgmtTargetAttributes extends HashMap<String, String> { public class MgmtTargetAttributes extends HashMap<String, String> {
private static final long serialVersionUID = 1L;
} }

View File

@@ -20,7 +20,7 @@ import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity;
public class AbstractPropertyChangeEvent<E extends TenantAwareBaseEntity> extends AbstractBaseEntityEvent<E> { public class AbstractPropertyChangeEvent<E extends TenantAwareBaseEntity> extends AbstractBaseEntityEvent<E> {
private static final long serialVersionUID = -3671601415138242311L; private static final long serialVersionUID = -3671601415138242311L;
private final transient Map<String, Values> changeSet; private final transient Map<String, PropertyChange> changeSet;
/** /**
* Initialize base entity and property changed with old and new value. * Initialize base entity and property changed with old and new value.
@@ -31,7 +31,7 @@ public class AbstractPropertyChangeEvent<E extends TenantAwareBaseEntity> extend
* details of properties changed and old value and new value of * details of properties changed and old value and new value of
* the changed properties * the changed properties
*/ */
public AbstractPropertyChangeEvent(final E baseEntity, final Map<String, Values> changeSetValues) { public AbstractPropertyChangeEvent(final E baseEntity, final Map<String, PropertyChange> changeSetValues) {
super(baseEntity); super(baseEntity);
this.changeSet = changeSetValues; this.changeSet = changeSetValues;
} }
@@ -39,15 +39,15 @@ public class AbstractPropertyChangeEvent<E extends TenantAwareBaseEntity> extend
/** /**
* @return the changeSet * @return the changeSet
*/ */
public Map<String, Values> getChangeSet() { public Map<String, PropertyChange> getChangeSet() {
return changeSet; return changeSet;
} }
/** /**
* Carries old value and new value of a property . * Carries old value and new value of a property .
*
*/ */
public class Values { public static class PropertyChange {
private final Object oldValue; private final Object oldValue;
private final Object newValue; private final Object newValue;
@@ -59,7 +59,7 @@ public class AbstractPropertyChangeEvent<E extends TenantAwareBaseEntity> extend
* @param newValue * @param newValue
* new value after change * new value after change
*/ */
public Values(final Object oldValue, final Object newValue) { public PropertyChange(final Object oldValue, final Object newValue) {
super(); super();
this.oldValue = oldValue; this.oldValue = oldValue;
this.newValue = newValue; this.newValue = newValue;
@@ -78,6 +78,5 @@ public class AbstractPropertyChangeEvent<E extends TenantAwareBaseEntity> extend
public Object getNewValue() { public Object getNewValue() {
return newValue; return newValue;
} }
} }
} }

View File

@@ -22,8 +22,7 @@ public class ActionPropertyChangeEvent extends AbstractPropertyChangeEvent<Actio
* @param action * @param action
* @param changeSetValues * @param changeSetValues
*/ */
public ActionPropertyChangeEvent(final Action action, public ActionPropertyChangeEvent(final Action action, final Map<String, PropertyChange> changeSetValues) {
final Map<String, AbstractPropertyChangeEvent<Action>.Values> changeSetValues) {
super(action, changeSetValues); super(action, changeSetValues);
} }

View File

@@ -25,7 +25,7 @@ public class RolloutGroupPropertyChangeEvent extends AbstractPropertyChangeEvent
* @param changeSetValues * @param changeSetValues
*/ */
public RolloutGroupPropertyChangeEvent(final RolloutGroup rolloutGroup, public RolloutGroupPropertyChangeEvent(final RolloutGroup rolloutGroup,
final Map<String, AbstractPropertyChangeEvent<RolloutGroup>.Values> changeSetValues) { final Map<String, PropertyChange> changeSetValues) {
super(rolloutGroup, changeSetValues); super(rolloutGroup, changeSetValues);
} }

View File

@@ -23,8 +23,7 @@ public class RolloutPropertyChangeEvent extends AbstractPropertyChangeEvent<Roll
* @param rollout * @param rollout
* @param changeSetValues * @param changeSetValues
*/ */
public RolloutPropertyChangeEvent(final Rollout rollout, public RolloutPropertyChangeEvent(final Rollout rollout, final Map<String, PropertyChange> changeSetValues) {
final Map<String, AbstractPropertyChangeEvent<Rollout>.Values> changeSetValues) {
super(rollout, changeSetValues); super(rollout, changeSetValues);
} }

View File

@@ -12,16 +12,9 @@ import java.io.Serializable;
/** /**
* An abstract report series. * An abstract report series.
*
*
*
*
*/ */
public class AbstractReportSeries implements Serializable { public class AbstractReportSeries implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private final String name; private final String name;

View File

@@ -14,13 +14,11 @@ import java.util.List;
/** /**
* A simple list report series which just contains a list of values of a report. * A simple list report series which just contains a list of values of a report.
*
*
*
*
*/ */
public class ListReportSeries extends AbstractReportSeries { public class ListReportSeries extends AbstractReportSeries {
private static final long serialVersionUID = 1L;
private final List<Number> data = new ArrayList<>(); private final List<Number> data = new ArrayList<>();
/** /**
@@ -50,8 +48,8 @@ public class ListReportSeries extends AbstractReportSeries {
* @param values * @param values
*/ */
private void setData(final Number... values) { private void setData(final Number... values) {
this.data.clear(); data.clear();
Collections.addAll(this.data, values); Collections.addAll(data, values);
} }
/** /**

View File

@@ -82,7 +82,6 @@ import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice; import org.springframework.data.domain.Slice;
import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
@@ -599,11 +598,16 @@ public class JpaDeploymentManagement implements DeploymentManagement {
@Override @Override
public Page<Action> findActionsByTarget(final String rsqlParam, final Target target, final Pageable pageable) { public Page<Action> findActionsByTarget(final String rsqlParam, final Target target, final Pageable pageable) {
final Specification<JpaAction> specification = RSQLUtility.parse(rsqlParam, ActionFields.class);
return convertAcPage(actionRepository.findAll((Specification<JpaAction>) (root, query, cb) -> cb final Specification<JpaAction> byTargetSpec = createSpecificationFor(target, rsqlParam);
.and(specification.toPredicate(root, query, cb), cb.equal(root.get(JpaAction_.target), target)), final Page<JpaAction> actions = actionRepository.findAll(byTargetSpec, pageable);
pageable), pageable); return convertAcPage(actions, pageable);
}
private Specification<JpaAction> createSpecificationFor(final Target target, final String rsqlParam) {
final Specification<JpaAction> spec = RSQLUtility.parse(rsqlParam, ActionFields.class);
return (root, query, cb) -> cb.and(spec.toPredicate(root, query, cb),
cb.equal(root.get(JpaAction_.target), target));
} }
private static Page<Action> convertAcPage(final Page<JpaAction> findAll, final Pageable pageable) { private static Page<Action> convertAcPage(final Page<JpaAction> findAll, final Pageable pageable) {
@@ -642,10 +646,7 @@ public class JpaDeploymentManagement implements DeploymentManagement {
@Override @Override
public Long countActionsByTarget(final String rsqlParam, final Target target) { public Long countActionsByTarget(final String rsqlParam, final Target target) {
final Specification<JpaAction> spec = RSQLUtility.parse(rsqlParam, ActionFields.class); return actionRepository.count(createSpecificationFor(target, rsqlParam));
return actionRepository.count((root, query, cb) -> cb.and(spec.toPredicate(root, query, cb),
cb.equal(root.get(JpaAction_.target), target)));
} }
@Override @Override

View File

@@ -599,7 +599,7 @@ public class JpaRolloutManagement implements RolloutManagement {
/** /**
* Get count of targets in different status in rollout. * Get count of targets in different status in rollout.
* *
* @param page * @param pageable
* the page request to sort and limit the result * the page request to sort and limit the result
* @return a list of rollouts with details of targets count for different * @return a list of rollouts with details of targets count for different
* statuses * statuses

View File

@@ -26,7 +26,6 @@ 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.domain.Specifications;
import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert; import org.springframework.util.Assert;

View File

@@ -46,6 +46,7 @@ import org.springframework.transaction.TransactionSystemException;
*/ */
@Aspect @Aspect
public class ExceptionMappingAspectHandler implements Ordered { public class ExceptionMappingAspectHandler implements Ordered {
private static final Logger LOG = LoggerFactory.getLogger(ExceptionMappingAspectHandler.class); private static final Logger LOG = LoggerFactory.getLogger(ExceptionMappingAspectHandler.class);
private static final Map<String, String> EXCEPTION_MAPPING = new HashMap<>(); private static final Map<String, String> EXCEPTION_MAPPING = new HashMap<>();
@@ -63,6 +64,7 @@ public class ExceptionMappingAspectHandler implements Ordered {
private final SQLStateSQLExceptionTranslator sqlStateExceptionTranslator = new SQLStateSQLExceptionTranslator(); private final SQLStateSQLExceptionTranslator sqlStateExceptionTranslator = new SQLStateSQLExceptionTranslator();
static { static {
MAPPED_EXCEPTION_ORDER.add(DuplicateKeyException.class); MAPPED_EXCEPTION_ORDER.add(DuplicateKeyException.class);
MAPPED_EXCEPTION_ORDER.add(DataIntegrityViolationException.class); MAPPED_EXCEPTION_ORDER.add(DataIntegrityViolationException.class);
MAPPED_EXCEPTION_ORDER.add(ConcurrencyFailureException.class); MAPPED_EXCEPTION_ORDER.add(ConcurrencyFailureException.class);
@@ -90,9 +92,11 @@ public class ExceptionMappingAspectHandler implements Ordered {
+ " || execution( * org.eclipse.hawkbit.controller.*.*(..)) " + " || execution( * org.eclipse.hawkbit.controller.*.*(..)) "
+ " || execution( * org.eclipse.hawkbit.rest.resource.*.*(..)) " + " || execution( * org.eclipse.hawkbit.rest.resource.*.*(..)) "
+ " || execution( * org.eclipse.hawkbit.service.*.*(..)) )", throwing = "ex") + " || execution( * org.eclipse.hawkbit.service.*.*(..)) )", throwing = "ex")
// Exception squid:S00112 - Is aspectJ proxy // Exception for squid:S00112, squid:S1162
@SuppressWarnings({ "squid:S00112" }) // It is a AspectJ proxy which deals with exceptions.
@SuppressWarnings({ "squid:S00112", "squid:S1162" })
public void catchAndWrapJpaExceptionsService(final Exception ex) throws Throwable { public void catchAndWrapJpaExceptionsService(final Exception ex) throws Throwable {
LOG.trace("exception occured", ex); LOG.trace("exception occured", ex);
Exception translatedAccessException = translateEclipseLinkExceptionIfPossible(ex); Exception translatedAccessException = translateEclipseLinkExceptionIfPossible(ex);
@@ -122,6 +126,7 @@ public class ExceptionMappingAspectHandler implements Ordered {
break; break;
} }
} }
LOG.trace("mapped exception {} to {}", translatedAccessException.getClass(), mappingException.getClass()); LOG.trace("mapped exception {} to {}", translatedAccessException.getClass(), mappingException.getClass());
throw mappingException; throw mappingException;
} }

View File

@@ -11,7 +11,7 @@ package org.eclipse.hawkbit.repository.jpa.model;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.eclipse.hawkbit.repository.eventbus.event.AbstractPropertyChangeEvent; import org.eclipse.hawkbit.repository.eventbus.event.AbstractPropertyChangeEvent.PropertyChange;
import org.eclipse.hawkbit.repository.eventbus.event.ActionCreatedEvent; import org.eclipse.hawkbit.repository.eventbus.event.ActionCreatedEvent;
import org.eclipse.hawkbit.repository.eventbus.event.ActionPropertyChangeEvent; import org.eclipse.hawkbit.repository.eventbus.event.ActionPropertyChangeEvent;
import org.eclipse.hawkbit.repository.eventbus.event.RolloutGroupPropertyChangeEvent; import org.eclipse.hawkbit.repository.eventbus.event.RolloutGroupPropertyChangeEvent;
@@ -33,7 +33,6 @@ import com.google.common.eventbus.EventBus;
/** /**
* Listens to change in property values of an entity. * Listens to change in property values of an entity.
*
*/ */
public class EntityPropertyChangeListener extends DescriptorEventAdapter { public class EntityPropertyChangeListener extends DescriptorEventAdapter {
@@ -53,27 +52,23 @@ public class EntityPropertyChangeListener extends DescriptorEventAdapter {
@Override @Override
public void postUpdate(final DescriptorEvent event) { public void postUpdate(final DescriptorEvent event) {
if (event.getObject().getClass().equals(JpaAction.class)) { if (event.getObject().getClass().equals(JpaAction.class)) {
getAfterTransactionCommmitExecutor().afterCommit(() -> getEventBus().post( getAfterTransactionCommmitExecutor().afterCommit(() -> getEventBus()
new ActionPropertyChangeEvent((Action) event.getObject(), getChangeSet(Action.class, event)))); .post(new ActionPropertyChangeEvent((Action) event.getObject(), getChangeSet(event))));
} else if (event.getObject().getClass().equals(JpaRollout.class)) { } else if (event.getObject().getClass().equals(JpaRollout.class)) {
getAfterTransactionCommmitExecutor().afterCommit(() -> getEventBus().post( getAfterTransactionCommmitExecutor().afterCommit(() -> getEventBus()
new RolloutPropertyChangeEvent((Rollout) event.getObject(), getChangeSet(Rollout.class, event)))); .post(new RolloutPropertyChangeEvent((Rollout) event.getObject(), getChangeSet(event))));
} else if (event.getObject().getClass().equals(JpaRolloutGroup.class)) { } else if (event.getObject().getClass().equals(JpaRolloutGroup.class)) {
getAfterTransactionCommmitExecutor().afterCommit( getAfterTransactionCommmitExecutor().afterCommit(() -> getEventBus()
() -> getEventBus().post(new RolloutGroupPropertyChangeEvent((RolloutGroup) event.getObject(), .post(new RolloutGroupPropertyChangeEvent((RolloutGroup) event.getObject(), getChangeSet(event))));
getChangeSet(RolloutGroup.class, event))));
} }
} }
private <T extends TenantAwareBaseEntity> Map<String, AbstractPropertyChangeEvent<T>.Values> getChangeSet( private <T extends TenantAwareBaseEntity> Map<String, PropertyChange> getChangeSet(final DescriptorEvent event) {
final Class<T> clazz, final DescriptorEvent event) {
final T rolloutGroup = clazz.cast(event.getObject());
final ObjectChangeSet changeSet = ((UpdateObjectQuery) event.getQuery()).getObjectChangeSet(); final ObjectChangeSet changeSet = ((UpdateObjectQuery) event.getQuery()).getObjectChangeSet();
return changeSet.getChanges().stream().filter(record -> record instanceof DirectToFieldChangeRecord) return changeSet.getChanges().stream().filter(record -> record instanceof DirectToFieldChangeRecord)
.map(record -> (DirectToFieldChangeRecord) record) .map(record -> (DirectToFieldChangeRecord) record)
.collect(Collectors.toMap(record -> record.getAttribute(), .collect(Collectors.toMap(record -> record.getAttribute(),
record -> new AbstractPropertyChangeEvent<T>(rolloutGroup, null).new Values( record -> new PropertyChange(record.getOldValue(), record.getNewValue())));
record.getOldValue(), record.getNewValue())));
} }
private AfterTransactionCommitExecutor getAfterTransactionCommmitExecutor() { private AfterTransactionCommitExecutor getAfterTransactionCommmitExecutor() {

View File

@@ -98,8 +98,8 @@ public class JpaActionStatus extends AbstractJpaTenantAwareBaseEntity implements
* the status for this action status * the status for this action status
* @param occurredAt * @param occurredAt
* the occurred timestamp * the occurred timestamp
* @param messages * @param message
* the messages which should be added to this action status * the message which should be added to this action status
*/ */
public JpaActionStatus(final JpaAction action, final Status status, final Long occurredAt, final String message) { public JpaActionStatus(final JpaAction action, final Status status, final Long occurredAt, final String message) {
this.action = action; this.action = action;

View File

@@ -65,6 +65,7 @@ import org.springframework.data.domain.Persistable;
// sub entities // sub entities
@SuppressWarnings("squid:S2160") @SuppressWarnings("squid:S2160")
public class JpaTarget extends AbstractJpaNamedEntity implements Persistable<Long>, Target { public class JpaTarget extends AbstractJpaNamedEntity implements Persistable<Long>, Target {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@Column(name = "controller_id", length = 64) @Column(name = "controller_id", length = 64)
@@ -180,7 +181,7 @@ public class JpaTarget extends AbstractJpaNamedEntity implements Persistable<Lon
} }
/** /**
* @param isNew * @param entityNew
* the isNew to set * the isNew to set
*/ */
public void setNew(final boolean entityNew) { public void setNew(final boolean entityNew) {
@@ -222,6 +223,7 @@ public class JpaTarget extends AbstractJpaNamedEntity implements Persistable<Lon
* @param securityToken * @param securityToken
* the securityToken to set * the securityToken to set
*/ */
@Override
public void setSecurityToken(final String securityToken) { public void setSecurityToken(final String securityToken) {
this.securityToken = securityToken; this.securityToken = securityToken;
} }

View File

@@ -117,7 +117,7 @@ public class JpaTargetInfo implements Persistable<Long>, TargetInfo {
private boolean requestControllerAttributes = true; private boolean requestControllerAttributes = true;
/** /**
* Constructor for {@link TargetStatus}. * Constructor for {@link JpaTargetInfo}.
* *
* @param target * @param target
* related to this status. * related to this status.
@@ -144,7 +144,7 @@ public class JpaTargetInfo implements Persistable<Long>, TargetInfo {
} }
/** /**
* @param isNew * @param entityNew
* the isNew to set * the isNew to set
*/ */
public void setNew(final boolean entityNew) { public void setNew(final boolean entityNew) {

View File

@@ -8,6 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository.jpa.rsql; package org.eclipse.hawkbit.repository.jpa.rsql;
import static org.eclipse.hawkbit.repository.FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
@@ -15,7 +17,6 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
@@ -89,8 +90,6 @@ public final class RSQLUtility {
* @param fieldNameProvider * @param fieldNameProvider
* the enum class type which implements the * the enum class type which implements the
* {@link FieldNameProvider} * {@link FieldNameProvider}
* @param entityManager
* {@link EntityManager}
* @return an specification which can be used with JPA * @return an specification which can be used with JPA
* @throws RSQLParameterUnsupportedFieldException * @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the * if a field in the RSQL string is used but not provided by the
@@ -205,7 +204,7 @@ public final class RSQLUtility {
} }
private String getAndValidatePropertyFieldName(final A propertyEnum, final ComparisonNode node) { private String getAndValidatePropertyFieldName(final A propertyEnum, final ComparisonNode node) {
String finalProperty = propertyEnum.getFieldName();
final String[] graph = node.getSelector().split("\\" + FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR); final String[] graph = node.getSelector().split("\\" + FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR);
validateMapParamter(propertyEnum, node, graph); validateMapParamter(propertyEnum, node, graph);
@@ -215,9 +214,12 @@ public final class RSQLUtility {
throw createRSQLParameterUnsupportedException(node); throw createRSQLParameterUnsupportedException(node);
} }
final StringBuilder fieldNameBuilder = new StringBuilder(propertyEnum.getFieldName());
for (int i = 1; i < graph.length; i++) { for (int i = 1; i < graph.length; i++) {
final String propertyField = graph[i]; final String propertyField = graph[i];
finalProperty += FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR + propertyField; fieldNameBuilder.append(SUB_ATTRIBUTE_SEPERATOR).append(propertyField);
// the key of map is not in the graph // the key of map is not in the graph
if (propertyEnum.isMap() && graph.length == (i + 1)) { if (propertyEnum.isMap() && graph.length == (i + 1)) {
@@ -229,7 +231,7 @@ public final class RSQLUtility {
} }
} }
return finalProperty; return fieldNameBuilder.toString();
} }
private void validateMapParamter(final A propertyEnum, final ComparisonNode node, final String[] graph) { private void validateMapParamter(final A propertyEnum, final ComparisonNode node, final String[] graph) {

View File

@@ -9,11 +9,24 @@
package org.eclipse.hawkbit.rest.util; package org.eclipse.hawkbit.rest.util;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.net.HttpHeaders.ACCEPT_RANGES;
import static com.google.common.net.HttpHeaders.CONTENT_DISPOSITION;
import static com.google.common.net.HttpHeaders.CONTENT_LENGTH;
import static com.google.common.net.HttpHeaders.CONTENT_RANGE;
import static com.google.common.net.HttpHeaders.ETAG;
import static com.google.common.net.HttpHeaders.IF_RANGE;
import static com.google.common.net.HttpHeaders.LAST_MODIFIED;
import static java.math.RoundingMode.DOWN;
import static javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT;
import static org.eclipse.hawkbit.rest.util.ByteRange.MULTIPART_BOUNDARY;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.HttpStatus.PARTIAL_CONTENT;
import static org.springframework.http.HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE;
import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.math.RoundingMode;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@@ -27,23 +40,19 @@ import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.eclipse.hawkbit.repository.model.LocalArtifact;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import com.google.common.math.DoubleMath; import com.google.common.math.DoubleMath;
import com.google.common.net.HttpHeaders;
/** /**
* Utility class for the Rest Source API. * Utility class for the Rest Source API.
*
*/ */
public final class RestResourceConversionHelper { public final class RestResourceConversionHelper {
private static final Logger LOG = LoggerFactory.getLogger(RestResourceConversionHelper.class); private static final Logger LOG = LoggerFactory.getLogger(RestResourceConversionHelper.class);
private static final int BUFFER_SIZE = 4096; private static final int BUFFER_SIZE = 4096;
// utility class, private constructor.
private RestResourceConversionHelper() { private RestResourceConversionHelper() {
} }
@@ -92,7 +101,8 @@ public final class RestResourceConversionHelper {
* *
* @return http code * @return http code
* *
* @see https://tools.ietf.org/html/rfc7233 * @see <a href="https://tools.ietf.org/html/rfc7233">https://tools.ietf.org
* /html/rfc7233</a>
*/ */
public static ResponseEntity<InputStream> writeFileResponse(final LocalArtifact artifact, public static ResponseEntity<InputStream> writeFileResponse(final LocalArtifact artifact,
final HttpServletResponse response, final HttpServletRequest request, final DbArtifact file, final HttpServletResponse response, final HttpServletRequest request, final DbArtifact file,
@@ -107,11 +117,11 @@ public final class RestResourceConversionHelper {
response.reset(); response.reset();
response.setBufferSize(BUFFER_SIZE); response.setBufferSize(BUFFER_SIZE);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + artifact.getFilename()); response.setHeader(CONTENT_DISPOSITION, "attachment;filename=" + artifact.getFilename());
response.setHeader(HttpHeaders.ETAG, etag); response.setHeader(ETAG, etag);
response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes"); response.setHeader(ACCEPT_RANGES, "bytes");
response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified); response.setDateHeader(LAST_MODIFIED, lastModified);
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); response.setContentType(APPLICATION_OCTET_STREAM_VALUE);
final ByteRange full = new ByteRange(0, length - 1, length); final ByteRange full = new ByteRange(0, length - 1, length);
final List<ByteRange> ranges = new ArrayList<>(); final List<ByteRange> ranges = new ArrayList<>();
@@ -123,9 +133,9 @@ public final class RestResourceConversionHelper {
// Range header matches"bytes=n-n,n-n,n-n..." // Range header matches"bytes=n-n,n-n,n-n..."
if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + length); response.setHeader(CONTENT_RANGE, "bytes */" + length);
LOG.debug("range header for filename ({}) is not satisfiable: ", artifact.getFilename()); LOG.debug("range header for filename ({}) is not satisfiable: ", artifact.getFilename());
return new ResponseEntity<>(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE); return new ResponseEntity<>(REQUESTED_RANGE_NOT_SATISFIABLE);
} }
// RFC: if the representation is unchanged, send me the part(s) that // RFC: if the representation is unchanged, send me the part(s) that
@@ -144,32 +154,31 @@ public final class RestResourceConversionHelper {
// full request - no range // full request - no range
if (ranges.isEmpty() || ranges.get(0).equals(full)) { if (ranges.isEmpty() || ranges.get(0).equals(full)) {
LOG.debug("filename ({}) results into a full request: ", artifact.getFilename()); LOG.debug("filename ({}) results into a full request: ", artifact.getFilename());
fullfileRequest(artifact, response, file, controllerManagement, statusId, full); handleFullFileRequest(artifact, response, file, controllerManagement, statusId, full);
result = new ResponseEntity<>(HttpStatus.OK); result = new ResponseEntity<>(OK);
} }
// standard range request // standard range request
else if (ranges.size() == 1) { else if (ranges.size() == 1) {
LOG.debug("filename ({}) results into a standard range request: ", artifact.getFilename()); LOG.debug("filename ({}) results into a standard range request: ", artifact.getFilename());
standardRangeRequest(artifact, response, file, controllerManagement, statusId, ranges); handleStandardRangeRequest(artifact, response, file, controllerManagement, statusId, ranges);
result = new ResponseEntity<>(HttpStatus.PARTIAL_CONTENT); result = new ResponseEntity<>(PARTIAL_CONTENT);
} }
// multipart range request // multipart range request
else { else {
LOG.debug("filename ({}) results into a multipart range request: ", artifact.getFilename()); LOG.debug("filename ({}) results into a multipart range request: ", artifact.getFilename());
multipartRangeRequest(artifact, response, file, controllerManagement, statusId, ranges); handleMultipartRangeRequest(artifact, response, file, controllerManagement, statusId, ranges);
result = new ResponseEntity<>(HttpStatus.PARTIAL_CONTENT); result = new ResponseEntity<>(PARTIAL_CONTENT);
} }
return result; return result;
} }
private static void fullfileRequest(final LocalArtifact artifact, final HttpServletResponse response, private static void handleFullFileRequest(final LocalArtifact artifact, final HttpServletResponse response,
final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId, final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId,
final ByteRange full) { final ByteRange full) {
final ByteRange r = full; final ByteRange r = full;
response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal()); response.setHeader(CONTENT_RANGE, "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal());
response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(r.getLength())); response.setHeader(CONTENT_LENGTH, String.valueOf(r.getLength()));
try { try {
copyStreams(file.getFileInputStream(), response.getOutputStream(), controllerManagement, statusId, copyStreams(file.getFileInputStream(), response.getOutputStream(), controllerManagement, statusId,
@@ -182,7 +191,7 @@ public final class RestResourceConversionHelper {
private static ResponseEntity<InputStream> extractRange(final HttpServletResponse response, final long length, private static ResponseEntity<InputStream> extractRange(final HttpServletResponse response, final long length,
final List<ByteRange> ranges, final String range) { final List<ByteRange> ranges, final String range) {
ResponseEntity<InputStream> result = null;
if (ranges.isEmpty()) { if (ranges.isEmpty()) {
for (final String part : range.substring(6).split(",")) { for (final String part : range.substring(6).split(",")) {
long start = sublong(part, 0, part.indexOf('-')); long start = sublong(part, 0, part.indexOf('-'));
@@ -198,9 +207,8 @@ public final class RestResourceConversionHelper {
// Check if Range is syntactically valid. If not, then return // Check if Range is syntactically valid. If not, then return
// 416. // 416.
if (start > end) { if (start > end) {
response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + length); response.setHeader(CONTENT_RANGE, "bytes */" + length);
result = new ResponseEntity<>(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE); return new ResponseEntity<>(REQUESTED_RANGE_NOT_SATISFIABLE);
return result;
} }
// Add range. // Add range.
@@ -218,10 +226,10 @@ public final class RestResourceConversionHelper {
private static void checkForShortcut(final HttpServletRequest request, final String etag, final long lastModified, private static void checkForShortcut(final HttpServletRequest request, final String etag, final long lastModified,
final ByteRange full, final List<ByteRange> ranges) { final ByteRange full, final List<ByteRange> ranges) {
final String ifRange = request.getHeader(HttpHeaders.IF_RANGE); final String ifRange = request.getHeader(IF_RANGE);
if (ifRange != null && !ifRange.equals(etag)) { if (ifRange != null && !ifRange.equals(etag)) {
try { try {
final long ifRangeTime = request.getDateHeader(HttpHeaders.IF_RANGE); final long ifRangeTime = request.getDateHeader(IF_RANGE);
if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) { if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
ranges.add(full); ranges.add(full);
} }
@@ -232,17 +240,17 @@ public final class RestResourceConversionHelper {
} }
} }
private static void multipartRangeRequest(final LocalArtifact artifact, final HttpServletResponse response, private static void handleMultipartRangeRequest(final LocalArtifact artifact, final HttpServletResponse response,
final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId, final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId,
final List<ByteRange> ranges) { final List<ByteRange> ranges) {
response.setContentType("multipart/byteranges; boundary=" + ByteRange.MULTIPART_BOUNDARY); response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); response.setStatus(SC_PARTIAL_CONTENT);
try { try {
for (final ByteRange r : ranges) { for (final ByteRange r : ranges) {
// Add multipart boundary and header fields for every range. // Add multipart boundary and header fields for every range.
response.getOutputStream().println(); response.getOutputStream().println();
response.getOutputStream().println("--" + ByteRange.MULTIPART_BOUNDARY); response.getOutputStream().println("--" + MULTIPART_BOUNDARY);
response.getOutputStream() response.getOutputStream()
.println("Content-Range: bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal()); .println("Content-Range: bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal());
@@ -253,20 +261,20 @@ public final class RestResourceConversionHelper {
// End with final multipart boundary. // End with final multipart boundary.
response.getOutputStream().println(); response.getOutputStream().println();
response.getOutputStream().print("--" + ByteRange.MULTIPART_BOUNDARY + "--"); response.getOutputStream().print("--" + MULTIPART_BOUNDARY + "--");
} catch (final IOException e) { } catch (final IOException e) {
LOG.error("multipartRangeRequest of file ({}) failed!", artifact.getFilename(), e); LOG.error("multipartRangeRequest of file ({}) failed!", artifact.getFilename(), e);
throw new FileSteamingFailedException(artifact.getFilename()); throw new FileSteamingFailedException(artifact.getFilename());
} }
} }
private static void standardRangeRequest(final LocalArtifact artifact, final HttpServletResponse response, private static void handleStandardRangeRequest(final LocalArtifact artifact, final HttpServletResponse response,
final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId, final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId,
final List<ByteRange> ranges) { final List<ByteRange> ranges) {
final ByteRange r = ranges.get(0); final ByteRange r = ranges.get(0);
response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal()); response.setHeader(CONTENT_RANGE, "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal());
response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(r.getLength())); response.setHeader(CONTENT_LENGTH, String.valueOf(r.getLength()));
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); response.setStatus(SC_PARTIAL_CONTENT);
try { try {
copyStreams(file.getFileInputStream(), response.getOutputStream(), controllerManagement, statusId, copyStreams(file.getFileInputStream(), response.getOutputStream(), controllerManagement, statusId,
@@ -315,7 +323,7 @@ public final class RestResourceConversionHelper {
} }
if (controllerManagement != null) { if (controllerManagement != null) {
final int newPercent = DoubleMath.roundToInt(total * 100.0 / length, RoundingMode.DOWN); final int newPercent = DoubleMath.roundToInt(total * 100.0 / length, DOWN);
// every 10 percent an event // every 10 percent an event
if (newPercent == 100 || newPercent > progressPercent + 10) { if (newPercent == 100 || newPercent > progressPercent + 10) {

View File

@@ -100,7 +100,8 @@ public class DosFilter extends OncePerRequestFilter {
boolean processChain; boolean processChain;
final String ip = IpUtil.getClientIpFromRequest(request, forwardHeader, true).getHost(); final String ip = IpUtil.getClientIpFromRequest(request, forwardHeader).getHost();
if (checkIpFails(ip)) { if (checkIpFails(ip)) {
processChain = handleMissingIpAddress(response); processChain = handleMissingIpAddress(response);
} else { } else {
@@ -121,7 +122,6 @@ public class DosFilter extends OncePerRequestFilter {
if (processChain) { if (processChain) {
filterChain.doFilter(request, response); filterChain.doFilter(request, response);
} }
} }
/** /**

View File

@@ -72,14 +72,16 @@ public final class IpUtil {
* @param forwardHeader * @param forwardHeader
* the header name containing the IP address e.g. forwarded by a * the header name containing the IP address e.g. forwarded by a
* proxy {@code x-forwarded-for} * proxy {@code x-forwarded-for}
*
* @param trackRemoteIp
* to <code>true</code> if remote IP should be tracked.
* @return the {@link URI} based IP address from the client which sent the * @return the {@link URI} based IP address from the client which sent the
* request * request
*/ */
public static URI getClientIpFromRequest(final HttpServletRequest request, final String forwardHeader, public static URI getClientIpFromRequest(final HttpServletRequest request, final String forwardHeader) {
return getClientIpFromRequest(request, forwardHeader, true);
}
private static URI getClientIpFromRequest(final HttpServletRequest request, final String forwardHeader,
final boolean trackRemoteIp) { final boolean trackRemoteIp) {
String ip; String ip;
if (trackRemoteIp) { if (trackRemoteIp) {

View File

@@ -8,6 +8,7 @@
*/ */
package org.eclipse.hawkbit.util; package org.eclipse.hawkbit.util;
import static com.google.common.net.HttpHeaders.X_FORWARDED_FOR;
import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
@@ -21,13 +22,13 @@ import java.net.URI;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.eclipse.hawkbit.security.HawkbitSecurityProperties;
import org.eclipse.hawkbit.security.HawkbitSecurityProperties.Clients;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
import com.google.common.net.HttpHeaders;
import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories; import ru.yandex.qatools.allure.annotations.Stories;
@@ -37,69 +38,73 @@ import ru.yandex.qatools.allure.annotations.Stories;
@Stories("IP Util Test") @Stories("IP Util Test")
public class IpUtilTest { public class IpUtilTest {
private static final String KNOWN_REQUEST_HEADER = "bumlux";
@Mock @Mock
private HttpServletRequest requestMock; private HttpServletRequest requestMock;
@Mock
private Clients clientMock;
@Mock
private HawkbitSecurityProperties securityPropertyMock;
@Test @Test
@Description("Tests create uri from request") @Description("Tests create uri from request")
public void getRemoteAddrFromRequestIfForwaredHeaderNotPresent() { public void getRemoteAddrFromRequestIfForwaredHeaderNotPresent() {
// known values
final URI knownRemoteClientIP = IpUtil.createHttpUri("127.0.0.1"); final URI knownRemoteClientIP = IpUtil.createHttpUri("127.0.0.1");
// mock when(requestMock.getHeader(X_FORWARDED_FOR)).thenReturn(null);
when(requestMock.getHeader(HttpHeaders.X_FORWARDED_FOR)).thenReturn(null);
when(requestMock.getRemoteAddr()).thenReturn(knownRemoteClientIP.getHost()); when(requestMock.getRemoteAddr()).thenReturn(knownRemoteClientIP.getHost());
// test final URI remoteAddr = IpUtil.getClientIpFromRequest(requestMock, KNOWN_REQUEST_HEADER);
final URI remoteAddr = IpUtil.getClientIpFromRequest(requestMock, "bumlux", true);
// verify // verify
assertThat(remoteAddr).as("The remote address should be as the known client IP address") assertThat(remoteAddr).as("The remote address should be as the known client IP address")
.isEqualTo(knownRemoteClientIP); .isEqualTo(knownRemoteClientIP);
verify(requestMock, times(1)).getHeader("bumlux"); verify(requestMock, times(1)).getHeader(KNOWN_REQUEST_HEADER);
verify(requestMock, times(1)).getRemoteAddr(); verify(requestMock, times(1)).getRemoteAddr();
} }
@Test @Test
@Description("Tests create uri from request with masked IP when IP tracking is disabled") @Description("Tests create uri from request with masked IP when IP tracking is disabled")
public void maskRemoteAddrIfDisabled() { public void maskRemoteAddrIfDisabled() {
// known values
final URI knownRemoteClientIP = IpUtil.createHttpUri("***"); final URI knownRemoteClientIP = IpUtil.createHttpUri("***");
// mock when(requestMock.getHeader(X_FORWARDED_FOR)).thenReturn(null);
when(requestMock.getHeader(HttpHeaders.X_FORWARDED_FOR)).thenReturn(null);
when(requestMock.getRemoteAddr()).thenReturn(knownRemoteClientIP.getHost()); when(requestMock.getRemoteAddr()).thenReturn(knownRemoteClientIP.getHost());
when(securityPropertyMock.getClients()).thenReturn(clientMock);
when(clientMock.getRemoteIpHeader()).thenReturn(KNOWN_REQUEST_HEADER);
when(clientMock.isTrackRemoteIp()).thenReturn(false);
// test final URI remoteAddr = IpUtil.getClientIpFromRequest(requestMock, securityPropertyMock);
final URI remoteAddr = IpUtil.getClientIpFromRequest(requestMock, "bumlux", false);
// verify
assertThat(remoteAddr).as("The remote address should be as the known client IP address") assertThat(remoteAddr).as("The remote address should be as the known client IP address")
.isEqualTo(knownRemoteClientIP); .isEqualTo(knownRemoteClientIP);
verify(requestMock, times(0)).getHeader("bumlux"); verify(requestMock, times(0)).getHeader(KNOWN_REQUEST_HEADER);
verify(requestMock, times(0)).getRemoteAddr(); verify(requestMock, times(0)).getRemoteAddr();
} }
@Test @Test
@Description("Tests create uri from x forward header") @Description("Tests create uri from x forward header")
public void getRemoteAddrFromXForwardedForHeader() { public void getRemoteAddrFromXForwardedForHeader() {
// known values
final URI knownRemoteClientIP = IpUtil.createHttpUri("10.99.99.1"); final URI knownRemoteClientIP = IpUtil.createHttpUri("10.99.99.1");
// mock when(requestMock.getHeader(X_FORWARDED_FOR)).thenReturn(knownRemoteClientIP.getHost());
when(requestMock.getHeader(HttpHeaders.X_FORWARDED_FOR)).thenReturn(knownRemoteClientIP.getHost());
when(requestMock.getRemoteAddr()).thenReturn(null); when(requestMock.getRemoteAddr()).thenReturn(null);
// test final URI remoteAddr = IpUtil.getClientIpFromRequest(requestMock, "X-Forwarded-For");
final URI remoteAddr = IpUtil.getClientIpFromRequest(requestMock, "X-Forwarded-For", true);
// verify
assertThat(remoteAddr).as("The remote address should be as the known client IP address") assertThat(remoteAddr).as("The remote address should be as the known client IP address")
.isEqualTo(knownRemoteClientIP); .isEqualTo(knownRemoteClientIP);
verify(requestMock, times(1)).getHeader(HttpHeaders.X_FORWARDED_FOR); verify(requestMock, times(1)).getHeader(X_FORWARDED_FOR);
verify(requestMock, times(0)).getRemoteAddr(); verify(requestMock, times(0)).getRemoteAddr();
} }
@Test @Test
@Description("Tests create http uri ipv4 and ipv6") @Description("Tests create http uri ipv4 and ipv6")
public void testCreateHttpUri() { public void testCreateHttpUri() {
final String ipv4 = "10.99.99.1"; final String ipv4 = "10.99.99.1";
URI httpUri = IpUtil.createHttpUri(ipv4); URI httpUri = IpUtil.createHttpUri(ipv4);
assertHttpUri(ipv4, httpUri); assertHttpUri(ipv4, httpUri);
@@ -111,7 +116,6 @@ public class IpUtilTest {
final String ipv6 = "0:0:0:0:0:0:0:1"; final String ipv6 = "0:0:0:0:0:0:0:1";
httpUri = IpUtil.createHttpUri(ipv6); httpUri = IpUtil.createHttpUri(ipv6);
assertHttpUri("[" + ipv6 + "]", httpUri); assertHttpUri("[" + ipv6 + "]", httpUri);
} }
private void assertHttpUri(final String host, final URI httpUri) { private void assertHttpUri(final String host, final URI httpUri) {
@@ -124,6 +128,7 @@ public class IpUtilTest {
@Test @Test
@Description("Tests create amqp uri ipv4 and ipv6") @Description("Tests create amqp uri ipv4 and ipv6")
public void testCreateAmqpUri() { public void testCreateAmqpUri() {
final String ipv4 = "10.99.99.1"; final String ipv4 = "10.99.99.1";
URI amqpUri = IpUtil.createAmqpUri(ipv4, "path"); URI amqpUri = IpUtil.createAmqpUri(ipv4, "path");
assertAmqpUri(ipv4, amqpUri); assertAmqpUri(ipv4, amqpUri);
@@ -138,6 +143,7 @@ public class IpUtilTest {
} }
private void assertAmqpUri(final String host, final URI amqpUri) { private void assertAmqpUri(final String host, final URI amqpUri) {
assertTrue("The given URI is an AMQP scheme", IpUtil.isAmqpUri(amqpUri)); assertTrue("The given URI is an AMQP scheme", IpUtil.isAmqpUri(amqpUri));
assertFalse("The given URI is not an HTTP scheme", IpUtil.isHttpUri(amqpUri)); assertFalse("The given URI is not an HTTP scheme", IpUtil.isHttpUri(amqpUri));
assertEquals("The given host matches the URI host", host, amqpUri.getHost()); assertEquals("The given host matches the URI host", host, amqpUri.getHost());
@@ -148,17 +154,19 @@ public class IpUtilTest {
@Test @Test
@Description("Tests create invalid uri") @Description("Tests create invalid uri")
public void testCreateInvalidUri() { public void testCreateInvalidUri() {
final String host = "10.99.99.1"; final String host = "10.99.99.1";
final URI testUri = IpUtil.createUri("test", host); final URI testUri = IpUtil.createUri("test", host);
assertFalse("The given URI is not an AMQP address", IpUtil.isAmqpUri(testUri)); assertFalse("The given URI is not an AMQP address", IpUtil.isAmqpUri(testUri));
assertFalse("The given URI is not an HTTP address", IpUtil.isHttpUri(testUri)); assertFalse("The given URI is not an HTTP address", IpUtil.isHttpUri(testUri));
assertEquals("The given host matches the URI host", host, testUri.getHost()); assertEquals("The given host matches the URI host", host, testUri.getHost());
try { try {
IpUtil.createUri(":/", host); IpUtil.createUri(":/", host);
fail("Missing expected IllegalArgumentException due invalid URI"); fail("Missing expected IllegalArgumentException due invalid URI");
} catch (final IllegalArgumentException e) { } catch (final IllegalArgumentException e) {
// expected // expected
} }
} }
} }

View File

@@ -52,8 +52,8 @@ import com.vaadin.ui.UI;
/** /**
* Header of Software module table. * Header of Software module table.
*/ */
@SpringComponent
@ViewScope @ViewScope
@SpringComponent
public class SoftwareModuleTable extends AbstractNamedVersionTable<SoftwareModule, Long> { public class SoftwareModuleTable extends AbstractNamedVersionTable<SoftwareModule, Long> {
private static final long serialVersionUID = 6469417305487144809L; private static final long serialVersionUID = 6469417305487144809L;
@@ -162,7 +162,7 @@ public class SoftwareModuleTable extends AbstractNamedVersionTable<SoftwareModul
@EventBusListenerMethod(scope = EventScope.SESSION) @EventBusListenerMethod(scope = EventScope.SESSION)
void onEvent(final UploadArtifactUIEvent event) { void onEvent(final UploadArtifactUIEvent event) {
if (event == UploadArtifactUIEvent.DELETED_ALL_SOFWARE) { if (event == UploadArtifactUIEvent.DELETED_ALL_SOFWARE) {
UI.getCurrent().access(() -> refreshFilter()); UI.getCurrent().access(this::refreshFilter);
} }
} }
@@ -197,7 +197,7 @@ public class SoftwareModuleTable extends AbstractNamedVersionTable<SoftwareModul
public Object generateCell(final Table source, final Object itemId, final Object columnId) { public Object generateCell(final Table source, final Object itemId, final Object columnId) {
final String nameVersionStr = getNameAndVerion(itemId); final String nameVersionStr = getNameAndVerion(itemId);
final Button manageMetaDataBtn = createManageMetadataButton(nameVersionStr); final Button manageMetaDataBtn = createManageMetadataButton(nameVersionStr);
manageMetaDataBtn.addClickListener(event -> showMetadataDetails((Long) itemId, nameVersionStr)); manageMetaDataBtn.addClickListener(event -> showMetadataDetails((Long) itemId));
return manageMetaDataBtn; return manageMetaDataBtn;
} }
}); });
@@ -237,8 +237,7 @@ public class SoftwareModuleTable extends AbstractNamedVersionTable<SoftwareModul
artifactUploadState.setNoDataAvilableSoftwareModule(!available); artifactUploadState.setNoDataAvilableSoftwareModule(!available);
} }
private Button createManageMetadataButton(final String nameVersionStr) {
private Button createManageMetadataButton(String nameVersionStr) {
final Button manageMetadataBtn = SPUIComponentProvider.getButton( final Button manageMetadataBtn = SPUIComponentProvider.getButton(
SPUIComponentIdProvider.SW_TABLE_MANAGE_METADATA_ID + "." + nameVersionStr, "", "", null, false, SPUIComponentIdProvider.SW_TABLE_MANAGE_METADATA_ID + "." + nameVersionStr, "", "", null, false,
FontAwesome.LIST_ALT, SPUIButtonStyleSmallNoBorder.class); FontAwesome.LIST_ALT, SPUIButtonStyleSmallNoBorder.class);
@@ -254,9 +253,9 @@ public class SoftwareModuleTable extends AbstractNamedVersionTable<SoftwareModul
return name + "." + version; return name + "." + version;
} }
private void showMetadataDetails(Long itemId, String nameVersionStr) { private void showMetadataDetails(final Long itemId) {
SoftwareModule swmodule = softwareManagement.findSoftwareModuleWithDetails(itemId); final SoftwareModule swmodule = softwareManagement.findSoftwareModuleWithDetails(itemId);
/* display the window */ /* display the window */
UI.getCurrent().addWindow(swMetadataPopupLayout.getWindow(swmodule,null)); UI.getCurrent().addWindow(swMetadataPopupLayout.getWindow(swmodule, null));
} }
} }

View File

@@ -8,6 +8,9 @@
*/ */
package org.eclipse.hawkbit.ui.artifacts.upload; package org.eclipse.hawkbit.ui.artifacts.upload;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.FAILED;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.SUCCESS;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@@ -58,11 +61,11 @@ import com.vaadin.ui.themes.ValoTheme;
* Artifact upload confirmation popup. * Artifact upload confirmation popup.
* *
*/ */
public class UploadConfirmationwindow implements Button.ClickListener { public class UploadConfirmationWindow implements Button.ClickListener {
private static final long serialVersionUID = -1679035890140031740L; private static final long serialVersionUID = -1679035890140031740L;
private static final Logger LOG = LoggerFactory.getLogger(UploadConfirmationwindow.class); private static final Logger LOG = LoggerFactory.getLogger(UploadConfirmationWindow.class);
private static final String MD5_CHECKSUM = "md5Checksum"; private static final String MD5_CHECKSUM = "md5Checksum";
@@ -120,7 +123,7 @@ public class UploadConfirmationwindow implements Button.ClickListener {
* @param artifactUploadState * @param artifactUploadState
* reference of session variable {@link ArtifactUploadState}. * reference of session variable {@link ArtifactUploadState}.
*/ */
public UploadConfirmationwindow(final UploadLayout artifactUploadView, public UploadConfirmationWindow(final UploadLayout artifactUploadView,
final ArtifactUploadState artifactUploadState) { final ArtifactUploadState artifactUploadState) {
this.uploadLayout = artifactUploadView; this.uploadLayout = artifactUploadView;
this.artifactUploadState = artifactUploadState; this.artifactUploadState = artifactUploadState;
@@ -615,6 +618,7 @@ public class UploadConfirmationwindow implements Button.ClickListener {
private void createLocalArtifact(final String itemId, final String filePath, private void createLocalArtifact(final String itemId, final String filePath,
final ArtifactManagement artifactManagement, final SoftwareModule baseSw) { final ArtifactManagement artifactManagement, final SoftwareModule baseSw) {
final File newFile = new File(filePath); final File newFile = new File(filePath);
final Item item = tabelContainer.getItem(itemId); final Item item = tabelContainer.getItem(itemId);
final String sha1Checksum = ((TextField) item.getItemProperty(SHA1_CHECKSUM).getValue()).getValue(); final String sha1Checksum = ((TextField) item.getItemProperty(SHA1_CHECKSUM).getValue()).getValue();
@@ -624,27 +628,25 @@ public class UploadConfirmationwindow implements Button.ClickListener {
final String[] itemDet = itemId.split("/"); final String[] itemDet = itemId.split("/");
final String swModuleNameVersion = itemDet[0]; final String swModuleNameVersion = itemDet[0];
FileInputStream fis = null; try (FileInputStream fis = new FileInputStream(newFile)) {
try {
fis = new FileInputStream(newFile);
artifactManagement.createLocalArtifact(fis, baseSw.getId(), providedFileName, artifactManagement.createLocalArtifact(fis, baseSw.getId(), providedFileName,
HawkbitCommonUtil.trimAndNullIfEmpty(md5Checksum), HawkbitCommonUtil.trimAndNullIfEmpty(md5Checksum),
HawkbitCommonUtil.trimAndNullIfEmpty(sha1Checksum), true, customFile.getMimeType()); HawkbitCommonUtil.trimAndNullIfEmpty(sha1Checksum), true, customFile.getMimeType());
saveUploadStatus(providedFileName, swModuleNameVersion, SPUILabelDefinitions.SUCCESS, ""); saveUploadStatus(providedFileName, swModuleNameVersion, SUCCESS, "");
} catch (final FileNotFoundException e) {
saveUploadStatus(providedFileName, swModuleNameVersion, SPUILabelDefinitions.FAILED, e.getMessage()); } catch (final ArtifactUploadFailedException | InvalidSHA1HashException | InvalidMD5HashException
LOG.error(ARTIFACT_UPLOAD_EXCEPTION, e); | FileNotFoundException e) {
} catch (final ArtifactUploadFailedException e) {
saveUploadStatus(providedFileName, swModuleNameVersion, SPUILabelDefinitions.FAILED, e.getMessage()); saveUploadStatus(providedFileName, swModuleNameVersion, FAILED, e.getMessage());
LOG.error(ARTIFACT_UPLOAD_EXCEPTION, e);
} catch (final InvalidSHA1HashException e) {
saveUploadStatus(providedFileName, swModuleNameVersion, SPUILabelDefinitions.FAILED, e.getMessage());
LOG.error(ARTIFACT_UPLOAD_EXCEPTION, e);
} catch (final InvalidMD5HashException e) {
saveUploadStatus(providedFileName, swModuleNameVersion, SPUILabelDefinitions.FAILED, e.getMessage());
LOG.error(ARTIFACT_UPLOAD_EXCEPTION, e); LOG.error(ARTIFACT_UPLOAD_EXCEPTION, e);
} catch (final IOException ex) {
LOG.error(ARTIFACT_UPLOAD_EXCEPTION, ex);
} finally { } finally {
closeFileStream(fis, newFile); if (newFile.exists() && !newFile.delete()) {
LOG.error("Could not delete temporary file: {}", newFile);
}
} }
} }
@@ -659,21 +661,6 @@ public class UploadConfirmationwindow implements Button.ClickListener {
} }
private static void closeFileStream(final FileInputStream fis, final File newFile) {
if (fis != null) {
try {
fis.close();
} catch (final IOException e) {
LOG.error(ARTIFACT_UPLOAD_EXCEPTION, e);
}
}
if (newFile.exists() && !newFile.delete()) {
LOG.error("Could not delete temporary file: {}", newFile);
}
}
public Table getUploadDetailsTable() { public Table getUploadDetailsTable() {
return uploadDetailsTable; return uploadDetailsTable;
} }

View File

@@ -109,7 +109,7 @@ public class UploadLayout extends VerticalLayout {
private Button discardBtn; private Button discardBtn;
private UploadConfirmationwindow currentUploadConfirmationwindow; private UploadConfirmationWindow currentUploadConfirmationwindow;
private VerticalLayout dropAreaLayout; private VerticalLayout dropAreaLayout;
@@ -634,7 +634,7 @@ public class UploadLayout extends VerticalLayout {
if (artifactUploadState.getFileSelected().isEmpty()) { if (artifactUploadState.getFileSelected().isEmpty()) {
uiNotification.displayValidationError(i18n.get("message.error.noFileSelected")); uiNotification.displayValidationError(i18n.get("message.error.noFileSelected"));
} else { } else {
currentUploadConfirmationwindow = new UploadConfirmationwindow(this, artifactUploadState); currentUploadConfirmationwindow = new UploadConfirmationWindow(this, artifactUploadState);
UI.getCurrent().addWindow(currentUploadConfirmationwindow.getUploadConfrimationWindow()); UI.getCurrent().addWindow(currentUploadConfirmationwindow.getUploadConfrimationWindow());
setConfirmationPopupHeightWidth(Page.getCurrent().getBrowserWindowWidth(), setConfirmationPopupHeightWidth(Page.getCurrent().getBrowserWindowWidth(),
Page.getCurrent().getBrowserWindowHeight()); Page.getCurrent().getBrowserWindowHeight());
@@ -656,7 +656,7 @@ public class UploadLayout extends VerticalLayout {
return spInfo; return spInfo;
} }
void setCurrentUploadConfirmationwindow(final UploadConfirmationwindow currentUploadConfirmationwindow) { void setCurrentUploadConfirmationwindow(final UploadConfirmationWindow currentUploadConfirmationwindow) {
this.currentUploadConfirmationwindow = currentUploadConfirmationwindow; this.currentUploadConfirmationwindow = currentUploadConfirmationwindow;
} }

View File

@@ -136,25 +136,25 @@ public class UploadStatusInfoWindow extends Window {
@EventBusListenerMethod(scope = EventScope.SESSION) @EventBusListenerMethod(scope = EventScope.SESSION)
void onEvent(final UploadStatusEvent event) { void onEvent(final UploadStatusEvent event) {
if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_IN_PROGRESS) { if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_IN_PROGRESS) {
UI.getCurrent().access( UI.getCurrent()
() -> updateProgress(event.getUploadStatus().getFileName(), event.getUploadStatus().getBytesRead(), .access(() -> updateProgress(event.getUploadStatus().getFileName(),
event.getUploadStatus().getContentLength(), event.getUploadStatus().getSoftwareModule())); event.getUploadStatus().getBytesRead(), event.getUploadStatus().getContentLength(),
event.getUploadStatus().getSoftwareModule()));
} else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_STARTED) { } else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_STARTED) {
UI.getCurrent().access(() -> onStartOfUpload(event)); UI.getCurrent().access(() -> onStartOfUpload(event));
} else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_STREAMING_FAILED) { } else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_STREAMING_FAILED) {
ui.access(() -> uploadFailed(event.getUploadStatus().getFileName(), event.getUploadStatus() ui.access(() -> uploadFailed(event.getUploadStatus().getFileName(),
.getFailureReason(), event.getUploadStatus().getSoftwareModule())); event.getUploadStatus().getFailureReason(), event.getUploadStatus().getSoftwareModule()));
} else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_SUCCESSFUL) { } else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_SUCCESSFUL) {
UI.getCurrent().access( UI.getCurrent().access(() -> uploadSucceeded(event.getUploadStatus().getFileName(),
() -> uploadSucceeded(event.getUploadStatus().getFileName(), event.getUploadStatus() event.getUploadStatus().getSoftwareModule()));
.getSoftwareModule()));
} else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_STREAMING_FINISHED) { } else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_STREAMING_FINISHED) {
ui.access(() -> uploadSucceeded(event.getUploadStatus().getFileName(), event.getUploadStatus() ui.access(() -> uploadSucceeded(event.getUploadStatus().getFileName(),
.getSoftwareModule())); event.getUploadStatus().getSoftwareModule()));
} }
} }
private void onStartOfUpload(UploadStatusEvent event) { private void onStartOfUpload(final UploadStatusEvent event) {
uploadSessionStarted(); uploadSessionStarted();
uploadStarted(event.getUploadStatus().getFileName(), event.getUploadStatus().getSoftwareModule()); uploadStarted(event.getUploadStatus().getFileName(), event.getUploadStatus().getSoftwareModule());
} }
@@ -169,19 +169,19 @@ public class UploadStatusInfoWindow extends Window {
} }
private void restoreState() { private void restoreState() {
Indexed container = grid.getContainerDataSource(); final Indexed container = grid.getContainerDataSource();
if (container.getItemIds().isEmpty()) { if (container.getItemIds().isEmpty()) {
container.removeAllItems(); container.removeAllItems();
for (UploadStatusObject statusObject : artifactUploadState.getUploadedFileStatusList()) { for (final UploadStatusObject statusObject : artifactUploadState.getUploadedFileStatusList()) {
Item item = container.addItem(getItemid(statusObject.getFilename(), final Item item = container
statusObject.getSelectedSoftwareModule())); .addItem(getItemid(statusObject.getFilename(), statusObject.getSelectedSoftwareModule()));
item.getItemProperty(REASON).setValue(statusObject.getReason() != null ? statusObject.getReason() : ""); item.getItemProperty(REASON).setValue(statusObject.getReason() != null ? statusObject.getReason() : "");
item.getItemProperty(STATUS).setValue(statusObject.getStatus()); item.getItemProperty(STATUS).setValue(statusObject.getStatus());
item.getItemProperty(PROGRESS).setValue(statusObject.getProgress()); item.getItemProperty(PROGRESS).setValue(statusObject.getProgress());
item.getItemProperty(FILE_NAME).setValue(statusObject.getFilename()); item.getItemProperty(FILE_NAME).setValue(statusObject.getFilename());
SoftwareModule sw = statusObject.getSelectedSoftwareModule(); final SoftwareModule sw = statusObject.getSelectedSoftwareModule();
item.getItemProperty(SPUILabelDefinitions.NAME_VERSION).setValue( item.getItemProperty(SPUILabelDefinitions.NAME_VERSION)
HawkbitCommonUtil.getFormattedNameVersion(sw.getName(), sw.getVersion())); .setValue(HawkbitCommonUtil.getFormattedNameVersion(sw.getName(), sw.getVersion()));
} }
if (artifactUploadState.isUploadCompleted()) { if (artifactUploadState.isUploadCompleted()) {
minimizeButton.setEnabled(false); minimizeButton.setEnabled(false);
@@ -209,7 +209,7 @@ public class UploadStatusInfoWindow extends Window {
} }
private Grid createGrid() { private Grid createGrid() {
Grid statusGrid = new Grid(uploads); final Grid statusGrid = new Grid(uploads);
statusGrid.addStyleName(SPUIStyleDefinitions.UPLOAD_STATUS_GRID); statusGrid.addStyleName(SPUIStyleDefinitions.UPLOAD_STATUS_GRID);
statusGrid.setSelectionMode(SelectionMode.NONE); statusGrid.setSelectionMode(SelectionMode.NONE);
statusGrid.setHeaderVisible(true); statusGrid.setHeaderVisible(true);
@@ -219,7 +219,7 @@ public class UploadStatusInfoWindow extends Window {
} }
private IndexedContainer getGridContainer() { private IndexedContainer getGridContainer() {
IndexedContainer uploadContainer = new IndexedContainer(); final IndexedContainer uploadContainer = new IndexedContainer();
uploadContainer.addContainerProperty(STATUS, String.class, "Active"); uploadContainer.addContainerProperty(STATUS, String.class, "Active");
uploadContainer.addContainerProperty(FILE_NAME, String.class, null); uploadContainer.addContainerProperty(FILE_NAME, String.class, null);
uploadContainer.addContainerProperty(PROGRESS, Double.class, 0D); uploadContainer.addContainerProperty(PROGRESS, Double.class, 0D);
@@ -329,7 +329,7 @@ public class UploadStatusInfoWindow extends Window {
HawkbitCommonUtil.getFormattedNameVersion(softwareModule.getName(), softwareModule.getVersion())); HawkbitCommonUtil.getFormattedNameVersion(softwareModule.getName(), softwareModule.getVersion()));
} }
grid.scrollToEnd(); grid.scrollToEnd();
UploadStatusObject uploadStatus = new UploadStatusObject(filename, softwareModule); final UploadStatusObject uploadStatus = new UploadStatusObject(filename, softwareModule);
uploadStatus.setStatus("Active"); uploadStatus.setStatus("Active");
artifactUploadState.getUploadedFileStatusList().add(uploadStatus); artifactUploadState.getUploadedFileStatusList().add(uploadStatus);
} }
@@ -337,15 +337,14 @@ public class UploadStatusInfoWindow extends Window {
void updateProgress(final String filename, final long readBytes, final long contentLength, void updateProgress(final String filename, final long readBytes, final long contentLength,
final SoftwareModule softwareModule) { final SoftwareModule softwareModule) {
final Item item = uploads.getItem(getItemid(filename, softwareModule)); final Item item = uploads.getItem(getItemid(filename, softwareModule));
double progress = (double) readBytes / (double) contentLength; final double progress = (double) readBytes / (double) contentLength;
if (item != null) { if (item != null) {
item.getItemProperty(PROGRESS).setValue(progress); item.getItemProperty(PROGRESS).setValue(progress);
} }
List<UploadStatusObject> uploadStatusObjectList = (List<UploadStatusObject>) artifactUploadState final List<UploadStatusObject> uploadStatusObjectList = artifactUploadState.getUploadedFileStatusList().stream()
.getUploadedFileStatusList().stream().filter(e -> e.getFilename().equals(filename)) .filter(e -> e.getFilename().equals(filename)).collect(Collectors.toList());
.collect(Collectors.toList());
if (!uploadStatusObjectList.isEmpty()) { if (!uploadStatusObjectList.isEmpty()) {
UploadStatusObject uploadStatusObject = uploadStatusObjectList.get(0); final UploadStatusObject uploadStatusObject = uploadStatusObjectList.get(0);
uploadStatusObject.setProgress(progress); uploadStatusObject.setProgress(progress);
} }
} }
@@ -358,35 +357,33 @@ public class UploadStatusInfoWindow extends Window {
* @param softwareModule * @param softwareModule
* selected software module * selected software module
*/ */
public void uploadSucceeded(final String filename, SoftwareModule softwareModule) { public void uploadSucceeded(final String filename, final SoftwareModule softwareModule) {
final Item item = uploads.getItem(getItemid(filename, softwareModule)); final Item item = uploads.getItem(getItemid(filename, softwareModule));
String status = "Finished"; final String status = "Finished";
if (item != null) { if (item != null) {
item.getItemProperty(STATUS).setValue(status); item.getItemProperty(STATUS).setValue(status);
} }
List<UploadStatusObject> uploadStatusObjectList = (List<UploadStatusObject>) artifactUploadState final List<UploadStatusObject> uploadStatusObjectList = artifactUploadState.getUploadedFileStatusList().stream()
.getUploadedFileStatusList().stream().filter(e -> e.getFilename().equals(filename)) .filter(e -> e.getFilename().equals(filename)).collect(Collectors.toList());
.collect(Collectors.toList());
if (!uploadStatusObjectList.isEmpty()) { if (!uploadStatusObjectList.isEmpty()) {
UploadStatusObject uploadStatusObject = uploadStatusObjectList.get(0); final UploadStatusObject uploadStatusObject = uploadStatusObjectList.get(0);
uploadStatusObject.setStatus(status); uploadStatusObject.setStatus(status);
uploadStatusObject.setProgress(1d); uploadStatusObject.setProgress(1d);
} }
} }
void uploadFailed(final String filename, final String errorReason, SoftwareModule softwareModule) { void uploadFailed(final String filename, final String errorReason, final SoftwareModule softwareModule) {
errorOccured = true; errorOccured = true;
String status = "Failed"; final String status = "Failed";
final Item item = uploads.getItem(getItemid(filename, softwareModule)); final Item item = uploads.getItem(getItemid(filename, softwareModule));
if (item != null) { if (item != null) {
item.getItemProperty(REASON).setValue(errorReason); item.getItemProperty(REASON).setValue(errorReason);
item.getItemProperty(STATUS).setValue(status); item.getItemProperty(STATUS).setValue(status);
} }
List<UploadStatusObject> uploadStatusObjectList = (List<UploadStatusObject>) artifactUploadState final List<UploadStatusObject> uploadStatusObjectList = artifactUploadState.getUploadedFileStatusList().stream()
.getUploadedFileStatusList().stream().filter(e -> e.getFilename().equals(filename)) .filter(e -> e.getFilename().equals(filename)).collect(Collectors.toList());
.collect(Collectors.toList());
if (!uploadStatusObjectList.isEmpty()) { if (!uploadStatusObjectList.isEmpty()) {
UploadStatusObject uploadStatusObject = uploadStatusObjectList.get(0); final UploadStatusObject uploadStatusObject = uploadStatusObjectList.get(0);
uploadStatusObject.setStatus(status); uploadStatusObject.setStatus(status);
uploadStatusObject.setReason(errorReason); uploadStatusObject.setReason(errorReason);
} }
@@ -428,8 +425,8 @@ public class UploadStatusInfoWindow extends Window {
return resizeBtn; return resizeBtn;
} }
private void resizeWindow(ClickEvent event) { private void resizeWindow(final ClickEvent event) {
if (event.getButton().getIcon() == FontAwesome.EXPAND) { if (FontAwesome.EXPAND.equals(event.getButton().getIcon())) {
event.getButton().setIcon(FontAwesome.COMPRESS); event.getButton().setIcon(FontAwesome.COMPRESS);
setWindowMode(WindowMode.MAXIMIZED); setWindowMode(WindowMode.MAXIMIZED);
resetColumnWidth(); resetColumnWidth();

View File

@@ -13,10 +13,6 @@ import com.vaadin.ui.AbstractColorPicker.Coordinates2Color;
/** /**
* Converts 2d-coordinates to a Color. * Converts 2d-coordinates to a Color.
*
*
*
*
*/ */
public class CoordinatesToColor implements Coordinates2Color { public class CoordinatesToColor implements Coordinates2Color {
@@ -30,32 +26,31 @@ public class CoordinatesToColor implements Coordinates2Color {
@Override @Override
public int[] calculate(final Color color) { public int[] calculate(final Color color) {
final float[] hsv = color.getHSV(); final float[] hsv = color.getHSV();
final int x = Math.round(hsv[0] * 220f); final int x = Math.round(hsv[0] * 220F);
int y = 0; final int y = calculateYCoordinateOfColor(hsv);
y = calculateYCoordinateOfColor(hsv);
return new int[] { x, y }; return new int[] { x, y };
} }
private Color calculateHSVColor(final int x, final int y) { private static Color calculateHSVColor(final int x, final int y) {
final float h = x / 220f; final float h = x / 220F;
float s = 1f; float s = 1F;
float v = 1f; float v = 1F;
if (y < 110) { if (y < 110) {
s = y / 110f; s = y / 110F;
} else if (y > 110) { } else if (y > 110) {
v = 1f - (y - 110f) / 110f; v = 1F - (y - 110F) / 110F;
} }
return new Color(Color.HSVtoRGB(h, s, v)); return new Color(Color.HSVtoRGB(h, s, v));
} }
private int calculateYCoordinateOfColor(final float[] hsv) { private static int calculateYCoordinateOfColor(final float[] hsv) {
int y; int y;
// lower half // lower half
/* Assuming hsv[] array value will have in the range of 0 to 1 */ /* Assuming hsv[] array value will have in the range of 0 to 1 */
if (hsv[1] < 1f) { if (hsv[1] < 1F) {
y = Math.round(hsv[1] * 110f); y = Math.round(hsv[1] * 110F);
} else { } else {
y = Math.round(110f - (hsv[1] + hsv[2]) * 110f); y = Math.round(110F - (hsv[1] + hsv[2]) * 110F);
} }
return y; return y;
} }

View File

@@ -40,18 +40,17 @@ import com.vaadin.ui.themes.ValoTheme;
@SpringComponent @SpringComponent
@VaadinSessionScope @VaadinSessionScope
public class DistributionSetMetadatadetailslayout extends Table{ public class DistributionSetMetadatadetailslayout extends Table {
private static final long serialVersionUID = 2913758299611837718L; private static final long serialVersionUID = 2913758299611837718L;
private DistributionSetManagement distributionSetManagement;
private DsMetadataPopupLayout dsMetadataPopupLayout;
private static final String METADATA_KEY = "Key"; private static final String METADATA_KEY = "Key";
private static final String VIEW ="view"; private static final String VIEW = "view";
private transient DistributionSetManagement distributionSetManagement;
private DsMetadataPopupLayout dsMetadataPopupLayout;
private SpPermissionChecker permissionChecker; private SpPermissionChecker permissionChecker;
@@ -70,8 +69,7 @@ public class DistributionSetMetadatadetailslayout extends Table{
*/ */
public void init(final I18N i18n, final SpPermissionChecker permissionChecker, public void init(final I18N i18n, final SpPermissionChecker permissionChecker,
final DistributionSetManagement distributionSetManagement, final DistributionSetManagement distributionSetManagement,
final DsMetadataPopupLayout dsMetadataPopupLayout, final DsMetadataPopupLayout dsMetadataPopupLayout, final EntityFactory entityFactory) {
final EntityFactory entityFactory) {
this.i18n = i18n; this.i18n = i18n;
this.permissionChecker = permissionChecker; this.permissionChecker = permissionChecker;
this.distributionSetManagement = distributionSetManagement; this.distributionSetManagement = distributionSetManagement;
@@ -81,7 +79,6 @@ public class DistributionSetMetadatadetailslayout extends Table{
addCustomGeneratedColumns(); addCustomGeneratedColumns();
} }
/** /**
* Populate software module metadata. * Populate software module metadata.
* *
@@ -101,11 +98,11 @@ public class DistributionSetMetadatadetailslayout extends Table{
} }
/** /**
* Create metadata . * Create metadata.
* *
* @param metadataKeyName * @param metadataKeyName
*/ */
public void createMetadata(final String metadataKeyName){ public void createMetadata(final String metadataKeyName) {
final IndexedContainer metadataContainer = (IndexedContainer) getContainerDataSource(); final IndexedContainer metadataContainer = (IndexedContainer) getContainerDataSource();
final Item item = metadataContainer.addItem(metadataKeyName); final Item item = metadataContainer.addItem(metadataKeyName);
item.getItemProperty(METADATA_KEY).setValue(metadataKeyName); item.getItemProperty(METADATA_KEY).setValue(metadataKeyName);
@@ -116,7 +113,7 @@ public class DistributionSetMetadatadetailslayout extends Table{
* *
* @param metadataKeyName * @param metadataKeyName
*/ */
public void deleteMetadata(final String metadataKeyName){ public void deleteMetadata(final String metadataKeyName) {
final IndexedContainer metadataContainer = (IndexedContainer) getContainerDataSource(); final IndexedContainer metadataContainer = (IndexedContainer) getContainerDataSource();
metadataContainer.removeItem(metadataKeyName); metadataContainer.removeItem(metadataKeyName);
} }
@@ -132,8 +129,8 @@ public class DistributionSetMetadatadetailslayout extends Table{
setColumnHeaderMode(ColumnHeaderMode.EXPLICIT); setColumnHeaderMode(ColumnHeaderMode.EXPLICIT);
addDSMetadataTableHeader(); addDSMetadataTableHeader();
setSizeFull(); setSizeFull();
//same as height of other tabs in details tabsheet // same as height of other tabs in details tabsheet
setHeight(116,Unit.PIXELS); setHeight(116, Unit.PIXELS);
} }
private IndexedContainer getDistSetContainer() { private IndexedContainer getDistSetContainer() {
@@ -154,21 +151,19 @@ public class DistributionSetMetadatadetailslayout extends Table{
setColumnHeader(METADATA_KEY, i18n.get("header.key")); setColumnHeader(METADATA_KEY, i18n.get("header.key"));
} }
private void setDSMetadataProperties(final DistributionSetMetadata dsMetadata) {
private void setDSMetadataProperties(final DistributionSetMetadata dsMetadata){
final Item item = getContainerDataSource().addItem(dsMetadata.getKey()); final Item item = getContainerDataSource().addItem(dsMetadata.getKey());
item.getItemProperty(METADATA_KEY).setValue(dsMetadata.getKey()); item.getItemProperty(METADATA_KEY).setValue(dsMetadata.getKey());
} }
private void addCustomGeneratedColumns() { private void addCustomGeneratedColumns() {
addGeneratedColumn(METADATA_KEY, addGeneratedColumn(METADATA_KEY, (source, itemId, columnId) -> customMetadataDetailButton((String) itemId));
(source, itemId, columnId) -> customMetadataDetailButton((String) itemId));
} }
private Button customMetadataDetailButton(final String metadataKey) { private Button customMetadataDetailButton(final String metadataKey) {
final Button viewIcon = SPUIComponentProvider.getButton(getDetailLinkId(metadataKey), metadataKey, "View " final Button viewIcon = SPUIComponentProvider.getButton(getDetailLinkId(metadataKey), metadataKey,
+ metadataKey + " Metadata details", null, false, null, SPUIButtonStyleSmallNoBorder.class); "View " + metadataKey + " Metadata details", null, false, null, SPUIButtonStyleSmallNoBorder.class);
viewIcon.setData(metadataKey); viewIcon.setData(metadataKey);
viewIcon.addStyleName(ValoTheme.BUTTON_TINY + " " + ValoTheme.BUTTON_LINK + " " + "on-focus-no-border link" viewIcon.addStyleName(ValoTheme.BUTTON_TINY + " " + ValoTheme.BUTTON_LINK + " " + "on-focus-no-border link"
+ " " + "text-style"); + " " + "text-style");
@@ -177,16 +172,15 @@ public class DistributionSetMetadatadetailslayout extends Table{
} }
private static String getDetailLinkId(final String name) { private static String getDetailLinkId(final String name) {
return new StringBuilder(SPUIComponentIdProvider.DS_METADATA_DETAIL_LINK).append('.').append(name) return new StringBuilder(SPUIComponentIdProvider.DS_METADATA_DETAIL_LINK).append('.').append(name).toString();
.toString();
} }
private void showMetadataDetails(final Long selectedDistSetId , final String metadataKey) { private void showMetadataDetails(final Long selectedDistSetId, final String metadataKey) {
DistributionSet distSet = distributionSetManagement.findDistributionSetById(selectedDistSetId); final DistributionSet distSet = distributionSetManagement.findDistributionSetById(selectedDistSetId);
/* display the window */ /* display the window */
UI.getCurrent().addWindow(dsMetadataPopupLayout.getWindow(distSet, UI.getCurrent().addWindow(dsMetadataPopupLayout.getWindow(distSet,
entityFactory.generateDistributionSetMetadata(distSet, metadataKey, "") )); entityFactory.generateDistributionSetMetadata(distSet, metadataKey, "")));
} }
} }

View File

@@ -8,6 +8,8 @@
*/ */
package org.eclipse.hawkbit.ui.common.filterlayout; package org.eclipse.hawkbit.ui.common.filterlayout;
import static org.eclipse.hawkbit.ui.utils.SPUIDefinitions.NO_TAG_BUTTON_ID;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -95,16 +97,12 @@ public abstract class AbstractFilterButtons extends Table {
container.addContainerProperty(SPUILabelDefinitions.VAR_NAME, String.class, null, true, true); container.addContainerProperty(SPUILabelDefinitions.VAR_NAME, String.class, null, true, true);
} }
@SuppressWarnings("serial")
protected void addColumn() { protected void addColumn() {
addGeneratedColumn(FILTER_BUTTON_COLUMN, (source, itemId, columnId) -> addGeneratedCell(itemId)); addGeneratedColumn(FILTER_BUTTON_COLUMN, (source, itemId, columnId) -> addGeneratedCell(itemId));
} }
/**
* @param itemId
* @return
*/
private DragAndDropWrapper addGeneratedCell(final Object itemId) { private DragAndDropWrapper addGeneratedCell(final Object itemId) {
final Item item = getItem(itemId); final Item item = getItem(itemId);
final Long id = (Long) item.getItemProperty(SPUILabelDefinitions.VAR_ID).getValue(); final Long id = (Long) item.getItemProperty(SPUILabelDefinitions.VAR_ID).getValue();
final String name = (String) item.getItemProperty(SPUILabelDefinitions.VAR_NAME).getValue(); final String name = (String) item.getItemProperty(SPUILabelDefinitions.VAR_NAME).getValue();
@@ -116,16 +114,18 @@ public abstract class AbstractFilterButtons extends Table {
? item.getItemProperty(SPUILabelDefinitions.VAR_COLOR).getValue().toString() : DEFAULT_GREEN; ? item.getItemProperty(SPUILabelDefinitions.VAR_COLOR).getValue().toString() : DEFAULT_GREEN;
final Button typeButton = createFilterButton(id, name, desc, color, itemId); final Button typeButton = createFilterButton(id, name, desc, color, itemId);
typeButton.addClickListener(event -> filterButtonClickBehaviour.processFilterButtonClick(event)); typeButton.addClickListener(event -> filterButtonClickBehaviour.processFilterButtonClick(event));
if (typeButton.getData().equals(SPUIDefinitions.NO_TAG_BUTTON_ID) && isNoTagSateSelected()) {
filterButtonClickBehaviour.setDefaultClickedButton(typeButton); if ((NO_TAG_BUTTON_ID.equals(typeButton.getData()) && isNoTagStateSelected())
} else if (id != null && isClickedByDefault(name)) { || (id != null && isClickedByDefault(name))) {
filterButtonClickBehaviour.setDefaultClickedButton(typeButton); filterButtonClickBehaviour.setDefaultClickedButton(typeButton);
} }
return createDragAndDropWrapper(typeButton, name, id); return createDragAndDropWrapper(typeButton, name, id);
} }
protected boolean isNoTagSateSelected() { protected boolean isNoTagStateSelected() {
return Boolean.FALSE; return false;
} }
private DragAndDropWrapper createDragAndDropWrapper(final Button tagButton, final String name, final Long id) { private DragAndDropWrapper createDragAndDropWrapper(final Button tagButton, final String name, final Long id) {

View File

@@ -15,9 +15,9 @@ import org.apache.commons.lang3.StringUtils;
import org.eclipse.hawkbit.repository.model.BaseEntity; import org.eclipse.hawkbit.repository.model.BaseEntity;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.common.UserDetailsFormatter;
import org.eclipse.hawkbit.ui.decorators.HeaderLayoutDecorator;
import org.eclipse.hawkbit.ui.decorators.SPUIButtonDecorator; import org.eclipse.hawkbit.ui.decorators.SPUIButtonDecorator;
import org.eclipse.hawkbit.ui.decorators.SPUIComboBoxDecorator; import org.eclipse.hawkbit.ui.decorators.SPUIComboBoxDecorator;
import org.eclipse.hawkbit.ui.decorators.HeaderLayoutDecorator;
import org.eclipse.hawkbit.ui.decorators.SPUILabelDecorator; import org.eclipse.hawkbit.ui.decorators.SPUILabelDecorator;
import org.eclipse.hawkbit.ui.decorators.SPUITextAreaDecorator; import org.eclipse.hawkbit.ui.decorators.SPUITextAreaDecorator;
import org.eclipse.hawkbit.ui.decorators.SPUITextFieldDecorator; import org.eclipse.hawkbit.ui.decorators.SPUITextFieldDecorator;
@@ -82,8 +82,6 @@ public final class SPUIComponentProvider {
/** /**
* Get HorizontalLayout UI component. * Get HorizontalLayout UI component.
* *
* @param className
* as Layout
* @return HorizontalLayout as UI * @return HorizontalLayout as UI
*/ */
public static HorizontalLayout getHorizontalLayout() { public static HorizontalLayout getHorizontalLayout() {
@@ -117,8 +115,7 @@ public final class SPUIComponentProvider {
hLayout = layoutDecorator.decorate(hLayout); hLayout = layoutDecorator.decorate(hLayout);
} catch (final InstantiationException | IllegalAccessException exception) { } catch (final InstantiationException | IllegalAccessException exception) {
LOG.error("Error occured while creating horizontal decorator " + HeaderLayoutDecorator.class, LOG.error("Error occured while creating horizontal decorator " + HeaderLayoutDecorator.class, exception);
exception);
} }
return hLayout; return hLayout;

View File

@@ -17,6 +17,7 @@ import com.vaadin.client.renderers.ClickableRenderer.RendererClickHandler;
import com.vaadin.shared.ui.Connect; import com.vaadin.shared.ui.Connect;
import elemental.json.JsonObject; import elemental.json.JsonObject;
/** /**
* A connector for {@link CustomObjectRenderer }. * A connector for {@link CustomObjectRenderer }.
* *
@@ -25,13 +26,13 @@ import elemental.json.JsonObject;
public class RolloutRendererConnector extends ClickableRendererConnector<RolloutRendererData> { public class RolloutRendererConnector extends ClickableRendererConnector<RolloutRendererData> {
private static final long serialVersionUID = 7734682321931830566L; private static final long serialVersionUID = 7734682321931830566L;
@Override
public org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRenderer getRenderer() { public org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRenderer getRenderer() {
return (org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRenderer) super.getRenderer(); return (org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRenderer) super.getRenderer();
} }
@Override @Override
protected HandlerRegistration addClickHandler( protected HandlerRegistration addClickHandler(final RendererClickHandler<JsonObject> handler) {
RendererClickHandler<JsonObject> handler) {
return getRenderer().addClickHandler(handler); return getRenderer().addClickHandler(handler);
} }
} }

View File

@@ -11,24 +11,16 @@ package org.eclipse.hawkbit.ui.customrenderers.client.renderers;
import java.io.Serializable; import java.io.Serializable;
/** /**
* RendererData class with Name and Status. * RendererData class with name and status.
*
*/ */
public class RolloutRendererData implements Serializable { public class RolloutRendererData implements Serializable {
private static final long serialVersionUID = -5018181529953620263L; private static final long serialVersionUID = -5018181529953620263L;
private String name; private String name;
private String status; private String status;
/**
* Initialize the RendererData.
*/
public RolloutRendererData() {
}
/** /**
* Initialize the RendererData. * Initialize the RendererData.
* *
@@ -37,8 +29,7 @@ public class RolloutRendererData implements Serializable {
* @param status * @param status
* Status of Rollout. * Status of Rollout.
*/ */
public RolloutRendererData(String name, String status) { public RolloutRendererData(final String name, final String status) {
super();
this.name = name; this.name = name;
this.status = status; this.status = status;
} }
@@ -47,7 +38,7 @@ public class RolloutRendererData implements Serializable {
return name; return name;
} }
public void setName(String name) { public void setName(final String name) {
this.name = name; this.name = name;
} }
@@ -55,8 +46,7 @@ public class RolloutRendererData implements Serializable {
return status; return status;
} }
public void setStatus(String status) { public void setStatus(final String status) {
this.status = status; this.status = status;
} }
} }

View File

@@ -16,11 +16,8 @@ import com.vaadin.ui.renderers.ClickableRenderer;
import elemental.json.JsonValue; import elemental.json.JsonValue;
/** /**
* Renders button with provided CustomObject. * Renders button with provided CustomObject. Used to display button with link.
* Used to display button with link.
*
*/ */
public class RolloutRenderer extends ClickableRenderer<RolloutRendererData> { public class RolloutRenderer extends ClickableRenderer<RolloutRendererData> {
private static final long serialVersionUID = -8754180585906263554L; private static final long serialVersionUID = -8754180585906263554L;
@@ -33,29 +30,30 @@ public class RolloutRenderer extends ClickableRenderer<RolloutRendererData> {
} }
/** /**
* Initialize custom object renderer with {@link Class<CustomObject>} * Initialize custom object renderer with the given type.
* *
* @param presentationType * @param presentationType
* Class<CustomObject> * Class<CustomObject>
*/ */
public RolloutRenderer(Class<RolloutRendererData> presentationType) { public RolloutRenderer(final Class<RolloutRendererData> presentationType) {
super(presentationType); super(presentationType);
} }
/** /**
* Creates a new custom object renderer and adds the given click listener to it. * Creates a new custom object renderer and adds the given click listener to
* it.
* *
* @param listener * @param listener
* the click listener to register * the click listener to register
*/ */
public RolloutRenderer(RendererClickListener listener) { public RolloutRenderer(final RendererClickListener listener) {
this(); this();
addClickListener(listener); addClickListener(listener);
} }
@Override @Override
public JsonValue encode(RolloutRendererData resource) { public JsonValue encode(final RolloutRendererData resource) {
return super.encode(resource, RolloutRendererData.class); return super.encode(resource, RolloutRendererData.class);
} }
} }

View File

@@ -21,9 +21,6 @@ import com.vaadin.ui.Window;
/** /**
* Decorator for Window. * Decorator for Window.
*
*
*
*/ */
public final class SPUIWindowDecorator { public final class SPUIWindowDecorator {
@@ -49,7 +46,9 @@ public final class SPUIWindowDecorator {
final Component content, final ClickListener saveButtonClickListener, final Component content, final ClickListener saveButtonClickListener,
final ClickListener cancelButtonClickListener, final String helpLink, final AbstractLayout layout, final ClickListener cancelButtonClickListener, final String helpLink, final AbstractLayout layout,
final I18N i18n) { final I18N i18n) {
CommonDialogWindow window = null;
CommonDialogWindow window;
if (SPUIDefinitions.CUSTOM_METADATA_WINDOW.equals(type)) { if (SPUIDefinitions.CUSTOM_METADATA_WINDOW.equals(type)) {
window = new CustomCommonDialogWindow(caption, content, helpLink, saveButtonClickListener, window = new CustomCommonDialogWindow(caption, content, helpLink, saveButtonClickListener,
cancelButtonClickListener, layout, i18n); cancelButtonClickListener, layout, i18n);
@@ -71,10 +70,10 @@ public final class SPUIWindowDecorator {
window.setClosable(true); window.setClosable(true);
} }
} }
return window; return window;
} }
/** /**
* Decorates window based on type. * Decorates window based on type.
* *

View File

@@ -117,5 +117,4 @@ public class DSTypeFilterButtons extends AbstractFilterButtons {
private void refreshTypeTable() { private void refreshTypeTable() {
setContainerDataSource(createButtonsLazyQueryContainer()); setContainerDataSource(createButtonsLazyQueryContainer());
} }
} }

View File

@@ -15,11 +15,9 @@ import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.SpPermissionChecker;
import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata;
import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState;
import org.eclipse.hawkbit.ui.common.AbstractMetadataPopupLayout; import org.eclipse.hawkbit.ui.common.AbstractMetadataPopupLayout;
import org.eclipse.hawkbit.ui.distributions.event.MetadataEvent; import org.eclipse.hawkbit.ui.distributions.event.MetadataEvent;
import org.eclipse.hawkbit.ui.distributions.event.MetadataEvent.MetadataUIEvent; import org.eclipse.hawkbit.ui.distributions.event.MetadataEvent.MetadataUIEvent;
import org.eclipse.hawkbit.ui.distributions.state.ManageDistUIState;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.SpringComponent;
@@ -27,7 +25,6 @@ import com.vaadin.spring.annotation.ViewScope;
/** /**
* Pop up layout to display software module metadata. * Pop up layout to display software module metadata.
*
*/ */
@SpringComponent @SpringComponent
@ViewScope @ViewScope
@@ -39,39 +36,35 @@ public class SwMetadataPopupLayout extends AbstractMetadataPopupLayout<SoftwareM
private transient SoftwareManagement softwareManagement; private transient SoftwareManagement softwareManagement;
@Autowired @Autowired
private ArtifactUploadState artifactUploadState; private transient EntityFactory entityFactory;
@Autowired
private EntityFactory entityFactory;
@Autowired
private ManageDistUIState manageDistUIState;
@Autowired @Autowired
protected SpPermissionChecker permChecker; protected SpPermissionChecker permChecker;
@Override @Override
protected void checkForDuplicate(SoftwareModule entity, String value) { protected void checkForDuplicate(final SoftwareModule entity, final String value) {
softwareManagement.findSoftwareModuleMetadata(entity, value); softwareManagement.findSoftwareModuleMetadata(entity, value);
} }
/** /**
* Create metadata for SWModule. * Create metadata for SWModule.
*/ */
@Override @Override
protected SoftwareModuleMetadata createMetadata(SoftwareModule entity, String key, String value) { protected SoftwareModuleMetadata createMetadata(final SoftwareModule entity, final String key, final String value) {
SoftwareModuleMetadata swMetadata = softwareManagement.createSoftwareModuleMetadata(entityFactory final SoftwareModuleMetadata swMetadata = softwareManagement
.generateSoftwareModuleMetadata(entity, key, value)); .createSoftwareModuleMetadata(entityFactory.generateSoftwareModuleMetadata(entity, key, value));
setSelectedEntity(swMetadata.getSoftwareModule()); setSelectedEntity(swMetadata.getSoftwareModule());
eventBus.publish(this, new MetadataEvent(MetadataUIEvent.CREATE_SOFTWARE_MODULE_METADATA, swMetadata)); eventBus.publish(this, new MetadataEvent(MetadataUIEvent.CREATE_SOFTWARE_MODULE_METADATA, swMetadata));
return swMetadata; return swMetadata;
} }
/** /**
* Update metadata for SWModule. * Update metadata for SWModule.
*/ */
@Override @Override
protected SoftwareModuleMetadata updateMetadata(SoftwareModule entity, String key, String value) { protected SoftwareModuleMetadata updateMetadata(final SoftwareModule entity, final String key, final String value) {
SoftwareModuleMetadata swMetadata = softwareManagement.updateSoftwareModuleMetadata(entityFactory final SoftwareModuleMetadata swMetadata = softwareManagement
.generateSoftwareModuleMetadata(entity, key, value)); .updateSoftwareModuleMetadata(entityFactory.generateSoftwareModuleMetadata(entity, key, value));
setSelectedEntity(swMetadata.getSoftwareModule()); setSelectedEntity(swMetadata.getSoftwareModule());
return swMetadata; return swMetadata;
} }
@@ -85,8 +78,8 @@ public class SwMetadataPopupLayout extends AbstractMetadataPopupLayout<SoftwareM
* delete metadata for SWModule. * delete metadata for SWModule.
*/ */
@Override @Override
protected void deleteMetadata(SoftwareModule entity, String key, String value) { protected void deleteMetadata(final SoftwareModule entity, final String key, final String value) {
SoftwareModuleMetadata swMetadata = entityFactory.generateSoftwareModuleMetadata(entity, key, value); final SoftwareModuleMetadata swMetadata = entityFactory.generateSoftwareModuleMetadata(entity, key, value);
softwareManagement.deleteSoftwareModuleMetadata(entity, key); softwareManagement.deleteSoftwareModuleMetadata(entity, key);
eventBus.publish(this, new MetadataEvent(MetadataUIEvent.DELETE_SOFTWARE_MODULE_METADATA, swMetadata)); eventBus.publish(this, new MetadataEvent(MetadataUIEvent.DELETE_SOFTWARE_MODULE_METADATA, swMetadata));
} }
@@ -100,5 +93,4 @@ public class SwMetadataPopupLayout extends AbstractMetadataPopupLayout<SoftwareM
protected boolean hasUpdatePermission() { protected boolean hasUpdatePermission() {
return permChecker.hasUpdateDistributionPermission(); return permChecker.hasUpdateDistributionPermission();
} }
} }

View File

@@ -8,6 +8,11 @@
*/ */
package org.eclipse.hawkbit.ui.distributions.smtype; package org.eclipse.hawkbit.ui.distributions.smtype;
import static org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleTypeEvent.SoftwareModuleTypeEnum.ADD_SOFTWARE_MODULE_TYPE;
import static org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleTypeEvent.SoftwareModuleTypeEnum.UPDATE_SOFTWARE_MODULE_TYPE;
import static org.eclipse.hawkbit.ui.utils.SPUIComponentIdProvider.SW_MODULE_TYPE_TABLE_ID;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_NAME;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@@ -19,7 +24,6 @@ import org.eclipse.hawkbit.ui.distributions.event.SaveActionWindowEvent;
import org.eclipse.hawkbit.ui.distributions.state.ManageDistUIState; import org.eclipse.hawkbit.ui.distributions.state.ManageDistUIState;
import org.eclipse.hawkbit.ui.utils.SPUIComponentIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIComponentIdProvider;
import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions;
import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.vaadin.addons.lazyquerycontainer.BeanQueryFactory; import org.vaadin.addons.lazyquerycontainer.BeanQueryFactory;
import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer; import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer;
@@ -35,10 +39,9 @@ import com.vaadin.spring.annotation.ViewScope;
/** /**
* Software Module Type filter buttons. * Software Module Type filter buttons.
*
*/ */
@SpringComponent
@ViewScope @ViewScope
@SpringComponent
public class DistSMTypeFilterButtons extends AbstractFilterButtons { public class DistSMTypeFilterButtons extends AbstractFilterButtons {
private static final long serialVersionUID = 6804534533362387433L; private static final long serialVersionUID = 6804534533362387433L;
@@ -51,7 +54,7 @@ public class DistSMTypeFilterButtons extends AbstractFilterButtons {
@Override @Override
protected String getButtonsTableId() { protected String getButtonsTableId() {
return SPUIComponentIdProvider.SW_MODULE_TYPE_TABLE_ID; return SW_MODULE_TYPE_TABLE_ID;
} }
@Override @Override
@@ -60,7 +63,7 @@ public class DistSMTypeFilterButtons extends AbstractFilterButtons {
final BeanQueryFactory<SoftwareModuleTypeBeanQuery> typeQF = new BeanQueryFactory<>( final BeanQueryFactory<SoftwareModuleTypeBeanQuery> typeQF = new BeanQueryFactory<>(
SoftwareModuleTypeBeanQuery.class); SoftwareModuleTypeBeanQuery.class);
typeQF.setQueryConfiguration(queryConfig); typeQF.setQueryConfiguration(queryConfig);
return new LazyQueryContainer(new LazyQueryDefinition(true, 20, SPUILabelDefinitions.VAR_NAME), typeQF); return new LazyQueryContainer(new LazyQueryDefinition(true, 20, VAR_NAME), typeQF);
} }
@Override @Override
@@ -70,8 +73,8 @@ public class DistSMTypeFilterButtons extends AbstractFilterButtons {
@Override @Override
protected boolean isClickedByDefault(final String typeName) { protected boolean isClickedByDefault(final String typeName) {
return manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType().isPresent() return manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType().isPresent() && manageDistUIState
&& manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType().get().getName().equals(typeName); .getSoftwareModuleFilters().getSoftwareModuleType().get().getName().equals(typeName);
} }
@Override @Override
@@ -104,13 +107,16 @@ public class DistSMTypeFilterButtons extends AbstractFilterButtons {
@EventBusListenerMethod(scope = EventScope.SESSION) @EventBusListenerMethod(scope = EventScope.SESSION)
void onEvent(final SoftwareModuleTypeEvent event) { void onEvent(final SoftwareModuleTypeEvent event) {
if (event.getSoftwareModuleTypeEnum() == SoftwareModuleTypeEvent.SoftwareModuleTypeEnum.ADD_SOFTWARE_MODULE_TYPE if (isCreateOrUpdate(event) && event.getSoftwareModuleType() != null) {
|| event.getSoftwareModuleTypeEnum() == SoftwareModuleTypeEvent.SoftwareModuleTypeEnum.UPDATE_SOFTWARE_MODULE_TYPE
&& event.getSoftwareModuleType() != null) {
refreshTypeTable(); refreshTypeTable();
} }
} }
private boolean isCreateOrUpdate(final SoftwareModuleTypeEvent event) {
return event.getSoftwareModuleTypeEnum() == ADD_SOFTWARE_MODULE_TYPE
|| event.getSoftwareModuleTypeEnum() == UPDATE_SOFTWARE_MODULE_TYPE;
}
@EventBusListenerMethod(scope = EventScope.SESSION) @EventBusListenerMethod(scope = EventScope.SESSION)
void onEvent(final SaveActionWindowEvent event) { void onEvent(final SaveActionWindowEvent event) {
if (event == SaveActionWindowEvent.SAVED_DELETE_SW_MODULE_TYPES) { if (event == SaveActionWindowEvent.SAVED_DELETE_SW_MODULE_TYPES) {
@@ -121,6 +127,4 @@ public class DistSMTypeFilterButtons extends AbstractFilterButtons {
private void refreshTypeTable() { private void refreshTypeTable() {
setContainerDataSource(createButtonsLazyQueryContainer()); setContainerDataSource(createButtonsLazyQueryContainer());
} }
} }

View File

@@ -8,8 +8,9 @@
*/ */
package org.eclipse.hawkbit.ui.distributions.state; package org.eclipse.hawkbit.ui.distributions.state;
import static java.util.Collections.emptySet;
import java.io.Serializable; import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
@@ -49,7 +50,7 @@ public class ManageDistUIState implements ManagmentEntityState<DistributionSetId
private DistributionSetIdName lastSelectedDistribution; private DistributionSetIdName lastSelectedDistribution;
private Set<Long> selectedSoftwareModules = Collections.emptySet(); private Set<Long> selectedSoftwareModules = emptySet();
private Set<String> selectedDeleteDistSetTypes = new HashSet<>(); private Set<String> selectedDeleteDistSetTypes = new HashSet<>();
@@ -57,23 +58,23 @@ public class ManageDistUIState implements ManagmentEntityState<DistributionSetId
private Long selectedBaseSwModuleId; private Long selectedBaseSwModuleId;
private boolean distTypeFilterClosed = Boolean.FALSE; private boolean distTypeFilterClosed;
private boolean swTypeFilterClosed = Boolean.FALSE; private boolean swTypeFilterClosed;
private final Map<Long, String> deleteSofwareModulesList = new HashMap<>(); private final Map<Long, String> deleteSofwareModulesList = new HashMap<>();
private boolean swModuleTableMaximized = Boolean.FALSE; private boolean swModuleTableMaximized;
private boolean dsTableMaximized = Boolean.FALSE; private boolean dsTableMaximized;
private final Map<String, SoftwareModuleIdName> assignedSoftwareModuleDetails = new HashMap<>(); private final Map<String, SoftwareModuleIdName> assignedSoftwareModuleDetails = new HashMap<>();
private final Map<DistributionSetIdName, HashMap<Long, HashSet<SoftwareModuleIdName>>> consolidatedDistSoftwarewList = new HashMap<>(); private final Map<DistributionSetIdName, HashMap<Long, HashSet<SoftwareModuleIdName>>> consolidatedDistSoftwarewList = new HashMap<>();
private boolean noDataAvilableSwModule = Boolean.FALSE; private boolean noDataAvilableSwModule;
private boolean noDataAvailableDist = Boolean.FALSE; private boolean noDataAvailableDist;
/** /**
* @return the manageDistFilters * @return the manageDistFilters
@@ -117,6 +118,7 @@ public class ManageDistUIState implements ManagmentEntityState<DistributionSetId
this.lastSelectedDistribution = value; this.lastSelectedDistribution = value;
} }
@Override
public void setSelectedEnitities(final Set<DistributionSetIdName> values) { public void setSelectedEnitities(final Set<DistributionSetIdName> values) {
selectedDistributions = values; selectedDistributions = values;
} }
@@ -223,7 +225,7 @@ public class ManageDistUIState implements ManagmentEntityState<DistributionSetId
/*** /***
* Set isDsModuleTableMaximized. * Set isDsModuleTableMaximized.
* *
* @param isDsModuleTableMaximized * @param dsModuleTableMaximized
*/ */
public void setDsTableMaximized(final boolean dsModuleTableMaximized) { public void setDsTableMaximized(final boolean dsModuleTableMaximized) {
dsTableMaximized = dsModuleTableMaximized; dsTableMaximized = dsModuleTableMaximized;
@@ -241,7 +243,7 @@ public class ManageDistUIState implements ManagmentEntityState<DistributionSetId
} }
/** /**
* @param isSwModuleTableMaximized * @param swModuleTableMaximized
* the isSwModuleTableMaximized to set * the isSwModuleTableMaximized to set
*/ */
public void setSwModuleTableMaximized(final boolean swModuleTableMaximized) { public void setSwModuleTableMaximized(final boolean swModuleTableMaximized) {
@@ -271,8 +273,8 @@ public class ManageDistUIState implements ManagmentEntityState<DistributionSetId
} }
/** /**
* @param noDilableDist * @param noDataAvailableDist
* the noDataAvailableDist to set * the isNoDataAvailableDist to set
*/ */
public void setNoDataAvailableDist(final boolean noDataAvailableDist) { public void setNoDataAvailableDist(final boolean noDataAvailableDist) {
this.noDataAvailableDist = noDataAvailableDist; this.noDataAvailableDist = noDataAvailableDist;

View File

@@ -114,10 +114,8 @@ public abstract class AbstractCreateUpdateTagLayout extends CustomComponent
/** /**
* Discard the changes and close the popup. * Discard the changes and close the popup.
*
* @param event
*/ */
protected void discard(final Button.ClickEvent event) { protected void discard() {
UI.getCurrent().removeWindow(window); UI.getCurrent().removeWindow(window);
} }
@@ -463,7 +461,7 @@ public abstract class AbstractCreateUpdateTagLayout extends CustomComponent
public CommonDialogWindow getWindow() { public CommonDialogWindow getWindow() {
reset(); reset();
window = SPUIWindowDecorator.getWindow(getWindowCaption(), null, SPUIDefinitions.CREATE_UPDATE_WINDOW, this, window = SPUIWindowDecorator.getWindow(getWindowCaption(), null, SPUIDefinitions.CREATE_UPDATE_WINDOW, this,
this::save, this::discard, null, mainLayout, i18n); this::save, cancleEvent -> discard(), null, mainLayout, i18n);
return window; return window;
} }

View File

@@ -118,12 +118,10 @@ public class CreateUpdateDistributionTagLayoutWindow extends AbstractCreateUpdat
/** /**
* RESET. * RESET.
*
* @param event
*/ */
@Override @Override
public void discard(final ClickEvent event) { public void discard() {
super.discard(event); super.discard();
resetDistTagValues(); resetDistTagValues();
} }

View File

@@ -121,7 +121,7 @@ public class DistributionTagButtons extends AbstractFilterButtons {
} }
@Override @Override
protected boolean isNoTagSateSelected() { protected boolean isNoTagStateSelected() {
return managementUIState.getDistributionTableFilters().isNoTagSelected(); return managementUIState.getDistributionTableFilters().isNoTagSelected();
} }

View File

@@ -391,7 +391,6 @@ public class BulkUploadHandler extends CustomComponent
eventBus.publish(this, new BulkUploadValidationMessageEvent(errorMessage.toString())); eventBus.publish(this, new BulkUploadValidationMessageEvent(errorMessage.toString()));
} }
} }
}
private void addNewTarget(final String controllerId, final String name) { private void addNewTarget(final String controllerId, final String name) {
final String newControllerId = HawkbitCommonUtil.trimAndNullIfEmpty(controllerId); final String newControllerId = HawkbitCommonUtil.trimAndNullIfEmpty(controllerId);
@@ -408,6 +407,7 @@ public class BulkUploadHandler extends CustomComponent
} }
} }
}
private static void setTargetValues(final Target target, final String name, final String description) { private static void setTargetValues(final Target target, final String name, final String description) {
if (null == name) { if (null == name) {

View File

@@ -131,7 +131,7 @@ public class TargetTagFilterButtons extends AbstractFilterButtons {
} }
@Override @Override
protected boolean isNoTagSateSelected() { protected boolean isNoTagStateSelected() {
return managementUIState.getTargetTableFilters().isNoTagSelected(); return managementUIState.getTargetTableFilters().isNoTagSelected();
} }

View File

@@ -37,6 +37,7 @@ import com.vaadin.spring.annotation.SpringComponent;
import com.vaadin.spring.annotation.UIScope; import com.vaadin.spring.annotation.UIScope;
import com.vaadin.ui.Alignment; import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button; import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Component; import com.vaadin.ui.Component;
import com.vaadin.ui.CustomComponent; import com.vaadin.ui.CustomComponent;
@@ -52,14 +53,11 @@ import com.vaadin.ui.themes.ValoTheme;
* A responsive menu component providing user information and the controls for * A responsive menu component providing user information and the controls for
* primary navigation between the views. * primary navigation between the views.
*/ */
@SpringComponent
@UIScope @UIScope
@SpringComponent
public final class DashboardMenu extends CustomComponent { public final class DashboardMenu extends CustomComponent {
private static final String STYLE_VISIBLE = "valo-menu-visible"; private static final String ID = "dashboard-menu";
public static final String ID = "dashboard-menu";
public static final String REPORTS_BADGE_ID = "dashboard-menu-reports-badge";
public static final String NOTIFICATIONS_BADGE_ID = "dashboard-menu-notifications-badge";
@Autowired @Autowired
private I18N i18n; private I18N i18n;
@@ -208,13 +206,7 @@ public final class DashboardMenu extends CustomComponent {
} }
private Component buildToggleButton() { private Component buildToggleButton() {
final Button valoMenuToggleButton = new Button("Menu", (ClickListener) event -> { final Button valoMenuToggleButton = new Button("Menu", new MenuToggleClickListenerMyClickListener());
if (getCompositionRoot().getStyleName().contains(STYLE_VISIBLE)) {
getCompositionRoot().removeStyleName(STYLE_VISIBLE);
} else {
getCompositionRoot().addStyleName(STYLE_VISIBLE);
}
});
valoMenuToggleButton.setIcon(FontAwesome.LIST); valoMenuToggleButton.setIcon(FontAwesome.LIST);
valoMenuToggleButton.addStyleName("valo-menu-toggle"); valoMenuToggleButton.addStyleName("valo-menu-toggle");
valoMenuToggleButton.addStyleName(ValoTheme.BUTTON_BORDERLESS); valoMenuToggleButton.addStyleName(ValoTheme.BUTTON_BORDERLESS);
@@ -329,15 +321,28 @@ public final class DashboardMenu extends CustomComponent {
return accessDeined; return accessDeined;
} }
private class MenuToggleClickListenerMyClickListener implements ClickListener {
private static final long serialVersionUID = 1L;
private static final String STYLE_VISIBLE = "valo-menu-visible";
@Override
public void buttonClick(final ClickEvent event) {
if (getCompositionRoot().getStyleName().contains(STYLE_VISIBLE)) {
getCompositionRoot().removeStyleName(STYLE_VISIBLE);
} else {
getCompositionRoot().addStyleName(STYLE_VISIBLE);
}
}
}
/** /**
* An menu item button wrapper for the dashboard menu item. * An menu item button wrapper for the dashboard menu item.
*
*
*
*
*/ */
public static final class ValoMenuItemButton extends Button { public static final class ValoMenuItemButton extends Button {
private static final long serialVersionUID = 1L;
private static final String STYLE_SELECTED = "selected"; private static final String STYLE_SELECTED = "selected";
private final DashboardMenuItem view; private final DashboardMenuItem view;
@@ -358,7 +363,6 @@ public final class DashboardMenu extends CustomComponent {
/* Avoid double click */ /* Avoid double click */
setDisableOnClick(true); setDisableOnClick(true);
addClickListener(event -> event.getComponent().getUI().getNavigator().navigateTo(view.getViewName())); addClickListener(event -> event.getComponent().getUI().getNavigator().navigateTo(view.getViewName()));
} }
/** /**

View File

@@ -20,6 +20,7 @@ import org.vaadin.alump.distributionbar.gwt.client.GwtDistributionBar;
* *
*/ */
public final class DistributionBarHelper { public final class DistributionBarHelper {
private static final String HTML_DIV_END = "</div>";
private static final int PARENT_SIZE_IN_PCT = 100; private static final int PARENT_SIZE_IN_PCT = 100;
private static final double MINIMUM_PART_SIZE = 10; private static final double MINIMUM_PART_SIZE = 10;
private static final String DISTRIBUTION_BAR_PART_MAIN_STYLE = GwtDistributionBar.CLASSNAME + "-part"; private static final String DISTRIBUTION_BAR_PART_MAIN_STYLE = GwtDistributionBar.CLASSNAME + "-part";
@@ -38,23 +39,23 @@ public final class DistributionBarHelper {
* *
* @return string of format "status1:count,status2:count" * @return string of format "status1:count,status2:count"
*/ */
public static String getDistributionBarAsHTMLString(Map<Status, Long> statusTotalCountMap) { public static String getDistributionBarAsHTMLString(final Map<Status, Long> statusTotalCountMap) {
StringBuilder htmlString = new StringBuilder(); final StringBuilder htmlString = new StringBuilder();
Map<Status, Long> statusMapWithNonZeroValues = getStatusMapWithNonZeroValues(statusTotalCountMap); final Map<Status, Long> statusMapWithNonZeroValues = getStatusMapWithNonZeroValues(statusTotalCountMap);
Long totalValue = getTotalSizes(statusTotalCountMap); final Long totalValue = getTotalSizes(statusTotalCountMap);
if (statusMapWithNonZeroValues.size() <= 0) { if (statusMapWithNonZeroValues.size() <= 0) {
return getUnintialisedBar(); return getUnintialisedBar();
} }
int partIndex = 1; int partIndex = 1;
htmlString.append(getParentDivStart()); htmlString.append(getParentDivStart());
for (Map.Entry<Status, Long> entry : statusMapWithNonZeroValues.entrySet()) { for (final Map.Entry<Status, Long> entry : statusMapWithNonZeroValues.entrySet()) {
if (entry.getValue() > 0) { if (entry.getValue() > 0) {
htmlString.append(getPart(partIndex, entry.getKey(), entry.getValue(), totalValue, htmlString.append(getPart(partIndex, entry.getKey(), entry.getValue(), totalValue,
statusMapWithNonZeroValues.size())); statusMapWithNonZeroValues.size()));
partIndex++; partIndex++;
} }
} }
htmlString.append(getParentDivEnd()); htmlString.append(HTML_DIV_END);
return htmlString.toString(); return htmlString.toString();
} }
@@ -65,7 +66,7 @@ public final class DistributionBarHelper {
* map with status and count * map with status and count
* @return map with non zero values * @return map with non zero values
*/ */
public static Map<Status, Long> getStatusMapWithNonZeroValues(Map<Status, Long> statusTotalCountMap) { public static Map<Status, Long> getStatusMapWithNonZeroValues(final Map<Status, Long> statusTotalCountMap) {
return statusTotalCountMap.entrySet().stream().filter(p -> p.getValue() > 0) return statusTotalCountMap.entrySet().stream().filter(p -> p.getValue() > 0)
.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue())); .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
} }
@@ -77,19 +78,20 @@ public final class DistributionBarHelper {
* map with status and count details * map with status and count details
* @return tool tip * @return tool tip
*/ */
public static String getTooltip(Map<Status, Long> statusCountMap) { public static String getTooltip(final Map<Status, Long> statusCountMap) {
Map<Status, Long> nonZeroStatusCountMap = DistributionBarHelper.getStatusMapWithNonZeroValues(statusCountMap); final Map<Status, Long> nonZeroStatusCountMap = DistributionBarHelper
StringBuilder tooltip = new StringBuilder(); .getStatusMapWithNonZeroValues(statusCountMap);
for (Entry<Status, Long> entry : nonZeroStatusCountMap.entrySet()) { final StringBuilder tooltip = new StringBuilder();
for (final Entry<Status, Long> entry : nonZeroStatusCountMap.entrySet()) {
tooltip.append(entry.getKey().toString().toLowerCase()).append(" : ").append(entry.getValue()) tooltip.append(entry.getKey().toString().toLowerCase()).append(" : ").append(entry.getValue())
.append("<br>"); .append("<br>");
} }
return tooltip.toString(); return tooltip.toString();
} }
private static String getPartStyle(int partIndex, int noOfParts, String customStyle) { private static String getPartStyle(final int partIndex, final int noOfParts, final String customStyle) {
StringBuilder mainStyle = new StringBuilder(); final StringBuilder mainStyle = new StringBuilder();
StringBuilder styleName = new StringBuilder(GwtDistributionBar.CLASSNAME); final StringBuilder styleName = new StringBuilder(GwtDistributionBar.CLASSNAME);
if (noOfParts == 1) { if (noOfParts == 1) {
styleName.append("-only"); styleName.append("-only");
} else if (partIndex == 1) { } else if (partIndex == 1) {
@@ -108,15 +110,16 @@ public final class DistributionBarHelper {
return mainStyle.toString(); return mainStyle.toString();
} }
private static String getPartWidth(Long value, Long totalValue, int noOfParts) { private static String getPartWidth(final Long value, final Long totalValue, final int noOfParts) {
final double minTotalSize = MINIMUM_PART_SIZE * noOfParts; final double minTotalSize = MINIMUM_PART_SIZE * noOfParts;
final double availableSize = PARENT_SIZE_IN_PCT - minTotalSize; final double availableSize = PARENT_SIZE_IN_PCT - minTotalSize;
double val = MINIMUM_PART_SIZE + (double) value / totalValue * availableSize; final double val = MINIMUM_PART_SIZE + (double) value / totalValue * availableSize;
return String.format("%.3f", val) + "%"; return String.format("%.3f", val) + "%";
} }
private static String getPart(int partIndex, Status status, Long value, Long totalValue, int noOfParts) { private static String getPart(final int partIndex, final Status status, final Long value, final Long totalValue,
String partValue = status.toString().toLowerCase(); final int noOfParts) {
final String partValue = status.toString().toLowerCase();
return "<div class=\"" + getPartStyle(partIndex, noOfParts, partValue) + "\" style=\"width: " return "<div class=\"" + getPartStyle(partIndex, noOfParts, partValue) + "\" style=\"width: "
+ getPartWidth(value, totalValue, noOfParts) + ";\"><span class=\"" + getPartWidth(value, totalValue, noOfParts) + ";\"><span class=\""
+ DISTRIBUTION_BAR_PART_VALUE_CLASSNAME + "\">" + value + "</span></div>"; + DISTRIBUTION_BAR_PART_VALUE_CLASSNAME + "\">" + value + "</span></div>";
@@ -127,9 +130,9 @@ public final class DistributionBarHelper {
+ DISTRIBUTION_BAR_PART_VALUE_CLASSNAME + "\">uninitialized</span></div>"; + DISTRIBUTION_BAR_PART_VALUE_CLASSNAME + "\">uninitialized</span></div>";
} }
private static Long getTotalSizes(Map<Status, Long> statusTotalCountMap) { private static Long getTotalSizes(final Map<Status, Long> statusTotalCountMap) {
Long total = 0L; Long total = 0L;
for (Long value : statusTotalCountMap.values()) { for (final Long value : statusTotalCountMap.values()) {
total = total + value; total = total + value;
} }
return total; return total;
@@ -139,8 +142,4 @@ public final class DistributionBarHelper {
return "<div class=\"" + GwtDistributionBar.CLASSNAME return "<div class=\"" + GwtDistributionBar.CLASSNAME
+ "\" style=\"width: 100%; height: 100%;\" id=\"rollout.status.progress.bar.id\">"; + "\" style=\"width: 100%; height: 100%;\" id=\"rollout.status.progress.bar.id\">";
} }
private static String getParentDivEnd() {
return "</div>";
}
} }

View File

@@ -499,14 +499,6 @@ public class AddUpdateRolloutWindowLayout extends GridLayout {
return errorThresoldPercent; return errorThresoldPercent;
} }
private boolean validateFields() {
if (!noOfGroups.isValid() || !errorThreshold.isValid() || !triggerThreshold.isValid()) {
uiNotification.displayValidationError(i18n.get("message.correct.invalid.value"));
return false;
}
return true;
}
private boolean duplicateCheck() { private boolean duplicateCheck() {
if (rolloutManagement.findRolloutByName(getRolloutName()) != null) { if (rolloutManagement.findRolloutByName(getRolloutName()) != null) {
uiNotification.displayValidationError( uiNotification.displayValidationError(

View File

@@ -242,6 +242,12 @@ public class RolloutGroupListGrid extends AbstractGrid {
} }
} }
private void onClickOfRolloutGroupName(final RendererClickEvent event) {
rolloutUIState
.setRolloutGroup(rolloutGroupManagement.findRolloutGroupWithDetailedStatus((Long) event.getItemId()));
eventBus.publish(this, RolloutEvent.SHOW_ROLLOUT_GROUP_TARGETS);
}
@Override @Override
protected void setHiddenColumns() { protected void setHiddenColumns() {
final List<Object> columnsToBeHidden = new ArrayList<>(); final List<Object> columnsToBeHidden = new ArrayList<>();
@@ -261,12 +267,6 @@ public class RolloutGroupListGrid extends AbstractGrid {
return this::getDescription; return this::getDescription;
} }
private void onClickOfRolloutGroupName(final RendererClickEvent event) {
rolloutUIState
.setRolloutGroup(rolloutGroupManagement.findRolloutGroupWithDetailedStatus((Long) event.getItemId()));
eventBus.publish(this, RolloutEvent.SHOW_ROLLOUT_GROUP_TARGETS);
}
private void createRolloutGroupStatusToFontMap() { private void createRolloutGroupStatusToFontMap() {
statusIconMap.put(RolloutGroupStatus.FINISHED, statusIconMap.put(RolloutGroupStatus.FINISHED,
new StatusFontIcon(FontAwesome.CHECK_CIRCLE, SPUIStyleDefinitions.STATUS_ICON_GREEN)); new StatusFontIcon(FontAwesome.CHECK_CIRCLE, SPUIStyleDefinitions.STATUS_ICON_GREEN));

View File

@@ -161,13 +161,13 @@ public class AuthenticationConfigurationView extends BaseConfigurationView
final CheckBox checkBox = (CheckBox) event.getProperty(); final CheckBox checkBox = (CheckBox) event.getProperty();
AuthenticationConfigurationItem configurationItem; AuthenticationConfigurationItem configurationItem;
if (checkBox == gatewaySecTokenCheckBox) { if (gatewaySecTokenCheckBox.equals(checkBox)) {
configurationItem = gatewaySecurityTokenAuthenticationConfigurationItem; configurationItem = gatewaySecurityTokenAuthenticationConfigurationItem;
} else if (checkBox == targetSecTokenCheckBox) { } else if (targetSecTokenCheckBox.equals(checkBox)) {
configurationItem = targetSecurityTokenAuthenticationConfigurationItem; configurationItem = targetSecurityTokenAuthenticationConfigurationItem;
} else if (checkBox == certificateAuthCheckbox) { } else if (certificateAuthCheckbox.equals(checkBox)) {
configurationItem = certificateAuthenticationConfigurationItem; configurationItem = certificateAuthenticationConfigurationItem;
} else if (checkBox == downloadAnonymousCheckBox) { } else if (downloadAnonymousCheckBox.equals(checkBox)) {
configurationItem = anonymousDownloadAuthenticationConfigurationItem; configurationItem = anonymousDownloadAuthenticationConfigurationItem;
} else { } else {
return; return;

View File

@@ -441,7 +441,7 @@ public final class HawkbitCommonUtil {
*/ */
public static float findRequiredExtraHeight(final float newBrowserHeight) { public static float findRequiredExtraHeight(final float newBrowserHeight) {
return newBrowserHeight > SPUIDefinitions.REQ_MIN_BROWSER_HEIGHT return newBrowserHeight > SPUIDefinitions.REQ_MIN_BROWSER_HEIGHT
? newBrowserHeight - SPUIDefinitions.REQ_MIN_BROWSER_HEIGHT : 0; ? (newBrowserHeight - SPUIDefinitions.REQ_MIN_BROWSER_HEIGHT) : 0;
} }
/** /**
@@ -453,7 +453,7 @@ public final class HawkbitCommonUtil {
*/ */
public static float findRequiredSwModuleExtraHeight(final float newBrowserHeight) { public static float findRequiredSwModuleExtraHeight(final float newBrowserHeight) {
return newBrowserHeight > SPUIDefinitions.REQ_MIN_UPLOAD_BROWSER_HEIGHT return newBrowserHeight > SPUIDefinitions.REQ_MIN_UPLOAD_BROWSER_HEIGHT
? newBrowserHeight - SPUIDefinitions.REQ_MIN_UPLOAD_BROWSER_HEIGHT : 0; ? (newBrowserHeight - SPUIDefinitions.REQ_MIN_UPLOAD_BROWSER_HEIGHT) : 0;
} }
/** /**
@@ -465,7 +465,7 @@ public final class HawkbitCommonUtil {
*/ */
public static float findRequiredSwModuleExtraWidth(final float newBrowserWidth) { public static float findRequiredSwModuleExtraWidth(final float newBrowserWidth) {
return newBrowserWidth > SPUIDefinitions.REQ_MIN_UPLOAD_BROWSER_WIDTH return newBrowserWidth > SPUIDefinitions.REQ_MIN_UPLOAD_BROWSER_WIDTH
? newBrowserWidth - SPUIDefinitions.REQ_MIN_UPLOAD_BROWSER_WIDTH : 0; ? (newBrowserWidth - SPUIDefinitions.REQ_MIN_UPLOAD_BROWSER_WIDTH) : 0;
} }
/** /**
@@ -528,7 +528,7 @@ public final class HawkbitCommonUtil {
*/ */
public static float findExtraWidth(final float newBrowserWidth) { public static float findExtraWidth(final float newBrowserWidth) {
return newBrowserWidth > SPUIDefinitions.REQ_MIN_BROWSER_WIDTH return newBrowserWidth > SPUIDefinitions.REQ_MIN_BROWSER_WIDTH
? newBrowserWidth - SPUIDefinitions.REQ_MIN_BROWSER_WIDTH : 0; ? (newBrowserWidth - SPUIDefinitions.REQ_MIN_BROWSER_WIDTH) : 0;
} }
/** /**
@@ -570,7 +570,7 @@ public final class HawkbitCommonUtil {
final float requiredExtraWidth = findExtraWidth(newBrowserWidth); final float requiredExtraWidth = findExtraWidth(newBrowserWidth);
float expectedDistWidth = minTableWidth; float expectedDistWidth = minTableWidth;
if (requiredExtraWidth > 0) { if (requiredExtraWidth > 0) {
expectedDistWidth = expectedDistWidth + Math.round(requiredExtraWidth * 0.5f); expectedDistWidth = expectedDistWidth + Math.round(requiredExtraWidth * 0.5F);
} }
return expectedDistWidth; return expectedDistWidth;
} }
@@ -741,6 +741,8 @@ public final class HawkbitCommonUtil {
* base software module type * base software module type
* @param description * @param description
* base software module description * base software module description
* @param entityFactory
* the entity factory to create new entity instances
* @return BaseSoftwareModule new base software module * @return BaseSoftwareModule new base software module
*/ */
public static SoftwareModule addNewBaseSoftware(final EntityFactory entityFactory, final String bsname, public static SoftwareModule addNewBaseSoftware(final EntityFactory entityFactory, final String bsname,

View File

@@ -273,10 +273,6 @@ public final class SPUIDefinitions {
* New Target save icon id. * New Target save icon id.
*/ */
public static final String NEW_TARGET_SAVE = "target.add.save"; public static final String NEW_TARGET_SAVE = "target.add.save";
/**
* New Target discard icon id.
*/
// public static final String NEW_TARGET_DISCARD = "target.add.discard";
/** /**
* New Target add icon id. * New Target add icon id.
*/ */