Upgrade sonar to new 6.2 installation (#456)

* Upgrade to new sonar instance. Fix new identified issues.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>
This commit is contained in:
Kai Zimmermann
2017-03-14 10:06:56 +01:00
committed by GitHub
parent 809fe4a8b6
commit 67d17fe661
66 changed files with 558 additions and 713 deletions

View File

@@ -5,7 +5,7 @@
Eclipse [hawkBit](https://projects.eclipse.org/projects/iot.hawkbit) is an domain independent back end solution for rolling out software updates to constrained edge devices as well as more powerful controllers and gateways connected to IP based networking infrastructure. Eclipse [hawkBit](https://projects.eclipse.org/projects/iot.hawkbit) is an domain independent back end solution for rolling out software updates to constrained edge devices as well as more powerful controllers and gateways connected to IP based networking infrastructure.
Build: [![Circle CI](https://circleci.com/gh/eclipse/hawkbit.svg?style=shield)](https://circleci.com/gh/eclipse/hawkbit) Build: [![Circle CI](https://circleci.com/gh/eclipse/hawkbit.svg?style=shield)](https://circleci.com/gh/eclipse/hawkbit)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/83b1ace1fba94ea2aec93b202b52f39a)](https://www.codacy.com/app/kai-zimmermann/hawkbit?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=eclipse/hawkbit&amp;utm_campaign=Badge_Grade) [![SonarQuality](https://sonar.eu-gb.mybluemix.net/api/badges/gate?key=org.eclipse.hawkbit:hawkbit-parent)](https://sonar.eu-gb.mybluemix.net) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.eclipse.hawkbit/hawkbit-parent/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.eclipse.hawkbit/hawkbit-parent) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/83b1ace1fba94ea2aec93b202b52f39a)](https://www.codacy.com/app/kai-zimmermann/hawkbit?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=eclipse/hawkbit&amp;utm_campaign=Badge_Grade) [![SonarQuality](https://sonar.ops.bosch-iot-rollouts.com/api/badges/gate?key=org.eclipse.hawkbit:hawkbit-parent)](https://sonar.ops.bosch-iot-rollouts.com) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.eclipse.hawkbit/hawkbit-parent/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.eclipse.hawkbit/hawkbit-parent)
# Documentation # Documentation

View File

@@ -8,8 +8,6 @@
*/ */
package org.eclipse.hawkbit.simulator; package org.eclipse.hawkbit.simulator;
import static java.util.concurrent.Executors.newScheduledThreadPool;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
@@ -46,7 +44,7 @@ public class DeviceSimulator {
*/ */
@Bean @Bean
public ScheduledExecutorService threadPool() { public ScheduledExecutorService threadPool() {
return newScheduledThreadPool(8); return Executors.newScheduledThreadPool(8);
} }
/** /**

View File

@@ -8,8 +8,6 @@
*/ */
package org.eclipse.hawkbit.simulator; package org.eclipse.hawkbit.simulator;
import static org.eclipse.hawkbit.simulator.amqp.AmqpProperties.CONFIGURATION_PREFIX;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
@@ -84,7 +82,7 @@ public class SimulationController {
if (protocol == Protocol.DMF_AMQP && isDmfDisabled()) { if (protocol == Protocol.DMF_AMQP && isDmfDisabled()) {
return ResponseEntity.badRequest() return ResponseEntity.badRequest()
.body("The AMQP interface has been disabled, to use DMF protocol you need to enable the AMQP interface via '" .body("The AMQP interface has been disabled, to use DMF protocol you need to enable the AMQP interface via '"
+ CONFIGURATION_PREFIX + ".enabled=true'"); + AmqpProperties.CONFIGURATION_PREFIX + ".enabled=true'");
} }
for (int i = 0; i < amount; i++) { for (int i = 0; i < amount; i++) {

View File

@@ -8,8 +8,6 @@
*/ */
package org.eclipse.hawkbit.simulator.amqp; package org.eclipse.hawkbit.simulator.amqp;
import static org.eclipse.hawkbit.simulator.amqp.AmqpProperties.CONFIGURATION_PREFIX;
import java.time.Duration; import java.time.Duration;
import java.util.Map; import java.util.Map;
@@ -43,7 +41,7 @@ import com.google.common.collect.Maps;
*/ */
@Configuration @Configuration
@EnableConfigurationProperties(AmqpProperties.class) @EnableConfigurationProperties(AmqpProperties.class)
@ConditionalOnProperty(prefix = CONFIGURATION_PREFIX, name = "enabled") @ConditionalOnProperty(prefix = AmqpProperties.CONFIGURATION_PREFIX, name = "enabled")
public class AmqpConfiguration { public class AmqpConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(AmqpConfiguration.class); private static final Logger LOGGER = LoggerFactory.getLogger(AmqpConfiguration.class);

View File

@@ -14,9 +14,6 @@ import java.time.LocalDateTime;
/** /**
* Object for holding attributes for a simulated update for the device * Object for holding attributes for a simulated update for the device
* simulator. * simulator.
*
*
*
*/ */
public class SimulatedUpdate implements Serializable { public class SimulatedUpdate implements Serializable {
@@ -27,7 +24,7 @@ public class SimulatedUpdate implements Serializable {
protected final Long actionId; protected final Long actionId;
protected LocalDateTime startCacheTime; protected transient LocalDateTime startCacheTime;
/** /**
* Constructor of the class. * Constructor of the class.

View File

@@ -8,8 +8,6 @@
*/ */
package org.eclipse.hawkbit.simulator.amqp; package org.eclipse.hawkbit.simulator.amqp;
import static org.eclipse.hawkbit.simulator.amqp.AmqpProperties.CONFIGURATION_PREFIX;
import java.util.Map; import java.util.Map;
import org.eclipse.hawkbit.dmf.amqp.api.EventTopic; import org.eclipse.hawkbit.dmf.amqp.api.EventTopic;
@@ -35,7 +33,7 @@ import com.google.common.collect.Lists;
* *
*/ */
@Component @Component
@ConditionalOnProperty(prefix = CONFIGURATION_PREFIX, name = "enabled") @ConditionalOnProperty(prefix = AmqpProperties.CONFIGURATION_PREFIX, name = "enabled")
public class SpReceiverService extends ReceiverService { public class SpReceiverService extends ReceiverService {
private static final Logger LOGGER = LoggerFactory.getLogger(ReceiverService.class); private static final Logger LOGGER = LoggerFactory.getLogger(ReceiverService.class);

View File

@@ -163,11 +163,10 @@ public class MongoDBArtifactStore implements ArtifactRepository {
storedArtifact = map(result); storedArtifact = map(result);
} }
} catch (final NoSuchAlgorithmException | IOException e) { } catch (final NoSuchAlgorithmException | IOException e) {
throw new ArtifactStoreException(e.getMessage(), e); throw new ArtifactStoreException(e);
} }
if (hash != null && hash.getMd5() != null if (notNull(hash, storedArtifact) && !storedArtifact.getHashes().getMd5().equalsIgnoreCase(hash.getMd5())) {
&& !storedArtifact.getHashes().getMd5().equalsIgnoreCase(hash.getMd5())) {
throw new HashNotMatchException("The given md5 hash " + hash.getMd5() throw new HashNotMatchException("The given md5 hash " + hash.getMd5()
+ " not matching the calculated md5 hash " + storedArtifact.getHashes().getMd5(), + " not matching the calculated md5 hash " + storedArtifact.getHashes().getMd5(),
HashNotMatchException.MD5); HashNotMatchException.MD5);
@@ -177,6 +176,10 @@ public class MongoDBArtifactStore implements ArtifactRepository {
} }
private static boolean notNull(final DbArtifactHash hash, final GridFsArtifact storedArtifact) {
return hash != null && hash.getMd5() != null && storedArtifact != null && storedArtifact.getHashes() != null;
}
private static String computeSHA1Hash(final InputStream stream, final OutputStream os, final String providedSHA1Sum) private static String computeSHA1Hash(final InputStream stream, final OutputStream os, final String providedSHA1Sum)
throws NoSuchAlgorithmException, IOException { throws NoSuchAlgorithmException, IOException {
String sha1Hash; String sha1Hash;
@@ -206,7 +209,7 @@ public class MongoDBArtifactStore implements ArtifactRepository {
* the list of mongoDB gridFs files. * the list of mongoDB gridFs files.
* @return a paged list of artifacts mapped from the given dbFiles * @return a paged list of artifacts mapped from the given dbFiles
*/ */
private List<DbArtifact> map(final List<GridFSDBFile> dbFiles) { private static List<DbArtifact> map(final List<GridFSDBFile> dbFiles) {
return dbFiles.stream().map(MongoDBArtifactStore::map).collect(Collectors.toList()); return dbFiles.stream().map(MongoDBArtifactStore::map).collect(Collectors.toList());
} }

View File

@@ -106,7 +106,9 @@ public class S3Repository implements ArtifactRepository {
} catch (final IOException e) { } catch (final IOException e) {
throw new ArtifactStoreException(e.getMessage(), e); throw new ArtifactStoreException(e.getMessage(), e);
} finally { } finally {
file.delete(); if (!file.delete()) {
LOG.error("Could not delete temp file {}", file);
}
} }
} }

View File

@@ -24,6 +24,8 @@ import java.util.List;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifactHash; import org.eclipse.hawkbit.artifact.repository.model.DbArtifactHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.io.BaseEncoding; import com.google.common.io.BaseEncoding;
@@ -44,6 +46,8 @@ import com.google.common.io.Files;
*/ */
public class ArtifactFilesystemRepository implements ArtifactRepository { public class ArtifactFilesystemRepository implements ArtifactRepository {
private static final Logger LOG = LoggerFactory.getLogger(ArtifactFilesystemRepository.class);
private static final String TEMP_FILE_PREFIX = "tmp"; private static final String TEMP_FILE_PREFIX = "tmp";
private static final String TEMP_FILE_SUFFIX = "artifactrepo"; private static final String TEMP_FILE_SUFFIX = "artifactrepo";
private final ArtifactFilesystemProperties artifactResourceProperties; private final ArtifactFilesystemProperties artifactResourceProperties;
@@ -119,7 +123,9 @@ public class ArtifactFilesystemRepository implements ArtifactRepository {
} catch (final IOException e) { } catch (final IOException e) {
throw new ArtifactStoreException(e.getMessage(), e); throw new ArtifactStoreException(e.getMessage(), e);
} catch (final HashNotMatchException e) { } catch (final HashNotMatchException e) {
file.delete(); if (!file.delete()) {
LOG.error("Could not delete temp file {}", file);
}
throw e; throw e;
} }
return artifact; return artifact;
@@ -138,7 +144,9 @@ public class ArtifactFilesystemRepository implements ArtifactRepository {
} }
} }
file.delete(); if (!file.delete()) {
LOG.debug("Could not delete temp file {}", file);
}
fileSystemArtifact.setArtifactId(artifact.getArtifactId()); fileSystemArtifact.setArtifactId(artifact.getArtifactId());
fileSystemArtifact.setContentType(artifact.getContentType()); fileSystemArtifact.setContentType(artifact.getContentType());
fileSystemArtifact.setHashes(artifact.getHashes()); fileSystemArtifact.setHashes(artifact.getHashes());

View File

@@ -8,8 +8,6 @@
*/ */
package org.eclipse.hawkbit.autoconfigure.cache; package org.eclipse.hawkbit.autoconfigure.cache;
import static com.google.common.cache.CacheBuilder.newBuilder;
import java.util.Collection; import java.util.Collection;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -87,7 +85,7 @@ public class CacheAutoConfiguration {
final GuavaCacheManager cacheManager = new GuavaCacheManager(); final GuavaCacheManager cacheManager = new GuavaCacheManager();
if (cacheProperties.getTtl() > 0) { if (cacheProperties.getTtl() > 0) {
final CacheBuilder<Object, Object> cacheBuilder = newBuilder() final CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder()
.expireAfterWrite(cacheProperties.getTtl(), cacheProperties.getTtlUnit()); .expireAfterWrite(cacheProperties.getTtl(), cacheProperties.getTtlUnit());
cacheManager.setCacheBuilder(cacheBuilder); cacheManager.setCacheBuilder(cacheBuilder);
} }

View File

@@ -8,8 +8,6 @@
*/ */
package org.eclipse.hawkbit.autoconfigure.cache; package org.eclipse.hawkbit.autoconfigure.cache;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
@@ -49,6 +47,6 @@ public class CacheProperties {
} }
public final TimeUnit getTtlUnit() { public final TimeUnit getTtlUnit() {
return MILLISECONDS; return TimeUnit.MILLISECONDS;
} }
} }

View File

@@ -8,10 +8,6 @@
*/ */
package org.eclipse.hawkbit.autoconfigure.security; package org.eclipse.hawkbit.autoconfigure.security;
import static com.google.common.collect.Lists.newArrayList;
import static org.springframework.context.annotation.AdviceMode.ASPECTJ;
import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;
import java.io.IOException; import java.io.IOException;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
@@ -55,8 +51,10 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.embedded.ServletListenerRegistrationBean; import org.springframework.boot.context.embedded.ServletListenerRegistrationBean;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
@@ -88,14 +86,16 @@ import org.vaadin.spring.security.web.VaadinRedirectStrategy;
import org.vaadin.spring.security.web.authentication.VaadinAuthenticationSuccessHandler; import org.vaadin.spring.security.web.authentication.VaadinAuthenticationSuccessHandler;
import org.vaadin.spring.security.web.authentication.VaadinUrlAuthenticationSuccessHandler; import org.vaadin.spring.security.web.authentication.VaadinUrlAuthenticationSuccessHandler;
import com.google.common.collect.Lists;
/** /**
* All configurations related to HawkBit's authentication and authorization * All configurations related to HawkBit's authentication and authorization
* layer. * layer.
*/ */
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, mode = ASPECTJ, proxyTargetClass = true, securedEnabled = true) @EnableGlobalMethodSecurity(prePostEnabled = true, mode = AdviceMode.ASPECTJ, proxyTargetClass = true, securedEnabled = true)
@Order(value = HIGHEST_PRECEDENCE) @Order(value = Ordered.HIGHEST_PRECEDENCE)
public class SecurityManagedConfiguration { public class SecurityManagedConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(SecurityManagedConfiguration.class); private static final Logger LOG = LoggerFactory.getLogger(SecurityManagedConfiguration.class);
@@ -217,7 +217,7 @@ public class SecurityManagedConfiguration {
final AnonymousAuthenticationFilter anoymousFilter = new AnonymousAuthenticationFilter( final AnonymousAuthenticationFilter anoymousFilter = new AnonymousAuthenticationFilter(
"controllerAnonymousFilter", "anonymous", "controllerAnonymousFilter", "anonymous",
newArrayList(new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS), Lists.newArrayList(new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS),
new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_DOWNLOAD_ROLE))); new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_DOWNLOAD_ROLE)));
anoymousFilter.setAuthenticationDetailsSource(authenticationDetailsSource); anoymousFilter.setAuthenticationDetailsSource(authenticationDetailsSource);
httpSec.requestMatchers().antMatchers("/*/controller/v1/**", "/*/controller/artifacts/v1/**").and() httpSec.requestMatchers().antMatchers("/*/controller/v1/**", "/*/controller/artifacts/v1/**").and()

View File

@@ -11,9 +11,6 @@ package org.eclipse.hawkbit.artifact.repository;
/** /**
* {@link ArtifactStoreException} is thrown in case storing of an artifact was * {@link ArtifactStoreException} is thrown in case storing of an artifact was
* not successful. * not successful.
*
*
*
*/ */
public class ArtifactStoreException extends RuntimeException { public class ArtifactStoreException extends RuntimeException {
@@ -25,7 +22,7 @@ public class ArtifactStoreException extends RuntimeException {
* @param message * @param message
* the message of the exception * the message of the exception
* @param cause * @param cause
* the cause of the exception * of the exception
*/ */
public ArtifactStoreException(final String message, final Throwable cause) { public ArtifactStoreException(final String message, final Throwable cause) {
super(message, cause); super(message, cause);
@@ -40,4 +37,14 @@ public class ArtifactStoreException extends RuntimeException {
public ArtifactStoreException(final String message) { public ArtifactStoreException(final String message) {
super(message); super(message);
} }
/**
* Constructs a ArtifactStoreException with cause.
*
* @param cause
* of the exception
*/
public ArtifactStoreException(final Throwable cause) {
super(cause);
}
} }

View File

@@ -8,9 +8,8 @@
*/ */
package org.eclipse.hawkbit.cache; package org.eclipse.hawkbit.cache;
import static java.util.Collections.emptyList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.hawkbit.tenancy.TenantAware;
@@ -64,7 +63,7 @@ public class TenantAwareCacheManager implements TenancyCacheManager {
public Collection<String> getCacheNames() { public Collection<String> getCacheNames() {
String currentTenant = tenantAware.getCurrentTenant(); String currentTenant = tenantAware.getCurrentTenant();
if (isTenantInvalid(currentTenant)) { if (isTenantInvalid(currentTenant)) {
return emptyList(); return Collections.emptyList();
} }
currentTenant = currentTenant.toUpperCase(); currentTenant = currentTenant.toUpperCase();

View File

@@ -8,9 +8,6 @@
*/ */
package org.eclipse.hawkbit.ddi.rest.resource; package org.eclipse.hawkbit.ddi.rest.resource;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -36,6 +33,7 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.rest.data.ResponseList; import org.eclipse.hawkbit.rest.data.ResponseList;
import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.hawkbit.tenancy.TenantAware;
import org.springframework.hateoas.Link; import org.springframework.hateoas.Link;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.http.HttpRequest; import org.springframework.http.HttpRequest;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
@@ -107,27 +105,30 @@ public final class DataConversionHelper {
if (action != null) { if (action != null) {
if (action.isCancelingOrCanceled()) { if (action.isCancelingOrCanceled()) {
result.add(linkTo( result.add(ControllerLinkBuilder
methodOn(DdiRootController.class, tenantAware.getCurrentTenant()).getControllerCancelAction( .linkTo(ControllerLinkBuilder.methodOn(DdiRootController.class, tenantAware.getCurrentTenant())
tenantAware.getCurrentTenant(), target.getControllerId(), action.getId())) .getControllerCancelAction(tenantAware.getCurrentTenant(), target.getControllerId(),
.withRel(DdiRestConstants.CANCEL_ACTION)); action.getId()))
.withRel(DdiRestConstants.CANCEL_ACTION));
} else { } else {
// we need to add the hashcode here of the actionWithStatus // we need to add the hashcode here of the actionWithStatus
// because the action might // because the action might
// have changed from 'soft' to 'forced' type and we need to // have changed from 'soft' to 'forced' type and we need to
// change the payload of the // change the payload of the
// response because of eTags. // response because of eTags.
result.add(linkTo(methodOn(DdiRootController.class, tenantAware.getCurrentTenant()) result.add(ControllerLinkBuilder
.getControllerBasedeploymentAction(tenantAware.getCurrentTenant(), target.getControllerId(), .linkTo(ControllerLinkBuilder.methodOn(DdiRootController.class, tenantAware.getCurrentTenant())
action.getId(), calculateEtag(action))) .getControllerBasedeploymentAction(tenantAware.getCurrentTenant(),
.withRel(DdiRestConstants.DEPLOYMENT_BASE_ACTION)); target.getControllerId(), action.getId(), calculateEtag(action)))
.withRel(DdiRestConstants.DEPLOYMENT_BASE_ACTION));
} }
} }
if (target.getTargetInfo().isRequestControllerAttributes()) { if (target.getTargetInfo().isRequestControllerAttributes()) {
result.add(linkTo(methodOn(DdiRootController.class, tenantAware.getCurrentTenant()).putConfigData(null, result.add(ControllerLinkBuilder
tenantAware.getCurrentTenant(), target.getControllerId())) .linkTo(ControllerLinkBuilder.methodOn(DdiRootController.class, tenantAware.getCurrentTenant())
.withRel(DdiRestConstants.CONFIG_DATA_ACTION)); .putConfigData(null, tenantAware.getCurrentTenant(), target.getControllerId()))
.withRel(DdiRestConstants.CONFIG_DATA_ACTION));
} }
return result; return result;
} }

View File

@@ -322,7 +322,7 @@ public class AmqpMessageHandlerService extends BaseAmqpService {
private Action checkActionExist(final Message message, final ActionUpdateStatus actionUpdateStatus) { private Action checkActionExist(final Message message, final ActionUpdateStatus actionUpdateStatus) {
final Long actionId = actionUpdateStatus.getActionId(); final Long actionId = actionUpdateStatus.getActionId();
LOG.debug("Target notifies intermediate about action {} with status {}.", actionId, LOG.debug("Target notifies intermediate about action {} with status {}.", actionId,
actionUpdateStatus.getActionStatus().name()); actionUpdateStatus.getActionStatus());
if (actionId == null) { if (actionId == null) {
logAndThrowMessageError(message, "Invalid message no action id"); logAndThrowMessageError(message, "Invalid message no action id");

View File

@@ -8,12 +8,6 @@
*/ */
package org.eclipse.hawkbit.mgmt.rest.resource; package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.eclipse.hawkbit.mgmt.rest.resource.MgmtDistributionSetTypeMapper.toResponse;
import static org.eclipse.hawkbit.mgmt.rest.resource.MgmtDistributionSetTypeMapper.toTypesResponse;
import static org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleTypeMapper.toResponse;
import static org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleTypeMapper.toTypesResponse;
import static org.springframework.http.HttpStatus.CREATED;
import java.util.List; import java.util.List;
import org.eclipse.hawkbit.mgmt.json.model.MgmtId; import org.eclipse.hawkbit.mgmt.json.model.MgmtId;
@@ -39,6 +33,7 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice; import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
@@ -95,7 +90,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId) { @PathVariable("distributionSetTypeId") final Long distributionSetTypeId) {
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
return ResponseEntity.ok(toResponse(foundType)); return ResponseEntity.ok(MgmtDistributionSetTypeMapper.toResponse(foundType));
} }
@Override @Override
@@ -111,9 +106,10 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @PathVariable("distributionSetTypeId") final Long distributionSetTypeId,
@RequestBody final MgmtDistributionSetTypeRequestBodyPut restDistributionSetType) { @RequestBody final MgmtDistributionSetTypeRequestBodyPut restDistributionSetType) {
return ResponseEntity.ok(toResponse(distributionSetManagement.updateDistributionSetType(entityFactory return ResponseEntity.ok(MgmtDistributionSetTypeMapper
.distributionSetType().update(distributionSetTypeId) .toResponse(distributionSetManagement.updateDistributionSetType(entityFactory.distributionSetType()
.description(restDistributionSetType.getDescription()).colour(restDistributionSetType.getColour())))); .update(distributionSetTypeId).description(restDistributionSetType.getDescription())
.colour(restDistributionSetType.getColour()))));
} }
@Override @Override
@@ -123,7 +119,8 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
final List<DistributionSetType> createdSoftwareModules = distributionSetManagement.createDistributionSetTypes( final List<DistributionSetType> createdSoftwareModules = distributionSetManagement.createDistributionSetTypes(
MgmtDistributionSetTypeMapper.smFromRequest(entityFactory, distributionSetTypes)); MgmtDistributionSetTypeMapper.smFromRequest(entityFactory, distributionSetTypes));
return ResponseEntity.status(CREATED).body(toTypesResponse(createdSoftwareModules)); return ResponseEntity.status(HttpStatus.CREATED)
.body(MgmtDistributionSetTypeMapper.toTypesResponse(createdSoftwareModules));
} }
private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final Long distributionSetTypeId) { private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final Long distributionSetTypeId) {
@@ -136,7 +133,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId) { @PathVariable("distributionSetTypeId") final Long distributionSetTypeId) {
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
return ResponseEntity.ok(toTypesResponse(foundType.getMandatoryModuleTypes())); return ResponseEntity.ok(MgmtSoftwareModuleTypeMapper.toTypesResponse(foundType.getMandatoryModuleTypes()));
} }
@Override @Override
@@ -151,7 +148,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
throw new SoftwareModuleTypeNotInDistributionSetTypeException(softwareModuleTypeId, distributionSetTypeId); throw new SoftwareModuleTypeNotInDistributionSetTypeException(softwareModuleTypeId, distributionSetTypeId);
} }
return ResponseEntity.ok(toResponse(foundSmType)); return ResponseEntity.ok(MgmtSoftwareModuleTypeMapper.toResponse(foundSmType));
} }
@Override @Override
@@ -166,7 +163,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
throw new SoftwareModuleTypeNotInDistributionSetTypeException(softwareModuleTypeId, distributionSetTypeId); throw new SoftwareModuleTypeNotInDistributionSetTypeException(softwareModuleTypeId, distributionSetTypeId);
} }
return ResponseEntity.ok(toResponse(foundSmType)); return ResponseEntity.ok(MgmtSoftwareModuleTypeMapper.toResponse(foundSmType));
} }
@Override @Override
@@ -174,7 +171,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId) { @PathVariable("distributionSetTypeId") final Long distributionSetTypeId) {
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
return ResponseEntity.ok(toTypesResponse(foundType.getOptionalModuleTypes())); return ResponseEntity.ok(MgmtSoftwareModuleTypeMapper.toTypesResponse(foundType.getOptionalModuleTypes()));
} }
@Override @Override

