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.
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

View File

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

View File

@@ -8,8 +8,6 @@
*/
package org.eclipse.hawkbit.simulator;
import static org.eclipse.hawkbit.simulator.amqp.AmqpProperties.CONFIGURATION_PREFIX;
import java.net.MalformedURLException;
import java.net.URL;
@@ -84,7 +82,7 @@ public class SimulationController {
if (protocol == Protocol.DMF_AMQP && isDmfDisabled()) {
return ResponseEntity.badRequest()
.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++) {

View File

@@ -8,8 +8,6 @@
*/
package org.eclipse.hawkbit.simulator.amqp;
import static org.eclipse.hawkbit.simulator.amqp.AmqpProperties.CONFIGURATION_PREFIX;
import java.time.Duration;
import java.util.Map;
@@ -43,7 +41,7 @@ import com.google.common.collect.Maps;
*/
@Configuration
@EnableConfigurationProperties(AmqpProperties.class)
@ConditionalOnProperty(prefix = CONFIGURATION_PREFIX, name = "enabled")
@ConditionalOnProperty(prefix = AmqpProperties.CONFIGURATION_PREFIX, name = "enabled")
public class AmqpConfiguration {
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
* simulator.
*
*
*
*/
public class SimulatedUpdate implements Serializable {
@@ -27,7 +24,7 @@ public class SimulatedUpdate implements Serializable {
protected final Long actionId;
protected LocalDateTime startCacheTime;
protected transient LocalDateTime startCacheTime;
/**
* Constructor of the class.

View File

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

View File

@@ -163,11 +163,10 @@ public class MongoDBArtifactStore implements ArtifactRepository {
storedArtifact = map(result);
}
} catch (final NoSuchAlgorithmException | IOException e) {
throw new ArtifactStoreException(e.getMessage(), e);
throw new ArtifactStoreException(e);
}
if (hash != null && hash.getMd5() != null
&& !storedArtifact.getHashes().getMd5().equalsIgnoreCase(hash.getMd5())) {
if (notNull(hash, storedArtifact) && !storedArtifact.getHashes().getMd5().equalsIgnoreCase(hash.getMd5())) {
throw new HashNotMatchException("The given md5 hash " + hash.getMd5()
+ " not matching the calculated md5 hash " + storedArtifact.getHashes().getMd5(),
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)
throws NoSuchAlgorithmException, IOException {
String sha1Hash;
@@ -206,7 +209,7 @@ public class MongoDBArtifactStore implements ArtifactRepository {
* the list of mongoDB gridFs files.
* @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());
}

View File

@@ -106,7 +106,9 @@ public class S3Repository implements ArtifactRepository {
} catch (final IOException e) {
throw new ArtifactStoreException(e.getMessage(), e);
} 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.eclipse.hawkbit.artifact.repository.model.DbArtifact;
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.io.BaseEncoding;
@@ -44,6 +46,8 @@ import com.google.common.io.Files;
*/
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_SUFFIX = "artifactrepo";
private final ArtifactFilesystemProperties artifactResourceProperties;
@@ -119,7 +123,9 @@ public class ArtifactFilesystemRepository implements ArtifactRepository {
} catch (final IOException e) {
throw new ArtifactStoreException(e.getMessage(), e);
} catch (final HashNotMatchException e) {
file.delete();
if (!file.delete()) {
LOG.error("Could not delete temp file {}", file);
}
throw e;
}
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.setContentType(artifact.getContentType());
fileSystemArtifact.setHashes(artifact.getHashes());

View File

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

View File

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

View File

@@ -8,10 +8,6 @@
*/
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 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.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.embedded.ServletListenerRegistrationBean;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
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.VaadinUrlAuthenticationSuccessHandler;
import com.google.common.collect.Lists;
/**
* All configurations related to HawkBit's authentication and authorization
* layer.
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, mode = ASPECTJ, proxyTargetClass = true, securedEnabled = true)
@Order(value = HIGHEST_PRECEDENCE)
@EnableGlobalMethodSecurity(prePostEnabled = true, mode = AdviceMode.ASPECTJ, proxyTargetClass = true, securedEnabled = true)
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class SecurityManagedConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(SecurityManagedConfiguration.class);
@@ -217,7 +217,7 @@ public class SecurityManagedConfiguration {
final AnonymousAuthenticationFilter anoymousFilter = new AnonymousAuthenticationFilter(
"controllerAnonymousFilter", "anonymous",
newArrayList(new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS),
Lists.newArrayList(new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS),
new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_DOWNLOAD_ROLE)));
anoymousFilter.setAuthenticationDetailsSource(authenticationDetailsSource);
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
* not successful.
*
*
*
*/
public class ArtifactStoreException extends RuntimeException {
@@ -25,7 +22,7 @@ public class ArtifactStoreException extends RuntimeException {
* @param message
* the message of the exception
* @param cause
* the cause of the exception
* of the exception
*/
public ArtifactStoreException(final String message, final Throwable cause) {
super(message, cause);
@@ -40,4 +37,14 @@ public class ArtifactStoreException extends RuntimeException {
public ArtifactStoreException(final String 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;
import static java.util.Collections.emptyList;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.tenancy.TenantAware;
@@ -64,7 +63,7 @@ public class TenantAwareCacheManager implements TenancyCacheManager {
public Collection<String> getCacheNames() {
String currentTenant = tenantAware.getCurrentTenant();
if (isTenantInvalid(currentTenant)) {
return emptyList();
return Collections.emptyList();
}
currentTenant = currentTenant.toUpperCase();

View File

@@ -8,9 +8,6 @@
*/
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.util.List;
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.tenancy.TenantAware;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.http.HttpRequest;
import com.google.common.base.Charsets;
@@ -107,9 +105,10 @@ public final class DataConversionHelper {
if (action != null) {
if (action.isCancelingOrCanceled()) {
result.add(linkTo(
methodOn(DdiRootController.class, tenantAware.getCurrentTenant()).getControllerCancelAction(
tenantAware.getCurrentTenant(), target.getControllerId(), action.getId()))
result.add(ControllerLinkBuilder
.linkTo(ControllerLinkBuilder.methodOn(DdiRootController.class, tenantAware.getCurrentTenant())
.getControllerCancelAction(tenantAware.getCurrentTenant(), target.getControllerId(),
action.getId()))
.withRel(DdiRestConstants.CANCEL_ACTION));
} else {
// we need to add the hashcode here of the actionWithStatus
@@ -117,16 +116,18 @@ public final class DataConversionHelper {
// have changed from 'soft' to 'forced' type and we need to
// change the payload of the
// response because of eTags.
result.add(linkTo(methodOn(DdiRootController.class, tenantAware.getCurrentTenant())
.getControllerBasedeploymentAction(tenantAware.getCurrentTenant(), target.getControllerId(),
action.getId(), calculateEtag(action)))
result.add(ControllerLinkBuilder
.linkTo(ControllerLinkBuilder.methodOn(DdiRootController.class, tenantAware.getCurrentTenant())
.getControllerBasedeploymentAction(tenantAware.getCurrentTenant(),
target.getControllerId(), action.getId(), calculateEtag(action)))
.withRel(DdiRestConstants.DEPLOYMENT_BASE_ACTION));
}
}
if (target.getTargetInfo().isRequestControllerAttributes()) {
result.add(linkTo(methodOn(DdiRootController.class, tenantAware.getCurrentTenant()).putConfigData(null,
tenantAware.getCurrentTenant(), target.getControllerId()))
result.add(ControllerLinkBuilder
.linkTo(ControllerLinkBuilder.methodOn(DdiRootController.class, tenantAware.getCurrentTenant())
.putConfigData(null, tenantAware.getCurrentTenant(), target.getControllerId()))
.withRel(DdiRestConstants.CONFIG_DATA_ACTION));
}
return result;

View File

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

View File

@@ -8,12 +8,6 @@
*/
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 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.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
@@ -95,7 +90,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId) {
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
return ResponseEntity.ok(toResponse(foundType));
return ResponseEntity.ok(MgmtDistributionSetTypeMapper.toResponse(foundType));
}
@Override
@@ -111,9 +106,10 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId,
@RequestBody final MgmtDistributionSetTypeRequestBodyPut restDistributionSetType) {
return ResponseEntity.ok(toResponse(distributionSetManagement.updateDistributionSetType(entityFactory
.distributionSetType().update(distributionSetTypeId)
.description(restDistributionSetType.getDescription()).colour(restDistributionSetType.getColour()))));
return ResponseEntity.ok(MgmtDistributionSetTypeMapper
.toResponse(distributionSetManagement.updateDistributionSetType(entityFactory.distributionSetType()
.update(distributionSetTypeId).description(restDistributionSetType.getDescription())
.colour(restDistributionSetType.getColour()))));
}
@Override
@@ -123,7 +119,8 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
final List<DistributionSetType> createdSoftwareModules = distributionSetManagement.createDistributionSetTypes(
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) {
@@ -136,7 +133,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId) {
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
return ResponseEntity.ok(toTypesResponse(foundType.getMandatoryModuleTypes()));
return ResponseEntity.ok(MgmtSoftwareModuleTypeMapper.toTypesResponse(foundType.getMandatoryModuleTypes()));
}
@Override
@@ -151,7 +148,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
throw new SoftwareModuleTypeNotInDistributionSetTypeException(softwareModuleTypeId, distributionSetTypeId);
}
return ResponseEntity.ok(toResponse(foundSmType));
return ResponseEntity.ok(MgmtSoftwareModuleTypeMapper.toResponse(foundSmType));
}
@Override
@@ -166,7 +163,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
throw new SoftwareModuleTypeNotInDistributionSetTypeException(softwareModuleTypeId, distributionSetTypeId);
}
return ResponseEntity.ok(toResponse(foundSmType));
return ResponseEntity.ok(MgmtSoftwareModuleTypeMapper.toResponse(foundSmType));
}
@Override
@@ -174,7 +171,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId) {
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId);
return ResponseEntity.ok(toTypesResponse(foundType.getOptionalModuleTypes()));
return ResponseEntity.ok(MgmtSoftwareModuleTypeMapper.toTypesResponse(foundType.getOptionalModuleTypes()));
}
@Override

View File

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

View File

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

View File

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

View File

@@ -58,10 +58,12 @@ public class JpaArtifactManagement implements ArtifactManagement {
private static Artifact checkForExistingArtifact(final String filename, final boolean overrideExisting,
final SoftwareModule softwareModule) {
if (softwareModule.getArtifactByFilename(filename).isPresent()) {
final Optional<Artifact> artifact = softwareModule.getArtifactByFilename(filename);
if (artifact.isPresent()) {
if (overrideExisting) {
LOG.debug("overriding existing artifact with new filename {}", filename);
return softwareModule.getArtifactByFilename(filename).get();
return artifact.get();
} else {
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.TargetWithActionType;
import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer;
import org.hibernate.validator.constraints.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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
@Modifying
@Transactional(isolation = Isolation.READ_COMMITTED)
@@ -383,8 +374,7 @@ public class JpaDeploymentManagement implements DeploymentManagement {
return saveAction;
} else {
throw new CancelActionNotAllowedException(
"Action [id: " + action.getId() + "] is not active and cannot be canceled");
throw new CancelActionNotAllowedException(action.getId() + " is not active and cannot be canceled");
}
}
@@ -416,12 +406,11 @@ public class JpaDeploymentManagement implements DeploymentManagement {
if (!action.isCancelingOrCanceled()) {
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()) {
throw new ForceQuitActionNotAllowedException(
"Action [id: " + action.getId() + "] is not active and cannot be force quit");
throw new ForceQuitActionNotAllowedException(action.getId() + " is not active and cannot be force quit");
}
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)));
}
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) {
throw new EntityAlreadyExistsException("Metadata entry with key '" + metadataKey + "' already exists");
}

View File

@@ -8,8 +8,6 @@
*/
package org.eclipse.hawkbit.repository.jpa.rsql;
import static org.eclipse.hawkbit.repository.FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -214,7 +212,7 @@ public final class RSQLUtility {
simpleTypeConverter = new SimpleTypeConverter();
}
private void beginLevel(boolean isOr) {
private void beginLevel(final boolean isOr) {
level++;
isOrLevel = isOr;
joinsInLevel.put(level, new HashSet<>(2));
@@ -227,19 +225,18 @@ public final class RSQLUtility {
}
private Set<Join<Object, Object>> getCurrentJoins() {
if(level > 0) {
if (level > 0) {
return joinsInLevel.get(level);
}
return Collections.emptySet();
}
private Optional<Join<Object, Object>> findCurrentJoinOfType(final Class<?> type) {
return getCurrentJoins().stream()
.filter(j -> type.equals(j.getJavaType())).findAny();
return getCurrentJoins().stream().filter(j -> type.equals(j.getJavaType())).findAny();
}
private void addCurrentJoin(Join<Object, Object> join) {
if(level > 0) {
private void addCurrentJoin(final Join<Object, Object> join) {
if (level > 0) {
getCurrentJoins().add(join);
}
}
@@ -272,7 +269,7 @@ public final class RSQLUtility {
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);
@@ -286,7 +283,7 @@ public final class RSQLUtility {
for (int i = 1; i < graph.length; 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
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) {
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++) {
final boolean isMapKeyField = enumField.isMap() && i == (split.length - 1);
@@ -360,13 +357,13 @@ public final class RSQLUtility {
if (fieldPath instanceof PluralJoin) {
final Join<Object, ?> join = (Join<Object, ?>) fieldPath;
final From<?, Object> joinParent = join.getParent();
Optional<Join<Object, Object>> currentJoinOfType = findCurrentJoinOfType(join.getJavaType());
if(currentJoinOfType.isPresent() && isOrLevel) {
final Optional<Join<Object, Object>> currentJoinOfType = findCurrentJoinOfType(join.getJavaType());
if (currentJoinOfType.isPresent() && isOrLevel) {
// remove the additional join and use the existing one
joinParent.getJoins().remove(join);
fieldPath = currentJoinOfType.get();
} else {
Join<Object, Object> newJoin = joinParent.join(fieldNameSplit, JoinType.LEFT);
final Join<Object, Object> newJoin = joinParent.join(fieldNameSplit, JoinType.LEFT);
addCurrentJoin(newJoin);
fieldPath = newJoin;
}
@@ -414,7 +411,7 @@ public final class RSQLUtility {
final String enumFieldName = enumField.name().toLowerCase();
if (enumField.isMap()) {
return enumFieldName + SUB_ATTRIBUTE_SEPERATOR + "keyName";
return enumFieldName + FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR + "keyName";
}
return enumFieldName;
@@ -423,7 +420,8 @@ public final class RSQLUtility {
final List<String> expectedSubFieldList = Arrays.stream(enumType.getEnumConstants())
.filter(enumField -> !enumField.getSubEntityAttributes().isEmpty()).flatMap(enumField -> {
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());
return subEntity.stream();
@@ -434,7 +432,7 @@ public final class RSQLUtility {
private A getFieldEnumByName(final ComparisonNode node) {
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) {
enumName = graph[0];
}
@@ -613,7 +611,7 @@ public final class RSQLUtility {
if (!enumField.isMap()) {
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];
if (fieldPath instanceof MapJoin) {
// 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());
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() {
@@ -292,8 +292,7 @@ public class RsqlParserValidationOracle implements RsqlValidationOracle {
final String finalTmpTokenName = tmpTokenName;
return Arrays.stream(TargetFields.values())
.filter(field -> field.toString().equalsIgnoreCase(finalTmpTokenName))
.map(field -> field.getSubEntityAttributes()).flatMap(subentities -> subentities.stream())
.count() > 0;
.map(TargetFields::getSubEntityAttributes).flatMap(List::stream).count() > 0;
}
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,
final String topToken, final String tokenImageName) {
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))
.collect(Collectors.toList());
}
@@ -318,8 +317,7 @@ public class RsqlParserValidationOracle implements RsqlValidationOracle {
final String[] split = imageName.split("\\.");
if (split.length > 1 && FIELD_NAMES.contains(split[0].toLowerCase())) {
return SUB_NAMES.get(split[0].toLowerCase()).stream()
.filter(subname -> new String(split[0] + "." + subname).equalsIgnoreCase(imageName))
.count() > 0;
.filter(subname -> (split[0] + "." + subname).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;
import static java.util.Optional.ofNullable;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.Matchers.equalTo;
import java.util.Iterator;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.repository.test.util.TestContextProvider;
@@ -60,7 +59,7 @@ public class EventVerifier implements TestRule {
}
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() {
@@ -78,8 +77,8 @@ public class EventVerifier implements TestRule {
for (final Expect expectedEvent : expectedEvents) {
try {
Awaitility.await().atMost(5, SECONDS).until(() -> eventCaptor.getCountFor(expectedEvent.type()),
equalTo(expectedEvent.count()));
Awaitility.await().atMost(5, TimeUnit.SECONDS)
.until(() -> eventCaptor.getCountFor(expectedEvent.type()), equalTo(expectedEvent.count()));
} catch (final ConditionTimeoutException ex) {
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;
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.InputStream;
import java.io.OutputStream;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -40,9 +25,13 @@ import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.Artifact;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import com.google.common.base.Preconditions;
import com.google.common.math.DoubleMath;
import com.google.common.net.HttpHeaders;
/**
* Utility class for the Rest Source API.
@@ -117,11 +106,11 @@ public final class RestResourceConversionHelper {
response.reset();
response.setBufferSize(BUFFER_SIZE);
response.setHeader(CONTENT_DISPOSITION, "attachment;filename=" + artifact.getFilename());
response.setHeader(ETAG, etag);
response.setHeader(ACCEPT_RANGES, "bytes");
response.setDateHeader(LAST_MODIFIED, lastModified);
response.setContentType(APPLICATION_OCTET_STREAM_VALUE);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + artifact.getFilename());
response.setHeader(HttpHeaders.ETAG, etag);
response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified);
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
final ByteRange full = new ByteRange(0, length - 1, length);
final List<ByteRange> ranges = new ArrayList<>();
@@ -133,9 +122,9 @@ public final class RestResourceConversionHelper {
// Range header matches"bytes=n-n,n-n,n-n..."
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());
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
@@ -155,19 +144,19 @@ public final class RestResourceConversionHelper {
if (ranges.isEmpty() || ranges.get(0).equals(full)) {
LOG.debug("filename ({}) results into a full request: ", artifact.getFilename());
handleFullFileRequest(artifact, response, file, controllerManagement, statusId, full);
result = new ResponseEntity<>(OK);
result = new ResponseEntity<>(HttpStatus.OK);
}
// standard range request
else if (ranges.size() == 1) {
LOG.debug("filename ({}) results into a standard range request: ", artifact.getFilename());
handleStandardRangeRequest(artifact, response, file, controllerManagement, statusId, ranges);
result = new ResponseEntity<>(PARTIAL_CONTENT);
result = new ResponseEntity<>(HttpStatus.PARTIAL_CONTENT);
}
// multipart range request
else {
LOG.debug("filename ({}) results into a multipart range request: ", artifact.getFilename());
handleMultipartRangeRequest(artifact, response, file, controllerManagement, statusId, ranges);
result = new ResponseEntity<>(PARTIAL_CONTENT);
result = new ResponseEntity<>(HttpStatus.PARTIAL_CONTENT);
}
return result;
@@ -177,8 +166,8 @@ public final class RestResourceConversionHelper {
final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId,
final ByteRange full) {
final ByteRange r = full;
response.setHeader(CONTENT_RANGE, "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal());
response.setHeader(CONTENT_LENGTH, String.valueOf(r.getLength()));
response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal());
response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(r.getLength()));
try (InputStream inputStream = file.getFileInputStream()) {
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
// 416.
if (start > end) {
response.setHeader(CONTENT_RANGE, "bytes */" + length);
return new ResponseEntity<>(REQUESTED_RANGE_NOT_SATISFIABLE);
response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + length);
return new ResponseEntity<>(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
}
// Add range.
@@ -226,10 +215,10 @@ public final class RestResourceConversionHelper {
private static void checkForShortcut(final HttpServletRequest request, final String etag, final long lastModified,
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)) {
try {
final long ifRangeTime = request.getDateHeader(IF_RANGE);
final long ifRangeTime = request.getDateHeader(HttpHeaders.IF_RANGE);
if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
ranges.add(full);
}
@@ -243,15 +232,15 @@ public final class RestResourceConversionHelper {
private static void handleMultipartRangeRequest(final Artifact artifact, final HttpServletResponse response,
final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId,
final List<ByteRange> ranges) {
response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
response.setStatus(SC_PARTIAL_CONTENT);
response.setContentType("multipart/byteranges; boundary=" + ByteRange.MULTIPART_BOUNDARY);
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
for (final ByteRange r : ranges) {
try (InputStream inputStream = file.getFileInputStream()) {
// Add multipart boundary and header fields for every range.
response.getOutputStream().println();
response.getOutputStream().println("--" + MULTIPART_BOUNDARY);
response.getOutputStream().println("--" + ByteRange.MULTIPART_BOUNDARY);
response.getOutputStream()
.println("Content-Range: bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal());
@@ -265,7 +254,7 @@ public final class RestResourceConversionHelper {
try {
// End with final multipart boundary.
response.getOutputStream().println();
response.getOutputStream().print("--" + MULTIPART_BOUNDARY + "--");
response.getOutputStream().print("--" + ByteRange.MULTIPART_BOUNDARY + "--");
} catch (final IOException e) {
throwFileStreamingFailedException(artifact, e);
}
@@ -280,9 +269,9 @@ public final class RestResourceConversionHelper {
final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId,
final List<ByteRange> ranges) {
final ByteRange r = ranges.get(0);
response.setHeader(CONTENT_RANGE, "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal());
response.setHeader(CONTENT_LENGTH, String.valueOf(r.getLength()));
response.setStatus(SC_PARTIAL_CONTENT);
response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal());
response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(r.getLength()));
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
try (InputStream inputStream = file.getFileInputStream()) {
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,
final ControllerManagement controllerManagement, final Long statusId, final long start, final long length)
throws IOException {
checkNotNull(from);
checkNotNull(to);
Preconditions.checkNotNull(from);
Preconditions.checkNotNull(to);
final byte[] buf = new byte[BUFFER_SIZE];
long total = 0;
int progressPercent = 1;
@@ -331,7 +320,7 @@ public final class RestResourceConversionHelper {
}
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
if (newPercent == 100 || newPercent > progressPercent + 10) {

View File

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

View File

@@ -8,18 +8,14 @@
*/
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.Map;
import org.apache.commons.lang3.ArrayUtils;
import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
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.SpringContextHelper;
import org.springframework.data.domain.Page;
@@ -37,7 +33,6 @@ public class ArtifactBeanQuery extends AbstractBeanQuery<Artifact> {
private static final long serialVersionUID = 1L;
private Sort sort = new Sort(Direction.DESC, "filename");
private transient ArtifactManagement artifactManagement;
private transient EntityFactory entityFactory;
private transient Page<Artifact> firstPagetArtifacts;
private Long baseSwModuleId;
@@ -58,15 +53,15 @@ public class ArtifactBeanQuery extends AbstractBeanQuery<Artifact> {
super(definition, queryConfig, sortIds, sortStates);
if (isNotNullOrEmpty(queryConfig)) {
if (HawkbitCommonUtil.isNotNullOrEmpty(queryConfig)) {
baseSwModuleId = (Long) queryConfig.get(SPUIDefinitions.BY_BASE_SOFTWARE_MODULE);
}
if (!isEmpty(sortStates)) {
sort = new Sort(sortStates[0] ? ASC : DESC, (String) sortIds[0]);
if (!ArrayUtils.isEmpty(sortStates)) {
sort = new Sort(sortStates[0] ? Direction.ASC : Direction.DESC, (String) sortIds[0]);
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;
}
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 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.SoftwareModuleEvent;
import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType;
@@ -114,11 +113,11 @@ public class ArtifactDetailsLayout extends VerticalLayout {
createComponents();
buildLayout();
eventBus.subscribe(this);
if (artifactUploadState.getSelectedBaseSoftwareModule().isPresent()) {
final SoftwareModule selectedSoftwareModule = artifactUploadState.getSelectedBaseSoftwareModule().get();
populateArtifactDetails(selectedSoftwareModule.getId(), HawkbitCommonUtil
.getFormattedNameVersion(selectedSoftwareModule.getName(), selectedSoftwareModule.getVersion()));
}
artifactUploadState.getSelectedBaseSoftwareModule()
.ifPresent(selectedSoftwareModule -> populateArtifactDetails(selectedSoftwareModule.getId(),
HawkbitCommonUtil.getFormattedNameVersion(selectedSoftwareModule.getName(),
selectedSoftwareModule.getVersion())));
if (isMaximized()) {
maximizedArtifactDetailsView();
}

View File

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

View File

@@ -8,9 +8,6 @@
*/
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.FileInputStream;
import java.io.FileNotFoundException;
@@ -140,12 +137,9 @@ public class UploadConfirmationWindow implements Button.ClickListener {
buildLayout();
}
private Boolean checkIfArtifactDetailsDisplayed(final Long bSoftwareModuleId) {
if (artifactUploadState.getSelectedBaseSoftwareModule().isPresent()
&& artifactUploadState.getSelectedBaseSoftwareModule().get().getId().equals(bSoftwareModuleId)) {
return true;
}
return false;
private boolean checkIfArtifactDetailsDisplayed(final Long bSoftwareModuleId) {
return artifactUploadState.getSelectedBaseSoftwareModule()
.map(module -> module.getId().equals(bSoftwareModuleId)).orElse(false);
}
private Boolean preUploadValidation(final List<String> itemIds) {
@@ -640,12 +634,12 @@ public class UploadConfirmationWindow implements Button.ClickListener {
artifactManagement.createArtifact(fis, baseSw.getId(), providedFileName,
HawkbitCommonUtil.trimAndNullIfEmpty(md5Checksum),
HawkbitCommonUtil.trimAndNullIfEmpty(sha1Checksum), true, customFile.getMimeType());
saveUploadStatus(providedFileName, swModuleNameVersion, SUCCESS, "");
saveUploadStatus(providedFileName, swModuleNameVersion, SPUILabelDefinitions.SUCCESS, "");
} catch (final ArtifactUploadFailedException | InvalidSHA1HashException | InvalidMD5HashException
| FileNotFoundException e) {
saveUploadStatus(providedFileName, swModuleNameVersion, FAILED, e.getMessage());
saveUploadStatus(providedFileName, swModuleNameVersion, SPUILabelDefinitions.FAILED, e.getMessage());
LOG.error(ARTIFACT_UPLOAD_EXCEPTION, e);
} 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.UploadStatusEventType;
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.VaadinMessageSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vaadin.spring.events.EventBus;
@@ -207,16 +207,13 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene
@Override
public void uploadStarted(final StartedEvent event) {
uploadInterrupted = false;
selectedSwForUpload = artifactUploadState.getSelectedBaseSoftwareModule().isPresent()
? artifactUploadState.getSelectedBaseSoftwareModule().get() : null;
selectedSwForUpload = artifactUploadState.getSelectedBaseSoftwareModule().orElse(null);
if (view.isSoftwareModuleSelected()) {
// single file session
if (!view.checkIfFileIsDuplicate(event.getFilename(), selectedSwForUpload)) {
if (selectedSwForUpload != null && view.checkIfSoftwareModuleIsSelected()
&& !view.checkIfFileIsDuplicate(event.getFilename(), selectedSwForUpload)) {
LOG.debug("Upload started for file :{}", event.getFilename());
eventBus.publish(this, new UploadStatusEvent(UploadStatusEventType.UPLOAD_STARTED,
new UploadFileStatus(event.getFilename(), 0, 0, selectedSwForUpload)));
}
} else {
failureReason = i18n.getMessage("message.upload.failed");
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.decorators.SPUIButtonStyleSmall;
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.SPUILabelDefinitions;
import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions;
import org.eclipse.hawkbit.ui.utils.UIComponentIdProvider;
import org.eclipse.hawkbit.ui.utils.UINotification;
import org.eclipse.hawkbit.ui.utils.VaadinMessageSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
@@ -106,7 +106,7 @@ public class UploadLayout extends VerticalLayout {
private DragAndDropWrapper dropAreaWrapper;
private Boolean hasDirectory = Boolean.FALSE;
private boolean hasDirectory;
private Button uploadStatusButton;
@@ -136,13 +136,13 @@ public class UploadLayout extends VerticalLayout {
@EventBusListenerMethod(scope = EventScope.UI)
void onEvent(final UploadArtifactUIEvent event) {
if (event == UploadArtifactUIEvent.DELETED_ALL_SOFWARE) {
ui.access(() -> updateActionCount());
ui.access(this::updateActionCount);
} else if (event == UploadArtifactUIEvent.MINIMIZED_STATUS_POPUP) {
ui.access(() -> showUploadStatusButton());
ui.access(this::showUploadStatusButton);
} else if (event == UploadArtifactUIEvent.MAXIMIZED_STATUS_POPUP) {
ui.access(() -> maximizeStatusPopup());
ui.access(this::maximizeStatusPopup);
} else if (event == UploadArtifactUIEvent.ARTIFACT_RESULT_POPUP_CLOSED) {
ui.access(() -> closeUploadStatusPopup());
ui.access(this::closeUploadStatusPopup);
}
}
@@ -243,13 +243,9 @@ public class UploadLayout extends VerticalLayout {
// selected software module at the time of file drop is
// considered for upload
if (!artifactUploadState.getSelectedBaseSoftwareModule().isPresent()) {
return;
}
final SoftwareModule selectedSw = artifactUploadState.getSelectedBaseSoftwareModule().get();
artifactUploadState.getSelectedBaseSoftwareModule().ifPresent(selectedSw -> {
// reset the flag
hasDirectory = Boolean.FALSE;
hasDirectory = false;
for (final Html5File file : files) {
processFile(file, selectedSw);
}
@@ -261,9 +257,28 @@ public class UploadLayout extends VerticalLayout {
// 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) {
if (!isDirectory(file)) {
if (!checkForDuplicate(file.getFileName(), selectedSw)) {
@@ -401,34 +416,9 @@ public class UploadLayout extends VerticalLayout {
}
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 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() {
boolean checkIfSoftwareModuleIsSelected() {
if (!artifactUploadState.getSelectedBaseSwModuleId().isPresent()) {
uiNotification.displayValidationError(i18n.getMessage("message.error.noSwModuleSelected"));
return false;
}
return true;

View File

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

View File

@@ -12,7 +12,6 @@ import java.util.List;
import java.util.Map;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
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 transient Page<DistributionSetType> firstPageDistSetType;
private transient DistributionSetManagement distributionSetManagement;
private transient EntityFactory entityFactory;
/**
* Parametric constructor.
@@ -80,13 +78,6 @@ public class DistributionSetTypeBeanQuery extends AbstractBeanQuery<Distribution
return distributionSetManagement;
}
private EntityFactory getEntityFactory() {
if (entityFactory == null) {
entityFactory = SpringContextHelper.getBean(EntityFactory.class);
}
return entityFactory;
}
@Override
protected List<DistributionSetType> loadBeans(final int startIndex, final int count) {
Page<DistributionSetType> typeBeans;

View File

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

View File

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

View File

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

View File

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

View File

@@ -8,13 +8,8 @@
*/
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.stream.Collectors;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
@@ -33,6 +28,7 @@ import com.vaadin.shared.Connector;
import com.vaadin.ui.Component;
import com.vaadin.ui.Notification.Type;
import com.vaadin.ui.UI;
import com.vaadin.ui.themes.ValoTheme;
/**
* Default handler for Hawkbit UI.
@@ -42,7 +38,8 @@ public class HawkbitUIErrorHandler extends DefaultErrorHandler {
private static final long serialVersionUID = 1L;
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
public void error(final ErrorEvent event) {
@@ -121,6 +118,6 @@ public class HawkbitUIErrorHandler extends DefaultErrorHandler {
}
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;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
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.SoftwareModuleDetailsTable;
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.tagdetails.DistributionTagToken;
import org.eclipse.hawkbit.ui.components.SPUIComponentProvider;
@@ -139,42 +137,40 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet
@SuppressWarnings("unchecked")
private void showUnsavedAssignment() {
Item item;
final Map<DistributionSetIdName, HashSet<SoftwareModuleIdName>> assignedList = manageDistUIState
.getAssignedList();
final Long selectedDistId = manageDistUIState.getLastSelectedDistribution().isPresent()
? manageDistUIState.getLastSelectedDistribution().get() : 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;
}
}
final Set<SoftwareModuleIdName> softwareModuleIdNameList = manageDistUIState.getLastSelectedDistribution()
.map(selectedDistId -> manageDistUIState.getAssignedList().entrySet().stream()
.filter(entry -> entry.getKey().getId().equals(selectedDistId)).findAny()
.map(Map.Entry::getValue).orElse(null))
.orElse(null);
if (null != softwareModuleIdNameList) {
if (assignedSWModule == null) {
assignedSWModule = new HashMap<>();
}
for (final SoftwareModuleIdName swIdName : softwareModuleIdNameList) {
final SoftwareModule softwareModule = softwareManagement.findSoftwareModuleById(swIdName.getId()).get();
softwareModuleIdNameList.stream().map(SoftwareModuleIdName::getId)
.map(softwareManagement::findSoftwareModuleById)
.forEach(found -> found.ifPresent(softwareModule -> {
if (assignedSWModule.containsKey(softwareModule.getType().getName())) {
assignedSWModule.get(softwareModule.getType().getName()).append("</br>").append("<I>")
.append(getUnsavedAssigedSwModule(softwareModule.getName(), softwareModule.getVersion()))
.append(HawkbitCommonUtil.getFormattedNameVersion(softwareModule.getName(),
softwareModule.getVersion()))
.append("<I>");
} else {
assignedSWModule.put(softwareModule.getType().getName(),
new StringBuilder().append("<I>").append(
getUnsavedAssigedSwModule(softwareModule.getName(), softwareModule.getVersion()))
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()) {
item = softwareModuleTable.getContainerDataSource().getItem(entry.getKey());
final Item item = softwareModuleTable.getContainerDataSource().getItem(entry.getKey());
if (item != null) {
item.getItemProperty(SOFT_MODULE).setValue(createSoftModuleLayout(entry.getValue().toString()));
}
@@ -183,10 +179,9 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet
}
private Button assignSoftModuleButton(final String softwareModuleName) {
if (getPermissionChecker().hasUpdateDistributionPermission()
&& manageDistUIState.getLastSelectedDistribution().isPresent()
&& targetManagement.countTargetByAssignedDistributionSet(
manageDistUIState.getLastSelectedDistribution().get()) <= 0) {
if (getPermissionChecker().hasUpdateDistributionPermission() && manageDistUIState.getLastSelectedDistribution()
.map(selected -> targetManagement.countTargetByAssignedDistributionSet(selected) <= 0).orElse(false)) {
final Button reassignSoftModule = SPUIComponentProvider.getButton(softwareModuleName, "", "", "", true,
FontAwesome.TIMES, SPUIButtonStyleSmallNoBorder.class);
reassignSoftModule.setEnabled(false);
@@ -195,10 +190,6 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet
return null;
}
private static String getUnsavedAssigedSwModule(final String name, final String version) {
return HawkbitCommonUtil.getFormattedNameVersion(name, version);
}
@SuppressWarnings("unchecked")
private void updateSoftwareModule(final SoftwareModule module) {
if (assignedSWModule == null) {
@@ -209,28 +200,33 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet
if (assignedSWModule.containsKey(module.getType().getName())) {
/*
* If software module type is software, means multiple softwares can
* assigned to that type. Hence if multipe softwares belongs to same
* type is drroped, then add to the list.
* assigned to that type. Hence if multiple softwares belongs to
* same type is dropped, then add to the list.
*/
if (module.getType().getMaxAssignments() > 1) {
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
* same type is dropped, then override with previous one.
*/
if (module.getType().getMaxAssignments() == 1) {
assignedSWModule.put(module.getType().getName(), new StringBuilder().append("<I>")
.append(getUnsavedAssigedSwModule(module.getName(), module.getVersion())).append("</I>"));
assignedSWModule.put(module.getType().getName(),
new StringBuilder().append("<I>").append(
HawkbitCommonUtil.getFormattedNameVersion(module.getName(), module.getVersion()))
.append("</I>"));
}
} else {
assignedSWModule.put(module.getType().getName(), new StringBuilder().append("<I>")
.append(getUnsavedAssigedSwModule(module.getName(), module.getVersion())).append("</I>"));
assignedSWModule.put(module.getType().getName(),
new StringBuilder().append("<I>")
.append(HawkbitCommonUtil.getFormattedNameVersion(module.getName(), module.getVersion()))
.append("</I>"));
}
for (final Map.Entry<String, StringBuilder> entry : assignedSWModule.entrySet()) {
@@ -322,13 +318,12 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet
}
@Override
protected Boolean onLoadIsTableRowSelected() {
return manageDistUIState.getSelectedDistributions().isPresent()
&& !manageDistUIState.getSelectedDistributions().get().isEmpty();
protected boolean onLoadIsTableRowSelected() {
return manageDistUIState.getSelectedDistributions().map(selected -> !selected.isEmpty()).orElse(false);
}
@Override
protected Boolean onLoadIsTableMaximized() {
protected boolean onLoadIsTableMaximized() {
return manageDistUIState.isDsTableMaximized();
}
@@ -349,7 +344,7 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet
}
@Override
protected Boolean hasEditPermission() {
protected boolean hasEditPermission() {
return getPermissionChecker().hasUpdateDistributionPermission();
}
@@ -404,7 +399,7 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet
}
@Override
protected Boolean isMetadataIconToBeDisplayed() {
protected boolean isMetadataIconToBeDisplayed() {
return true;
}

View File

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

View File

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

View File

@@ -170,9 +170,8 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
final String swModuleTypeName = HawkbitCommonUtil.removePrefix(swTypeId,
SPUIDefinitions.SOFTWARE_MODULE_TAG_ID_PREFIXS);
if (manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType().isPresent()
&& manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType().get().getName()
.equalsIgnoreCase(swModuleTypeName)) {
if (manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType()
.map(type -> type.getName().equalsIgnoreCase(swModuleTypeName)).orElse(false)) {
notification.displayValidationError(
i18n.getMessage("message.swmodule.type.check.delete", new Object[] { swModuleTypeName }));
} else {
@@ -194,7 +193,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout {
}
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();
manageDistUIState.getDeletedDistributionList().addAll(distributionIdNameSet);

View File

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

View File

@@ -74,8 +74,8 @@ public class DistSMTypeFilterButtons extends AbstractFilterButtons {
@Override
protected boolean isClickedByDefault(final String typeName) {
return manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType().isPresent() && manageDistUIState
.getSoftwareModuleFilters().getSoftwareModuleType().get().getName().equals(typeName);
return manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType()
.map(type -> type.getName().equals(typeName)).orElse(false);
}
@Override

View File

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

View File

@@ -139,10 +139,7 @@ public class DistributionSetSelectTable extends Table {
}
private Object getItemIdToSelect() {
if (manageDistUIState.getSelectedDistributions().isPresent()) {
return manageDistUIState.getSelectedDistributions().get();
}
return null;
return manageDistUIState.getSelectedDistributions().orElse(null);
}
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.ui.common.ConfirmationDialog;
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.components.SPUIComponentProvider;
import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder;
@@ -803,13 +804,8 @@ public class ActionHistoryTable extends TreeTable {
* Pinning.
*/
private void updateDistributionTableStyle() {
if (!managementUIState.getDistributionTableFilters().getPinnedTarget().isPresent()) {
return;
}
final Long alreadyPinnedControllerId = managementUIState.getDistributionTableFilters().getPinnedTarget().get()
.getTargetId();
if (alreadyPinnedControllerId.equals(target.getId())) {
if (managementUIState.getDistributionTableFilters().getPinnedTarget().map(TargetIdName::getTargetId)
.map(target.getId()::equals).orElse(false)) {
eventBus.publish(this, PinUnpinEvent.PIN_TARGET);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -8,18 +8,12 @@
*/
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.Collection;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.ArrayUtils;
import org.eclipse.hawkbit.repository.FilterParams;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
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.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.util.CollectionUtils;
import org.vaadin.addons.lazyquerycontainer.AbstractBeanQuery;
import org.vaadin.addons.lazyquerycontainer.QueryDefinition;
@@ -50,7 +45,7 @@ public class TargetBeanQuery extends AbstractBeanQuery<ProxyTarget> {
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 Boolean overdueState;
private String[] targetTags;
@@ -80,7 +75,7 @@ public class TargetBeanQuery extends AbstractBeanQuery<ProxyTarget> {
super(definition, queryConfig, sortIds, sortStates);
if (isNotNullOrEmpty(queryConfig)) {
if (HawkbitCommonUtil.isNotNullOrEmpty(queryConfig)) {
status = (Collection<TargetUpdateStatus>) queryConfig.get(SPUIDefinitions.FILTER_BY_STATUS);
overdueState = (Boolean) queryConfig.get(SPUIDefinitions.FILTER_BY_OVERDUE_STATE);
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);
}
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++) {
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() {
final boolean isFilterSelected = isTagSelected() || isOverdueFilterEnabled();
return isFilterSelected || !CollectionUtils.isEmpty(status) || distributionId != null
|| !isNullOrEmpty(searchText);
|| !Strings.isNullOrEmpty(searchText);
}
private TargetManagement getTargetManagement() {

View File

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

View File

@@ -8,15 +8,6 @@
*/
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.Collection;
import java.util.Date;
@@ -283,8 +274,7 @@ public class TargetTable extends AbstractTable<Target, Long> {
@Override
protected boolean isFirstRowSelectedOnLoad() {
return !managementUIState.getSelectedTargetId().isPresent()
|| managementUIState.getSelectedTargetId().get().isEmpty();
return managementUIState.getSelectedTargetId().map(Set::isEmpty).orElse(true);
}
@Override
@@ -403,9 +393,9 @@ public class TargetTable extends AbstractTable<Target, Long> {
return pinBtn;
}
private boolean isPinned(final TargetIdName pinnedTarget) {
return managementUIState.getDistributionTableFilters().getPinnedTarget().isPresent()
&& managementUIState.getDistributionTableFilters().getPinnedTarget().get().equals(pinnedTarget);
private boolean isPinned(final TargetIdName target) {
return managementUIState.getDistributionTableFilters().getPinnedTarget()
.map(pinnedTarget -> pinnedTarget.equals(target)).orElse(false);
}
/**
@@ -431,10 +421,8 @@ public class TargetTable extends AbstractTable<Target, Long> {
*/
private void checkifAlreadyPinned(final Button eventBtn) {
final TargetIdName newPinnedTargetItemId = (TargetIdName) eventBtn.getData();
TargetIdName targetId = null;
if (managementUIState.getDistributionTableFilters().getPinnedTarget().isPresent()) {
targetId = managementUIState.getDistributionTableFilters().getPinnedTarget().get();
}
final TargetIdName targetId = managementUIState.getDistributionTableFilters().getPinnedTarget().orElse(null);
if (targetId == null) {
isTargetPinned = !isTargetPinned;
managementUIState.getDistributionTableFilters().setPinnedTarget(newPinnedTargetItemId);
@@ -621,7 +609,7 @@ public class TargetTable extends AbstractTable<Target, Long> {
final List<DistributionSet> findDistributionSetAllById) {
String message = null;
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) {
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) {
if (message == null) {
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) {
return filterEvent == REMOVE_FILTER_BY_TEXT || filterEvent == REMOVE_FILTER_BY_TAG
|| filterEvent == REMOVE_FILTER_BY_DISTRIBUTION || filterEvent == REMOVE_FILTER_BY_TARGET_FILTER_QUERY;
return filterEvent == TargetFilterEvent.REMOVE_FILTER_BY_TEXT
|| 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) {
return filterEvent == FILTER_BY_TEXT || filterEvent == FILTER_BY_TAG || filterEvent == FILTER_BY_DISTRIBUTION
|| filterEvent == FILTER_BY_TARGET_FILTER_QUERY;
return filterEvent == TargetFilterEvent.FILTER_BY_TEXT || filterEvent == TargetFilterEvent.FILTER_BY_TAG
|| filterEvent == TargetFilterEvent.FILTER_BY_DISTRIBUTION
|| filterEvent == TargetFilterEvent.FILTER_BY_TARGET_FILTER_QUERY;
}
private String getTargetTableStyle(final Long assignedDistributionSetId, final Long installedDistributionSetId) {
final Long distPinned = managementUIState.getTargetTableFilters().getPinnedDistId().isPresent()
? managementUIState.getTargetTableFilters().getPinnedDistId().get() : null;
if (null != distPinned && distPinned.equals(installedDistributionSetId)) {
return managementUIState.getTargetTableFilters().getPinnedDistId().map(distPinned -> {
if (distPinned.equals(installedDistributionSetId)) {
return SPUIDefinitions.HIGHTLIGHT_GREEN;
} else if (null != distPinned && distPinned.equals(assignedDistributionSetId)) {
}
if (distPinned.equals(assignedDistributionSetId)) {
return SPUIDefinitions.HIGHTLIGHT_ORANGE;
}
return null;
}).orElse(null);
}
private String createTargetTableStyle(final Object itemId, final Object propertyId) {
@@ -849,32 +831,31 @@ public class TargetTable extends AbstractTable<Target, Long> {
final long totalTargetsCount = getTotalTargetsCount();
managementUIState.setTargetsCountAll(totalTargetsCount);
Collection<TargetUpdateStatus> status = null;
Boolean overdueState = null;
String[] targetTags = null;
Long distributionId = null;
String searchText = null;
Long pinnedDistId = null;
final boolean noTagClicked = managementUIState.getTargetTableFilters().isNoTagSelected();
final Long distributionId = managementUIState.getTargetTableFilters().getDistributionSet()
.map(DistributionSetIdName::getId).orElse(null);
final Long pinnedDistId = managementUIState.getTargetTableFilters().getPinnedDistId().orElse(null);
final String searchText = managementUIState.getTargetTableFilters().getSearchText().map(text -> {
if (Strings.isNullOrEmpty(text)) {
return null;
}
return String.format("%%%s%%", text);
}).orElse(null);
String[] targetTags = null;
if (isFilteredByTags()) {
targetTags = managementUIState.getTargetTableFilters().getClickedTargetTags().toArray(new String[0]);
}
Collection<TargetUpdateStatus> status = null;
if (isFilteredByStatus()) {
status = managementUIState.getTargetTableFilters().getClickedStatusTargetTags();
}
Boolean overdueState = null;
if (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,
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,
final FilterParams filterParams) {
final Optional<Long> query = managementUIState.getTargetTableFilters().getTargetFilterQuery();
final long size;
if (managementUIState.getTargetTableFilters().getTargetFilterQuery().isPresent()) {
size = targetManagement.countTargetByTargetFilterQuery(
managementUIState.getTargetTableFilters().getTargetFilterQuery().get());
if (query.isPresent()) {
size = targetManagement.countTargetByTargetFilterQuery(query.get());
} else if (noFilterSelected(filterParams.getFilterByStatus(), pinnedDistId,
filterParams.getSelectTargetWithNoTag(), filterParams.getFilterByTagNames(),
filterParams.getFilterBySearchText())) {
@@ -903,11 +885,6 @@ public class TargetTable extends AbstractTable<Target, Long> {
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,
final Boolean noTagClicked, final String[] targetTags, final String searchText) {
return CollectionUtils.isEmpty(status) && distributionId == null && Strings.isNullOrEmpty(searchText)

View File

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

View File

@@ -9,23 +9,6 @@
package org.eclipse.hawkbit.ui.rollout.rollout;
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.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.VaadinMessageSource;
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.UIComponentIdProvider;
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) {
final TotalTargetCountStatus totalTargetCountStatus = rollout.getTotalTargetCountStatus();
item.getItemProperty(VAR_STATUS).setValue(rollout.getStatus());
item.getItemProperty(VAR_TOTAL_TARGETS_COUNT_STATUS).setValue(totalTargetCountStatus);
final Integer groupCount = (Integer) item.getItemProperty(VAR_NUMBER_OF_GROUPS).getValue();
item.getItemProperty(SPUILabelDefinitions.VAR_STATUS).setValue(rollout.getStatus());
item.getItemProperty(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS).setValue(totalTargetCountStatus);
final Integer groupCount = (Integer) item.getItemProperty(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).getValue();
final int groupsCreated = rollout.getRolloutGroupsCreated();
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())) {
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)
.setValue(new RolloutRendererData(rollout.getName(), rollout.getStatus().toString()));
@@ -228,29 +213,38 @@ public class RolloutListGrid extends AbstractGrid {
@Override
protected Container createContainer() {
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
protected void addContainerProperties() {
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(SW_MODULES, Set.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(VAR_STATUS, RolloutStatus.class, null, false, false);
rolloutGridContainer.addContainerProperty(VAR_DIST_NAME_VERSION, String.class, null, false, false);
rolloutGridContainer.addContainerProperty(VAR_CREATED_DATE, String.class, null, false, false);
rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_STATUS, RolloutStatus.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(VAR_CREATED_USER, String.class, null, false, false);
rolloutGridContainer.addContainerProperty(VAR_MODIFIED_BY, String.class, null, false, false);
rolloutGridContainer.addContainerProperty(VAR_NUMBER_OF_GROUPS, Integer.class, 0, false, false);
rolloutGridContainer.addContainerProperty(VAR_TOTAL_TARGETS, String.class, "0", false, false);
rolloutGridContainer.addContainerProperty(VAR_TOTAL_TARGETS_COUNT_STATUS, TotalTargetCountStatus.class, null,
false, false);
rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_MODIFIED_DATE, String.class, null, false,
false);
rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_CREATED_USER, String.class, null, false,
false);
rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_MODIFIED_BY, String.class, null, 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(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).setMaximumWidth(150);
getColumn(VAR_DIST_NAME_VERSION).setMinimumWidth(40);
getColumn(VAR_DIST_NAME_VERSION).setMaximumWidth(150);
getColumn(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).setMinimumWidth(40);
getColumn(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).setMaximumWidth(150);
getColumn(VAR_STATUS).setMinimumWidth(75);
getColumn(VAR_STATUS).setMaximumWidth(75);
getColumn(SPUILabelDefinitions.VAR_STATUS).setMinimumWidth(75);
getColumn(SPUILabelDefinitions.VAR_STATUS).setMaximumWidth(75);
getColumn(VAR_TOTAL_TARGETS).setMinimumWidth(40);
getColumn(VAR_TOTAL_TARGETS).setMaximumWidth(100);
getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS).setMinimumWidth(40);
getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS).setMaximumWidth(100);
getColumn(VAR_NUMBER_OF_GROUPS).setMinimumWidth(40);
getColumn(VAR_NUMBER_OF_GROUPS).setMaximumWidth(100);
getColumn(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setMinimumWidth(40);
getColumn(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setMaximumWidth(100);
getColumn(RUN_OPTION).setMinimumWidth(25);
getColumn(RUN_OPTION).setMaximumWidth(25);
@@ -305,7 +299,7 @@ public class RolloutListGrid extends AbstractGrid {
getColumn(DELETE_OPTION).setMinimumWidth(25);
getColumn(DELETE_OPTION).setMaximumWidth(40);
getColumn(VAR_TOTAL_TARGETS_COUNT_STATUS).setMinimumWidth(280);
getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS).setMinimumWidth(280);
}
@Override
@@ -314,16 +308,17 @@ public class RolloutListGrid extends AbstractGrid {
getColumn(DS_TYPE).setHeaderCaption(i18n.getMessage("header.type"));
getColumn(SW_MODULES).setHeaderCaption(i18n.getMessage("header.swmodules"));
getColumn(IS_REQUIRED_MIGRATION_STEP).setHeaderCaption(i18n.getMessage("header.migrations.step"));
getColumn(VAR_DIST_NAME_VERSION).setHeaderCaption(i18n.getMessage("header.distributionset"));
getColumn(VAR_NUMBER_OF_GROUPS).setHeaderCaption(i18n.getMessage("header.numberofgroups"));
getColumn(VAR_TOTAL_TARGETS).setHeaderCaption(i18n.getMessage("header.total.targets"));
getColumn(VAR_CREATED_DATE).setHeaderCaption(i18n.getMessage("header.createdDate"));
getColumn(VAR_CREATED_USER).setHeaderCaption(i18n.getMessage("header.createdBy"));
getColumn(VAR_MODIFIED_DATE).setHeaderCaption(i18n.getMessage("header.modifiedDate"));
getColumn(VAR_MODIFIED_BY).setHeaderCaption(i18n.getMessage("header.modifiedBy"));
getColumn(VAR_DESC).setHeaderCaption(i18n.getMessage("header.description"));
getColumn(VAR_TOTAL_TARGETS_COUNT_STATUS).setHeaderCaption(i18n.getMessage("header.detail.status"));
getColumn(VAR_STATUS).setHeaderCaption(i18n.getMessage("header.status"));
getColumn(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).setHeaderCaption(i18n.getMessage("header.distributionset"));
getColumn(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setHeaderCaption(i18n.getMessage("header.numberofgroups"));
getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS).setHeaderCaption(i18n.getMessage("header.total.targets"));
getColumn(SPUILabelDefinitions.VAR_CREATED_DATE).setHeaderCaption(i18n.getMessage("header.createdDate"));
getColumn(SPUILabelDefinitions.VAR_CREATED_USER).setHeaderCaption(i18n.getMessage("header.createdBy"));
getColumn(SPUILabelDefinitions.VAR_MODIFIED_DATE).setHeaderCaption(i18n.getMessage("header.modifiedDate"));
getColumn(SPUILabelDefinitions.VAR_MODIFIED_BY).setHeaderCaption(i18n.getMessage("header.modifiedBy"));
getColumn(SPUILabelDefinitions.VAR_DESC).setHeaderCaption(i18n.getMessage("header.description"));
getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_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(PAUSE_OPTION).setHeaderCaption(i18n.getMessage("header.action.pause"));
@@ -363,14 +358,14 @@ public class RolloutListGrid extends AbstractGrid {
protected void setColumnProperties() {
final List<Object> columnList = new ArrayList<>();
columnList.add(ROLLOUT_RENDERER_DATA);
columnList.add(VAR_DIST_NAME_VERSION);
columnList.add(SPUILabelDefinitions.VAR_DIST_NAME_VERSION);
columnList.add(DS_TYPE);
columnList.add(SW_MODULES);
columnList.add(IS_REQUIRED_MIGRATION_STEP);
columnList.add(VAR_STATUS);
columnList.add(VAR_TOTAL_TARGETS_COUNT_STATUS);
columnList.add(VAR_NUMBER_OF_GROUPS);
columnList.add(VAR_TOTAL_TARGETS);
columnList.add(SPUILabelDefinitions.VAR_STATUS);
columnList.add(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS);
columnList.add(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS);
columnList.add(SPUILabelDefinitions.VAR_TOTAL_TARGETS);
columnList.add(RUN_OPTION);
columnList.add(PAUSE_OPTION);
@@ -383,11 +378,11 @@ public class RolloutListGrid extends AbstractGrid {
}
columnList.add(DELETE_OPTION);
columnList.add(VAR_CREATED_DATE);
columnList.add(VAR_CREATED_USER);
columnList.add(VAR_MODIFIED_DATE);
columnList.add(VAR_MODIFIED_BY);
columnList.add(VAR_DESC);
columnList.add(SPUILabelDefinitions.VAR_CREATED_DATE);
columnList.add(SPUILabelDefinitions.VAR_CREATED_USER);
columnList.add(SPUILabelDefinitions.VAR_MODIFIED_DATE);
columnList.add(SPUILabelDefinitions.VAR_MODIFIED_BY);
columnList.add(SPUILabelDefinitions.VAR_DESC);
setColumnOrder(columnList.toArray());
alignColumns();
}
@@ -395,12 +390,12 @@ public class RolloutListGrid extends AbstractGrid {
@Override
protected void setHiddenColumns() {
final List<Object> columnsToBeHidden = new ArrayList<>();
columnsToBeHidden.add(VAR_NAME);
columnsToBeHidden.add(VAR_CREATED_DATE);
columnsToBeHidden.add(VAR_CREATED_USER);
columnsToBeHidden.add(VAR_MODIFIED_DATE);
columnsToBeHidden.add(VAR_MODIFIED_BY);
columnsToBeHidden.add(VAR_DESC);
columnsToBeHidden.add(SPUILabelDefinitions.VAR_NAME);
columnsToBeHidden.add(SPUILabelDefinitions.VAR_CREATED_DATE);
columnsToBeHidden.add(SPUILabelDefinitions.VAR_CREATED_USER);
columnsToBeHidden.add(SPUILabelDefinitions.VAR_MODIFIED_DATE);
columnsToBeHidden.add(SPUILabelDefinitions.VAR_MODIFIED_BY);
columnsToBeHidden.add(SPUILabelDefinitions.VAR_DESC);
columnsToBeHidden.add(IS_REQUIRED_MIGRATION_STEP);
columnsToBeHidden.add(DS_TYPE);
columnsToBeHidden.add(SW_MODULES);
@@ -416,11 +411,12 @@ public class RolloutListGrid extends AbstractGrid {
@Override
protected void addColumnRenderes() {
getColumn(VAR_NUMBER_OF_GROUPS).setRenderer(new HtmlRenderer(), new TotalTargetGroupsConverter());
getColumn(VAR_TOTAL_TARGETS_COUNT_STATUS).setRenderer(new HtmlRenderer(),
getColumn(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setRenderer(new HtmlRenderer(),
new TotalTargetGroupsConverter());
getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS).setRenderer(new HtmlRenderer(),
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);
customObjectRenderer.addClickListener(this::onClickOfRolloutName);
@@ -453,10 +449,10 @@ public class RolloutListGrid extends AbstractGrid {
private void onClickOfRolloutName(final RendererClickEvent event) {
rolloutUIState.setRolloutId((long) event.getItemId());
final String rolloutName = (String) getContainerDataSource().getItem(event.getItemId())
.getItemProperty(VAR_NAME).getValue();
.getItemProperty(SPUILabelDefinitions.VAR_NAME).getValue();
rolloutUIState.setRolloutName(rolloutName);
final String ds = (String) getContainerDataSource().getItem(event.getItemId())
.getItemProperty(VAR_DIST_NAME_VERSION).getValue();
.getItemProperty(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).getValue();
rolloutUIState.setRolloutDistributionSet(ds);
eventBus.publish(this, RolloutEvent.SHOW_ROLLOUT_GROUPS);
}
@@ -464,13 +460,14 @@ public class RolloutListGrid extends AbstractGrid {
private void pauseRollout(final Long 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)) {
return;
}
final String rolloutName = (String) row.getItemProperty(VAR_NAME).getValue();
final String rolloutName = (String) row.getItemProperty(SPUILabelDefinitions.VAR_NAME).getValue();
rolloutManagement.pauseRollout(rolloutId);
uiNotification.displaySuccess(i18n.getMessage("message.rollout.paused", rolloutName));
@@ -479,8 +476,9 @@ public class RolloutListGrid extends AbstractGrid {
private void startOrResumeRollout(final Long rolloutId) {
final Item row = getContainerDataSource().getItem(rolloutId);
final RolloutStatus rolloutStatus = (RolloutStatus) row.getItemProperty(VAR_STATUS).getValue();
final String rolloutName = (String) row.getItemProperty(VAR_NAME).getValue();
final RolloutStatus rolloutStatus = (RolloutStatus) row.getItemProperty(SPUILabelDefinitions.VAR_STATUS)
.getValue();
final String rolloutName = (String) row.getItemProperty(SPUILabelDefinitions.VAR_NAME).getValue();
if (RolloutStatus.READY.equals(rolloutStatus)) {
rolloutManagement.startRollout(rolloutId);
@@ -523,7 +521,7 @@ public class RolloutListGrid extends AbstractGrid {
return;
}
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);
uiNotification.displaySuccess(i18n.getMessage("message.rollout.deleted", rolloutName));
});
@@ -551,15 +549,15 @@ public class RolloutListGrid extends AbstractGrid {
String description = null;
if (VAR_STATUS.equals(cell.getPropertyId())) {
if (SPUILabelDefinitions.VAR_STATUS.equals(cell.getPropertyId())) {
description = cell.getProperty().getValue().toString().toLowerCase();
} else if (ACTION.equals(cell.getPropertyId())) {
description = ACTION.toLowerCase();
} else if (SPUILabelDefinitions.ACTION.equals(cell.getPropertyId())) {
description = SPUILabelDefinitions.ACTION.toLowerCase();
} else if (ROLLOUT_RENDERER_DATA.equals(cell.getPropertyId())) {
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());
} else if (VAR_DIST_NAME_VERSION.equals(cell.getPropertyId())) {
} else if (SPUILabelDefinitions.VAR_DIST_NAME_VERSION.equals(cell.getPropertyId())) {
description = getDSDetails(cell.getItem());
}
@@ -578,29 +576,29 @@ public class RolloutListGrid extends AbstractGrid {
swModuleVendors.append(" , ");
});
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(HTML_UL_OPEN_TAG);
stringBuilder.append(HTML_LI_OPEN_TAG);
stringBuilder.append(HawkbitCommonUtil.HTML_UL_OPEN_TAG);
stringBuilder.append(HawkbitCommonUtil.HTML_LI_OPEN_TAG);
stringBuilder.append(" DistributionSet Description : ")
.append((String) rolloutItem.getItemProperty(VAR_DESC).getValue());
stringBuilder.append(HTML_LI_CLOSE_TAG);
stringBuilder.append(HTML_LI_OPEN_TAG);
.append((String) rolloutItem.getItemProperty(SPUILabelDefinitions.VAR_DESC).getValue());
stringBuilder.append(HawkbitCommonUtil.HTML_LI_CLOSE_TAG);
stringBuilder.append(HawkbitCommonUtil.HTML_LI_OPEN_TAG);
stringBuilder.append(" DistributionSet Type : ")
.append((String) rolloutItem.getItemProperty(DS_TYPE).getValue());
stringBuilder.append(HTML_LI_CLOSE_TAG);
stringBuilder.append(HTML_LI_OPEN_TAG);
stringBuilder.append(HawkbitCommonUtil.HTML_LI_CLOSE_TAG);
stringBuilder.append(HawkbitCommonUtil.HTML_LI_OPEN_TAG);
stringBuilder.append("Required Migration step : ")
.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(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(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();
}
@@ -635,7 +633,7 @@ public class RolloutListGrid extends AbstractGrid {
@Override
public String getStyle(final CellReference cellReference) {
if (VAR_STATUS.equals(cellReference.getPropertyId())) {
if (SPUILabelDefinitions.VAR_STATUS.equals(cellReference.getPropertyId())) {
return "centeralign";
}
return convertRolloutStatusToString(cellReference);
@@ -675,7 +673,7 @@ public class RolloutListGrid extends AbstractGrid {
private RolloutStatus getRolloutStatus(final Object 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() {
long size = 0;
if (rolloutGroup.isPresent()) {
try {
firstPageTargetSets = getRolloutGroupManagement().findAllTargetsWithActionStatus(
new PageRequest(0, SPUIDefinitions.PAGE_SIZE, sort), rolloutGroup.get().getId());
size = firstPageTargetSets.getTotalElements();
firstPageTargetSets = rolloutGroup.map(group -> getRolloutGroupManagement()
.findAllTargetsWithActionStatus(new PageRequest(0, SPUIDefinitions.PAGE_SIZE, sort), group.getId()))
.orElse(null);
size = firstPageTargetSets == null ? 0 : firstPageTargetSets.getTotalElements();
} catch (final EntityNotFoundException e) {
LOG.error("Rollout does not exists. Redirect to Rollouts overview", e);
rolloutUIState.setShowRolloutGroupTargets(false);
rolloutUIState.setShowRollOuts(true);
return 0;
}
}
getRolloutUIState().setRolloutGroupTargetsTotalCount(size);
if (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 fieldPollingOverdueTime;
private Duration tenantPollTime;
private Duration tenantOverdueTime;
private transient Duration tenantPollTime;
private transient Duration tenantOverdueTime;
PollingConfigurationView(final VaadinMessageSource i18n, final ControllerPollProperties controllerPollProperties,
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 DurationField durationField = new DurationField();
private Duration globalDuration;
private transient Duration globalDuration;
private DurationConfigField(final String id) {
super(2, 2);
@@ -124,7 +124,7 @@ public final class DurationConfigField extends GridLayout implements Configurati
}
private void notifyConfigurationChanged() {
configurationChangeListeners.forEach(listener -> listener.configurationHasChanged());
configurationChangeListeners.forEach(ConfigurationItemChangeListener::configurationHasChanged);
}
@Override

View File

@@ -160,9 +160,9 @@
<!-- Release - END -->
<!-- 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.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>
<jacoco.version>0.7.7.201606060606</jacoco.version>
<jacoco.outputDir>${project.basedir}/../target/</jacoco.outputDir>
@@ -296,7 +296,7 @@
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.1.1</version>
<version>3.2</version>
</plugin>
<plugin>
<groupId>org.eclipse.m2e</groupId>

View File

@@ -11,7 +11,7 @@
echo $CI_PULL_REQUEST pull request
# regular sonar on master
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
else
#if [ -n "$CI_PULL_REQUEST" ]; then