View File

@@ -61,13 +61,11 @@ public class MgmtDownloadArtifactResource implements MgmtDownloadArtifactRestApi
@ResponseBody @ResponseBody
public ResponseEntity<InputStream> downloadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, public ResponseEntity<InputStream> downloadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("artifactId") final Long artifactId) { @PathVariable("artifactId") final Long artifactId) {
final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, artifactId); final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
final Artifact artifact = module.getArtifact(artifactId)
.orElseThrow(() -> new EntityNotFoundException(Artifact.class, artifactId));
if (null == module || !module.getArtifact(artifactId).isPresent()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
final Artifact artifact = module.getArtifact(artifactId).get();
final DbArtifact file = artifactManagement.loadArtifactBinary(artifact.getSha1Hash()) final DbArtifact file = artifactManagement.loadArtifactBinary(artifact.getSha1Hash())
.orElseThrow(() -> new ArtifactBinaryNotFoundException(artifact.getSha1Hash())); .orElseThrow(() -> new ArtifactBinaryNotFoundException(artifact.getSha1Hash()));
final HttpServletRequest request = requestResponseContextHolder.getHttpServletRequest(); final HttpServletRequest request = requestResponseContextHolder.getHttpServletRequest();
@@ -81,14 +79,4 @@ public class MgmtDownloadArtifactResource implements MgmtDownloadArtifactRestApi
} }
private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId,
final Long artifactId) {
final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
if (artifactId != null && !module.getArtifact(artifactId).isPresent()) {
throw new EntityNotFoundException(Artifact.class, artifactId);
}
return module;
}
} }

View File

@@ -8,11 +8,6 @@
*/ */
package org.eclipse.hawkbit.mgmt.rest.resource; package org.eclipse.hawkbit.mgmt.rest.resource;
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.ETAG;
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;
@@ -30,6 +25,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
@@ -37,6 +33,7 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.WebApplicationContext;
import com.google.common.io.ByteStreams; import com.google.common.io.ByteStreams;
import com.google.common.net.HttpHeaders;
/** /**
* A resource for download artifacts. * A resource for download artifacts.
@@ -94,10 +91,10 @@ public class MgmtDownloadResource implements MgmtDownloadRestApi {
final HttpServletResponse response = requestResponseContextHolder.getHttpServletResponse(); final HttpServletResponse response = requestResponseContextHolder.getHttpServletResponse();
final String etag = artifact.getHashes().getSha1(); final String etag = artifact.getHashes().getSha1();
final long length = artifact.getSize(); final long length = artifact.getSize();
response.setHeader(CONTENT_DISPOSITION, "attachment;filename=" + downloadId); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + downloadId);
response.setHeader(ETAG, etag); response.setHeader(HttpHeaders.ETAG, etag);
response.setContentType(APPLICATION_OCTET_STREAM_VALUE); response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader(CONTENT_LENGTH, String.valueOf(length)); response.setContentLengthLong(length);
try (InputStream inputstream = artifact.getFileInputStream()) { try (InputStream inputstream = artifact.getFileInputStream()) {
ByteStreams.copy(inputstream, requestResponseContextHolder.getHttpServletResponse().getOutputStream()); ByteStreams.copy(inputstream, requestResponseContextHolder.getHttpServletResponse().getOutputStream());

View File

@@ -8,13 +8,6 @@
*/ */
package org.eclipse.hawkbit.mgmt.rest.resource; package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleMapper.artifactsToResponse;
import static org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleMapper.toResponse;
import static org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleMapper.toResponseSwMetadata;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import java.io.IOException; import java.io.IOException;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@@ -77,7 +70,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@RequestParam(value = "sha1sum", required = false) final String sha1Sum) { @RequestParam(value = "sha1sum", required = false) final String sha1Sum) {
if (file.isEmpty()) { if (file.isEmpty()) {
return new ResponseEntity<>(BAD_REQUEST); return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} }
String fileName = optionalFileName; String fileName = optionalFileName;
@@ -89,10 +82,10 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
final Artifact result = artifactManagement.createArtifact(file.getInputStream(), softwareModuleId, fileName, final Artifact result = artifactManagement.createArtifact(file.getInputStream(), softwareModuleId, fileName,
md5Sum == null ? null : md5Sum.toLowerCase(), sha1Sum == null ? null : sha1Sum.toLowerCase(), false, md5Sum == null ? null : md5Sum.toLowerCase(), sha1Sum == null ? null : sha1Sum.toLowerCase(), false,
file.getContentType()); file.getContentType());
return ResponseEntity.status(CREATED).body(toResponse(result)); return ResponseEntity.status(HttpStatus.CREATED).body(MgmtSoftwareModuleMapper.toResponse(result));
} catch (final IOException e) { } catch (final IOException e) {
LOG.error("Failed to store artifact", e); LOG.error("Failed to store artifact", e);
return new ResponseEntity<>(INTERNAL_SERVER_ERROR); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }
@@ -101,7 +94,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@PathVariable("softwareModuleId") final Long softwareModuleId) { @PathVariable("softwareModuleId") final Long softwareModuleId) {
final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
return ResponseEntity.ok(artifactsToResponse(module.getArtifacts())); return ResponseEntity.ok(MgmtSoftwareModuleMapper.artifactsToResponse(module.getArtifacts()));
} }
@Override @Override
@@ -115,7 +108,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, artifactId); final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, artifactId);
return ResponseEntity.ok(toResponse(module.getArtifact(artifactId).get())); return ResponseEntity.ok(MgmtSoftwareModuleMapper.toResponse(module.getArtifact(artifactId).get()));
} }
@Override @Override
@@ -161,7 +154,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@PathVariable("softwareModuleId") final Long softwareModuleId) { @PathVariable("softwareModuleId") final Long softwareModuleId) {
final SoftwareModule findBaseSoftareModule = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); final SoftwareModule findBaseSoftareModule = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
return ResponseEntity.ok(toResponse(findBaseSoftareModule)); return ResponseEntity.ok(MgmtSoftwareModuleMapper.toResponse(findBaseSoftareModule));
} }
@Override @Override
@@ -173,7 +166,8 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
.createSoftwareModule(MgmtSoftwareModuleMapper.smFromRequest(entityFactory, softwareModules)); .createSoftwareModule(MgmtSoftwareModuleMapper.smFromRequest(entityFactory, softwareModules));
LOG.debug("{} softwareModules created, return status {}", softwareModules.size(), HttpStatus.CREATED); LOG.debug("{} softwareModules created, return status {}", softwareModules.size(), HttpStatus.CREATED);
return ResponseEntity.status(CREATED).body(toResponse(createdSoftwareModules)); return ResponseEntity.status(HttpStatus.CREATED)
.body(MgmtSoftwareModuleMapper.toResponse(createdSoftwareModules));
} }
@Override @Override
@@ -181,7 +175,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@PathVariable("softwareModuleId") final Long softwareModuleId, @PathVariable("softwareModuleId") final Long softwareModuleId,
@RequestBody final MgmtSoftwareModuleRequestBodyPut restSoftwareModule) { @RequestBody final MgmtSoftwareModuleRequestBodyPut restSoftwareModule) {
return ResponseEntity.ok(toResponse( return ResponseEntity.ok(MgmtSoftwareModuleMapper.toResponse(
softwareManagement.updateSoftwareModule(entityFactory.softwareModule().update(softwareModuleId) softwareManagement.updateSoftwareModule(entityFactory.softwareModule().update(softwareModuleId)
.description(restSoftwareModule.getDescription()).vendor(restSoftwareModule.getVendor())))); .description(restSoftwareModule.getDescription()).vendor(restSoftwareModule.getVendor()))));
} }
@@ -221,7 +215,8 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
} }
return ResponseEntity return ResponseEntity
.ok(new PagedList<>(toResponseSwMetadata(metaDataPage.getContent()), metaDataPage.getTotalElements())); .ok(new PagedList<>(MgmtSoftwareModuleMapper.toResponseSwMetadata(metaDataPage.getContent()),
metaDataPage.getTotalElements()));
} }
@Override @Override
@@ -232,7 +227,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
.findSoftwareModuleMetadata(softwareModuleId, metadataKey).orElseThrow( .findSoftwareModuleMetadata(softwareModuleId, metadataKey).orElseThrow(
() -> new EntityNotFoundException(SoftwareModuleMetadata.class, softwareModuleId, metadataKey)); () -> new EntityNotFoundException(SoftwareModuleMetadata.class, softwareModuleId, metadataKey));
return ResponseEntity.ok(toResponseSwMetadata(findOne)); return ResponseEntity.ok(MgmtSoftwareModuleMapper.toResponseSwMetadata(findOne));
} }
@Override @Override
@@ -241,7 +236,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
final SoftwareModuleMetadata updated = softwareManagement.updateSoftwareModuleMetadata(softwareModuleId, final SoftwareModuleMetadata updated = softwareManagement.updateSoftwareModuleMetadata(softwareModuleId,
entityFactory.generateMetadata(metadataKey, metadata.getValue())); entityFactory.generateMetadata(metadataKey, metadata.getValue()));
return ResponseEntity.ok(toResponseSwMetadata(updated)); return ResponseEntity.ok(MgmtSoftwareModuleMapper.toResponseSwMetadata(updated));
} }
@Override @Override
@@ -260,7 +255,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
final List<SoftwareModuleMetadata> created = softwareManagement.createSoftwareModuleMetadata(softwareModuleId, final List<SoftwareModuleMetadata> created = softwareManagement.createSoftwareModuleMetadata(softwareModuleId,
MgmtSoftwareModuleMapper.fromRequestSwMetadata(entityFactory, metadataRest)); MgmtSoftwareModuleMapper.fromRequestSwMetadata(entityFactory, metadataRest));
return ResponseEntity.status(CREATED).body(toResponseSwMetadata(created)); return ResponseEntity.status(HttpStatus.CREATED).body(MgmtSoftwareModuleMapper.toResponseSwMetadata(created));
} }
private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId, private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId,

View File

@@ -121,7 +121,7 @@ public class TenantUsage {
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (!(obj instanceof TenantUsage)) { if (getClass() != obj.getClass()) {
return false; return false;
} }
final TenantUsage other = (TenantUsage) obj; final TenantUsage other = (TenantUsage) obj;
@@ -137,9 +137,6 @@ public class TenantUsage {
if (targets != other.targets) { if (targets != other.targets) {
return false; return false;
} }
if (!this.getUsageData().equals(other.getUsageData())) {
return false;
}
if (tenantName == null) { if (tenantName == null) {
if (other.tenantName != null) { if (other.tenantName != null) {
return false; return false;
@@ -147,6 +144,13 @@ public class TenantUsage {
} else if (!tenantName.equals(other.tenantName)) { } else if (!tenantName.equals(other.tenantName)) {
return false; return false;
} }
if (usageData == null) {
if (other.usageData != null) {
return false;
}
} else if (!usageData.equals(other.usageData)) {
return false;
}
return true; return true;
} }

View File

@@ -58,10 +58,12 @@ public class JpaArtifactManagement implements ArtifactManagement {
private static Artifact checkForExistingArtifact(final String filename, final boolean overrideExisting, private static Artifact checkForExistingArtifact(final String filename, final boolean overrideExisting,
final SoftwareModule softwareModule) { final SoftwareModule softwareModule) {
if (softwareModule.getArtifactByFilename(filename).isPresent()) { final Optional<Artifact> artifact = softwareModule.getArtifactByFilename(filename);
if (artifact.isPresent()) {
if (overrideExisting) { if (overrideExisting) {
LOG.debug("overriding existing artifact with new filename {}", filename); LOG.debug("overriding existing artifact with new filename {}", filename);
return softwareModule.getArtifactByFilename(filename).get(); return artifact.get();
} else { } else {
throw new EntityAlreadyExistsException("File with that name already exists in the Software Module"); throw new EntityAlreadyExistsException("File with that name already exists in the Software Module");
} }

View File

@@ -70,7 +70,6 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.model.TargetWithActionType; import org.eclipse.hawkbit.repository.model.TargetWithActionType;
import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer; import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer;
import org.hibernate.validator.constraints.NotEmpty;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -350,14 +349,6 @@ public class JpaDeploymentManagement implements DeploymentManagement {
} }
private DistributionSetAssignmentResult assignDistributionSetByTargetId(@NotNull final JpaDistributionSet set,
@NotEmpty final List<String> tIDs, final ActionType actionType, final long forcedTime) {
return assignDistributionSetToTargets(set, tIDs.stream()
.map(t -> new TargetWithActionType(t, actionType, forcedTime)).collect(Collectors.toList()), null, null,
null);
}
@Override @Override
@Modifying @Modifying
@Transactional(isolation = Isolation.READ_COMMITTED) @Transactional(isolation = Isolation.READ_COMMITTED)
@@ -383,8 +374,7 @@ public class JpaDeploymentManagement implements DeploymentManagement {
return saveAction; return saveAction;
} else { } else {
throw new CancelActionNotAllowedException( throw new CancelActionNotAllowedException(action.getId() + " is not active and cannot be canceled");
"Action [id: " + action.getId() + "] is not active and cannot be canceled");
} }
} }
@@ -416,12 +406,11 @@ public class JpaDeploymentManagement implements DeploymentManagement {
if (!action.isCancelingOrCanceled()) { if (!action.isCancelingOrCanceled()) {
throw new ForceQuitActionNotAllowedException( throw new ForceQuitActionNotAllowedException(
"Action [id: " + action.getId() + "] is not canceled yet and cannot be force quit"); action.getId() + " is not canceled yet and cannot be force quit");
} }
if (!action.isActive()) { if (!action.isActive()) {
throw new ForceQuitActionNotAllowedException( throw new ForceQuitActionNotAllowedException(action.getId() + " is not active and cannot be force quit");
"Action [id: " + action.getId() + "] is not active and cannot be force quit");
} }
LOG.warn("action ({}) was still activ and has been force quite.", action); LOG.warn("action ({}) was still activ and has been force quite.", action);

View File

@@ -658,13 +658,6 @@ public class JpaSoftwareManagement implements SoftwareManagement {
return Optional.ofNullable(softwareModuleMetadataRepository.findOne(new SwMetadataCompositeKey(moduleId, key))); return Optional.ofNullable(softwareModuleMetadataRepository.findOne(new SwMetadataCompositeKey(moduleId, key)));
} }
private void checkAndThrowAlreadyExistsIfSoftwareModuleMetadataExists(final SwMetadataCompositeKey metadataId) {
if (softwareModuleMetadataRepository.exists(metadataId)) {
throw new EntityAlreadyExistsException(
"Metadata entry with key '" + metadataId.getKey() + "' already exists");
}
}
private static void throwMetadataKeyAlreadyExists(final String metadataKey) { private static void throwMetadataKeyAlreadyExists(final String metadataKey) {
throw new EntityAlreadyExistsException("Metadata entry with key '" + metadataKey + "' already exists"); throw new EntityAlreadyExistsException("Metadata entry with key '" + metadataKey + "' already exists");
} }

View File

@@ -8,8 +8,6 @@
*/ */
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;
@@ -214,7 +212,7 @@ public final class RSQLUtility {
simpleTypeConverter = new SimpleTypeConverter(); simpleTypeConverter = new SimpleTypeConverter();
} }
private void beginLevel(boolean isOr) { private void beginLevel(final boolean isOr) {
level++; level++;
isOrLevel = isOr; isOrLevel = isOr;
joinsInLevel.put(level, new HashSet<>(2)); joinsInLevel.put(level, new HashSet<>(2));
@@ -227,19 +225,18 @@ public final class RSQLUtility {
} }
private Set<Join<Object, Object>> getCurrentJoins() { private Set<Join<Object, Object>> getCurrentJoins() {
if(level > 0) { if (level > 0) {
return joinsInLevel.get(level); return joinsInLevel.get(level);
} }
return Collections.emptySet(); return Collections.emptySet();
} }
private Optional<Join<Object, Object>> findCurrentJoinOfType(final Class<?> type) { private Optional<Join<Object, Object>> findCurrentJoinOfType(final Class<?> type) {
return getCurrentJoins().stream() return getCurrentJoins().stream().filter(j -> type.equals(j.getJavaType())).findAny();
.filter(j -> type.equals(j.getJavaType())).findAny();
} }
private void addCurrentJoin(Join<Object, Object> join) { private void addCurrentJoin(final Join<Object, Object> join) {
if(level > 0) { if (level > 0) {
getCurrentJoins().add(join); getCurrentJoins().add(join);
} }
} }
@@ -272,7 +269,7 @@ public final class RSQLUtility {
private String getAndValidatePropertyFieldName(final A propertyEnum, final ComparisonNode node) { private String getAndValidatePropertyFieldName(final A propertyEnum, final ComparisonNode node) {
final String[] graph = node.getSelector().split("\\" + SUB_ATTRIBUTE_SEPERATOR); final String[] graph = node.getSelector().split("\\" + FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR);
validateMapParamter(propertyEnum, node, graph); validateMapParamter(propertyEnum, node, graph);
@@ -286,7 +283,7 @@ public final class RSQLUtility {
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];
fieldNameBuilder.append(SUB_ATTRIBUTE_SEPERATOR).append(propertyField); fieldNameBuilder.append(FieldNameProvider.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)) {
@@ -347,7 +344,7 @@ public final class RSQLUtility {
*/ */
private Path<Object> getFieldPath(final A enumField, final String finalProperty) { private Path<Object> getFieldPath(final A enumField, final String finalProperty) {
Path<Object> fieldPath = null; Path<Object> fieldPath = null;
final String[] split = finalProperty.split("\\" + SUB_ATTRIBUTE_SEPERATOR); final String[] split = finalProperty.split("\\" + FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR);
for (int i = 0; i < split.length; i++) { for (int i = 0; i < split.length; i++) {
final boolean isMapKeyField = enumField.isMap() && i == (split.length - 1); final boolean isMapKeyField = enumField.isMap() && i == (split.length - 1);
@@ -360,13 +357,13 @@ public final class RSQLUtility {
if (fieldPath instanceof PluralJoin) { if (fieldPath instanceof PluralJoin) {
final Join<Object, ?> join = (Join<Object, ?>) fieldPath; final Join<Object, ?> join = (Join<Object, ?>) fieldPath;
final From<?, Object> joinParent = join.getParent(); final From<?, Object> joinParent = join.getParent();
Optional<Join<Object, Object>> currentJoinOfType = findCurrentJoinOfType(join.getJavaType()); final Optional<Join<Object, Object>> currentJoinOfType = findCurrentJoinOfType(join.getJavaType());
if(currentJoinOfType.isPresent() && isOrLevel) { if (currentJoinOfType.isPresent() && isOrLevel) {
// remove the additional join and use the existing one // remove the additional join and use the existing one
joinParent.getJoins().remove(join); joinParent.getJoins().remove(join);
fieldPath = currentJoinOfType.get(); fieldPath = currentJoinOfType.get();
} else { } else {
Join<Object, Object> newJoin = joinParent.join(fieldNameSplit, JoinType.LEFT); final Join<Object, Object> newJoin = joinParent.join(fieldNameSplit, JoinType.LEFT);
addCurrentJoin(newJoin); addCurrentJoin(newJoin);
fieldPath = newJoin; fieldPath = newJoin;
} }
@@ -414,7 +411,7 @@ public final class RSQLUtility {
final String enumFieldName = enumField.name().toLowerCase(); final String enumFieldName = enumField.name().toLowerCase();
if (enumField.isMap()) { if (enumField.isMap()) {
return enumFieldName + SUB_ATTRIBUTE_SEPERATOR + "keyName"; return enumFieldName + FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR + "keyName";
} }
return enumFieldName; return enumFieldName;
@@ -423,7 +420,8 @@ public final class RSQLUtility {
final List<String> expectedSubFieldList = Arrays.stream(enumType.getEnumConstants()) final List<String> expectedSubFieldList = Arrays.stream(enumType.getEnumConstants())
.filter(enumField -> !enumField.getSubEntityAttributes().isEmpty()).flatMap(enumField -> { .filter(enumField -> !enumField.getSubEntityAttributes().isEmpty()).flatMap(enumField -> {
final List<String> subEntity = enumField.getSubEntityAttributes().stream() final List<String> subEntity = enumField.getSubEntityAttributes().stream()
.map(fieldName -> enumField.name().toLowerCase() + SUB_ATTRIBUTE_SEPERATOR + fieldName) .map(fieldName -> enumField.name().toLowerCase()
+ FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR + fieldName)
.collect(Collectors.toList()); .collect(Collectors.toList());
return subEntity.stream(); return subEntity.stream();
@@ -434,7 +432,7 @@ public final class RSQLUtility {
private A getFieldEnumByName(final ComparisonNode node) { private A getFieldEnumByName(final ComparisonNode node) {
String enumName = node.getSelector(); String enumName = node.getSelector();
final String[] graph = enumName.split("\\" + SUB_ATTRIBUTE_SEPERATOR); final String[] graph = enumName.split("\\" + FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR);
if (graph.length != 0) { if (graph.length != 0) {
enumName = graph[0]; enumName = graph[0];
} }
@@ -613,7 +611,7 @@ public final class RSQLUtility {
if (!enumField.isMap()) { if (!enumField.isMap()) {
return null; return null;
} }
final String[] graph = node.getSelector().split("\\" + SUB_ATTRIBUTE_SEPERATOR); final String[] graph = node.getSelector().split("\\" + FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR);
final String keyValue = graph[graph.length - 1]; final String keyValue = graph[graph.length - 1];
if (fieldPath instanceof MapJoin) { if (fieldPath instanceof MapJoin) {
// Currently we support only string key .So below cast is safe. // Currently we support only string key .So below cast is safe.

View File

@@ -274,7 +274,7 @@ public class RsqlParserValidationOracle implements RsqlValidationOracle {
.map(field -> field.toString().toLowerCase()).collect(Collectors.toSet()); .map(field -> field.toString().toLowerCase()).collect(Collectors.toSet());
private static final Map<String, List<String>> SUB_NAMES = Arrays.stream(TargetFields.values()).collect( private static final Map<String, List<String>> SUB_NAMES = Arrays.stream(TargetFields.values()).collect(
Collectors.toMap(field -> field.toString().toLowerCase(), field -> field.getSubEntityAttributes())); Collectors.toMap(field -> field.toString().toLowerCase(), TargetFields::getSubEntityAttributes));
private FieldNameDescription() { private FieldNameDescription() {
@@ -292,8 +292,7 @@ public class RsqlParserValidationOracle implements RsqlValidationOracle {
final String finalTmpTokenName = tmpTokenName; final String finalTmpTokenName = tmpTokenName;
return Arrays.stream(TargetFields.values()) return Arrays.stream(TargetFields.values())
.filter(field -> field.toString().equalsIgnoreCase(finalTmpTokenName)) .filter(field -> field.toString().equalsIgnoreCase(finalTmpTokenName))
.map(field -> field.getSubEntityAttributes()).flatMap(subentities -> subentities.stream()) .map(TargetFields::getSubEntityAttributes).flatMap(List::stream).count() > 0;
.count() > 0;
} }
private static List<SuggestToken> toTopSuggestToken(final int beginToken, final int endToken, private static List<SuggestToken> toTopSuggestToken(final int beginToken, final int endToken,
@@ -306,7 +305,7 @@ public class RsqlParserValidationOracle implements RsqlValidationOracle {
private static List<SuggestToken> toSubSuggestToken(final int beginToken, final int endToken, private static List<SuggestToken> toSubSuggestToken(final int beginToken, final int endToken,
final String topToken, final String tokenImageName) { final String topToken, final String tokenImageName) {
return Arrays.stream(TargetFields.values()).filter(field -> field.toString().equalsIgnoreCase(topToken)) return Arrays.stream(TargetFields.values()).filter(field -> field.toString().equalsIgnoreCase(topToken))
.map(field -> field.getSubEntityAttributes()).flatMap(list -> list.stream()) .map(TargetFields::getSubEntityAttributes).flatMap(List::stream)
.map(subentity -> new SuggestToken(beginToken, endToken, tokenImageName, subentity)) .map(subentity -> new SuggestToken(beginToken, endToken, tokenImageName, subentity))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@@ -318,8 +317,7 @@ public class RsqlParserValidationOracle implements RsqlValidationOracle {
final String[] split = imageName.split("\\."); final String[] split = imageName.split("\\.");
if (split.length > 1 && FIELD_NAMES.contains(split[0].toLowerCase())) { if (split.length > 1 && FIELD_NAMES.contains(split[0].toLowerCase())) {
return SUB_NAMES.get(split[0].toLowerCase()).stream() return SUB_NAMES.get(split[0].toLowerCase()).stream()
.filter(subname -> new String(split[0] + "." + subname).equalsIgnoreCase(imageName)) .filter(subname -> (split[0] + "." + subname).equalsIgnoreCase(imageName)).count() > 0;
.count() > 0;
} }
return FIELD_NAMES.stream().filter(value -> value.equalsIgnoreCase(imageName)).count() > 0; return FIELD_NAMES.stream().filter(value -> value.equalsIgnoreCase(imageName)).count() > 0;
} }

View File

@@ -9,13 +9,12 @@
package org.eclipse.hawkbit.repository.test.matcher; package org.eclipse.hawkbit.repository.test.matcher;
import static java.util.Optional.ofNullable;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import java.util.Iterator; import java.util.Iterator;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.eclipse.hawkbit.repository.test.util.TestContextProvider; import org.eclipse.hawkbit.repository.test.util.TestContextProvider;
@@ -60,7 +59,7 @@ public class EventVerifier implements TestRule {
} }
private Optional<Expect[]> getExpectationsFrom(final Description description) { private Optional<Expect[]> getExpectationsFrom(final Description description) {
return ofNullable(description.getAnnotation(ExpectEvents.class)).map(ExpectEvents::value); return Optional.ofNullable(description.getAnnotation(ExpectEvents.class)).map(ExpectEvents::value);
} }
private void beforeTest() { private void beforeTest() {
@@ -78,8 +77,8 @@ public class EventVerifier implements TestRule {
for (final Expect expectedEvent : expectedEvents) { for (final Expect expectedEvent : expectedEvents) {
try { try {
Awaitility.await().atMost(5, SECONDS).until(() -> eventCaptor.getCountFor(expectedEvent.type()), Awaitility.await().atMost(5, TimeUnit.SECONDS)
equalTo(expectedEvent.count())); .until(() -> eventCaptor.getCountFor(expectedEvent.type()), equalTo(expectedEvent.count()));
} catch (final ConditionTimeoutException ex) { } catch (final ConditionTimeoutException ex) {
Assert.fail("Did not receive the expected amount of events form " + expectedEvent.type() + " Expected: " Assert.fail("Did not receive the expected amount of events form " + expectedEvent.type() + " Expected: "

View File

@@ -8,25 +8,10 @@
*/ */
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.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;
@@ -40,9 +25,13 @@ import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.Artifact;
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.base.Preconditions;
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.
@@ -117,11 +106,11 @@ public final class RestResourceConversionHelper {
response.reset(); response.reset();
response.setBufferSize(BUFFER_SIZE); response.setBufferSize(BUFFER_SIZE);
response.setHeader(CONTENT_DISPOSITION, "attachment;filename=" + artifact.getFilename()); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + artifact.getFilename());
response.setHeader(ETAG, etag); response.setHeader(HttpHeaders.ETAG, etag);
response.setHeader(ACCEPT_RANGES, "bytes"); response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
response.setDateHeader(LAST_MODIFIED, lastModified); response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified);
response.setContentType(APPLICATION_OCTET_STREAM_VALUE); response.setContentType(MediaType.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<>();
@@ -133,9 +122,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(CONTENT_RANGE, "bytes */" + length); response.setHeader(HttpHeaders.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<>(REQUESTED_RANGE_NOT_SATISFIABLE); return new ResponseEntity<>(HttpStatus.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
@@ -155,19 +144,19 @@ public final class RestResourceConversionHelper {
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());
handleFullFileRequest(artifact, response, file, controllerManagement, statusId, full); handleFullFileRequest(artifact, response, file, controllerManagement, statusId, full);
result = new ResponseEntity<>(OK); result = new ResponseEntity<>(HttpStatus.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());
handleStandardRangeRequest(artifact, response, file, controllerManagement, statusId, ranges); handleStandardRangeRequest(artifact, response, file, controllerManagement, statusId, ranges);
result = new ResponseEntity<>(PARTIAL_CONTENT); result = new ResponseEntity<>(HttpStatus.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());
handleMultipartRangeRequest(artifact, response, file, controllerManagement, statusId, ranges); handleMultipartRangeRequest(artifact, response, file, controllerManagement, statusId, ranges);
result = new ResponseEntity<>(PARTIAL_CONTENT); result = new ResponseEntity<>(HttpStatus.PARTIAL_CONTENT);
} }
return result; return result;
@@ -177,8 +166,8 @@ public final class RestResourceConversionHelper {
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(CONTENT_RANGE, "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal()); response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal());
response.setHeader(CONTENT_LENGTH, String.valueOf(r.getLength())); response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(r.getLength()));
try (InputStream inputStream = file.getFileInputStream()) { try (InputStream inputStream = file.getFileInputStream()) {
copyStreams(inputStream, response.getOutputStream(), controllerManagement, statusId, r.getStart(), copyStreams(inputStream, response.getOutputStream(), controllerManagement, statusId, r.getStart(),
@@ -207,8 +196,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(CONTENT_RANGE, "bytes */" + length); response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + length);
return new ResponseEntity<>(REQUESTED_RANGE_NOT_SATISFIABLE); return new ResponseEntity<>(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
} }
// Add range. // Add range.
@@ -226,10 +215,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(IF_RANGE); final String ifRange = request.getHeader(HttpHeaders.IF_RANGE);
if (ifRange != null && !ifRange.equals(etag)) { if (ifRange != null && !ifRange.equals(etag)) {
try { try {
final long ifRangeTime = request.getDateHeader(IF_RANGE); final long ifRangeTime = request.getDateHeader(HttpHeaders.IF_RANGE);
if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) { if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
ranges.add(full); ranges.add(full);
} }
@@ -243,15 +232,15 @@ public final class RestResourceConversionHelper {
private static void handleMultipartRangeRequest(final Artifact artifact, final HttpServletResponse response, private static void handleMultipartRangeRequest(final Artifact 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=" + MULTIPART_BOUNDARY); response.setContentType("multipart/byteranges; boundary=" + ByteRange.MULTIPART_BOUNDARY);
response.setStatus(SC_PARTIAL_CONTENT); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
for (final ByteRange r : ranges) { for (final ByteRange r : ranges) {
try (InputStream inputStream = file.getFileInputStream()) { try (InputStream inputStream = file.getFileInputStream()) {
// 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("--" + MULTIPART_BOUNDARY); response.getOutputStream().println("--" + ByteRange.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());
@@ -265,7 +254,7 @@ public final class RestResourceConversionHelper {
try { try {
// End with final multipart boundary. // End with final multipart boundary.
response.getOutputStream().println(); response.getOutputStream().println();
response.getOutputStream().print("--" + MULTIPART_BOUNDARY + "--"); response.getOutputStream().print("--" + ByteRange.MULTIPART_BOUNDARY + "--");
} catch (final IOException e) { } catch (final IOException e) {
throwFileStreamingFailedException(artifact, e); throwFileStreamingFailedException(artifact, e);
} }
@@ -280,9 +269,9 @@ public final class RestResourceConversionHelper {
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(CONTENT_RANGE, "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal()); response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal());
response.setHeader(CONTENT_LENGTH, String.valueOf(r.getLength())); response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(r.getLength()));
response.setStatus(SC_PARTIAL_CONTENT); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
try (InputStream inputStream = file.getFileInputStream()) { try (InputStream inputStream = file.getFileInputStream()) {
copyStreams(inputStream, response.getOutputStream(), controllerManagement, statusId, r.getStart(), copyStreams(inputStream, response.getOutputStream(), controllerManagement, statusId, r.getStart(),
@@ -296,8 +285,8 @@ public final class RestResourceConversionHelper {
private static long copyStreams(final InputStream from, final OutputStream to, private static long copyStreams(final InputStream from, final OutputStream to,
final ControllerManagement controllerManagement, final Long statusId, final long start, final long length) final ControllerManagement controllerManagement, final Long statusId, final long start, final long length)
throws IOException { throws IOException {
checkNotNull(from); Preconditions.checkNotNull(from);
checkNotNull(to); Preconditions.checkNotNull(to);
final byte[] buf = new byte[BUFFER_SIZE]; final byte[] buf = new byte[BUFFER_SIZE];
long total = 0; long total = 0;
int progressPercent = 1; int progressPercent = 1;
@@ -331,7 +320,7 @@ public final class RestResourceConversionHelper {
} }
if (controllerManagement != null) { if (controllerManagement != null) {
final int newPercent = DoubleMath.roundToInt(total * 100.0 / length, DOWN); final int newPercent = DoubleMath.roundToInt(total * 100.0 / length, RoundingMode.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

@@ -8,10 +8,8 @@
*/ */
package org.eclipse.hawkbit.security; package org.eclipse.hawkbit.security;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.eclipse.hawkbit.security.SecurityConstants.SECURITY_LOG_PREFIX;
import java.io.IOException; import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -38,16 +36,17 @@ import com.google.common.cache.CacheBuilder;
public class DosFilter extends OncePerRequestFilter { public class DosFilter extends OncePerRequestFilter {
private static final Logger LOG = LoggerFactory.getLogger(DosFilter.class); private static final Logger LOG = LoggerFactory.getLogger(DosFilter.class);
private static final Logger LOG_DOS = LoggerFactory.getLogger(SECURITY_LOG_PREFIX + ".dos"); private static final Logger LOG_DOS = LoggerFactory.getLogger(SecurityConstants.SECURITY_LOG_PREFIX + ".dos");
private static final Logger LOG_BLACKLIST = LoggerFactory.getLogger(SECURITY_LOG_PREFIX + ".blacklist"); private static final Logger LOG_BLACKLIST = LoggerFactory
.getLogger(SecurityConstants.SECURITY_LOG_PREFIX + ".blacklist");
private final Pattern ipAdressBlacklist; private final Pattern ipAdressBlacklist;
private final Cache<String, AtomicInteger> readCountCache = CacheBuilder.newBuilder().expireAfterAccess(1, SECONDS) private final Cache<String, AtomicInteger> readCountCache = CacheBuilder.newBuilder()
.build(); .expireAfterAccess(1, TimeUnit.SECONDS).build();
private final Cache<String, AtomicInteger> writeCountCache = CacheBuilder.newBuilder().expireAfterAccess(1, SECONDS) private final Cache<String, AtomicInteger> writeCountCache = CacheBuilder.newBuilder()
.build(); .expireAfterAccess(1, TimeUnit.SECONDS).build();
private final Integer maxRead; private final Integer maxRead;
private final Integer maxWrite; private final Integer maxWrite;

View File

@@ -8,18 +8,14 @@
*/ */
package org.eclipse.hawkbit.ui.artifacts.details; package org.eclipse.hawkbit.ui.artifacts.details;
import static org.apache.commons.lang3.ArrayUtils.isEmpty;
import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.isNotNullOrEmpty;
import static org.springframework.data.domain.Sort.Direction.ASC;
import static org.springframework.data.domain.Sort.Direction.DESC;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.commons.lang3.ArrayUtils;
import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil;
import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions;
import org.eclipse.hawkbit.ui.utils.SpringContextHelper; import org.eclipse.hawkbit.ui.utils.SpringContextHelper;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
@@ -37,7 +33,6 @@ public class ArtifactBeanQuery extends AbstractBeanQuery<Artifact> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private Sort sort = new Sort(Direction.DESC, "filename"); private Sort sort = new Sort(Direction.DESC, "filename");
private transient ArtifactManagement artifactManagement; private transient ArtifactManagement artifactManagement;
private transient EntityFactory entityFactory;
private transient Page<Artifact> firstPagetArtifacts; private transient Page<Artifact> firstPagetArtifacts;
private Long baseSwModuleId; private Long baseSwModuleId;
@@ -58,15 +53,15 @@ public class ArtifactBeanQuery extends AbstractBeanQuery<Artifact> {
super(definition, queryConfig, sortIds, sortStates); super(definition, queryConfig, sortIds, sortStates);
if (isNotNullOrEmpty(queryConfig)) { if (HawkbitCommonUtil.isNotNullOrEmpty(queryConfig)) {
baseSwModuleId = (Long) queryConfig.get(SPUIDefinitions.BY_BASE_SOFTWARE_MODULE); baseSwModuleId = (Long) queryConfig.get(SPUIDefinitions.BY_BASE_SOFTWARE_MODULE);
} }
if (!isEmpty(sortStates)) { if (!ArrayUtils.isEmpty(sortStates)) {
sort = new Sort(sortStates[0] ? ASC : DESC, (String) sortIds[0]); sort = new Sort(sortStates[0] ? Direction.ASC : Direction.DESC, (String) sortIds[0]);
for (int targetId = 1; targetId < sortIds.length; targetId++) { for (int targetId = 1; targetId < sortIds.length; targetId++) {
sort.and(new Sort(sortStates[targetId] ? ASC : DESC, (String) sortIds[targetId])); sort.and(new Sort(sortStates[targetId] ? Direction.ASC : Direction.DESC, (String) sortIds[targetId]));
} }
} }
} }
@@ -116,11 +111,4 @@ public class ArtifactBeanQuery extends AbstractBeanQuery<Artifact> {
} }
return artifactManagement; return artifactManagement;
} }
private EntityFactory getEntityFactory() {
if (entityFactory == null) {
entityFactory = SpringContextHelper.getBean(EntityFactory.class);
}
return entityFactory;
}
} }

View File

@@ -15,7 +15,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.ui.artifacts.event.ArtifactDetailsEvent; import org.eclipse.hawkbit.ui.artifacts.event.ArtifactDetailsEvent;
import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent;
import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType;
@@ -114,11 +113,11 @@ public class ArtifactDetailsLayout extends VerticalLayout {
createComponents(); createComponents();
buildLayout(); buildLayout();
eventBus.subscribe(this); eventBus.subscribe(this);
if (artifactUploadState.getSelectedBaseSoftwareModule().isPresent()) { artifactUploadState.getSelectedBaseSoftwareModule()
final SoftwareModule selectedSoftwareModule = artifactUploadState.getSelectedBaseSoftwareModule().get(); .ifPresent(selectedSoftwareModule -> populateArtifactDetails(selectedSoftwareModule.getId(),
populateArtifactDetails(selectedSoftwareModule.getId(), HawkbitCommonUtil HawkbitCommonUtil.getFormattedNameVersion(selectedSoftwareModule.getName(),
.getFormattedNameVersion(selectedSoftwareModule.getName(), selectedSoftwareModule.getVersion())); selectedSoftwareModule.getVersion())));
}
if (isMaximized()) { if (isMaximized()) {
maximizedArtifactDetailsView(); maximizedArtifactDetailsView();
} }

View File

@@ -153,12 +153,12 @@ public class SoftwareModuleDetails extends AbstractNamedVersionedEntityTableDeta
} }
@Override @Override
protected Boolean onLoadIsTableRowSelected() { protected boolean onLoadIsTableRowSelected() {
return artifactUploadState.getSelectedBaseSoftwareModule().isPresent(); return artifactUploadState.getSelectedBaseSoftwareModule().isPresent();
} }
@Override @Override
protected Boolean onLoadIsTableMaximized() { protected boolean onLoadIsTableMaximized() {
return artifactUploadState.isSwModuleTableMaximized(); return artifactUploadState.isSwModuleTableMaximized();
} }
@@ -168,7 +168,7 @@ public class SoftwareModuleDetails extends AbstractNamedVersionedEntityTableDeta
} }
@Override @Override
protected Boolean hasEditPermission() { protected boolean hasEditPermission() {
return getPermissionChecker().hasUpdateDistributionPermission(); return getPermissionChecker().hasUpdateDistributionPermission();
} }
@@ -195,7 +195,7 @@ public class SoftwareModuleDetails extends AbstractNamedVersionedEntityTableDeta
} }
@Override @Override
protected Boolean isMetadataIconToBeDisplayed() { protected boolean isMetadataIconToBeDisplayed() {
return true; return true;
} }

View File

@@ -8,9 +8,6 @@
*/ */
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;
@@ -140,12 +137,9 @@ public class UploadConfirmationWindow implements Button.ClickListener {
buildLayout(); buildLayout();
} }
private Boolean checkIfArtifactDetailsDisplayed(final Long bSoftwareModuleId) { private boolean checkIfArtifactDetailsDisplayed(final Long bSoftwareModuleId) {
if (artifactUploadState.getSelectedBaseSoftwareModule().isPresent() return artifactUploadState.getSelectedBaseSoftwareModule()
&& artifactUploadState.getSelectedBaseSoftwareModule().get().getId().equals(bSoftwareModuleId)) { .map(module -> module.getId().equals(bSoftwareModuleId)).orElse(false);
return true;
}
return false;
} }
private Boolean preUploadValidation(final List<String> itemIds) { private Boolean preUploadValidation(final List<String> itemIds) {
@@ -640,12 +634,12 @@ public class UploadConfirmationWindow implements Button.ClickListener {
artifactManagement.createArtifact(fis, baseSw.getId(), providedFileName, artifactManagement.createArtifact(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, SUCCESS, ""); saveUploadStatus(providedFileName, swModuleNameVersion, SPUILabelDefinitions.SUCCESS, "");
} catch (final ArtifactUploadFailedException | InvalidSHA1HashException | InvalidMD5HashException } catch (final ArtifactUploadFailedException | InvalidSHA1HashException | InvalidMD5HashException
| FileNotFoundException e) { | FileNotFoundException e) {
saveUploadStatus(providedFileName, swModuleNameVersion, FAILED, e.getMessage()); saveUploadStatus(providedFileName, swModuleNameVersion, SPUILabelDefinitions.FAILED, e.getMessage());
LOG.error(ARTIFACT_UPLOAD_EXCEPTION, e); LOG.error(ARTIFACT_UPLOAD_EXCEPTION, e);
} catch (final IOException ex) { } catch (final IOException ex) {

View File

@@ -17,8 +17,8 @@ import org.eclipse.hawkbit.ui.artifacts.event.UploadFileStatus;
import org.eclipse.hawkbit.ui.artifacts.event.UploadStatusEvent; import org.eclipse.hawkbit.ui.artifacts.event.UploadStatusEvent;
import org.eclipse.hawkbit.ui.artifacts.event.UploadStatusEvent.UploadStatusEventType; import org.eclipse.hawkbit.ui.artifacts.event.UploadStatusEvent.UploadStatusEventType;
import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState; import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState;
import org.eclipse.hawkbit.ui.utils.VaadinMessageSource;
import org.eclipse.hawkbit.ui.utils.SpringContextHelper; import org.eclipse.hawkbit.ui.utils.SpringContextHelper;
import org.eclipse.hawkbit.ui.utils.VaadinMessageSource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventBus;
@@ -207,16 +207,13 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene
@Override @Override
public void uploadStarted(final StartedEvent event) { public void uploadStarted(final StartedEvent event) {
uploadInterrupted = false; uploadInterrupted = false;
selectedSwForUpload = artifactUploadState.getSelectedBaseSoftwareModule().isPresent() selectedSwForUpload = artifactUploadState.getSelectedBaseSoftwareModule().orElse(null);
? artifactUploadState.getSelectedBaseSoftwareModule().get() : null;
if (view.isSoftwareModuleSelected()) { if (selectedSwForUpload != null && view.checkIfSoftwareModuleIsSelected()
// single file session && !view.checkIfFileIsDuplicate(event.getFilename(), selectedSwForUpload)) {
if (!view.checkIfFileIsDuplicate(event.getFilename(), selectedSwForUpload)) { LOG.debug("Upload started for file :{}", event.getFilename());
LOG.debug("Upload started for file :{}", event.getFilename()); eventBus.publish(this, new UploadStatusEvent(UploadStatusEventType.UPLOAD_STARTED,
eventBus.publish(this, new UploadStatusEvent(UploadStatusEventType.UPLOAD_STARTED, new UploadFileStatus(event.getFilename(), 0, 0, selectedSwForUpload)));
new UploadFileStatus(event.getFilename(), 0, 0, selectedSwForUpload)));
}
} else { } else {
failureReason = i18n.getMessage("message.upload.failed"); failureReason = i18n.getMessage("message.upload.failed");
upload.interruptUpload(); upload.interruptUpload();

View File

@@ -36,12 +36,12 @@ import org.eclipse.hawkbit.ui.dd.criteria.ServerItemIdClientCriterion;
import org.eclipse.hawkbit.ui.dd.criteria.ServerItemIdClientCriterion.Mode; import org.eclipse.hawkbit.ui.dd.criteria.ServerItemIdClientCriterion.Mode;
import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmall; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmall;
import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil;
import org.eclipse.hawkbit.ui.utils.VaadinMessageSource;
import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions;
import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions;
import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions;
import org.eclipse.hawkbit.ui.utils.UIComponentIdProvider; import org.eclipse.hawkbit.ui.utils.UIComponentIdProvider;
import org.eclipse.hawkbit.ui.utils.UINotification; import org.eclipse.hawkbit.ui.utils.UINotification;
import org.eclipse.hawkbit.ui.utils.VaadinMessageSource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@@ -106,7 +106,7 @@ public class UploadLayout extends VerticalLayout {
private DragAndDropWrapper dropAreaWrapper; private DragAndDropWrapper dropAreaWrapper;
private Boolean hasDirectory = Boolean.FALSE; private boolean hasDirectory;
private Button uploadStatusButton; private Button uploadStatusButton;
@@ -136,13 +136,13 @@ public class UploadLayout extends VerticalLayout {
@EventBusListenerMethod(scope = EventScope.UI) @EventBusListenerMethod(scope = EventScope.UI)
void onEvent(final UploadArtifactUIEvent event) { void onEvent(final UploadArtifactUIEvent event) {
if (event == UploadArtifactUIEvent.DELETED_ALL_SOFWARE) { if (event == UploadArtifactUIEvent.DELETED_ALL_SOFWARE) {
ui.access(() -> updateActionCount()); ui.access(this::updateActionCount);
} else if (event == UploadArtifactUIEvent.MINIMIZED_STATUS_POPUP) { } else if (event == UploadArtifactUIEvent.MINIMIZED_STATUS_POPUP) {
ui.access(() -> showUploadStatusButton()); ui.access(this::showUploadStatusButton);
} else if (event == UploadArtifactUIEvent.MAXIMIZED_STATUS_POPUP) { } else if (event == UploadArtifactUIEvent.MAXIMIZED_STATUS_POPUP) {
ui.access(() -> maximizeStatusPopup()); ui.access(this::maximizeStatusPopup);
} else if (event == UploadArtifactUIEvent.ARTIFACT_RESULT_POPUP_CLOSED) { } else if (event == UploadArtifactUIEvent.ARTIFACT_RESULT_POPUP_CLOSED) {
ui.access(() -> closeUploadStatusPopup()); ui.access(this::closeUploadStatusPopup);
} }
} }
@@ -243,27 +243,42 @@ public class UploadLayout extends VerticalLayout {
// selected software module at the time of file drop is // selected software module at the time of file drop is
// considered for upload // considered for upload
if (!artifactUploadState.getSelectedBaseSoftwareModule().isPresent()) { artifactUploadState.getSelectedBaseSoftwareModule().ifPresent(selectedSw -> {
return; // reset the flag
} hasDirectory = false;
for (final Html5File file : files) {
final SoftwareModule selectedSw = artifactUploadState.getSelectedBaseSoftwareModule().get(); processFile(file, selectedSw);
// reset the flag }
hasDirectory = Boolean.FALSE; if (artifactUploadState.getNumberOfFileUploadsExpected().get() > 0) {
for (final Html5File file : files) { processBtn.setEnabled(false);
processFile(file, selectedSw); } else {
} // If the upload is not started, it signifies all
if (artifactUploadState.getNumberOfFileUploadsExpected().get() > 0) { // dropped files as either duplicate or directory.So
processBtn.setEnabled(false); // display message accordingly
} else { displayCompositeMessage();
// If the upload is not started, it signifies all }
// dropped files as either duplicate or directory.So });
// display message accordingly
displayCompositeMessage();
}
} }
} }
private boolean validate(final DragAndDropEvent event) {
// check if drop is valid.If valid ,check if software module is
// selected.
if (!isFilesDropped(event)) {
uiNotification.displayValidationError(i18n.getMessage("message.action.not.allowed"));
return false;
}
return checkIfSoftwareModuleIsSelected();
}
private boolean isFilesDropped(final DragAndDropEvent event) {
if (event.getTransferable() instanceof WrapperTransferable) {
final Html5File[] files = ((WrapperTransferable) event.getTransferable()).getFiles();
return files != null;
}
return false;
}
private void processFile(final Html5File file, final SoftwareModule selectedSw) { private void processFile(final Html5File file, final SoftwareModule selectedSw) {
if (!isDirectory(file)) { if (!isDirectory(file)) {
if (!checkForDuplicate(file.getFileName(), selectedSw)) { if (!checkForDuplicate(file.getFileName(), selectedSw)) {
@@ -401,34 +416,9 @@ public class UploadLayout extends VerticalLayout {
} }
private Boolean validate(final DragAndDropEvent event) { boolean checkIfSoftwareModuleIsSelected() {
// check if drop is valid.If valid ,check if software module is
// selected.
if (!isFilesDropped(event)) {
uiNotification.displayValidationError(i18n.getMessage("message.action.not.allowed"));
return false;
}
return checkIfSoftwareModuleIsSelected();
}
private static boolean isFilesDropped(final DragAndDropEvent event) {
if (event.getTransferable() instanceof WrapperTransferable) {
final Html5File[] files = ((WrapperTransferable) event.getTransferable()).getFiles();
return files != null;
}
return false;
}
Boolean checkIfSoftwareModuleIsSelected() {
if (!isSoftwareModuleSelected()) {
uiNotification.displayValidationError(i18n.getMessage("message.error.noSwModuleSelected"));
return false;
}
return true;
}
Boolean isSoftwareModuleSelected() {
if (!artifactUploadState.getSelectedBaseSwModuleId().isPresent()) { if (!artifactUploadState.getSelectedBaseSwModuleId().isPresent()) {
uiNotification.displayValidationError(i18n.getMessage("message.error.noSwModuleSelected"));
return false; return false;
} }
return true; return true;

View File

@@ -84,7 +84,7 @@ public class UploadStatusObject implements Serializable {
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (!(obj instanceof UploadStatusObject)) { if (getClass() != obj.getClass()) {
return false; return false;
} }
final UploadStatusObject other = (UploadStatusObject) obj; final UploadStatusObject other = (UploadStatusObject) obj;

View File

@@ -12,7 +12,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions;
@@ -41,7 +40,6 @@ public class DistributionSetTypeBeanQuery extends AbstractBeanQuery<Distribution
private final Sort sort = new Sort(Direction.ASC, "name"); private final Sort sort = new Sort(Direction.ASC, "name");
private transient Page<DistributionSetType> firstPageDistSetType; private transient Page<DistributionSetType> firstPageDistSetType;
private transient DistributionSetManagement distributionSetManagement; private transient DistributionSetManagement distributionSetManagement;
private transient EntityFactory entityFactory;
/** /**
* Parametric constructor. * Parametric constructor.
@@ -80,13 +78,6 @@ public class DistributionSetTypeBeanQuery extends AbstractBeanQuery<Distribution
return distributionSetManagement; return distributionSetManagement;
} }
private EntityFactory getEntityFactory() {
if (entityFactory == null) {
entityFactory = SpringContextHelper.getBean(EntityFactory.class);
}
return entityFactory;
}
@Override @Override
protected List<DistributionSetType> loadBeans(final int startIndex, final int count) { protected List<DistributionSetType> loadBeans(final int startIndex, final int count) {
Page<DistributionSetType> typeBeans; Page<DistributionSetType> typeBeans;

View File

@@ -11,7 +11,6 @@ package org.eclipse.hawkbit.ui.common;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
@@ -30,9 +29,8 @@ import org.vaadin.addons.lazyquerycontainer.QueryDefinition;
public class SoftwareModuleTypeBeanQuery extends AbstractBeanQuery<SoftwareModuleType> { public class SoftwareModuleTypeBeanQuery extends AbstractBeanQuery<SoftwareModuleType> {
private static final long serialVersionUID = 7824925429198339644L; private static final long serialVersionUID = 7824925429198339644L;
private final Sort sort = new Sort(Direction.ASC, "name"); private final Sort sort = new Sort(Direction.ASC, "name");
private transient Page<SoftwareModuleType> firstPageSwModuleType = null; private transient Page<SoftwareModuleType> firstPageSwModuleType;
private transient SoftwareManagement softwareManagement; private transient SoftwareManagement softwareManagement;
private transient EntityFactory entityFactory;
/** /**
* Parametric constructor. * Parametric constructor.
@@ -52,13 +50,6 @@ public class SoftwareModuleTypeBeanQuery extends AbstractBeanQuery<SoftwareModul
return null; return null;
} }
private EntityFactory getEntityFactory() {
if (entityFactory == null) {
entityFactory = SpringContextHelper.getBean(EntityFactory.class);
}
return entityFactory;
}
@Override @Override
public int size() { public int size() {
firstPageSwModuleType = getSoftwareManagement() firstPageSwModuleType = getSoftwareManagement()

View File

@@ -302,13 +302,13 @@ public abstract class AbstractTableDetailsLayout<T extends NamedEntity> extends
protected abstract String getEditButtonId(); protected abstract String getEditButtonId();
protected abstract Boolean onLoadIsTableRowSelected(); protected abstract boolean onLoadIsTableRowSelected();
protected abstract Boolean onLoadIsTableMaximized(); protected abstract boolean onLoadIsTableMaximized();
protected abstract String getTabSheetId(); protected abstract String getTabSheetId();
protected abstract Boolean hasEditPermission(); protected abstract boolean hasEditPermission();
public VerticalLayout getDetailsLayout() { public VerticalLayout getDetailsLayout() {
return detailsLayout; return detailsLayout;
@@ -334,7 +334,7 @@ public abstract class AbstractTableDetailsLayout<T extends NamedEntity> extends
protected abstract String getName(); protected abstract String getName();
protected abstract Boolean isMetadataIconToBeDisplayed(); protected abstract boolean isMetadataIconToBeDisplayed();
protected abstract void showMetadata(Button.ClickEvent event); protected abstract void showMetadata(Button.ClickEvent event);

View File

@@ -65,7 +65,7 @@ public class DistributionSetIdName implements Serializable {
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + (id == null ? 0 : id.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode());
return result; return result;
} }
@@ -77,7 +77,7 @@ public class DistributionSetIdName implements Serializable {
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (!(obj instanceof DistributionSetIdName)) { if (getClass() != obj.getClass()) {
return false; return false;
} }
final DistributionSetIdName other = (DistributionSetIdName) obj; final DistributionSetIdName other = (DistributionSetIdName) obj;

View File

@@ -85,7 +85,7 @@ public class TargetIdName implements Serializable {
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (!(obj instanceof TargetIdName)) { if (getClass() != obj.getClass()) {
return false; return false;
} }
final TargetIdName other = (TargetIdName) obj; final TargetIdName other = (TargetIdName) obj;

View File

@@ -8,13 +8,8 @@
*/ */
package org.eclipse.hawkbit.ui.components; package org.eclipse.hawkbit.ui.components;
import static com.vaadin.ui.themes.ValoTheme.NOTIFICATION_CLOSABLE;
import static com.vaadin.ui.themes.ValoTheme.NOTIFICATION_FAILURE;
import static com.vaadin.ui.themes.ValoTheme.NOTIFICATION_SMALL;
import static java.lang.System.lineSeparator;
import static java.util.stream.Collectors.joining;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException; import javax.validation.ConstraintViolationException;
@@ -33,6 +28,7 @@ import com.vaadin.shared.Connector;
import com.vaadin.ui.Component; import com.vaadin.ui.Component;
import com.vaadin.ui.Notification.Type; import com.vaadin.ui.Notification.Type;
import com.vaadin.ui.UI; import com.vaadin.ui.UI;
import com.vaadin.ui.themes.ValoTheme;
/** /**
* Default handler for Hawkbit UI. * Default handler for Hawkbit UI.
@@ -42,7 +38,8 @@ public class HawkbitUIErrorHandler extends DefaultErrorHandler {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(HawkbitUIErrorHandler.class); private static final Logger LOG = LoggerFactory.getLogger(HawkbitUIErrorHandler.class);
private static final String STYLE = NOTIFICATION_FAILURE + " " + NOTIFICATION_SMALL + " " + NOTIFICATION_CLOSABLE; private static final String STYLE = ValoTheme.NOTIFICATION_FAILURE + " " + ValoTheme.NOTIFICATION_SMALL + " "
+ ValoTheme.NOTIFICATION_CLOSABLE;
@Override @Override
public void error(final ErrorEvent event) { public void error(final ErrorEvent event) {
@@ -121,6 +118,6 @@ public class HawkbitUIErrorHandler extends DefaultErrorHandler {
} }
return violations.stream().map(violation -> violation.getPropertyPath() + " " + violation.getMessage()) return violations.stream().map(violation -> violation.getPropertyPath() + " " + violation.getMessage())
.collect(joining(lineSeparator())); .collect(Collectors.joining(System.lineSeparator()));
} }
} }

View File

@@ -9,7 +9,6 @@
package org.eclipse.hawkbit.ui.distributions.dstable; package org.eclipse.hawkbit.ui.distributions.dstable;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@@ -28,7 +27,6 @@ import org.eclipse.hawkbit.ui.common.detailslayout.AbstractNamedVersionedEntityT
import org.eclipse.hawkbit.ui.common.detailslayout.DistributionSetMetadatadetailslayout; import org.eclipse.hawkbit.ui.common.detailslayout.DistributionSetMetadatadetailslayout;
import org.eclipse.hawkbit.ui.common.detailslayout.SoftwareModuleDetailsTable; import org.eclipse.hawkbit.ui.common.detailslayout.SoftwareModuleDetailsTable;
import org.eclipse.hawkbit.ui.common.detailslayout.TargetFilterQueryDetailsTable; import org.eclipse.hawkbit.ui.common.detailslayout.TargetFilterQueryDetailsTable;
import org.eclipse.hawkbit.ui.common.entity.DistributionSetIdName;
import org.eclipse.hawkbit.ui.common.entity.SoftwareModuleIdName; import org.eclipse.hawkbit.ui.common.entity.SoftwareModuleIdName;
import org.eclipse.hawkbit.ui.common.tagdetails.DistributionTagToken; import org.eclipse.hawkbit.ui.common.tagdetails.DistributionTagToken;
import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider;
@@ -139,42 +137,40 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void showUnsavedAssignment() { private void showUnsavedAssignment() {
Item item; final Set<SoftwareModuleIdName> softwareModuleIdNameList = manageDistUIState.getLastSelectedDistribution()
final Map<DistributionSetIdName, HashSet<SoftwareModuleIdName>> assignedList = manageDistUIState .map(selectedDistId -> manageDistUIState.getAssignedList().entrySet().stream()
.getAssignedList(); .filter(entry -> entry.getKey().getId().equals(selectedDistId)).findAny()
final Long selectedDistId = manageDistUIState.getLastSelectedDistribution().isPresent() .map(Map.Entry::getValue).orElse(null))
? manageDistUIState.getLastSelectedDistribution().get() : null; .orElse(null);
Set<SoftwareModuleIdName> softwareModuleIdNameList = null;
for (final Map.Entry<DistributionSetIdName, HashSet<SoftwareModuleIdName>> entry : assignedList.entrySet()) {
if (entry.getKey().getId().equals(selectedDistId)) {
softwareModuleIdNameList = entry.getValue();
break;
}
}
if (null != softwareModuleIdNameList) { if (null != softwareModuleIdNameList) {
if (assignedSWModule == null) { if (assignedSWModule == null) {
assignedSWModule = new HashMap<>(); assignedSWModule = new HashMap<>();
} }
for (final SoftwareModuleIdName swIdName : softwareModuleIdNameList) { softwareModuleIdNameList.stream().map(SoftwareModuleIdName::getId)
final SoftwareModule softwareModule = softwareManagement.findSoftwareModuleById(swIdName.getId()).get(); .map(softwareManagement::findSoftwareModuleById)
if (assignedSWModule.containsKey(softwareModule.getType().getName())) { .forEach(found -> found.ifPresent(softwareModule -> {
assignedSWModule.get(softwareModule.getType().getName()).append("</br>").append("<I>")
.append(getUnsavedAssigedSwModule(softwareModule.getName(), softwareModule.getVersion()))
.append("<I>");
} else { if (assignedSWModule.containsKey(softwareModule.getType().getName())) {
assignedSWModule.put(softwareModule.getType().getName(), assignedSWModule.get(softwareModule.getType().getName()).append("</br>").append("<I>")
new StringBuilder().append("<I>").append( .append(HawkbitCommonUtil.getFormattedNameVersion(softwareModule.getName(),
getUnsavedAssigedSwModule(softwareModule.getName(), softwareModule.getVersion())) softwareModule.getVersion()))
.append("<I>")); .append("<I>");
}
} else {
assignedSWModule
.put(softwareModule.getType().getName(),
new StringBuilder().append("<I>")
.append(HawkbitCommonUtil.getFormattedNameVersion(
softwareModule.getName(), softwareModule.getVersion()))
.append("<I>"));
}
}));
}
for (final Map.Entry<String, StringBuilder> entry : assignedSWModule.entrySet()) { for (final Map.Entry<String, StringBuilder> entry : assignedSWModule.entrySet()) {
item = softwareModuleTable.getContainerDataSource().getItem(entry.getKey()); final Item item = softwareModuleTable.getContainerDataSource().getItem(entry.getKey());
if (item != null) { if (item != null) {
item.getItemProperty(SOFT_MODULE).setValue(createSoftModuleLayout(entry.getValue().toString())); item.getItemProperty(SOFT_MODULE).setValue(createSoftModuleLayout(entry.getValue().toString()));
} }
@@ -183,10 +179,9 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet
} }
private Button assignSoftModuleButton(final String softwareModuleName) { private Button assignSoftModuleButton(final String softwareModuleName) {
if (getPermissionChecker().hasUpdateDistributionPermission() if (getPermissionChecker().hasUpdateDistributionPermission() && manageDistUIState.getLastSelectedDistribution()
&& manageDistUIState.getLastSelectedDistribution().isPresent() .map(selected -> targetManagement.countTargetByAssignedDistributionSet(selected) <= 0).orElse(false)) {
&& targetManagement.countTargetByAssignedDistributionSet(
manageDistUIState.getLastSelectedDistribution().get()) <= 0) {
final Button reassignSoftModule = SPUIComponentProvider.getButton(softwareModuleName, "", "", "", true, final Button reassignSoftModule = SPUIComponentProvider.getButton(softwareModuleName, "", "", "", true,
FontAwesome.TIMES, SPUIButtonStyleSmallNoBorder.class); FontAwesome.TIMES, SPUIButtonStyleSmallNoBorder.class);
reassignSoftModule.setEnabled(false); reassignSoftModule.setEnabled(false);
@@ -195,10 +190,6 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet
return null; return null;
} }
private static String getUnsavedAssigedSwModule(final String name, final String version) {
return HawkbitCommonUtil.getFormattedNameVersion(name, version);
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void updateSoftwareModule(final SoftwareModule module) { private void updateSoftwareModule(final SoftwareModule module) {
if (assignedSWModule == null) { if (assignedSWModule == null) {
@@ -209,28 +200,33 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet
if (assignedSWModule.containsKey(module.getType().getName())) { if (assignedSWModule.containsKey(module.getType().getName())) {
/* /*
* If software module type is software, means multiple softwares can * If software module type is software, means multiple softwares can
* assigned to that type. Hence if multipe softwares belongs to same * assigned to that type. Hence if multiple softwares belongs to
* type is drroped, then add to the list. * same type is dropped, then add to the list.
*/ */
if (module.getType().getMaxAssignments() > 1) { if (module.getType().getMaxAssignments() > 1) {
assignedSWModule.get(module.getType().getName()).append("</br>").append("<I>") assignedSWModule.get(module.getType().getName()).append("</br>").append("<I>")
.append(getUnsavedAssigedSwModule(module.getName(), module.getVersion())).append("</I>"); .append(HawkbitCommonUtil.getFormattedNameVersion(module.getName(), module.getVersion()))
.append("</I>");
} }
/* /*
* If software mocule type is firmware, means single software can be * If software module type is firmware, means single software can be
* assigned to that type. Hence if multiple softwares belongs to * assigned to that type. Hence if multiple softwares belongs to
* same type is dropped, then override with previous one. * same type is dropped, then override with previous one.
*/ */
if (module.getType().getMaxAssignments() == 1) { if (module.getType().getMaxAssignments() == 1) {
assignedSWModule.put(module.getType().getName(), new StringBuilder().append("<I>") assignedSWModule.put(module.getType().getName(),
.append(getUnsavedAssigedSwModule(module.getName(), module.getVersion())).append("</I>")); new StringBuilder().append("<I>").append(
HawkbitCommonUtil.getFormattedNameVersion(module.getName(), module.getVersion()))
.append("</I>"));
} }
} else { } else {
assignedSWModule.put(module.getType().getName(), new StringBuilder().append("<I>") assignedSWModule.put(module.getType().getName(),
.append(getUnsavedAssigedSwModule(module.getName(), module.getVersion())).append("</I>")); new StringBuilder().append("<I>")
.append(HawkbitCommonUtil.getFormattedNameVersion(module.getName(), module.getVersion()))
.append("</I>"));
} }
for (final Map.Entry<String, StringBuilder> entry : assignedSWModule.entrySet()) { for (final Map.Entry<String, StringBuilder> entry : assignedSWModule.entrySet()) {
@@ -322,13 +318,12 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet
} }
@Override @Override
protected Boolean onLoadIsTableRowSelected() { protected boolean onLoadIsTableRowSelected() {
return manageDistUIState.getSelectedDistributions().isPresent() return manageDistUIState.getSelectedDistributions().map(selected -> !selected.isEmpty()).orElse(false);
&& !manageDistUIState.getSelectedDistributions().get().isEmpty();
} }
@Override @Override
protected Boolean onLoadIsTableMaximized() { protected boolean onLoadIsTableMaximized() {
return manageDistUIState.isDsTableMaximized(); return manageDistUIState.isDsTableMaximized();
} }
@@ -349,7 +344,7 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet
} }
@Override @Override
protected Boolean hasEditPermission() { protected boolean hasEditPermission() {
return getPermissionChecker().hasUpdateDistributionPermission(); return getPermissionChecker().hasUpdateDistributionPermission();
} }
@@ -404,7 +399,7 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet
} }
@Override @Override
protected Boolean isMetadataIconToBeDisplayed() { protected boolean isMetadataIconToBeDisplayed() {
return true; return true;
} }

View File

@@ -172,16 +172,12 @@ public class DistributionSetTable extends AbstractNamedVersionTable<Distribution
@Override @Override
protected boolean isFirstRowSelectedOnLoad() { protected boolean isFirstRowSelectedOnLoad() {
return !manageDistUIState.getSelectedDistributions().isPresent() return manageDistUIState.getSelectedDistributions().map(Set::isEmpty).orElse(true);
|| manageDistUIState.getSelectedDistributions().get().isEmpty();
} }
@Override @Override
protected Object getItemIdToSelect() { protected Object getItemIdToSelect() {
if (manageDistUIState.getSelectedDistributions().isPresent()) { return manageDistUIState.getSelectedDistributions().orElse(null);
return manageDistUIState.getSelectedDistributions().get();
}
return null;
} }
@Override @Override
@@ -287,8 +283,8 @@ public class DistributionSetTable extends AbstractNamedVersionTable<Distribution
} }
private void publishAssignEvent(final Long distId, final SoftwareModule softwareModule) { private void publishAssignEvent(final Long distId, final SoftwareModule softwareModule) {
if (manageDistUIState.getLastSelectedDistribution().isPresent() if (manageDistUIState.getLastSelectedDistribution().map(distId::equals).orElse(false)) {
&& manageDistUIState.getLastSelectedDistribution().get().equals(distId)) {
eventBus.publish(this, eventBus.publish(this,
new SoftwareModuleEvent(SoftwareModuleEventType.ASSIGN_SOFTWARE_MODULE, softwareModule)); new SoftwareModuleEvent(SoftwareModuleEventType.ASSIGN_SOFTWARE_MODULE, softwareModule));
} }

View File

@@ -71,10 +71,7 @@ public class DistributionSetTableHeader extends AbstractTableHeader {
@Override @Override
protected String onLoadSearchBoxValue() { protected String onLoadSearchBoxValue() {
if (manageDistUIstate.getManageDistFilters().getSearchText().isPresent()) { return manageDistUIstate.getManageDistFilters().getSearchText().orElse(null);
return manageDistUIstate.getManageDistFilters().getSearchText().get();
}
return null;
} }
@Override @Override

View File

@@ -170,9 +170,8 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
final String swModuleTypeName = HawkbitCommonUtil.removePrefix(swTypeId, final String swModuleTypeName = HawkbitCommonUtil.removePrefix(swTypeId,
SPUIDefinitions.SOFTWARE_MODULE_TAG_ID_PREFIXS); SPUIDefinitions.SOFTWARE_MODULE_TAG_ID_PREFIXS);
if (manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType().isPresent() if (manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType()
&& manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType().get().getName() .map(type -> type.getName().equalsIgnoreCase(swModuleTypeName)).orElse(false)) {
.equalsIgnoreCase(swModuleTypeName)) {
notification.displayValidationError( notification.displayValidationError(
i18n.getMessage("message.swmodule.type.check.delete", new Object[] { swModuleTypeName })); i18n.getMessage("message.swmodule.type.check.delete", new Object[] { swModuleTypeName }));
} else { } else {
@@ -194,7 +193,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
} }
final Set<DistributionSetIdName> distributionIdNameSet = findDistributionSetAllById.stream() final Set<DistributionSetIdName> distributionIdNameSet = findDistributionSetAllById.stream()
.map(distributionSet -> new DistributionSetIdName(distributionSet)).collect(Collectors.toSet()); .map(DistributionSetIdName::new).collect(Collectors.toSet());
final int existingDeletedDistributionsSize = manageDistUIState.getDeletedDistributionList().size(); final int existingDeletedDistributionsSize = manageDistUIState.getDeletedDistributionList().size();
manageDistUIState.getDeletedDistributionList().addAll(distributionIdNameSet); manageDistUIState.getDeletedDistributionList().addAll(distributionIdNameSet);

View File

@@ -125,17 +125,17 @@ public class SwModuleDetails extends AbstractNamedVersionedEntityTableDetailsLay
} }
@Override @Override
protected Boolean onLoadIsTableRowSelected() { protected boolean onLoadIsTableRowSelected() {
return !manageDistUIState.getSelectedSoftwareModules().isEmpty(); return !manageDistUIState.getSelectedSoftwareModules().isEmpty();
} }
@Override @Override
protected Boolean onLoadIsTableMaximized() { protected boolean onLoadIsTableMaximized() {
return manageDistUIState.isSwModuleTableMaximized(); return manageDistUIState.isSwModuleTableMaximized();
} }
@Override @Override
protected Boolean hasEditPermission() { protected boolean hasEditPermission() {
return getPermissionChecker().hasUpdateDistributionPermission(); return getPermissionChecker().hasUpdateDistributionPermission();
} }
@@ -209,7 +209,7 @@ public class SwModuleDetails extends AbstractNamedVersionedEntityTableDetailsLay
} }
@Override @Override
protected Boolean isMetadataIconToBeDisplayed() { protected boolean isMetadataIconToBeDisplayed() {
return true; return true;
} }

View File

@@ -74,8 +74,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() && manageDistUIState return manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType()
.getSoftwareModuleFilters().getSoftwareModuleType().get().getName().equals(typeName); .map(type -> type.getName().equals(typeName)).orElse(false);
} }
@Override @Override

View File

@@ -146,12 +146,12 @@ public class CreateOrUpdateFilterHeader extends VerticalLayout implements Button
} }
private void populateComponents() { private void populateComponents() {
if (filterManagementUIState.getTfQuery().isPresent()) { filterManagementUIState.getTfQuery().ifPresent(query -> {
queryTextField.setValue(filterManagementUIState.getTfQuery().get().getQuery()); queryTextField.setValue(query.getQuery());
nameLabel.setValue(filterManagementUIState.getTfQuery().get().getName()); nameLabel.setValue(query.getName());
oldFilterName = filterManagementUIState.getTfQuery().get().getName(); oldFilterName = query.getName();
oldFilterQuery = filterManagementUIState.getTfQuery().get().getQuery(); oldFilterQuery = query.getQuery();
} });
breadcrumbName.setValue(nameLabel.getValue()); breadcrumbName.setValue(nameLabel.getValue());
queryTextField.showValidationSuccesIcon(filterManagementUIState.getFilterQueryValue()); queryTextField.showValidationSuccesIcon(filterManagementUIState.getFilterQueryValue());
titleFilterIconsLayout.addStyleName(SPUIStyleDefinitions.TARGET_FILTER_CAPTION_LAYOUT); titleFilterIconsLayout.addStyleName(SPUIStyleDefinitions.TARGET_FILTER_CAPTION_LAYOUT);

View File

@@ -139,10 +139,7 @@ public class DistributionSetSelectTable extends Table {
} }
private Object getItemIdToSelect() { private Object getItemIdToSelect() {
if (manageDistUIState.getSelectedDistributions().isPresent()) { return manageDistUIState.getSelectedDistributions().orElse(null);
return manageDistUIState.getSelectedDistributions().get();
}
return null;
} }
private void selectRow() { private void selectRow() {

View File

@@ -24,6 +24,7 @@ import org.eclipse.hawkbit.repository.model.ActionWithStatusCount;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.ui.common.ConfirmationDialog; import org.eclipse.hawkbit.ui.common.ConfirmationDialog;
import org.eclipse.hawkbit.ui.common.builder.LabelBuilder; import org.eclipse.hawkbit.ui.common.builder.LabelBuilder;
import org.eclipse.hawkbit.ui.common.entity.TargetIdName;
import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType;
import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider;
import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder;
@@ -803,13 +804,8 @@ public class ActionHistoryTable extends TreeTable {
* Pinning. * Pinning.
*/ */
private void updateDistributionTableStyle() { private void updateDistributionTableStyle() {
if (managementUIState.getDistributionTableFilters().getPinnedTarget().map(TargetIdName::getTargetId)
if (!managementUIState.getDistributionTableFilters().getPinnedTarget().isPresent()) { .map(target.getId()::equals).orElse(false)) {
return;
}
final Long alreadyPinnedControllerId = managementUIState.getDistributionTableFilters().getPinnedTarget().get()
.getTargetId();
if (alreadyPinnedControllerId.equals(target.getId())) {
eventBus.publish(this, PinUnpinEvent.PIN_TARGET); eventBus.publish(this, PinUnpinEvent.PIN_TARGET);
} }
} }

View File

@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.ui.management.dstable; package org.eclipse.hawkbit.ui.management.dstable;
import java.util.Optional; import java.util.Optional;
import java.util.Set;
import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.EntityFactory;
@@ -113,18 +114,17 @@ public class DistributionDetails extends AbstractNamedVersionedEntityTableDetail
} }
@Override @Override
protected Boolean onLoadIsTableRowSelected() { protected boolean onLoadIsTableRowSelected() {
return !(managementUIState.getSelectedDsIdName().isPresent() return managementUIState.getSelectedDsIdName().map(Set::isEmpty).orElse(true);
&& managementUIState.getSelectedDsIdName().get().isEmpty());
} }
@Override @Override
protected Boolean onLoadIsTableMaximized() { protected boolean onLoadIsTableMaximized() {
return managementUIState.isDsTableMaximized(); return managementUIState.isDsTableMaximized();
} }
@Override @Override
protected Boolean hasEditPermission() { protected boolean hasEditPermission() {
return getPermissionChecker().hasUpdateDistributionPermission(); return getPermissionChecker().hasUpdateDistributionPermission();
} }
@@ -191,7 +191,7 @@ public class DistributionDetails extends AbstractNamedVersionedEntityTableDetail
} }
@Override @Override
protected Boolean isMetadataIconToBeDisplayed() { protected boolean isMetadataIconToBeDisplayed() {
return true; return true;
} }

View File

@@ -141,7 +141,7 @@ public class DistributionTable extends AbstractNamedVersionTable<DistributionSet
final List<DistributionSetUpdateEvent> events, final List<Long> visibleItemIds) { final List<DistributionSetUpdateEvent> events, final List<Long> visibleItemIds) {
final List<Long> setsThatAreVisibleButNotCompleteAnymore = events.stream() final List<Long> setsThatAreVisibleButNotCompleteAnymore = events.stream()
.filter(event -> visibleItemIds.contains(event.getEntityId())) .filter(event -> visibleItemIds.contains(event.getEntityId()))
.filter(event -> !event.getEntity().isComplete()).map(event -> event.getEntityId()) .filter(event -> !event.getEntity().isComplete()).map(DistributionSetUpdateEvent::getEntityId)
.collect(Collectors.toList()); .collect(Collectors.toList());
if (!setsThatAreVisibleButNotCompleteAnymore.isEmpty()) { if (!setsThatAreVisibleButNotCompleteAnymore.isEmpty()) {
@@ -168,7 +168,7 @@ public class DistributionTable extends AbstractNamedVersionTable<DistributionSet
if (event == DistributionTableFilterEvent.FILTER_BY_TEXT if (event == DistributionTableFilterEvent.FILTER_BY_TEXT
|| event == DistributionTableFilterEvent.REMOVE_FILTER_BY_TEXT || event == DistributionTableFilterEvent.REMOVE_FILTER_BY_TEXT
|| event == DistributionTableFilterEvent.FILTER_BY_TAG) { || event == DistributionTableFilterEvent.FILTER_BY_TAG) {
UI.getCurrent().access(() -> refreshFilter()); UI.getCurrent().access(this::refreshFilter);
} }
} }
@@ -291,16 +291,12 @@ public class DistributionTable extends AbstractNamedVersionTable<DistributionSet
@Override @Override
protected boolean isFirstRowSelectedOnLoad() { protected boolean isFirstRowSelectedOnLoad() {
return !managementUIState.getSelectedDsIdName().isPresent() return managementUIState.getSelectedDsIdName().map(Set::isEmpty).orElse(true);
|| managementUIState.getSelectedDsIdName().get().isEmpty();
} }
@Override @Override
protected Object getItemIdToSelect() { protected Object getItemIdToSelect() {
if (managementUIState.getSelectedDsIdName().isPresent()) { return managementUIState.getSelectedDsIdName().orElse(null);
return managementUIState.getSelectedDsIdName().get();
}
return null;
} }
@Override @Override
@@ -524,26 +520,24 @@ public class DistributionTable extends AbstractNamedVersionTable<DistributionSet
} }
private void styleDistributionTableOnPinning() { private void styleDistributionTableOnPinning() {
if (!managementUIState.getDistributionTableFilters().getPinnedTarget().isPresent()) {
return;
}
final Optional<Target> targetObj = targetService.findTargetByControllerIDWithDetails( managementUIState.getDistributionTableFilters().getPinnedTarget().map(TargetIdName::getControllerId)
managementUIState.getDistributionTableFilters().getPinnedTarget().get().getControllerId()); .map(targetService::findTargetByControllerIDWithDetails)
.ifPresent(pinnedTarget -> pinnedTarget.ifPresent(target -> {
final DistributionSet assignedDistribution = target.getAssignedDistributionSet();
final DistributionSet installedDistribution = target.getTargetInfo().getInstalledDistributionSet();
Long installedDistId = null;
Long assignedDistId = null;
if (null != installedDistribution) {
installedDistId = installedDistribution.getId();
}
if (null != assignedDistribution) {
assignedDistId = assignedDistribution.getId();
}
styleDistributionSetTable(installedDistId, assignedDistId);
}));
if (targetObj.isPresent()) {
final DistributionSet assignedDistribution = targetObj.get().getAssignedDistributionSet();
final DistributionSet installedDistribution = targetObj.get().getTargetInfo().getInstalledDistributionSet();
Long installedDistId = null;
Long assignedDistId = null;
if (null != installedDistribution) {
installedDistId = installedDistribution.getId();
}
if (null != assignedDistribution) {
assignedDistId = assignedDistribution.getId();
}
styleDistributionSetTable(installedDistId, assignedDistId);
}
} }
private static String getPinnedDistributionStyle(final Long installedDistItemIds, private static String getPinnedDistributionStyle(final Long installedDistItemIds,
@@ -573,9 +567,13 @@ public class DistributionTable extends AbstractNamedVersionTable<DistributionSet
} }
private void saveDistributionPinnedBtn(final Button pinBtn) { private void saveDistributionPinnedBtn(final Button pinBtn) {
if (managementUIState.getTargetTableFilters().getPinnedDistId().isPresent() if (pinBtn.getData() == null) {
&& managementUIState.getTargetTableFilters().getPinnedDistId().get() return;
.equals(((DistributionSetIdName) pinBtn.getData()).getId())) { }
final Long pinnedId = ((DistributionSetIdName) pinBtn.getData()).getId();
if (managementUIState.getTargetTableFilters().getPinnedDistId().map(pinnedId::equals).orElse(false)) {
setDistributinPinnedBtn(pinBtn); setDistributinPinnedBtn(pinBtn);
} }
} }
@@ -592,15 +590,13 @@ public class DistributionTable extends AbstractNamedVersionTable<DistributionSet
private void checkifAlreadyPinned(final Button eventBtn) { private void checkifAlreadyPinned(final Button eventBtn) {
final Long newPinnedDistItemId = ((DistributionSetIdName) eventBtn.getData()).getId(); final Long newPinnedDistItemId = ((DistributionSetIdName) eventBtn.getData()).getId();
Long pinnedDistId = null; final Long pinnedDistId = managementUIState.getTargetTableFilters().getPinnedDistId().orElse(null);
if (managementUIState.getTargetTableFilters().getPinnedDistId().isPresent()) {
pinnedDistId = managementUIState.getTargetTableFilters().getPinnedDistId().get();
}
if (pinnedDistId == null) { if (pinnedDistId == null) {
isDistPinned = !isDistPinned; isDistPinned = !isDistPinned;
managementUIState.getTargetTableFilters().setPinnedDistId(newPinnedDistItemId); managementUIState.getTargetTableFilters().setPinnedDistId(newPinnedDistItemId);
} else if (newPinnedDistItemId.equals(pinnedDistId)) { } else if (newPinnedDistItemId.equals(pinnedDistId)) {
isDistPinned = Boolean.FALSE; isDistPinned = false;
} else { } else {
isDistPinned = true; isDistPinned = true;
managementUIState.getTargetTableFilters().setPinnedDistId(newPinnedDistItemId); managementUIState.getTargetTableFilters().setPinnedDistId(newPinnedDistItemId);
@@ -632,8 +628,7 @@ public class DistributionTable extends AbstractNamedVersionTable<DistributionSet
} }
private void rePinDistribution(final Button pinBtn, final Long distID) { private void rePinDistribution(final Button pinBtn, final Long distID) {
if (managementUIState.getTargetTableFilters().getPinnedDistId().isPresent() if (managementUIState.getTargetTableFilters().getPinnedDistId().map(distID::equals).orElse(false)) {
&& distID.equals(managementUIState.getTargetTableFilters().getPinnedDistId().get())) {
applyPinStyle(pinBtn); applyPinStyle(pinBtn);
isDistPinned = Boolean.TRUE; isDistPinned = Boolean.TRUE;
distributinPinnedBtn = pinBtn; distributinPinnedBtn = pinBtn;

View File

@@ -67,10 +67,7 @@ public class DistributionTableHeader extends AbstractTableHeader {
@Override @Override
protected String onLoadSearchBoxValue() { protected String onLoadSearchBoxValue() {
if (managementUIState.getDistributionTableFilters().getSearchText().isPresent()) { return managementUIState.getDistributionTableFilters().getSearchText().orElse(null);
return managementUIState.getDistributionTableFilters().getSearchText().get();
}
return null;
} }
@Override @Override

View File

@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.ui.management.footer; package org.eclipse.hawkbit.ui.management.footer;
import java.util.List; import java.util.List;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.TargetManagement;
@@ -29,7 +30,6 @@ import org.vaadin.spring.events.EventBus.UIEventBus;
import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.EventScope;
import org.vaadin.spring.events.annotation.EventBusListenerMethod; import org.vaadin.spring.events.annotation.EventBusListenerMethod;
import com.google.common.base.Optional;
import com.vaadin.server.FontAwesome; import com.vaadin.server.FontAwesome;
import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.Label; import com.vaadin.ui.Label;
@@ -103,9 +103,10 @@ public class CountMessageLabel extends Label {
*/ */
@EventBusListenerMethod(scope = EventScope.UI) @EventBusListenerMethod(scope = EventScope.UI)
public void onEvent(final PinUnpinEvent event) { public void onEvent(final PinUnpinEvent event) {
if (event == PinUnpinEvent.PIN_DISTRIBUTION final Optional<Long> pinnedDist = managementUIState.getTargetTableFilters().getPinnedDistId();
&& managementUIState.getTargetTableFilters().getPinnedDistId().isPresent()) {
displayCountLabel(managementUIState.getTargetTableFilters().getPinnedDistId().get()); if (event == PinUnpinEvent.PIN_DISTRIBUTION && pinnedDist.isPresent()) {
displayCountLabel(pinnedDist.get());
} else { } else {
setValue(""); setValue("");
displayTargetCountStatus(); displayTargetCountStatus();
@@ -158,8 +159,8 @@ public class CountMessageLabel extends Label {
message.append(filterMesage); message.append(filterMesage);
} }
if ((targetTable.size() + Optional.fromNullable(managementUIState.getTargetsTruncated()) if ((targetTable.size() + Optional.ofNullable(managementUIState.getTargetsTruncated())
.or(0L)) > SPUIDefinitions.MAX_TABLE_ENTRIES) { .orElse(0L)) > SPUIDefinitions.MAX_TABLE_ENTRIES) {
message.append(HawkbitCommonUtil.SP_STRING_PIPE); message.append(HawkbitCommonUtil.SP_STRING_PIPE);
message.append(i18n.getMessage("label.filter.shown")); message.append(i18n.getMessage("label.filter.shown"));
message.append(SPUIDefinitions.MAX_TABLE_ENTRIES); message.append(SPUIDefinitions.MAX_TABLE_ENTRIES);

View File

@@ -15,6 +15,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -205,13 +206,16 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin
} }
private void resfreshPinnedDetails(final Map<Long, List<TargetIdName>> saveAssignedList) { private void resfreshPinnedDetails(final Map<Long, List<TargetIdName>> saveAssignedList) {
if (managementUIState.getTargetTableFilters().getPinnedDistId().isPresent()) { final Optional<Long> pinnedDist = managementUIState.getTargetTableFilters().getPinnedDistId();
if (saveAssignedList.keySet().contains(managementUIState.getTargetTableFilters().getPinnedDistId().get())) { final Optional<TargetIdName> pinnedTarget = managementUIState.getDistributionTableFilters().getPinnedTarget();
if (pinnedDist.isPresent()) {
if (saveAssignedList.keySet().contains(pinnedDist.get())) {
eventBus.publish(this, PinUnpinEvent.PIN_DISTRIBUTION); eventBus.publish(this, PinUnpinEvent.PIN_DISTRIBUTION);
} }
} else if (managementUIState.getDistributionTableFilters().getPinnedTarget().isPresent()) { } else if (pinnedTarget.isPresent()) {
final Set<TargetIdName> assignedTargetIds = managementUIState.getAssignedList().keySet(); final Set<TargetIdName> assignedTargetIds = managementUIState.getAssignedList().keySet();
if (assignedTargetIds.contains(managementUIState.getDistributionTableFilters().getPinnedTarget().get())) { if (assignedTargetIds.contains(pinnedTarget.get())) {
eventBus.publish(this, PinUnpinEvent.PIN_TARGET); eventBus.publish(this, PinUnpinEvent.PIN_TARGET);
} }
} }

View File

@@ -8,18 +8,12 @@
*/ */
package org.eclipse.hawkbit.ui.management.targettable; package org.eclipse.hawkbit.ui.management.targettable;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.apache.commons.lang3.ArrayUtils.isEmpty;
import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.isNotNullOrEmpty;
import static org.eclipse.hawkbit.ui.utils.SPUIDefinitions.TARGET_TABLE_CREATE_AT_SORT_ORDER;
import static org.springframework.data.domain.Sort.Direction.ASC;
import static org.springframework.data.domain.Sort.Direction.DESC;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.commons.lang3.ArrayUtils;
import org.eclipse.hawkbit.repository.FilterParams; import org.eclipse.hawkbit.repository.FilterParams;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.TargetManagement;
@@ -36,6 +30,7 @@ import org.eclipse.hawkbit.ui.utils.SpringContextHelper;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Slice; import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.vaadin.addons.lazyquerycontainer.AbstractBeanQuery; import org.vaadin.addons.lazyquerycontainer.AbstractBeanQuery;
import org.vaadin.addons.lazyquerycontainer.QueryDefinition; import org.vaadin.addons.lazyquerycontainer.QueryDefinition;
@@ -50,7 +45,7 @@ public class TargetBeanQuery extends AbstractBeanQuery<ProxyTarget> {
private static final long serialVersionUID = -5645680058303167558L; private static final long serialVersionUID = -5645680058303167558L;
private Sort sort = new Sort(TARGET_TABLE_CREATE_AT_SORT_ORDER, "id"); private Sort sort = new Sort(SPUIDefinitions.TARGET_TABLE_CREATE_AT_SORT_ORDER, "id");
private transient Collection<TargetUpdateStatus> status; private transient Collection<TargetUpdateStatus> status;
private transient Boolean overdueState; private transient Boolean overdueState;
private String[] targetTags; private String[] targetTags;
@@ -80,7 +75,7 @@ public class TargetBeanQuery extends AbstractBeanQuery<ProxyTarget> {
super(definition, queryConfig, sortIds, sortStates); super(definition, queryConfig, sortIds, sortStates);
if (isNotNullOrEmpty(queryConfig)) { if (HawkbitCommonUtil.isNotNullOrEmpty(queryConfig)) {
status = (Collection<TargetUpdateStatus>) queryConfig.get(SPUIDefinitions.FILTER_BY_STATUS); status = (Collection<TargetUpdateStatus>) queryConfig.get(SPUIDefinitions.FILTER_BY_STATUS);
overdueState = (Boolean) queryConfig.get(SPUIDefinitions.FILTER_BY_OVERDUE_STATE); overdueState = (Boolean) queryConfig.get(SPUIDefinitions.FILTER_BY_OVERDUE_STATE);
targetTags = (String[]) queryConfig.get(SPUIDefinitions.FILTER_BY_TAG); targetTags = (String[]) queryConfig.get(SPUIDefinitions.FILTER_BY_TAG);
@@ -94,12 +89,12 @@ public class TargetBeanQuery extends AbstractBeanQuery<ProxyTarget> {
pinnedDistId = (Long) queryConfig.get(SPUIDefinitions.ORDER_BY_DISTRIBUTION); pinnedDistId = (Long) queryConfig.get(SPUIDefinitions.ORDER_BY_DISTRIBUTION);
} }
if (!isEmpty(sortStates)) { if (!ArrayUtils.isEmpty(sortStates)) {
sort = new Sort(sortStates[0] ? ASC : DESC, (String) sortIds[0]); sort = new Sort(sortStates[0] ? Direction.ASC : Direction.DESC, (String) sortIds[0]);
for (int targetId = 1; targetId < sortIds.length; targetId++) { for (int targetId = 1; targetId < sortIds.length; targetId++) {
sort.and(new Sort(sortStates[targetId] ? ASC : DESC, (String) sortIds[targetId])); sort.and(new Sort(sortStates[targetId] ? Direction.ASC : Direction.DESC, (String) sortIds[targetId]));
} }
} }
} }
@@ -209,7 +204,7 @@ public class TargetBeanQuery extends AbstractBeanQuery<ProxyTarget> {
private boolean isAnyFilterSelected() { private boolean isAnyFilterSelected() {
final boolean isFilterSelected = isTagSelected() || isOverdueFilterEnabled(); final boolean isFilterSelected = isTagSelected() || isOverdueFilterEnabled();
return isFilterSelected || !CollectionUtils.isEmpty(status) || distributionId != null return isFilterSelected || !CollectionUtils.isEmpty(status) || distributionId != null
|| !isNullOrEmpty(searchText); || !Strings.isNullOrEmpty(searchText);
} }
private TargetManagement getTargetManagement() { private TargetManagement getTargetManagement() {

View File

@@ -129,12 +129,12 @@ public class TargetDetails extends AbstractTableDetailsLayout<Target> {
} }
@Override @Override
protected Boolean onLoadIsTableRowSelected() { protected boolean onLoadIsTableRowSelected() {
return managementUIState.getLastSelectedTargetId() != null; return managementUIState.getLastSelectedTargetId() != null;
} }
@Override @Override
protected Boolean onLoadIsTableMaximized() { protected boolean onLoadIsTableMaximized() {
return managementUIState.isTargetTableMaximized(); return managementUIState.isTargetTableMaximized();
} }
@@ -239,7 +239,7 @@ public class TargetDetails extends AbstractTableDetailsLayout<Target> {
} }
@Override @Override
protected Boolean hasEditPermission() { protected boolean hasEditPermission() {
return getPermissionChecker().hasUpdateTargetPermission(); return getPermissionChecker().hasUpdateTargetPermission();
} }
@@ -259,7 +259,7 @@ public class TargetDetails extends AbstractTableDetailsLayout<Target> {
} }
@Override @Override
protected Boolean isMetadataIconToBeDisplayed() { protected boolean isMetadataIconToBeDisplayed() {
return false; return false;
} }

View File

@@ -8,15 +8,6 @@
*/ */
package org.eclipse.hawkbit.ui.management.targettable; package org.eclipse.hawkbit.ui.management.targettable;
import static org.eclipse.hawkbit.ui.management.event.TargetFilterEvent.FILTER_BY_DISTRIBUTION;
import static org.eclipse.hawkbit.ui.management.event.TargetFilterEvent.FILTER_BY_TAG;
import static org.eclipse.hawkbit.ui.management.event.TargetFilterEvent.FILTER_BY_TARGET_FILTER_QUERY;
import static org.eclipse.hawkbit.ui.management.event.TargetFilterEvent.FILTER_BY_TEXT;
import static org.eclipse.hawkbit.ui.management.event.TargetFilterEvent.REMOVE_FILTER_BY_DISTRIBUTION;
import static org.eclipse.hawkbit.ui.management.event.TargetFilterEvent.REMOVE_FILTER_BY_TAG;
import static org.eclipse.hawkbit.ui.management.event.TargetFilterEvent.REMOVE_FILTER_BY_TARGET_FILTER_QUERY;
import static org.eclipse.hawkbit.ui.management.event.TargetFilterEvent.REMOVE_FILTER_BY_TEXT;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Date; import java.util.Date;
@@ -283,8 +274,7 @@ public class TargetTable extends AbstractTable<Target, Long> {
@Override @Override
protected boolean isFirstRowSelectedOnLoad() { protected boolean isFirstRowSelectedOnLoad() {
return !managementUIState.getSelectedTargetId().isPresent() return managementUIState.getSelectedTargetId().map(Set::isEmpty).orElse(true);
|| managementUIState.getSelectedTargetId().get().isEmpty();
} }
@Override @Override
@@ -403,9 +393,9 @@ public class TargetTable extends AbstractTable<Target, Long> {
return pinBtn; return pinBtn;
} }
private boolean isPinned(final TargetIdName pinnedTarget) { private boolean isPinned(final TargetIdName target) {
return managementUIState.getDistributionTableFilters().getPinnedTarget().isPresent() return managementUIState.getDistributionTableFilters().getPinnedTarget()
&& managementUIState.getDistributionTableFilters().getPinnedTarget().get().equals(pinnedTarget); .map(pinnedTarget -> pinnedTarget.equals(target)).orElse(false);
} }
/** /**
@@ -431,10 +421,8 @@ public class TargetTable extends AbstractTable<Target, Long> {
*/ */
private void checkifAlreadyPinned(final Button eventBtn) { private void checkifAlreadyPinned(final Button eventBtn) {
final TargetIdName newPinnedTargetItemId = (TargetIdName) eventBtn.getData(); final TargetIdName newPinnedTargetItemId = (TargetIdName) eventBtn.getData();
TargetIdName targetId = null; final TargetIdName targetId = managementUIState.getDistributionTableFilters().getPinnedTarget().orElse(null);
if (managementUIState.getDistributionTableFilters().getPinnedTarget().isPresent()) {
targetId = managementUIState.getDistributionTableFilters().getPinnedTarget().get();
}
if (targetId == null) { if (targetId == null) {
isTargetPinned = !isTargetPinned; isTargetPinned = !isTargetPinned;
managementUIState.getDistributionTableFilters().setPinnedTarget(newPinnedTargetItemId); managementUIState.getDistributionTableFilters().setPinnedTarget(newPinnedTargetItemId);
@@ -621,7 +609,7 @@ public class TargetTable extends AbstractTable<Target, Long> {
final List<DistributionSet> findDistributionSetAllById) { final List<DistributionSet> findDistributionSetAllById) {
String message = null; String message = null;
final Set<DistributionSetIdName> distributionIdNameSet = findDistributionSetAllById.stream() final Set<DistributionSetIdName> distributionIdNameSet = findDistributionSetAllById.stream()
.map(distributionSet -> new DistributionSetIdName(distributionSet)).collect(Collectors.toSet()); .map(DistributionSetIdName::new).collect(Collectors.toSet());
for (final DistributionSetIdName distributionNameId : distributionIdNameSet) { for (final DistributionSetIdName distributionNameId : distributionIdNameSet) {
if (distributionNameId != null) { if (distributionNameId != null) {
@@ -654,17 +642,6 @@ public class TargetTable extends AbstractTable<Target, Long> {
} }
} }
/**
* Get message for pending Action.
*
* @param message
* as message
* @param distName
* as Name
* @param targetId
* as ID of target
* @return String as msg
*/
private String getPendingActionMessage(final String message, final String distName, final String controllerId) { private String getPendingActionMessage(final String message, final String distName, final String controllerId) {
if (message == null) { if (message == null) {
return i18n.getMessage("message.dist.pending.action", new Object[] { controllerId, distName }); return i18n.getMessage("message.dist.pending.action", new Object[] { controllerId, distName });
@@ -723,25 +700,30 @@ public class TargetTable extends AbstractTable<Target, Long> {
} }
private static boolean isRemoveFilterEvent(final TargetFilterEvent filterEvent) { private static boolean isRemoveFilterEvent(final TargetFilterEvent filterEvent) {
return filterEvent == REMOVE_FILTER_BY_TEXT || filterEvent == REMOVE_FILTER_BY_TAG return filterEvent == TargetFilterEvent.REMOVE_FILTER_BY_TEXT
|| filterEvent == REMOVE_FILTER_BY_DISTRIBUTION || filterEvent == REMOVE_FILTER_BY_TARGET_FILTER_QUERY; || filterEvent == TargetFilterEvent.REMOVE_FILTER_BY_TAG
|| filterEvent == TargetFilterEvent.REMOVE_FILTER_BY_DISTRIBUTION
|| filterEvent == TargetFilterEvent.REMOVE_FILTER_BY_TARGET_FILTER_QUERY;
} }
private static boolean isNormalFilter(final TargetFilterEvent filterEvent) { private static boolean isNormalFilter(final TargetFilterEvent filterEvent) {
return filterEvent == FILTER_BY_TEXT || filterEvent == FILTER_BY_TAG || filterEvent == FILTER_BY_DISTRIBUTION return filterEvent == TargetFilterEvent.FILTER_BY_TEXT || filterEvent == TargetFilterEvent.FILTER_BY_TAG
|| filterEvent == FILTER_BY_TARGET_FILTER_QUERY; || filterEvent == TargetFilterEvent.FILTER_BY_DISTRIBUTION
|| filterEvent == TargetFilterEvent.FILTER_BY_TARGET_FILTER_QUERY;
} }
private String getTargetTableStyle(final Long assignedDistributionSetId, final Long installedDistributionSetId) { private String getTargetTableStyle(final Long assignedDistributionSetId, final Long installedDistributionSetId) {
final Long distPinned = managementUIState.getTargetTableFilters().getPinnedDistId().isPresent() return managementUIState.getTargetTableFilters().getPinnedDistId().map(distPinned -> {
? managementUIState.getTargetTableFilters().getPinnedDistId().get() : null; if (distPinned.equals(installedDistributionSetId)) {
return SPUIDefinitions.HIGHTLIGHT_GREEN;
}
if (null != distPinned && distPinned.equals(installedDistributionSetId)) { if (distPinned.equals(assignedDistributionSetId)) {
return SPUIDefinitions.HIGHTLIGHT_GREEN; return SPUIDefinitions.HIGHTLIGHT_ORANGE;
} else if (null != distPinned && distPinned.equals(assignedDistributionSetId)) { }
return SPUIDefinitions.HIGHTLIGHT_ORANGE;
} return null;
return null; }).orElse(null);
} }
private String createTargetTableStyle(final Object itemId, final Object propertyId) { private String createTargetTableStyle(final Object itemId, final Object propertyId) {
@@ -849,32 +831,31 @@ public class TargetTable extends AbstractTable<Target, Long> {
final long totalTargetsCount = getTotalTargetsCount(); final long totalTargetsCount = getTotalTargetsCount();
managementUIState.setTargetsCountAll(totalTargetsCount); managementUIState.setTargetsCountAll(totalTargetsCount);
Collection<TargetUpdateStatus> status = null; final boolean noTagClicked = managementUIState.getTargetTableFilters().isNoTagSelected();
Boolean overdueState = null; final Long distributionId = managementUIState.getTargetTableFilters().getDistributionSet()
String[] targetTags = null; .map(DistributionSetIdName::getId).orElse(null);
Long distributionId = null; final Long pinnedDistId = managementUIState.getTargetTableFilters().getPinnedDistId().orElse(null);
String searchText = null; final String searchText = managementUIState.getTargetTableFilters().getSearchText().map(text -> {
Long pinnedDistId = null; if (Strings.isNullOrEmpty(text)) {
return null;
}
return String.format("%%%s%%", text);
}).orElse(null);
String[] targetTags = null;
if (isFilteredByTags()) { if (isFilteredByTags()) {
targetTags = managementUIState.getTargetTableFilters().getClickedTargetTags().toArray(new String[0]); targetTags = managementUIState.getTargetTableFilters().getClickedTargetTags().toArray(new String[0]);
} }
Collection<TargetUpdateStatus> status = null;
if (isFilteredByStatus()) { if (isFilteredByStatus()) {
status = managementUIState.getTargetTableFilters().getClickedStatusTargetTags(); status = managementUIState.getTargetTableFilters().getClickedStatusTargetTags();
} }
Boolean overdueState = null;
if (managementUIState.getTargetTableFilters().isOverdueFilterEnabled()) { if (managementUIState.getTargetTableFilters().isOverdueFilterEnabled()) {
overdueState = managementUIState.getTargetTableFilters().isOverdueFilterEnabled(); overdueState = managementUIState.getTargetTableFilters().isOverdueFilterEnabled();
} }
if (managementUIState.getTargetTableFilters().getDistributionSet().isPresent()) {
distributionId = managementUIState.getTargetTableFilters().getDistributionSet().get().getId();
}
if (isFilteredByText()) {
searchText = String.format("%%%s%%", managementUIState.getTargetTableFilters().getSearchText().get());
}
final boolean noTagClicked = managementUIState.getTargetTableFilters().isNoTagSelected();
if (managementUIState.getTargetTableFilters().getPinnedDistId().isPresent()) {
pinnedDistId = managementUIState.getTargetTableFilters().getPinnedDistId().get();
}
final long size = getTargetsCountWithFilter(totalTargetsCount, pinnedDistId, final long size = getTargetsCountWithFilter(totalTargetsCount, pinnedDistId,
new FilterParams(distributionId, status, overdueState, searchText, noTagClicked, targetTags)); new FilterParams(distributionId, status, overdueState, searchText, noTagClicked, targetTags));
@@ -886,10 +867,11 @@ public class TargetTable extends AbstractTable<Target, Long> {
private long getTargetsCountWithFilter(final long totalTargetsCount, final Long pinnedDistId, private long getTargetsCountWithFilter(final long totalTargetsCount, final Long pinnedDistId,
final FilterParams filterParams) { final FilterParams filterParams) {
final Optional<Long> query = managementUIState.getTargetTableFilters().getTargetFilterQuery();
final long size; final long size;
if (managementUIState.getTargetTableFilters().getTargetFilterQuery().isPresent()) { if (query.isPresent()) {
size = targetManagement.countTargetByTargetFilterQuery( size = targetManagement.countTargetByTargetFilterQuery(query.get());
managementUIState.getTargetTableFilters().getTargetFilterQuery().get());
} else if (noFilterSelected(filterParams.getFilterByStatus(), pinnedDistId, } else if (noFilterSelected(filterParams.getFilterByStatus(), pinnedDistId,
filterParams.getSelectTargetWithNoTag(), filterParams.getFilterByTagNames(), filterParams.getSelectTargetWithNoTag(), filterParams.getFilterByTagNames(),
filterParams.getFilterBySearchText())) { filterParams.getFilterBySearchText())) {
@@ -903,11 +885,6 @@ public class TargetTable extends AbstractTable<Target, Long> {
return size; return size;
} }
private boolean isFilteredByText() {
return managementUIState.getTargetTableFilters().getSearchText().isPresent()
&& !Strings.isNullOrEmpty(managementUIState.getTargetTableFilters().getSearchText().get());
}
private static boolean noFilterSelected(final Collection<TargetUpdateStatus> status, final Long distributionId, private static boolean noFilterSelected(final Collection<TargetUpdateStatus> status, final Long distributionId,
final Boolean noTagClicked, final String[] targetTags, final String searchText) { final Boolean noTagClicked, final String[] targetTags, final String searchText) {
return CollectionUtils.isEmpty(status) && distributionId == null && Strings.isNullOrEmpty(searchText) return CollectionUtils.isEmpty(status) && distributionId == null && Strings.isNullOrEmpty(searchText)

View File

@@ -239,8 +239,7 @@ public class TargetTableHeader extends AbstractTableHeader {
} }
private String getSearchText() { private String getSearchText() {
return managementUIState.getTargetTableFilters().getSearchText().isPresent() return managementUIState.getTargetTableFilters().getSearchText().orElse(null);
? managementUIState.getTargetTableFilters().getSearchText().get() : null;
} }
@Override @Override
@@ -423,9 +422,7 @@ public class TargetTableHeader extends AbstractTableHeader {
@Override @Override
protected void displayFilterDropedInfoOnLoad() { protected void displayFilterDropedInfoOnLoad() {
if (managementUIState.getTargetTableFilters().getDistributionSet().isPresent()) { managementUIState.getTargetTableFilters().getDistributionSet().ifPresent(this::addFilterTextField);
addFilterTextField(managementUIState.getTargetTableFilters().getDistributionSet().get());
}
} }
@Override @Override

View File

@@ -9,23 +9,6 @@
package org.eclipse.hawkbit.ui.rollout.rollout; package org.eclipse.hawkbit.ui.rollout.rollout;
import static org.eclipse.hawkbit.ui.rollout.DistributionBarHelper.getTooltip; import static org.eclipse.hawkbit.ui.rollout.DistributionBarHelper.getTooltip;
import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.HTML_LI_CLOSE_TAG;
import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.HTML_LI_OPEN_TAG;
import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.HTML_UL_CLOSE_TAG;
import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.HTML_UL_OPEN_TAG;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.ACTION;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_CREATED_DATE;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_CREATED_USER;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_DESC;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_DIST_NAME_VERSION;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_ID;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_MODIFIED_BY;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_MODIFIED_DATE;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_NAME;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_STATUS;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_TOTAL_TARGETS;
import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -65,6 +48,7 @@ import org.eclipse.hawkbit.ui.rollout.state.RolloutUIState;
import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil;
import org.eclipse.hawkbit.ui.utils.VaadinMessageSource; import org.eclipse.hawkbit.ui.utils.VaadinMessageSource;
import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions;
import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions;
import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions;
import org.eclipse.hawkbit.ui.utils.UIComponentIdProvider; import org.eclipse.hawkbit.ui.utils.UIComponentIdProvider;
import org.eclipse.hawkbit.ui.utils.UINotification; import org.eclipse.hawkbit.ui.utils.UINotification;
@@ -212,14 +196,15 @@ public class RolloutListGrid extends AbstractGrid {
private void updateItem(final Rollout rollout, final Item item) { private void updateItem(final Rollout rollout, final Item item) {
final TotalTargetCountStatus totalTargetCountStatus = rollout.getTotalTargetCountStatus(); final TotalTargetCountStatus totalTargetCountStatus = rollout.getTotalTargetCountStatus();
item.getItemProperty(VAR_STATUS).setValue(rollout.getStatus()); item.getItemProperty(SPUILabelDefinitions.VAR_STATUS).setValue(rollout.getStatus());
item.getItemProperty(VAR_TOTAL_TARGETS_COUNT_STATUS).setValue(totalTargetCountStatus); item.getItemProperty(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS).setValue(totalTargetCountStatus);
final Integer groupCount = (Integer) item.getItemProperty(VAR_NUMBER_OF_GROUPS).getValue(); final Integer groupCount = (Integer) item.getItemProperty(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).getValue();
final int groupsCreated = rollout.getRolloutGroupsCreated(); final int groupsCreated = rollout.getRolloutGroupsCreated();
if (groupsCreated != 0) { if (groupsCreated != 0) {
item.getItemProperty(VAR_NUMBER_OF_GROUPS).setValue(Integer.valueOf(groupsCreated)); item.getItemProperty(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setValue(Integer.valueOf(groupsCreated));
} else if (rollout.getRolloutGroups() != null && !groupCount.equals(rollout.getRolloutGroups().size())) { } else if (rollout.getRolloutGroups() != null && !groupCount.equals(rollout.getRolloutGroups().size())) {
item.getItemProperty(VAR_NUMBER_OF_GROUPS).setValue(Integer.valueOf(rollout.getRolloutGroups().size())); item.getItemProperty(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS)
.setValue(Integer.valueOf(rollout.getRolloutGroups().size()));
} }
item.getItemProperty(ROLLOUT_RENDERER_DATA) item.getItemProperty(ROLLOUT_RENDERER_DATA)
.setValue(new RolloutRendererData(rollout.getName(), rollout.getStatus().toString())); .setValue(new RolloutRendererData(rollout.getName(), rollout.getStatus().toString()));
@@ -228,29 +213,38 @@ public class RolloutListGrid extends AbstractGrid {
@Override @Override
protected Container createContainer() { protected Container createContainer() {
final BeanQueryFactory<RolloutBeanQuery> rolloutQf = new BeanQueryFactory<>(RolloutBeanQuery.class); final BeanQueryFactory<RolloutBeanQuery> rolloutQf = new BeanQueryFactory<>(RolloutBeanQuery.class);
return new LazyQueryContainer(new LazyQueryDefinition(true, SPUIDefinitions.PAGE_SIZE, VAR_ID), rolloutQf); return new LazyQueryContainer(
new LazyQueryDefinition(true, SPUIDefinitions.PAGE_SIZE, SPUILabelDefinitions.VAR_ID), rolloutQf);
} }
@Override @Override
protected void addContainerProperties() { protected void addContainerProperties() {
final LazyQueryContainer rolloutGridContainer = (LazyQueryContainer) getContainerDataSource(); final LazyQueryContainer rolloutGridContainer = (LazyQueryContainer) getContainerDataSource();
rolloutGridContainer.addContainerProperty(VAR_NAME, String.class, "", false, false); rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_NAME, String.class, "", false, false);
rolloutGridContainer.addContainerProperty(DS_TYPE, String.class, null, false, false); rolloutGridContainer.addContainerProperty(DS_TYPE, String.class, null, false, false);
rolloutGridContainer.addContainerProperty(SW_MODULES, Set.class, null, false, false); rolloutGridContainer.addContainerProperty(SW_MODULES, Set.class, null, false, false);
rolloutGridContainer.addContainerProperty(ROLLOUT_RENDERER_DATA, RolloutRendererData.class, null, false, false); rolloutGridContainer.addContainerProperty(ROLLOUT_RENDERER_DATA, RolloutRendererData.class, null, false, false);
rolloutGridContainer.addContainerProperty(VAR_DESC, String.class, null, false, false); rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_DESC, String.class, null, false, false);
rolloutGridContainer.addContainerProperty(IS_REQUIRED_MIGRATION_STEP, boolean.class, null, false, false); rolloutGridContainer.addContainerProperty(IS_REQUIRED_MIGRATION_STEP, boolean.class, null, false, false);
rolloutGridContainer.addContainerProperty(VAR_STATUS, RolloutStatus.class, null, false, false); rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_STATUS, RolloutStatus.class, null, false,
rolloutGridContainer.addContainerProperty(VAR_DIST_NAME_VERSION, String.class, null, false, false); false);
rolloutGridContainer.addContainerProperty(VAR_CREATED_DATE, String.class, null, false, false); rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_DIST_NAME_VERSION, String.class, null, false,
false);
rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_CREATED_DATE, String.class, null, false,
false);
rolloutGridContainer.addContainerProperty(VAR_MODIFIED_DATE, String.class, null, false, false); rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_MODIFIED_DATE, String.class, null, false,
rolloutGridContainer.addContainerProperty(VAR_CREATED_USER, String.class, null, false, false); false);
rolloutGridContainer.addContainerProperty(VAR_MODIFIED_BY, String.class, null, false, false); rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_CREATED_USER, String.class, null, false,
rolloutGridContainer.addContainerProperty(VAR_NUMBER_OF_GROUPS, Integer.class, 0, false, false); false);
rolloutGridContainer.addContainerProperty(VAR_TOTAL_TARGETS, String.class, "0", false, false); rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_MODIFIED_BY, String.class, null, false,
rolloutGridContainer.addContainerProperty(VAR_TOTAL_TARGETS_COUNT_STATUS, TotalTargetCountStatus.class, null, false);
false, false); rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS, Integer.class, 0, false,
false);
rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_TOTAL_TARGETS, String.class, "0", false,
false);
rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS,
TotalTargetCountStatus.class, null, false, false);
rolloutGridContainer.addContainerProperty(RUN_OPTION, String.class, FontAwesome.PLAY.getHtml(), false, false); rolloutGridContainer.addContainerProperty(RUN_OPTION, String.class, FontAwesome.PLAY.getHtml(), false, false);
rolloutGridContainer.addContainerProperty(PAUSE_OPTION, String.class, FontAwesome.PAUSE.getHtml(), false, rolloutGridContainer.addContainerProperty(PAUSE_OPTION, String.class, FontAwesome.PAUSE.getHtml(), false,
@@ -274,17 +268,17 @@ public class RolloutListGrid extends AbstractGrid {
getColumn(ROLLOUT_RENDERER_DATA).setMinimumWidth(40); getColumn(ROLLOUT_RENDERER_DATA).setMinimumWidth(40);
getColumn(ROLLOUT_RENDERER_DATA).setMaximumWidth(150); getColumn(ROLLOUT_RENDERER_DATA).setMaximumWidth(150);
getColumn(VAR_DIST_NAME_VERSION).setMinimumWidth(40); getColumn(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).setMinimumWidth(40);
getColumn(VAR_DIST_NAME_VERSION).setMaximumWidth(150); getColumn(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).setMaximumWidth(150);
getColumn(VAR_STATUS).setMinimumWidth(75); getColumn(SPUILabelDefinitions.VAR_STATUS).setMinimumWidth(75);
getColumn(VAR_STATUS).setMaximumWidth(75); getColumn(SPUILabelDefinitions.VAR_STATUS).setMaximumWidth(75);
getColumn(VAR_TOTAL_TARGETS).setMinimumWidth(40); getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS).setMinimumWidth(40);
getColumn(VAR_TOTAL_TARGETS).setMaximumWidth(100); getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS).setMaximumWidth(100);
getColumn(VAR_NUMBER_OF_GROUPS).setMinimumWidth(40); getColumn(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setMinimumWidth(40);
getColumn(VAR_NUMBER_OF_GROUPS).setMaximumWidth(100); getColumn(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setMaximumWidth(100);
getColumn(RUN_OPTION).setMinimumWidth(25); getColumn(RUN_OPTION).setMinimumWidth(25);
getColumn(RUN_OPTION).setMaximumWidth(25); getColumn(RUN_OPTION).setMaximumWidth(25);
@@ -305,7 +299,7 @@ public class RolloutListGrid extends AbstractGrid {
getColumn(DELETE_OPTION).setMinimumWidth(25); getColumn(DELETE_OPTION).setMinimumWidth(25);
getColumn(DELETE_OPTION).setMaximumWidth(40); getColumn(DELETE_OPTION).setMaximumWidth(40);
getColumn(VAR_TOTAL_TARGETS_COUNT_STATUS).setMinimumWidth(280); getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS).setMinimumWidth(280);
} }
@Override @Override
@@ -314,16 +308,17 @@ public class RolloutListGrid extends AbstractGrid {
getColumn(DS_TYPE).setHeaderCaption(i18n.getMessage("header.type")); getColumn(DS_TYPE).setHeaderCaption(i18n.getMessage("header.type"));
getColumn(SW_MODULES).setHeaderCaption(i18n.getMessage("header.swmodules")); getColumn(SW_MODULES).setHeaderCaption(i18n.getMessage("header.swmodules"));
getColumn(IS_REQUIRED_MIGRATION_STEP).setHeaderCaption(i18n.getMessage("header.migrations.step")); getColumn(IS_REQUIRED_MIGRATION_STEP).setHeaderCaption(i18n.getMessage("header.migrations.step"));
getColumn(VAR_DIST_NAME_VERSION).setHeaderCaption(i18n.getMessage("header.distributionset")); getColumn(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).setHeaderCaption(i18n.getMessage("header.distributionset"));
getColumn(VAR_NUMBER_OF_GROUPS).setHeaderCaption(i18n.getMessage("header.numberofgroups")); getColumn(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setHeaderCaption(i18n.getMessage("header.numberofgroups"));
getColumn(VAR_TOTAL_TARGETS).setHeaderCaption(i18n.getMessage("header.total.targets")); getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS).setHeaderCaption(i18n.getMessage("header.total.targets"));
getColumn(VAR_CREATED_DATE).setHeaderCaption(i18n.getMessage("header.createdDate")); getColumn(SPUILabelDefinitions.VAR_CREATED_DATE).setHeaderCaption(i18n.getMessage("header.createdDate"));
getColumn(VAR_CREATED_USER).setHeaderCaption(i18n.getMessage("header.createdBy")); getColumn(SPUILabelDefinitions.VAR_CREATED_USER).setHeaderCaption(i18n.getMessage("header.createdBy"));
getColumn(VAR_MODIFIED_DATE).setHeaderCaption(i18n.getMessage("header.modifiedDate")); getColumn(SPUILabelDefinitions.VAR_MODIFIED_DATE).setHeaderCaption(i18n.getMessage("header.modifiedDate"));
getColumn(VAR_MODIFIED_BY).setHeaderCaption(i18n.getMessage("header.modifiedBy")); getColumn(SPUILabelDefinitions.VAR_MODIFIED_BY).setHeaderCaption(i18n.getMessage("header.modifiedBy"));
getColumn(VAR_DESC).setHeaderCaption(i18n.getMessage("header.description")); getColumn(SPUILabelDefinitions.VAR_DESC).setHeaderCaption(i18n.getMessage("header.description"));
getColumn(VAR_TOTAL_TARGETS_COUNT_STATUS).setHeaderCaption(i18n.getMessage("header.detail.status")); getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS)
getColumn(VAR_STATUS).setHeaderCaption(i18n.getMessage("header.status")); .setHeaderCaption(i18n.getMessage("header.detail.status"));
getColumn(SPUILabelDefinitions.VAR_STATUS).setHeaderCaption(i18n.getMessage("header.status"));
getColumn(RUN_OPTION).setHeaderCaption(i18n.getMessage("header.action.run")); getColumn(RUN_OPTION).setHeaderCaption(i18n.getMessage("header.action.run"));
getColumn(PAUSE_OPTION).setHeaderCaption(i18n.getMessage("header.action.pause")); getColumn(PAUSE_OPTION).setHeaderCaption(i18n.getMessage("header.action.pause"));
@@ -363,14 +358,14 @@ public class RolloutListGrid extends AbstractGrid {
protected void setColumnProperties() { protected void setColumnProperties() {
final List<Object> columnList = new ArrayList<>(); final List<Object> columnList = new ArrayList<>();
columnList.add(ROLLOUT_RENDERER_DATA); columnList.add(ROLLOUT_RENDERER_DATA);
columnList.add(VAR_DIST_NAME_VERSION); columnList.add(SPUILabelDefinitions.VAR_DIST_NAME_VERSION);
columnList.add(DS_TYPE); columnList.add(DS_TYPE);
columnList.add(SW_MODULES); columnList.add(SW_MODULES);
columnList.add(IS_REQUIRED_MIGRATION_STEP); columnList.add(IS_REQUIRED_MIGRATION_STEP);
columnList.add(VAR_STATUS); columnList.add(SPUILabelDefinitions.VAR_STATUS);
columnList.add(VAR_TOTAL_TARGETS_COUNT_STATUS); columnList.add(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS);
columnList.add(VAR_NUMBER_OF_GROUPS); columnList.add(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS);
columnList.add(VAR_TOTAL_TARGETS); columnList.add(SPUILabelDefinitions.VAR_TOTAL_TARGETS);
columnList.add(RUN_OPTION); columnList.add(RUN_OPTION);
columnList.add(PAUSE_OPTION); columnList.add(PAUSE_OPTION);
@@ -383,11 +378,11 @@ public class RolloutListGrid extends AbstractGrid {
} }
columnList.add(DELETE_OPTION); columnList.add(DELETE_OPTION);
columnList.add(VAR_CREATED_DATE); columnList.add(SPUILabelDefinitions.VAR_CREATED_DATE);
columnList.add(VAR_CREATED_USER); columnList.add(SPUILabelDefinitions.VAR_CREATED_USER);
columnList.add(VAR_MODIFIED_DATE); columnList.add(SPUILabelDefinitions.VAR_MODIFIED_DATE);
columnList.add(VAR_MODIFIED_BY); columnList.add(SPUILabelDefinitions.VAR_MODIFIED_BY);
columnList.add(VAR_DESC); columnList.add(SPUILabelDefinitions.VAR_DESC);
setColumnOrder(columnList.toArray()); setColumnOrder(columnList.toArray());
alignColumns(); alignColumns();
} }
@@ -395,12 +390,12 @@ public class RolloutListGrid extends AbstractGrid {
@Override @Override
protected void setHiddenColumns() { protected void setHiddenColumns() {
final List<Object> columnsToBeHidden = new ArrayList<>(); final List<Object> columnsToBeHidden = new ArrayList<>();
columnsToBeHidden.add(VAR_NAME); columnsToBeHidden.add(SPUILabelDefinitions.VAR_NAME);
columnsToBeHidden.add(VAR_CREATED_DATE); columnsToBeHidden.add(SPUILabelDefinitions.VAR_CREATED_DATE);
columnsToBeHidden.add(VAR_CREATED_USER); columnsToBeHidden.add(SPUILabelDefinitions.VAR_CREATED_USER);
columnsToBeHidden.add(VAR_MODIFIED_DATE); columnsToBeHidden.add(SPUILabelDefinitions.VAR_MODIFIED_DATE);
columnsToBeHidden.add(VAR_MODIFIED_BY); columnsToBeHidden.add(SPUILabelDefinitions.VAR_MODIFIED_BY);
columnsToBeHidden.add(VAR_DESC); columnsToBeHidden.add(SPUILabelDefinitions.VAR_DESC);
columnsToBeHidden.add(IS_REQUIRED_MIGRATION_STEP); columnsToBeHidden.add(IS_REQUIRED_MIGRATION_STEP);
columnsToBeHidden.add(DS_TYPE); columnsToBeHidden.add(DS_TYPE);
columnsToBeHidden.add(SW_MODULES); columnsToBeHidden.add(SW_MODULES);
@@ -416,11 +411,12 @@ public class RolloutListGrid extends AbstractGrid {
@Override @Override
protected void addColumnRenderes() { protected void addColumnRenderes() {
getColumn(VAR_NUMBER_OF_GROUPS).setRenderer(new HtmlRenderer(), new TotalTargetGroupsConverter()); getColumn(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setRenderer(new HtmlRenderer(),
getColumn(VAR_TOTAL_TARGETS_COUNT_STATUS).setRenderer(new HtmlRenderer(), new TotalTargetGroupsConverter());
getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS).setRenderer(new HtmlRenderer(),
new TotalTargetCountStatusConverter()); new TotalTargetCountStatusConverter());
getColumn(VAR_STATUS).setRenderer(new HtmlLabelRenderer(), new RolloutStatusConverter()); getColumn(SPUILabelDefinitions.VAR_STATUS).setRenderer(new HtmlLabelRenderer(), new RolloutStatusConverter());
final RolloutRenderer customObjectRenderer = new RolloutRenderer(RolloutRendererData.class); final RolloutRenderer customObjectRenderer = new RolloutRenderer(RolloutRendererData.class);
customObjectRenderer.addClickListener(this::onClickOfRolloutName); customObjectRenderer.addClickListener(this::onClickOfRolloutName);
@@ -453,10 +449,10 @@ public class RolloutListGrid extends AbstractGrid {
private void onClickOfRolloutName(final RendererClickEvent event) { private void onClickOfRolloutName(final RendererClickEvent event) {
rolloutUIState.setRolloutId((long) event.getItemId()); rolloutUIState.setRolloutId((long) event.getItemId());
final String rolloutName = (String) getContainerDataSource().getItem(event.getItemId()) final String rolloutName = (String) getContainerDataSource().getItem(event.getItemId())
.getItemProperty(VAR_NAME).getValue(); .getItemProperty(SPUILabelDefinitions.VAR_NAME).getValue();
rolloutUIState.setRolloutName(rolloutName); rolloutUIState.setRolloutName(rolloutName);
final String ds = (String) getContainerDataSource().getItem(event.getItemId()) final String ds = (String) getContainerDataSource().getItem(event.getItemId())
.getItemProperty(VAR_DIST_NAME_VERSION).getValue(); .getItemProperty(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).getValue();
rolloutUIState.setRolloutDistributionSet(ds); rolloutUIState.setRolloutDistributionSet(ds);
eventBus.publish(this, RolloutEvent.SHOW_ROLLOUT_GROUPS); eventBus.publish(this, RolloutEvent.SHOW_ROLLOUT_GROUPS);
} }
@@ -464,13 +460,14 @@ public class RolloutListGrid extends AbstractGrid {
private void pauseRollout(final Long rolloutId) { private void pauseRollout(final Long rolloutId) {
final Item row = getContainerDataSource().getItem(rolloutId); final Item row = getContainerDataSource().getItem(rolloutId);
final RolloutStatus rolloutStatus = (RolloutStatus) row.getItemProperty(VAR_STATUS).getValue(); final RolloutStatus rolloutStatus = (RolloutStatus) row.getItemProperty(SPUILabelDefinitions.VAR_STATUS)
.getValue();
if (!RolloutStatus.RUNNING.equals(rolloutStatus)) { if (!RolloutStatus.RUNNING.equals(rolloutStatus)) {
return; return;
} }
final String rolloutName = (String) row.getItemProperty(VAR_NAME).getValue(); final String rolloutName = (String) row.getItemProperty(SPUILabelDefinitions.VAR_NAME).getValue();
rolloutManagement.pauseRollout(rolloutId); rolloutManagement.pauseRollout(rolloutId);
uiNotification.displaySuccess(i18n.getMessage("message.rollout.paused", rolloutName)); uiNotification.displaySuccess(i18n.getMessage("message.rollout.paused", rolloutName));
@@ -479,8 +476,9 @@ public class RolloutListGrid extends AbstractGrid {
private void startOrResumeRollout(final Long rolloutId) { private void startOrResumeRollout(final Long rolloutId) {
final Item row = getContainerDataSource().getItem(rolloutId); final Item row = getContainerDataSource().getItem(rolloutId);
final RolloutStatus rolloutStatus = (RolloutStatus) row.getItemProperty(VAR_STATUS).getValue(); final RolloutStatus rolloutStatus = (RolloutStatus) row.getItemProperty(SPUILabelDefinitions.VAR_STATUS)
final String rolloutName = (String) row.getItemProperty(VAR_NAME).getValue(); .getValue();
final String rolloutName = (String) row.getItemProperty(SPUILabelDefinitions.VAR_NAME).getValue();
if (RolloutStatus.READY.equals(rolloutStatus)) { if (RolloutStatus.READY.equals(rolloutStatus)) {
rolloutManagement.startRollout(rolloutId); rolloutManagement.startRollout(rolloutId);
@@ -523,7 +521,7 @@ public class RolloutListGrid extends AbstractGrid {
return; return;
} }
final Item row = getContainerDataSource().getItem(rolloutId); final Item row = getContainerDataSource().getItem(rolloutId);
final String rolloutName = (String) row.getItemProperty(VAR_NAME).getValue(); final String rolloutName = (String) row.getItemProperty(SPUILabelDefinitions.VAR_NAME).getValue();
rolloutManagement.deleteRollout(rolloutId); rolloutManagement.deleteRollout(rolloutId);
uiNotification.displaySuccess(i18n.getMessage("message.rollout.deleted", rolloutName)); uiNotification.displaySuccess(i18n.getMessage("message.rollout.deleted", rolloutName));
}); });
@@ -551,15 +549,15 @@ public class RolloutListGrid extends AbstractGrid {
String description = null; String description = null;
if (VAR_STATUS.equals(cell.getPropertyId())) { if (SPUILabelDefinitions.VAR_STATUS.equals(cell.getPropertyId())) {
description = cell.getProperty().getValue().toString().toLowerCase(); description = cell.getProperty().getValue().toString().toLowerCase();
} else if (ACTION.equals(cell.getPropertyId())) { } else if (SPUILabelDefinitions.ACTION.equals(cell.getPropertyId())) {
description = ACTION.toLowerCase(); description = SPUILabelDefinitions.ACTION.toLowerCase();
} else if (ROLLOUT_RENDERER_DATA.equals(cell.getPropertyId())) { } else if (ROLLOUT_RENDERER_DATA.equals(cell.getPropertyId())) {
description = ((RolloutRendererData) cell.getProperty().getValue()).getName(); description = ((RolloutRendererData) cell.getProperty().getValue()).getName();
} else if (VAR_TOTAL_TARGETS_COUNT_STATUS.equals(cell.getPropertyId())) { } else if (SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS.equals(cell.getPropertyId())) {
description = getTooltip(((TotalTargetCountStatus) cell.getValue()).getStatusTotalCountMap()); description = getTooltip(((TotalTargetCountStatus) cell.getValue()).getStatusTotalCountMap());
} else if (VAR_DIST_NAME_VERSION.equals(cell.getPropertyId())) { } else if (SPUILabelDefinitions.VAR_DIST_NAME_VERSION.equals(cell.getPropertyId())) {
description = getDSDetails(cell.getItem()); description = getDSDetails(cell.getItem());
} }
@@ -578,29 +576,29 @@ public class RolloutListGrid extends AbstractGrid {
swModuleVendors.append(" , "); swModuleVendors.append(" , ");
}); });
final StringBuilder stringBuilder = new StringBuilder(); final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(HTML_UL_OPEN_TAG); stringBuilder.append(HawkbitCommonUtil.HTML_UL_OPEN_TAG);
stringBuilder.append(HTML_LI_OPEN_TAG); stringBuilder.append(HawkbitCommonUtil.HTML_LI_OPEN_TAG);
stringBuilder.append(" DistributionSet Description : ") stringBuilder.append(" DistributionSet Description : ")
.append((String) rolloutItem.getItemProperty(VAR_DESC).getValue()); .append((String) rolloutItem.getItemProperty(SPUILabelDefinitions.VAR_DESC).getValue());
stringBuilder.append(HTML_LI_CLOSE_TAG); stringBuilder.append(HawkbitCommonUtil.HTML_LI_CLOSE_TAG);
stringBuilder.append(HTML_LI_OPEN_TAG); stringBuilder.append(HawkbitCommonUtil.HTML_LI_OPEN_TAG);
stringBuilder.append(" DistributionSet Type : ") stringBuilder.append(" DistributionSet Type : ")
.append((String) rolloutItem.getItemProperty(DS_TYPE).getValue()); .append((String) rolloutItem.getItemProperty(DS_TYPE).getValue());
stringBuilder.append(HTML_LI_CLOSE_TAG); stringBuilder.append(HawkbitCommonUtil.HTML_LI_CLOSE_TAG);
stringBuilder.append(HTML_LI_OPEN_TAG); stringBuilder.append(HawkbitCommonUtil.HTML_LI_OPEN_TAG);
stringBuilder.append("Required Migration step : ") stringBuilder.append("Required Migration step : ")
.append((boolean) rolloutItem.getItemProperty(IS_REQUIRED_MIGRATION_STEP).getValue() ? "Yes" : "No"); .append((boolean) rolloutItem.getItemProperty(IS_REQUIRED_MIGRATION_STEP).getValue() ? "Yes" : "No");
stringBuilder.append(HTML_LI_CLOSE_TAG); stringBuilder.append(HawkbitCommonUtil.HTML_LI_CLOSE_TAG);
stringBuilder.append(HTML_LI_OPEN_TAG); stringBuilder.append(HawkbitCommonUtil.HTML_LI_OPEN_TAG);
stringBuilder.append("SoftWare Modules : ").append(swModuleNames.toString()); stringBuilder.append("SoftWare Modules : ").append(swModuleNames.toString());
stringBuilder.append(HTML_LI_CLOSE_TAG); stringBuilder.append(HawkbitCommonUtil.HTML_LI_CLOSE_TAG);
stringBuilder.append(HTML_LI_OPEN_TAG); stringBuilder.append(HawkbitCommonUtil.HTML_LI_OPEN_TAG);
stringBuilder.append("Vendor(s) : ").append(swModuleVendors.toString()); stringBuilder.append("Vendor(s) : ").append(swModuleVendors.toString());
stringBuilder.append(HTML_LI_CLOSE_TAG); stringBuilder.append(HawkbitCommonUtil.HTML_LI_CLOSE_TAG);
stringBuilder.append(HTML_UL_CLOSE_TAG); stringBuilder.append(HawkbitCommonUtil.HTML_UL_CLOSE_TAG);
return stringBuilder.toString(); return stringBuilder.toString();
} }
@@ -635,7 +633,7 @@ public class RolloutListGrid extends AbstractGrid {
@Override @Override
public String getStyle(final CellReference cellReference) { public String getStyle(final CellReference cellReference) {
if (VAR_STATUS.equals(cellReference.getPropertyId())) { if (SPUILabelDefinitions.VAR_STATUS.equals(cellReference.getPropertyId())) {
return "centeralign"; return "centeralign";
} }
return convertRolloutStatusToString(cellReference); return convertRolloutStatusToString(cellReference);
@@ -675,7 +673,7 @@ public class RolloutListGrid extends AbstractGrid {
private RolloutStatus getRolloutStatus(final Object itemId) { private RolloutStatus getRolloutStatus(final Object itemId) {
final Item row = containerDataSource.getItem(itemId); final Item row = containerDataSource.getItem(itemId);
return (RolloutStatus) row.getItemProperty(VAR_STATUS).getValue(); return (RolloutStatus) row.getItemProperty(SPUILabelDefinitions.VAR_STATUS).getValue();
} }
} }

View File

@@ -138,18 +138,19 @@ public class RolloutGroupTargetsBeanQuery extends AbstractBeanQuery<ProxyTarget>
public int size() { public int size() {
long size = 0; long size = 0;
if (rolloutGroup.isPresent()) { try {
try { firstPageTargetSets = rolloutGroup.map(group -> getRolloutGroupManagement()
firstPageTargetSets = getRolloutGroupManagement().findAllTargetsWithActionStatus( .findAllTargetsWithActionStatus(new PageRequest(0, SPUIDefinitions.PAGE_SIZE, sort), group.getId()))
new PageRequest(0, SPUIDefinitions.PAGE_SIZE, sort), rolloutGroup.get().getId()); .orElse(null);
size = firstPageTargetSets.getTotalElements();
} catch (final EntityNotFoundException e) { size = firstPageTargetSets == null ? 0 : firstPageTargetSets.getTotalElements();
LOG.error("Rollout does not exists. Redirect to Rollouts overview", e); } catch (final EntityNotFoundException e) {
rolloutUIState.setShowRolloutGroupTargets(false); LOG.error("Rollout does not exists. Redirect to Rollouts overview", e);
rolloutUIState.setShowRollOuts(true); rolloutUIState.setShowRolloutGroupTargets(false);
return 0; rolloutUIState.setShowRollOuts(true);
} return 0;
} }
getRolloutUIState().setRolloutGroupTargetsTotalCount(size); getRolloutUIState().setRolloutGroupTargetsTotalCount(size);
if (size > SPUIDefinitions.MAX_TABLE_ENTRIES) { if (size > SPUIDefinitions.MAX_TABLE_ENTRIES) {
getRolloutUIState().setRolloutGroupTargetsTruncated(size - SPUIDefinitions.MAX_TABLE_ENTRIES); getRolloutUIState().setRolloutGroupTargetsTruncated(size - SPUIDefinitions.MAX_TABLE_ENTRIES);

View File

@@ -36,8 +36,8 @@ public class PollingConfigurationView extends BaseConfigurationView
private final DurationConfigField fieldPollTime; private final DurationConfigField fieldPollTime;
private final DurationConfigField fieldPollingOverdueTime; private final DurationConfigField fieldPollingOverdueTime;
private Duration tenantPollTime; private transient Duration tenantPollTime;
private Duration tenantOverdueTime; private transient Duration tenantOverdueTime;
PollingConfigurationView(final VaadinMessageSource i18n, final ControllerPollProperties controllerPollProperties, PollingConfigurationView(final VaadinMessageSource i18n, final ControllerPollProperties controllerPollProperties,
final TenantConfigurationManagement tenantConfigurationManagement) { final TenantConfigurationManagement tenantConfigurationManagement) {

View File

@@ -32,7 +32,7 @@ public final class DurationConfigField extends GridLayout implements Configurati
private final CheckBox checkBox = new CheckBox(); private final CheckBox checkBox = new CheckBox();
private final DurationField durationField = new DurationField(); private final DurationField durationField = new DurationField();
private Duration globalDuration; private transient Duration globalDuration;
private DurationConfigField(final String id) { private DurationConfigField(final String id) {
super(2, 2); super(2, 2);
@@ -124,7 +124,7 @@ public final class DurationConfigField extends GridLayout implements Configurati
} }
private void notifyConfigurationChanged() { private void notifyConfigurationChanged() {
configurationChangeListeners.forEach(listener -> listener.configurationHasChanged()); configurationChangeListeners.forEach(ConfigurationItemChangeListener::configurationHasChanged);
} }
@Override @Override

View File

@@ -160,9 +160,9 @@
<!-- Release - END --> <!-- Release - END -->
<!-- Sonar - START --> <!-- Sonar - START -->
<sonar.host.url>https://sonar.eu-gb.mybluemix.net</sonar.host.url> <sonar.host.url>https://sonar.ops.bosch-iot-rollouts.com</sonar.host.url>
<sonar.github.repository>eclipse/hawkbit</sonar.github.repository> <sonar.github.repository>eclipse/hawkbit</sonar.github.repository>
<sonar.links.homepage>https://projects.eclipse.org/projects/iot.hawkbit</sonar.links.homepage> <sonar.links.homepage>https://www.eclipse.org/hawkbit</sonar.links.homepage>
<sonar.links.ci>https://circleci.com/gh/eclipse/hawkbit</sonar.links.ci> <sonar.links.ci>https://circleci.com/gh/eclipse/hawkbit</sonar.links.ci>
<jacoco.version>0.7.7.201606060606</jacoco.version> <jacoco.version>0.7.7.201606060606</jacoco.version>
<jacoco.outputDir>${project.basedir}/../target/</jacoco.outputDir> <jacoco.outputDir>${project.basedir}/../target/</jacoco.outputDir>
@@ -296,7 +296,7 @@
<plugin> <plugin>
<groupId>org.sonarsource.scanner.maven</groupId> <groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId> <artifactId>sonar-maven-plugin</artifactId>
<version>3.1.1</version> <version>3.2</version>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.eclipse.m2e</groupId> <groupId>org.eclipse.m2e</groupId>

View File

@@ -11,7 +11,7 @@
echo $CI_PULL_REQUEST pull request echo $CI_PULL_REQUEST pull request
# regular sonar on master # regular sonar on master
if [ "$CIRCLE_BRANCH" = "master" ]; then if [ "$CIRCLE_BRANCH" = "master" ]; then
mvn verify license:check sonar:sonar -Dsonar.login=$SONAR_SERVER_USER -Dsonar.password=$SONAR_SERVER_PASSWD -Dsonar.exclusions=**/target/generated-sources/apt/**,**/src/test/**,**/src/main/java/org/eclipse/hawkbit/repository/test/** -Dsonar.coverage.exclusions=**/src/main/java/org/eclipse/hawkbit/ui/**,**/target/generated-sources/apt/**,**/src/main/java/org/eclipse/hawkbit/repository/test/** mvn verify license:check sonar:sonar -Dsonar.login=$SONAR_SERVER_TOKEN -Dsonar.exclusions=**/target/generated-sources/apt/**,**/src/test/**,**/src/main/java/org/eclipse/hawkbit/repository/test/** -Dsonar.coverage.exclusions=**/src/main/java/org/eclipse/hawkbit/ui/**,**/target/generated-sources/apt/**,**/src/main/java/org/eclipse/hawkbit/repository/test/**
# preview in case of pull request - disabled as circle does not fill those with pull reuqests from different directories # preview in case of pull request - disabled as circle does not fill those with pull reuqests from different directories
else else
#if [ -n "$CI_PULL_REQUEST" ]; then #if [ -n "$CI_PULL_REQUEST" ]; then