diff --git a/.gitignore b/.gitignore index ba9cf4617..8cd3d476e 100644 --- a/.gitignore +++ b/.gitignore @@ -16,13 +16,13 @@ *.jar *.war -###################### # Sonar -###################### .sonar_lock -# Eclipse IDE +# Created by spring-boot-configuration-processor +.factorypath +# Eclipse IDE *.pydevproject .project .metadata diff --git a/CONTRUBUTING.md b/CONTRUBUTING.md index bc04d2abd..626e7f0f1 100644 --- a/CONTRUBUTING.md +++ b/CONTRUBUTING.md @@ -4,7 +4,9 @@ Please read this if you intend to contribute to the project. -## Code Conventions +## Conventions + +### Code Style * Java files: * we follow the standard eclipse IDE (built in) code formatter with the following changes: @@ -19,6 +21,37 @@ Please read this if you intend to contribute to the project. * Sonarqube: * Our rule set is defined [here](http://sonar.eu-gb.mybluemix.net) +### Test documentation + +Please documented the test cases that you contribute by means of [Allure](http://allure.qatools.ru) annotations and proper test method naming. + +All test classes are documented with [Allure's](https://github.com/allure-framework/allure-core/wiki/Features-and-Stories) **@Features** and **@Stories** annotations in the following format: +``` +@Features("TEST_TYPE - HAWKBIT_COMPONENT") +@Stories("Test class description") +``` + +Test types are: +* Unit Tests - for single units tests with a mocked environment +* Component Tests - for complete components including lower layers, e.g. Spring MVC test on rest API including repository and database. +* Integration Tests - including clients, e.g. Selenium UI tests with various browsers. +* System Tests - on target environments, e.g. Cloud Foundry. + +Examples for hawkBit components: +* Management API +* Direct Device Integration API +* Device Management Federation API +* Management UI +* Repository +* Security + +``` +@Features("Component Tests - Management API") +@Stories("Distribution Set Type Resource") +``` + +In addition all test method's name describes in **camel case** what the test is all about and has a long description aith Allures **@Description** annotation. + ## Legal considerations for your contribution The following steps are necessary to comply with the Eclipse Foundation's IP policy. diff --git a/MIGRATION.md b/MIGRATION.md new file mode 100644 index 000000000..eacce864d --- /dev/null +++ b/MIGRATION.md @@ -0,0 +1,9 @@ +# hawkBit Migration Guides +## Release 0.2 +### Configuration Property changes +- hawkbit.server.controller._ have changed to hawkbit.server.ddi._ +- info.build._ have changed to hawkbit.server.build._ +- hawkbit.server.demo._ have changed to hawkbit.server.ui.demo._ +- hawkbit.server.email.support has changed to hawkbit.server.ui.links.support +- hawkbit.server.email.request.account has changed to hawkbit.server.ui.links.requestAccount +- hawkbit.server.im.login.url has changed to hawkbit.server.ui.links.userManagement diff --git a/examples/hawkbit-device-simulator/pom.xml b/examples/hawkbit-device-simulator/pom.xml index 9a84d13f5..a2575e9db 100644 --- a/examples/hawkbit-device-simulator/pom.xml +++ b/examples/hawkbit-device-simulator/pom.xml @@ -100,7 +100,6 @@ com.google.guava guava - 19.0 com.netflix.feign @@ -116,13 +115,18 @@ com.jayway.jsonpath json-path + + org.springframework.boot + spring-boot-configuration-processor + true + com.vaadin vaadin-bom - 7.5.5 + 7.6.3 pom import diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/AmqpProperties.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/AmqpProperties.java index ff9762c5d..f9e6ab23d 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/AmqpProperties.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/AmqpProperties.java @@ -9,21 +9,35 @@ package org.eclipse.hawkbit.simulator.amqp; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; /** * Bean which holds the necessary properties for configuring the AMQP * connection. * - * - * */ +@Component @ConfigurationProperties("hawkbit.device.simulator.amqp") public class AmqpProperties { + /** + * Queue for receiving DMF messages from update server. + */ private String receiverConnectorQueueFromSp; + + /** + * Exchange for sending DMF messages to update server. + */ private String senderForSpExchange; + /** + * Simulator dead letter queue. + */ private String deadLetterQueue; + + /** + * Simulator dead letter exchange. + */ private String deadLetterExchange; public String getReceiverConnectorQueueFromSp() { diff --git a/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyUI.java b/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyUI.java index cafe0749d..e55cb02d2 100644 --- a/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyUI.java +++ b/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyUI.java @@ -8,21 +8,12 @@ */ package org.eclipse.hawkbit.app; -import org.eclipse.hawkbit.eventbus.EventSubscriber; -import org.eclipse.hawkbit.eventbus.event.EntityEvent; -import org.eclipse.hawkbit.ui.DispatcherRunnable; import org.eclipse.hawkbit.ui.HawkbitUI; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.web.context.HttpSessionSecurityContextRepository; -import org.vaadin.spring.events.EventBus.SessionEventBus; +import org.eclipse.hawkbit.ui.push.DelayedEventBusPushStrategy; +import org.springframework.beans.factory.annotation.Autowired; -import com.google.common.eventbus.AllowConcurrentEvents; -import com.google.common.eventbus.Subscribe; +import com.google.common.eventbus.EventBus; import com.vaadin.annotations.Push; -import com.vaadin.server.VaadinSession; -import com.vaadin.server.VaadinSession.State; -import com.vaadin.server.WrappedSession; import com.vaadin.shared.communication.PushMode; import com.vaadin.shared.ui.ui.Transport; import com.vaadin.spring.annotation.SpringUI; @@ -33,45 +24,16 @@ import com.vaadin.spring.annotation.SpringUI; * A {@link SpringUI} annotated class must be present in the classpath. The * easiest way to get an hawkBit UI running is to extend the {@link HawkbitUI} * and to annotated it with {@link SpringUI} as in this example. - * - * * */ @SpringUI @Push(value = PushMode.AUTOMATIC, transport = Transport.WEBSOCKET) -@EventSubscriber public class MyUI extends HawkbitUI { private static final long serialVersionUID = 1L; - /** - * An {@link com.google.common.eventbus.EventBus} subscriber which - * subscribes {@link EntityEvent} from the repository to dispatch these - * events to the UI {@link SessionEventBus}. - * - * @param event - * the entity event which has been published from the repository - */ - @Override - @Subscribe - @AllowConcurrentEvents - public void dispatch(final org.eclipse.hawkbit.eventbus.event.Event event) { - final VaadinSession session = getSession(); - if (session != null && session.getState() == State.OPEN) { - final WrappedSession wrappedSession = session.getSession(); - if (wrappedSession != null) { - final SecurityContext userContext = (SecurityContext) wrappedSession - .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); - if (eventSecurityCheck(userContext, event)) { - final SecurityContext oldContext = SecurityContextHolder.getContext(); - try { - access(new DispatcherRunnable(eventBus, session, userContext, event)); - } finally { - SecurityContextHolder.setContext(oldContext); - } - } - } - } + @Autowired + public MyUI(final EventBus systemEventBus, final org.vaadin.spring.events.EventBus.SessionEventBus eventBus) { + super(new DelayedEventBusPushStrategy(eventBus, systemEventBus)); } - } diff --git a/examples/hawkbit-example-app/src/main/resources/application.properties b/examples/hawkbit-example-app/src/main/resources/application.properties index 13ceca40a..d3eddeff1 100644 --- a/examples/hawkbit-example-app/src/main/resources/application.properties +++ b/examples/hawkbit-example-app/src/main/resources/application.properties @@ -7,23 +7,20 @@ # http://www.eclipse.org/legal/epl-v10.html # -# need to re-name these properties in the defaulthawkbit.properties and code! -hawkbit.server.controller.security.authentication.anonymous.enabled=true -hawkbit.server.controller.security.authentication.header.enabled=false -hawkbit.server.controller.security.authentication.targettoken.enabled=false -hawkbit.server.controller.security.authentication.gatewaytoken.enabled=false +hawkbit.server.ddi.security.authentication.anonymous.enabled=true +hawkbit.server.ddi.security.authentication.targettoken.enabled=false +hawkbit.server.ddi.security.authentication.gatewaytoken.enabled=false spring.profiles.active=amqp vaadin.servlet.productionMode=false -vaadin.static.servlet.productionMode=false ## Configuration for RabbitMQ integration -hawkbit.server.amqp.username=guest -hawkbit.server.amqp.password=guest -hawkbit.server.amqp.virtualHost=/ -hawkbit.server.amqp.host=localhost -hawkbit.server.amqp.port=5672 -hawkbit.server.amqp.deadLetterQueue=sp_deadletter -hawkbit.server.amqp.deadLetterExchange=sp.deadletter -hawkbit.server.amqp.receiverQueue=sp_receiver +spring.rabbitmq.username=guest +spring.rabbitmq.password=guest +spring.rabbitmq.virtualHost=/ +spring.rabbitmq.host=localhost +spring.rabbitmq.port=5672 +hawkbit.dmf.rabbitmq.deadLetterQueue=dmf_connector_deadletter +hawkbit.dmf.rabbitmq.deadLetterExchange=dmf.connector.deadletter +hawkbit.dmf.rabbitmq.receiverQueue=dmf_receiver diff --git a/examples/hawkbit-mgmt-api-client/pom.xml b/examples/hawkbit-mgmt-api-client/pom.xml index 6e62bfe4e..9aaf53dc6 100644 --- a/examples/hawkbit-mgmt-api-client/pom.xml +++ b/examples/hawkbit-mgmt-api-client/pom.xml @@ -87,5 +87,10 @@ google-collections 1.0-rc2 + + org.springframework.boot + spring-boot-configuration-processor + true + \ No newline at end of file diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/ClientConfigurationProperties.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/ClientConfigurationProperties.java index 6d15bcc04..68f35b550 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/ClientConfigurationProperties.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/ClientConfigurationProperties.java @@ -18,8 +18,19 @@ import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "hawkbit") public class ClientConfigurationProperties { + /** + * Update server URI. + */ private String url = "localhost:8080"; + + /** + * Update server user name. + */ private String username = "admin"; + + /** + * Update server password. + */ private String password = "admin"; // NOSONAR this password is only used for // examples diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleAssigmentBuilder.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleAssigmentBuilder.java index 840f16182..b209dbe8b 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleAssigmentBuilder.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleAssigmentBuilder.java @@ -25,7 +25,7 @@ public class SoftwareModuleAssigmentBuilder { private final List ids; public SoftwareModuleAssigmentBuilder() { - ids = new ArrayList(); + ids = new ArrayList<>(); } /** diff --git a/examples/hawkbit-mgmt-api-client/src/main/resources/application.properties b/examples/hawkbit-mgmt-api-client/src/main/resources/application.properties index da0aa79dd..d3a3eb969 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/resources/application.properties +++ b/examples/hawkbit-mgmt-api-client/src/main/resources/application.properties @@ -11,4 +11,4 @@ hawkbit.url=localhost:8080 hawkbit.username=admin hawkbit.password=admin -spring.main.banner-mode=OFF \ No newline at end of file +spring.main.show-banner=false \ No newline at end of file diff --git a/examples/hawkbit-mgmt-api-client/src/main/resources/logback.xml b/examples/hawkbit-mgmt-api-client/src/main/resources/logback.xml index 819566e0f..0174611e6 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/resources/logback.xml +++ b/examples/hawkbit-mgmt-api-client/src/main/resources/logback.xml @@ -1,6 +1,3 @@ - diff --git a/hawkbit-cache-redis/src/main/java/org/eclipse/hawkbit/cache/RedisConfiguration.java b/hawkbit-cache-redis/src/main/java/org/eclipse/hawkbit/cache/RedisConfiguration.java index acf50ad3f..edc183b17 100644 --- a/hawkbit-cache-redis/src/main/java/org/eclipse/hawkbit/cache/RedisConfiguration.java +++ b/hawkbit-cache-redis/src/main/java/org/eclipse/hawkbit/cache/RedisConfiguration.java @@ -26,8 +26,6 @@ import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer * The spring Redis configuration which is enabled by using the profile * {@code redis} to use a Redis server as cache. * - * - * */ @Configuration @EnableConfigurationProperties(RedisProperties.class) diff --git a/hawkbit-cache-redis/src/main/java/org/eclipse/hawkbit/cache/RedisProperties.java b/hawkbit-cache-redis/src/main/java/org/eclipse/hawkbit/cache/RedisProperties.java index c228cde4c..ab409bbf5 100644 --- a/hawkbit-cache-redis/src/main/java/org/eclipse/hawkbit/cache/RedisProperties.java +++ b/hawkbit-cache-redis/src/main/java/org/eclipse/hawkbit/cache/RedisProperties.java @@ -14,14 +14,18 @@ import org.springframework.boot.context.properties.ConfigurationProperties; * Bean which holds the necessary properties for configuring the Redis * connection. * - * - * - * */ @ConfigurationProperties("hawkbit.server.redis") public class RedisProperties { + /** + * Redis server hostname. + */ private String host; + + /** + * Redis server port. + */ private int port; /** diff --git a/hawkbit-cache-redis/src/test/java/org/eclipse/hawkbit/cache/eventbus/EventDistributorTest.java b/hawkbit-cache-redis/src/test/java/org/eclipse/hawkbit/cache/eventbus/EventDistributorTest.java index e44889f60..c1ff54961 100644 --- a/hawkbit-cache-redis/src/test/java/org/eclipse/hawkbit/cache/eventbus/EventDistributorTest.java +++ b/hawkbit-cache-redis/src/test/java/org/eclipse/hawkbit/cache/eventbus/EventDistributorTest.java @@ -29,7 +29,13 @@ import org.springframework.hateoas.Identifiable; import com.google.common.eventbus.EventBus; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@Features("Unit Tests - Cluster Cache") +@Stories("EventDistributor Test") @RunWith(MockitoJUnitRunner.class) +// TODO: create description annotations public class EventDistributorTest { @Mock diff --git a/hawkbit-cache-redis/src/test/java/org/eclipse/hawkbit/cache/redis/RedisPropertiesTest.java b/hawkbit-cache-redis/src/test/java/org/eclipse/hawkbit/cache/redis/RedisPropertiesTest.java index 6aac1b03f..ab57dd541 100644 --- a/hawkbit-cache-redis/src/test/java/org/eclipse/hawkbit/cache/redis/RedisPropertiesTest.java +++ b/hawkbit-cache-redis/src/test/java/org/eclipse/hawkbit/cache/redis/RedisPropertiesTest.java @@ -13,6 +13,11 @@ import static org.fest.assertions.api.Assertions.assertThat; import org.eclipse.hawkbit.cache.RedisProperties; import org.junit.Test; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@Features("Unit Tests - Cluster Cache") +@Stories("Redis Properties Test") public class RedisPropertiesTest { @Test diff --git a/hawkbit-core/pom.xml b/hawkbit-core/pom.xml index b56d30075..f9e140d40 100644 --- a/hawkbit-core/pom.xml +++ b/hawkbit-core/pom.xml @@ -43,6 +43,11 @@ allure-junit-adaptor test + + org.springframework.boot + spring-boot-configuration-processor + true + \ No newline at end of file diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/ControllerPollProperties.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/ControllerPollProperties.java index e66d86801..6812afbbd 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/ControllerPollProperties.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/ControllerPollProperties.java @@ -9,18 +9,26 @@ package org.eclipse.hawkbit; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; /** * Defines the polling time for the controllers in HH:MM:SS notation. * - * - * */ - +@Component @ConfigurationProperties(prefix = "hawkbit.controller") public class ControllerPollProperties { + /** + * Recommended target polling time for DDI API. Final choice is up to the + * target. + */ private String pollingTime = "00:05:00"; + + /** + * Assumed time frame where the target is considered overdue when no DDI + * polling has been registered by the update server. + */ private String pollingOverdueTime = "00:05:00"; private String maxPollingTime = "23:59:00"; private String minPollingTime = "00:00:30"; diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java new file mode 100644 index 000000000..878965102 --- /dev/null +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java @@ -0,0 +1,97 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * Properties for the server e.g. the server's URL which must be configured. + * + */ +@ConfigurationProperties("hawkbit.server") +public class HawkbitServerProperties { + /** + * Defines under which URI the update server can be reached. Used to + * calculate download URLs for DMF transmitted update actions. + */ + private String url = "http://localhost:8080"; + + private final Build build = new Build(); + + public Build getBuild() { + return build; + } + + /** + * Build information of the hawkBit instance. Influenced by maven. + * + */ + public static class Build { + /** + * Project artifact ID. + */ + private String artifact = ""; + + /** + * Project name. + */ + private String name = ""; + + /** + * Project description. + */ + private String description = ""; + + /** + * Project version. + */ + private String version = ""; + + public String getArtifact() { + return artifact; + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } + + public String getVersion() { + return version; + } + + public void setArtifact(final String artifact) { + this.artifact = artifact; + } + + public void setName(final String name) { + this.name = name; + } + + public void setDescription(final String description) { + this.description = description; + } + + public void setVersion(final String version) { + this.version = version; + } + + } + + public String getUrl() { + return url; + } + + public void setUrl(final String url) { + this.url = url; + } +} diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/cache/TenantAwareCacheManager.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/cache/TenantAwareCacheManager.java index 06d6e1719..435f1b2e1 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/cache/TenantAwareCacheManager.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/cache/TenantAwareCacheManager.java @@ -51,7 +51,12 @@ public class TenantAwareCacheManager implements TenancyCacheManager { @Override public Cache getCache(final String name) { - final String currentTenant = tenantAware.getCurrentTenant().toUpperCase(); + String currentTenant = tenantAware.getCurrentTenant(); + if (currentTenant == null) { + return null; + } + + currentTenant = currentTenant.toUpperCase(); if (currentTenant.contains(TENANT_CACHE_DELIMITER)) { return null; } @@ -60,7 +65,12 @@ public class TenantAwareCacheManager implements TenancyCacheManager { @Override public Collection getCacheNames() { - final String currentTenant = tenantAware.getCurrentTenant().toUpperCase(); + String currentTenant = tenantAware.getCurrentTenant(); + if (currentTenant == null) { + return null; + } + + currentTenant = currentTenant.toUpperCase(); if (currentTenant.contains(TENANT_CACHE_DELIMITER)) { return Collections.emptyList(); } diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/repository/ActionStatusFields.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/repository/ActionStatusFields.java index 22fa42474..ef8bf3c98 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/repository/ActionStatusFields.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/repository/ActionStatusFields.java @@ -20,7 +20,12 @@ public enum ActionStatusFields implements FieldNameProvider { /** * The id field. */ - ID("id"); + ID("id"), + + /** + * The reportedAt field. + */ + REPORTEDAT("createdAt"); private final String fieldName; diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/TenantConfigurationKey.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/TenantConfigurationKey.java index 68c68d0da..a4f92ccac 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/TenantConfigurationKey.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/TenantConfigurationKey.java @@ -29,32 +29,32 @@ public enum TenantConfigurationKey { * boolean value {@code true} {@code false}. */ AUTHENTICATION_MODE_HEADER_ENABLED("authentication.header.enabled", - "hawkbit.server.controller.security.authentication.header.enabled", Boolean.class, Boolean.FALSE.toString(), + "hawkbit.server.ddi.security.authentication.header.enabled", Boolean.class, Boolean.FALSE.toString(), TenantConfigurationBooleanValidator.class), /** * */ AUTHENTICATION_MODE_HEADER_AUTHORITY_NAME("authentication.header.authority", - "hawkbit.server.controller.security.authentication.header.authority", String.class, - Boolean.FALSE.toString(), TenantConfigurationStringValidator.class), + "hawkbit.server.ddi.security.authentication.header.authority", String.class, Boolean.FALSE.toString(), + TenantConfigurationStringValidator.class), /** * boolean value {@code true} {@code false}. */ AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED("authentication.targettoken.enabled", - "hawkbit.server.controller.security.authentication.targettoken.enabled", Boolean.class, - Boolean.FALSE.toString(), TenantConfigurationBooleanValidator.class), + "hawkbit.server.ddi.security.authentication.targettoken.enabled", Boolean.class, Boolean.FALSE.toString(), + TenantConfigurationBooleanValidator.class), /** * boolean value {@code true} {@code false}. */ AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_ENABLED("authentication.gatewaytoken.enabled", - "hawkbit.server.controller.security.authentication.gatewaytoken.enabled", Boolean.class, - Boolean.FALSE.toString(), TenantConfigurationBooleanValidator.class), + "hawkbit.server.ddi.security.authentication.gatewaytoken.enabled", Boolean.class, Boolean.FALSE.toString(), + TenantConfigurationBooleanValidator.class), /** * string value which holds the name of the security token key. */ AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_NAME("authentication.gatewaytoken.name", - "hawkbit.server.controller.security.authentication.gatewaytoken.name", String.class, null, + "hawkbit.server.ddi.security.authentication.gatewaytoken.name", String.class, null, TenantConfigurationStringValidator.class), /** @@ -62,7 +62,7 @@ public enum TenantConfigurationKey { * token. */ AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY("authentication.gatewaytoken.key", - "hawkbit.server.controller.security.authentication.gatewaytoken.key", String.class, null, + "hawkbit.server.ddi.security.authentication.gatewaytoken.key", String.class, null, TenantConfigurationStringValidator.class), /** diff --git a/hawkbit-core/src/test/java/org/eclipse/hawkbit/eventbus/EventBusSubscriberProcessorTest.java b/hawkbit-core/src/test/java/org/eclipse/hawkbit/eventbus/EventBusSubscriberProcessorTest.java index ac02aaad1..548bf7e7e 100644 --- a/hawkbit-core/src/test/java/org/eclipse/hawkbit/eventbus/EventBusSubscriberProcessorTest.java +++ b/hawkbit-core/src/test/java/org/eclipse/hawkbit/eventbus/EventBusSubscriberProcessorTest.java @@ -21,7 +21,13 @@ import org.mockito.runners.MockitoJUnitRunner; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@Features("Unit Tests - Cluster Event Bus") +@Stories("EventBus Subscriber Processor Test") @RunWith(MockitoJUnitRunner.class) +// TODO: create description annotations public class EventBusSubscriberProcessorTest { @Mock diff --git a/hawkbit-dmf-amqp/pom.xml b/hawkbit-dmf-amqp/pom.xml index a7dfc5b42..2fded8559 100644 --- a/hawkbit-dmf-amqp/pom.xml +++ b/hawkbit-dmf-amqp/pom.xml @@ -60,6 +60,11 @@ org.slf4j slf4j-api + + org.springframework.boot + spring-boot-configuration-processor + true + diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpConfiguration.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpConfiguration.java index 988a68ada..d2cd1eab8 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpConfiguration.java +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpConfiguration.java @@ -23,6 +23,7 @@ import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; import org.springframework.amqp.support.converter.MessageConverter; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; @@ -121,11 +122,22 @@ public class AmqpConfiguration { /** * Create amqp handler service bean. * - * @return + * @return handler service bean */ @Bean public AmqpMessageHandlerService amqpMessageHandlerService() { - return new AmqpMessageHandlerService(); + return new AmqpMessageHandlerService(rabbitTemplate); + } + + /** + * Create default amqp sender service bean. + * + * @return the default amqp sender service bean + */ + @Bean + @ConditionalOnMissingBean + public AmqpSenderService amqpSenderServiceBean() { + return new DefaultAmqpSenderService(rabbitTemplate); } /** diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthentfication.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthentfication.java index b7570f185..8f19d9f02 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthentfication.java +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthentfication.java @@ -21,9 +21,9 @@ import org.eclipse.hawkbit.security.CoapAnonymousPreAuthenticatedFilter; import org.eclipse.hawkbit.security.ControllerPreAuthenticateSecurityTokenFilter; import org.eclipse.hawkbit.security.ControllerPreAuthenticatedGatewaySecurityTokenFilter; import org.eclipse.hawkbit.security.ControllerPreAuthenticatedSecurityHeaderFilter; +import org.eclipse.hawkbit.security.DdiSecurityProperties; import org.eclipse.hawkbit.security.PreAuthTokenSourceTrustAuthenticationProvider; import org.eclipse.hawkbit.security.PreAuthenficationFilter; -import org.eclipse.hawkbit.security.SecurityProperties; import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.tenancy.TenantAware; import org.slf4j.Logger; @@ -56,7 +56,7 @@ public class AmqpControllerAuthentfication { private TenantAware tenantAware; @Autowired - private SecurityProperties secruityProperties; + private DdiSecurityProperties ddiSecruityProperties; @Autowired private SystemSecurityContext systemSecurityContext; @@ -82,7 +82,7 @@ public class AmqpControllerAuthentfication { filterChain.add(gatewaySecurityTokenFilter); final ControllerPreAuthenticatedSecurityHeaderFilter securityHeaderFilter = new ControllerPreAuthenticatedSecurityHeaderFilter( - secruityProperties.getRpCnHeader(), secruityProperties.getRpSslIssuerHashHeader(), + ddiSecruityProperties.getRp().getCnHeader(), ddiSecruityProperties.getRp().getSslIssuerHashHeader(), tenantConfigurationManagement, tenantAware, systemSecurityContext); filterChain.add(securityHeaderFilter); @@ -131,18 +131,15 @@ public class AmqpControllerAuthentfication { LOGGER.debug("preAuthenticatedPrincipal = {} trying to authenticate", principal); - final PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(principal, - credentials); - - return authRequest; + return new PreAuthenticatedAuthenticationToken(principal, credentials); } public void setControllerManagement(final ControllerManagement controllerManagement) { this.controllerManagement = controllerManagement; } - public void setSecruityProperties(final SecurityProperties secruityProperties) { - this.secruityProperties = secruityProperties; + public void setSecruityProperties(final DdiSecurityProperties secruityProperties) { + this.ddiSecruityProperties = secruityProperties; } public void setTenantConfigurationManagement(final TenantConfigurationManagement tenantConfigurationManagement) { diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java index 3708f942b..b9e6fe9da 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java @@ -25,35 +25,43 @@ import org.eclipse.hawkbit.eventbus.EventSubscriber; import org.eclipse.hawkbit.eventbus.event.CancelTargetAssignmentEvent; import org.eclipse.hawkbit.eventbus.event.TargetAssignDistributionSetEvent; import org.eclipse.hawkbit.repository.model.LocalArtifact; -import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.hawkbit.util.ArtifactUrlHandler; import org.eclipse.hawkbit.util.IpUtil; import org.springframework.amqp.core.Message; import org.springframework.amqp.core.MessageProperties; import org.springframework.amqp.rabbit.core.RabbitTemplate; -import org.springframework.amqp.support.converter.AbstractJavaTypeMapper; import org.springframework.beans.factory.annotation.Autowired; import com.google.common.eventbus.Subscribe; /** - * {@link AmqpMessageDispatcherService} handles all outgoing AMQP messages. - * - * + * {@link AmqpMessageDispatcherService} create all outgoing AMQP messages and + * delegate the messages to a {@link AmqpSenderService}. + * + * Additionally the dispatcher listener/subscribe for some target events e.g. + * assignment. * */ @EventSubscriber -public class AmqpMessageDispatcherService { - - @Autowired - private RabbitTemplate rabbitTemplate; - - @Autowired - private TenantAware tenantAware; +public class AmqpMessageDispatcherService extends BaseAmqpService { @Autowired private ArtifactUrlHandler artifactUrlHandler; + @Autowired + private AmqpSenderService amqpSenderService; + + /** + * Constructor. + * + * @param messageConverter + * message converter + */ + @Autowired + public AmqpMessageDispatcherService(final RabbitTemplate rabbitTemplate) { + super(rabbitTemplate); + } + /** * Method to send a message to a RabbitMQ Exchange after the Distribution * set has been assign to a Target. @@ -79,11 +87,10 @@ public class AmqpMessageDispatcherService { downloadAndUpdateRequest.addSoftwareModule(amqpSoftwareModule); } - final Message message = rabbitTemplate.getMessageConverter().toMessage( - downloadAndUpdateRequest, + final Message message = getMessageConverter().toMessage(downloadAndUpdateRequest, createConnectorMessageProperties(targetAssignDistributionSetEvent.getTenant(), controllerId, EventTopic.DOWNLOAD_AND_INSTALL)); - sendMessage(targetAdress.getHost(), message); + amqpSenderService.sendMessage(message, targetAdress); } /** @@ -98,29 +105,13 @@ public class AmqpMessageDispatcherService { final CancelTargetAssignmentEvent cancelTargetAssignmentDistributionSetEvent) { final String controllerId = cancelTargetAssignmentDistributionSetEvent.getControllerId(); final Long actionId = cancelTargetAssignmentDistributionSetEvent.getActionId(); - final Message message = rabbitTemplate.getMessageConverter().toMessage( - actionId, - createConnectorMessageProperties(cancelTargetAssignmentDistributionSetEvent.getTenant(), controllerId, - EventTopic.CANCEL_DOWNLOAD)); + final Message message = getMessageConverter().toMessage(actionId, createConnectorMessageProperties( + cancelTargetAssignmentDistributionSetEvent.getTenant(), controllerId, EventTopic.CANCEL_DOWNLOAD)); - sendMessage(cancelTargetAssignmentDistributionSetEvent.getTargetAdress().getHost(), message); + amqpSenderService.sendMessage(message, cancelTargetAssignmentDistributionSetEvent.getTargetAdress()); } - /** - * Send message to exchange. - * - * @param exchange - * the exchange - * @param message - * the message - */ - public void sendMessage(final String exchange, final Message message) { - message.getMessageProperties().getHeaders().remove(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME); - rabbitTemplate.setExchange(exchange); - rabbitTemplate.send(message); - } - private MessageProperties createConnectorMessageProperties(final String tenant, final String controllerId, final EventTopic topic) { final MessageProperties messageProperties = createMessageProperties(); @@ -155,9 +146,8 @@ public class AmqpMessageDispatcherService { return Collections.emptyList(); } - final List convertedArtifacts = localArtifacts.stream() - .map(localArtifact -> convertArtifact(targetId, localArtifact)).collect(Collectors.toList()); - return convertedArtifacts; + return localArtifacts.stream().map(localArtifact -> convertArtifact(targetId, localArtifact)) + .collect(Collectors.toList()); } private Artifact convertArtifact(final String targetId, final LocalArtifact localArtifact) { @@ -175,15 +165,11 @@ public class AmqpMessageDispatcherService { return artifact; } - public void setTenantAware(final TenantAware tenantAware) { - this.tenantAware = tenantAware; - } - - public void setRabbitTemplate(final RabbitTemplate rabbitTemplate) { - this.rabbitTemplate = rabbitTemplate; - } - public void setArtifactUrlHandler(final ArtifactUrlHandler artifactUrlHandler) { this.artifactUrlHandler = artifactUrlHandler; } + + public void setAmqpSenderService(final AmqpSenderService amqpSenderService) { + this.amqpSenderService = amqpSenderService; + } } diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerService.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerService.java index f8aed4f86..cfd5485a6 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerService.java +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerService.java @@ -12,7 +12,6 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.List; -import java.util.Map; import java.util.UUID; import org.apache.commons.lang3.StringUtils; @@ -50,8 +49,6 @@ import org.springframework.amqp.core.Message; import org.springframework.amqp.core.MessageProperties; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.amqp.rabbit.core.RabbitTemplate; -import org.springframework.amqp.support.converter.AbstractJavaTypeMapper; -import org.springframework.amqp.support.converter.MessageConverter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.Cache; @@ -72,19 +69,14 @@ import com.google.common.eventbus.EventBus; /** * - * {@link AmqpMessageHandlerService} handles all incoming AMQP messages. - * - * - * + * {@link AmqpMessageHandlerService} handles all incoming AMQP messages for the + * queue which is configure for the property hawkbit.dmf.rabbitmq.receiverQueue. * */ -public class AmqpMessageHandlerService { +public class AmqpMessageHandlerService extends BaseAmqpService { private static final Logger LOG = LoggerFactory.getLogger(AmqpMessageHandlerService.class); - @Autowired - private RabbitTemplate rabbitTemplate; - @Autowired private ControllerManagement controllerManagement; @@ -105,7 +97,23 @@ public class AmqpMessageHandlerService { private HostnameResolver hostnameResolver; /** - * /** Method to handle all incoming amqp messages. + * Constructor. + * + * @param defaultTemplate + * the configured amqp template. + */ + public AmqpMessageHandlerService(final RabbitTemplate defaultTemplate) { + super(defaultTemplate); + } + + @RabbitListener(queues = "${hawkbit.dmf.rabbitmq.receiverQueue}", containerFactory = "listenerContainerFactory") + private Message onMessage(final Message message, @Header(MessageHeaderKey.TYPE) final String type, + @Header(MessageHeaderKey.TENANT) final String tenant) { + return onMessage(message, type, tenant, getRabbitTemplate().getConnectionFactory().getVirtualHost()); + } + + /** + * Method to handle all incoming amqp messages. * * @param message * incoming message @@ -115,11 +123,11 @@ public class AmqpMessageHandlerService { * the contentType of the message * @param tenant * the contentType of the message + * @param virtualHost + * the virtual host * @return a message if no message is send back to sender */ - @RabbitListener(queues = "${hawkbit.dmf.rabbitmq.receiverQueue}", containerFactory = "listenerContainerFactory") - public Message onMessage(final Message message, @Header(MessageHeaderKey.TYPE) final String type, - @Header(MessageHeaderKey.TENANT) final String tenant) { + public Message onMessage(final Message message, final String type, final String tenant, final String virtualHost) { checkContentTypeJson(message); final SecurityContext oldContext = SecurityContextHolder.getContext(); try { @@ -127,7 +135,7 @@ public class AmqpMessageHandlerService { switch (messageType) { case THING_CREATED: setTenantSecurityContext(tenant); - registerTarget(message); + registerTarget(message, virtualHost); break; case EVENT: setTenantSecurityContext(tenant); @@ -153,8 +161,8 @@ public class AmqpMessageHandlerService { final String sha1 = secruityToken.getSha1(); try { SecurityContextHolder.getContext().setAuthentication(authenticationManager.doAuthenticate(secruityToken)); - final LocalArtifact localArtifact = artifactManagement.findFirstLocalArtifactsBySHA1(secruityToken - .getSha1()); + final LocalArtifact localArtifact = artifactManagement + .findFirstLocalArtifactsBySHA1(secruityToken.getSha1()); if (localArtifact == null) { throw new EntityNotFoundException(); } @@ -177,9 +185,9 @@ public class AmqpMessageHandlerService { final String downloadId = UUID.randomUUID().toString(); final DownloadArtifactCache downloadCache = new DownloadArtifactCache(DownloadType.BY_SHA1, sha1); cache.put(downloadId, downloadCache); - authentificationResponse.setDownloadUrl(UriComponentsBuilder - .fromUri(hostnameResolver.resolveHostname().toURI()).path("/api/v1/downloadserver/downloadId/") - .path(downloadId).build().toUriString()); + authentificationResponse + .setDownloadUrl(UriComponentsBuilder.fromUri(hostnameResolver.resolveHostname().toURI()) + .path("/api/v1/downloadserver/downloadId/").path(downloadId).build().toUriString()); authentificationResponse.setResponseCode(HttpStatus.OK.value()); } catch (final BadCredentialsException | AuthenticationServiceException | CredentialsExpiredException e) { LOG.error("Login failed", e); @@ -196,7 +204,7 @@ public class AmqpMessageHandlerService { authentificationResponse.setMessage(errorMessage); } - return rabbitTemplate.getMessageConverter().toMessage(authentificationResponse, messageProperties); + return getMessageConverter().toMessage(authentificationResponse, messageProperties); } private static Artifact convertDbArtifact(final DbArtifact dbArtifact) { @@ -207,11 +215,6 @@ public class AmqpMessageHandlerService { return artifact; } - protected void logAndThrowMessageError(final Message message, final String error) { - LOG.error("Error \"{}\" reported by message {}", error, message.getMessageProperties().getMessageId()); - throw new IllegalArgumentException(error); - } - private static void setSecurityContext(final Authentication authentication) { final SecurityContextImpl securityContextImpl = new SecurityContextImpl(); securityContextImpl.setAuthentication(authentication); @@ -219,22 +222,13 @@ public class AmqpMessageHandlerService { } private static void setTenantSecurityContext(final String tenantId) { - final AnonymousAuthenticationToken authenticationToken = new AnonymousAuthenticationToken(UUID.randomUUID() - .toString(), "AMQP-Controller", Collections.singletonList(new SimpleGrantedAuthority( - SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS))); + final AnonymousAuthenticationToken authenticationToken = new AnonymousAuthenticationToken( + UUID.randomUUID().toString(), "AMQP-Controller", + Collections.singletonList(new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS))); authenticationToken.setDetails(new TenantAwareAuthenticationDetails(tenantId, true)); setSecurityContext(authenticationToken); } - private String getStringHeaderKey(final Message message, final String key, final String errorMessageIfNull) { - final Map header = message.getMessageProperties().getHeaders(); - final Object value = header.get(key); - if (value == null) { - logAndThrowMessageError(message, errorMessageIfNull); - } - return value.toString(); - } - /** * Method to create a new target or to find the target if it already exists. * @@ -243,14 +237,15 @@ public class AmqpMessageHandlerService { * @param ip * the ip of the target/thing */ - private void registerTarget(final Message message) { + private void registerTarget(final Message message, final String virtualHost) { final String thingId = getStringHeaderKey(message, MessageHeaderKey.THING_ID, "ThingId is null"); final String replyTo = message.getMessageProperties().getReplyTo(); if (StringUtils.isEmpty(replyTo)) { logAndThrowMessageError(message, "No ReplyTo was set for the createThing Event."); } - final URI amqpUri = IpUtil.createAmqpUri(replyTo); + + final URI amqpUri = IpUtil.createAmqpUri(virtualHost, replyTo); final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotexist(thingId, amqpUri); LOG.debug("Target {} reported online state.", thingId); @@ -267,8 +262,8 @@ public class AmqpMessageHandlerService { final DistributionSet distributionSet = action.getDistributionSet(); final List softwareModuleList = controllerManagement .findSoftwareModulesByDistributionSet(distributionSet); - eventBus.post(new TargetAssignDistributionSetEvent(target.getOptLockRevision(), target.getTenant(), target - .getControllerId(), action.getId(), softwareModuleList, target.getTargetInfo().getAddress())); + eventBus.post(new TargetAssignDistributionSetEvent(target.getOptLockRevision(), target.getTenant(), + target.getControllerId(), action.getId(), softwareModuleList, target.getTargetInfo().getAddress())); } @@ -281,13 +276,11 @@ public class AmqpMessageHandlerService { * the topic of the event. */ private void handleIncomingEvent(final Message message, final EventTopic topic) { - switch (topic) { - case UPDATE_ACTION_STATUS: + if (EventTopic.UPDATE_ACTION_STATUS.equals(topic)) { updateActionStatus(message); return; - default: - logAndThrowMessageError(message, "Got event without appropriate topic."); } + logAndThrowMessageError(message, "Got event without appropriate topic."); } /** @@ -336,28 +329,24 @@ public class AmqpMessageHandlerService { logAndThrowMessageError(message, "Status for action does not exisit."); } - Action addUpdateActionStatus; - - if (!actionStatus.getStatus().equals(Status.CANCELED)) { - addUpdateActionStatus = controllerManagement.addUpdateActionStatus(actionStatus, action); - } else { - addUpdateActionStatus = controllerManagement.addCancelActionStatus(actionStatus, action); - } + final Action addUpdateActionStatus = getUpdateActionStatus(action, actionStatus); if (!addUpdateActionStatus.isActive()) { lookIfUpdateAvailable(action.getTarget()); } } - /** - * @param message - * @param actionUpdateStatus - * @return - */ + private Action getUpdateActionStatus(final Action action, final ActionStatus actionStatus) { + if (actionStatus.getStatus().equals(Status.CANCELED)) { + return controllerManagement.addCancelActionStatus(actionStatus, action); + } + return controllerManagement.addUpdateActionStatus(actionStatus, action); + } + 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()); + LOG.debug("Target notifies intermediate about action {} with status {}.", actionId, + actionUpdateStatus.getActionStatus().name()); if (actionId == null) { logAndThrowMessageError(message, "Invalid message no action id"); @@ -366,8 +355,8 @@ public class AmqpMessageHandlerService { final Action action = controllerManagement.findActionWithDetails(actionId); if (action == null) { - logAndThrowMessageError(message, "Got intermediate notification about action " + actionId - + " but action does not exist"); + logAndThrowMessageError(message, + "Got intermediate notification about action " + actionId + " but action does not exist"); } return action; } @@ -381,38 +370,12 @@ public class AmqpMessageHandlerService { // back to running action status } else { - logAndThrowMessageError(message, "Cancel Recjected message is not allowed, if action is on state: " - + action.getStatus()); + logAndThrowMessageError(message, + "Cancel recjected message is not allowed, if action is on state: " + action.getStatus()); } } - /** - * Is needed to convert a incoming message to is originally object type. - * - * @param message - * the message to convert. - * @param clazz - * the class of the originally object. - * @return - */ - @SuppressWarnings("unchecked") - private T convertMessage(final Message message, final Class clazz) { - message.getMessageProperties().getHeaders() - .put(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME, clazz.getTypeName()); - return (T) rabbitTemplate.getMessageConverter().fromMessage(message); - } - - /** - * Is needed to verify if an incoming message has the content type json. - * - * @param message - * the to verify - * @param contentType - * the content type - * @return true if the content type has json, false it not. - */ - - private static void checkContentTypeJson(final Message message) { + private void checkContentTypeJson(final Message message) { final MessageProperties messageProperties = message.getMessageProperties(); if (messageProperties.getContentType() != null && messageProperties.getContentType().contains("json")) { return; @@ -428,14 +391,6 @@ public class AmqpMessageHandlerService { this.hostnameResolver = hostnameResolver; } - void setRabbitTemplate(final RabbitTemplate rabbitTemplate) { - this.rabbitTemplate = rabbitTemplate; - } - - MessageConverter getMessageConverter() { - return rabbitTemplate.getMessageConverter(); - } - void setAuthenticationManager(final AmqpControllerAuthentfication authenticationManager) { this.authenticationManager = authenticationManager; } diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpProperties.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpProperties.java index ecd2dc3d7..38c6d34b3 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpProperties.java +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpProperties.java @@ -15,16 +15,27 @@ import org.springframework.boot.context.properties.ConfigurationProperties; * Bean which holds the necessary properties for configuring the AMQP * connection. * - * - * - * */ @ConfigurationProperties("hawkbit.dmf.rabbitmq") public class AmqpProperties { - + /** + * DMF API dead letter queue. + */ private String deadLetterQueue = "dmf_connector_deadletter"; + + /** + * DMF API dead letter exchange. + */ private String deadLetterExchange = "dmf.connector.deadletter"; + + /** + * DMF API receiving queue. + */ private String receiverQueue = "dmf_receiver"; + + /** + * Missing queue fatal. + */ private boolean missingQueuesFatal = false; /** diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpSenderService.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpSenderService.java new file mode 100644 index 000000000..6cb3dd9be --- /dev/null +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpSenderService.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.amqp; + +import java.net.URI; + +import org.springframework.amqp.core.Message; + +/** + * Interface to send a amqp message. + */ +@FunctionalInterface +public interface AmqpSenderService { + + /** + * Send the given message to the given uri. The uri contains the (virtual) + * host and exchange e.g amqp://host/exchange. + * + * @param message + * the amqp message + * @param uri + * the reply to uri + */ + void sendMessage(Message message, URI uri); + + /** + * Extract the exchange from the uri. Default implementation removes the + * first /. + * + * @param amqpUri + * the amqp uri + * @return the exchange. + */ + default String extractExchange(final URI amqpUri) { + return amqpUri.getPath().substring(1); + } + +} diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/BaseAmqpService.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/BaseAmqpService.java new file mode 100644 index 000000000..8a054165b --- /dev/null +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/BaseAmqpService.java @@ -0,0 +1,115 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.amqp; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.amqp.support.converter.AbstractJavaTypeMapper; +import org.springframework.amqp.support.converter.MessageConverter; + +/** + * A base class which provide basis amqp staff. + */ +public class BaseAmqpService { + + private static final Logger LOGGER = LoggerFactory.getLogger(BaseAmqpService.class); + private final RabbitTemplate rabbitTemplate; + + /** + * Constructor. + * + * @param rabbitTemplate + * the rabbit template. + */ + public BaseAmqpService(final RabbitTemplate rabbitTemplate) { + this.rabbitTemplate = rabbitTemplate; + } + + /** + * Clean message properties before sending a message. + * + * @param message + * the message to cleaned up + */ + protected void cleanMessageHeaderProperties(final Message message) { + message.getMessageProperties().getHeaders().remove(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME); + } + + /** + * Is needed to convert a incoming message to is originally object type. + * + * @param message + * the message to convert. + * @param clazz + * the class of the originally object. + * @return the converted object + */ + @SuppressWarnings("unchecked") + public T convertMessage(final Message message, final Class clazz) { + if (message == null || message.getBody() == null) { + return null; + } + message.getMessageProperties().getHeaders().put(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME, + clazz.getName()); + return (T) rabbitTemplate.getMessageConverter().fromMessage(message); + } + + /** + * Is needed to convert a incoming message to is originally list object + * type. + * + * @param message + * the message to convert. + * @param clazz + * the class of the list content. + * @return the list of converted objects + */ + @SuppressWarnings("unchecked") + public List convertMessageList(final Message message, final Class clazz) { + if (message == null || message.getBody() == null) { + return Collections.emptyList(); + } + message.getMessageProperties().getHeaders().put(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME, + ArrayList.class.getName()); + message.getMessageProperties().getHeaders().put(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, + clazz.getName()); + return (List) rabbitTemplate.getMessageConverter().fromMessage(message); + } + + public MessageConverter getMessageConverter() { + return rabbitTemplate.getMessageConverter(); + } + + protected final String getStringHeaderKey(final Message message, final String key, + final String errorMessageIfNull) { + final Map header = message.getMessageProperties().getHeaders(); + final Object value = header.get(key); + if (value == null) { + logAndThrowMessageError(message, errorMessageIfNull); + return null; + } + return value.toString(); + } + + protected final void logAndThrowMessageError(final Message message, final String error) { + LOGGER.error("Error \"{}\" reported by message {}", error, message.getMessageProperties().getMessageId()); + throw new IllegalArgumentException(error); + } + + protected RabbitTemplate getRabbitTemplate() { + return rabbitTemplate; + } +} diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/DefaultAmqpSenderService.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/DefaultAmqpSenderService.java new file mode 100644 index 000000000..9586633bf --- /dev/null +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/DefaultAmqpSenderService.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.amqp; + +import java.net.URI; + +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.core.RabbitTemplate; + +/** + * A default implementation for the sender service. The service sends all amqp + * message to the configured spring rabbitmq connections. The exchange is + * extracted from the uri. + */ +public class DefaultAmqpSenderService implements AmqpSenderService { + + private final RabbitTemplate internalAmqpTemplate; + + /** + * Constructor. + * + * @param internalAmqpTemplate + * the amqp template + */ + public DefaultAmqpSenderService(final RabbitTemplate internalAmqpTemplate) { + this.internalAmqpTemplate = internalAmqpTemplate; + } + + @Override + public void sendMessage(final Message message, final URI uri) { + internalAmqpTemplate.send(extractExchange(uri), null, message); + } + +} diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/AmqpTestConfiguration.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/AmqpTestConfiguration.java new file mode 100644 index 000000000..a1dd54710 --- /dev/null +++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/AmqpTestConfiguration.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit; + +import org.eclipse.hawkbit.amqp.AmqpSenderService; +import org.eclipse.hawkbit.amqp.DefaultAmqpSenderService; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; +import org.springframework.amqp.support.converter.MessageConverter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * + */ +@Configuration +public class AmqpTestConfiguration { + + /** + * Method to set the Jackson2JsonMessageConverter. + * + * @return the Jackson2JsonMessageConverter + */ + @Bean + public MessageConverter jsonMessageConverter() { + return new Jackson2JsonMessageConverter(); + } + + /** + * Create default amqp sender service bean. + * + * @param rabbitTemplate + * + * @return the default amqp sender service bean + */ + @Bean + @Autowired + public AmqpSenderService amqpSenderServiceBean(final RabbitTemplate rabbitTemplate) { + return new DefaultAmqpSenderService(rabbitTemplate); + } +} diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthentficationTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java similarity index 90% rename from hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthentficationTest.java rename to hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java index 19ecc22ca..df96834aa 100644 --- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthentficationTest.java +++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java @@ -24,9 +24,9 @@ import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; import org.eclipse.hawkbit.repository.model.TenantConfigurationValue; +import org.eclipse.hawkbit.security.DdiSecurityProperties; +import org.eclipse.hawkbit.security.DdiSecurityProperties.Rp; import org.eclipse.hawkbit.security.SecurityContextTenantAware; -import org.eclipse.hawkbit.security.SecurityProperties; -import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; import org.junit.Before; import org.junit.Test; @@ -47,11 +47,11 @@ import ru.yandex.qatools.allure.annotations.Stories; /** * - * Test Amqp controller authentfication. + * Test Amqp controller authentication. */ -@Features("AMQP Authenfication Test") -@Stories("Tests the authenfication") -public class AmqpControllerAuthentficationTest { +@Features("Component Tests - Device Management Federation API") +@Stories("AmqpController Authentication Test") +public class AmqpControllerAuthenticationTest { private static final String TENANT = "DEFAULT"; private static String CONTROLLLER_ID = "123"; @@ -68,17 +68,20 @@ public class AmqpControllerAuthentficationTest { @Before public void before() throws Exception { - amqpMessageHandlerService = new AmqpMessageHandlerService(); messageConverter = new Jackson2JsonMessageConverter(); - final RabbitTemplate rabbitTemplate = new RabbitTemplate(); - rabbitTemplate.setMessageConverter(messageConverter); - amqpMessageHandlerService.setRabbitTemplate(rabbitTemplate); + final RabbitTemplate rabbitTemplate = mock(RabbitTemplate.class); + when(rabbitTemplate.getMessageConverter()).thenReturn(messageConverter); + amqpMessageHandlerService = new AmqpMessageHandlerService(rabbitTemplate); authenticationManager = new AmqpControllerAuthentfication(); authenticationManager.setControllerManagement(mock(ControllerManagement.class)); - final SecurityProperties secruityProperties = mock(SecurityProperties.class); - when(secruityProperties.getRpSslIssuerHashHeader()).thenReturn("X-Ssl-Issuer-Hash-%d"); + + final DdiSecurityProperties secruityProperties = mock(DdiSecurityProperties.class); + final Rp rp = mock(Rp.class); + when(secruityProperties.getRp()).thenReturn(rp); + when(rp.getSslIssuerHashHeader()).thenReturn("X-Ssl-Issuer-Hash-%d"); authenticationManager.setSecruityProperties(secruityProperties); + tenantConfigurationManagement = mock(TenantConfigurationManagement.class); authenticationManager.setTenantConfigurationManagement(tenantConfigurationManagement); @@ -88,13 +91,9 @@ public class AmqpControllerAuthentficationTest { final ControllerManagement controllerManagement = mock(ControllerManagement.class); when(controllerManagement.getSecurityTokenByControllerId(anyString())).thenReturn(CONTROLLLER_ID); authenticationManager.setControllerManagement(controllerManagement); - amqpMessageHandlerService.setArtifactManagement(mock(ArtifactManagement.class)); - final SecurityContextTenantAware tenantAware = new SecurityContextTenantAware(); - authenticationManager.setTenantAware(tenantAware); - final SystemSecurityContext systemSecurityContext = new SystemSecurityContext(tenantAware); - authenticationManager.setSystemSecurityContext(systemSecurityContext); + authenticationManager.setTenantAware(new SecurityContextTenantAware()); authenticationManager.postConstruct(); amqpMessageHandlerService.setAuthenticationManager(authenticationManager); } @@ -152,7 +151,7 @@ public class AmqpControllerAuthentficationTest { // test final Message onMessage = amqpMessageHandlerService.onMessage(message, MessageType.AUTHENTIFICATION.name(), - TENANT); + TENANT, "vHost"); // verify final DownloadResponse downloadResponse = (DownloadResponse) messageConverter.fromMessage(onMessage); @@ -174,7 +173,7 @@ public class AmqpControllerAuthentficationTest { // test final Message onMessage = amqpMessageHandlerService.onMessage(message, MessageType.AUTHENTIFICATION.name(), - TENANT); + TENANT, "vHost"); // verify final DownloadResponse downloadResponse = (DownloadResponse) messageConverter.fromMessage(onMessage); @@ -196,7 +195,7 @@ public class AmqpControllerAuthentficationTest { // test final Message onMessage = amqpMessageHandlerService.onMessage(message, MessageType.AUTHENTIFICATION.name(), - TENANT); + TENANT, "vHost"); // verify final DownloadResponse downloadResponse = (DownloadResponse) messageConverter.fromMessage(onMessage); diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java index 4d313dd2c..46ddd35cc 100644 --- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java +++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java @@ -19,6 +19,7 @@ import static org.mockito.Matchers.eq; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; +import java.net.URI; import java.util.ArrayList; import java.util.List; @@ -45,7 +46,6 @@ import org.springframework.amqp.core.MessageProperties; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.support.converter.AbstractJavaTypeMapper; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; -import org.springframework.amqp.support.converter.MessageConverter; import org.springframework.test.context.ActiveProfiles; import ru.yandex.qatools.allure.annotations.Description; @@ -53,43 +53,44 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; @ActiveProfiles({ "test" }) -@Features("AMQP Dispatcher Test") -@Stories("Tests send messages") +@Features("Component Tests - Device Management Federation API") +@Stories("AmqpMessage Dispatcher Service Test") public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWithMongoDB { private AmqpMessageDispatcherService amqpMessageDispatcherService; - private MessageConverter messageConverter; - private RabbitTemplate rabbitTemplate; + private DefaultAmqpSenderService senderService; + private static final String CONTROLLER_ID = "1"; @Override public void before() throws Exception { super.before(); - amqpMessageDispatcherService = new AmqpMessageDispatcherService(); + this.rabbitTemplate = Mockito.mock(RabbitTemplate.class); + when(rabbitTemplate.getMessageConverter()).thenReturn(new Jackson2JsonMessageConverter()); + amqpMessageDispatcherService = new AmqpMessageDispatcherService(rabbitTemplate); amqpMessageDispatcherService = spy(amqpMessageDispatcherService); - messageConverter = new Jackson2JsonMessageConverter(); + + senderService = Mockito.mock(DefaultAmqpSenderService.class); + amqpMessageDispatcherService.setAmqpSenderService(senderService); final ArtifactUrlHandler artifactUrlHandlerMock = Mockito.mock(ArtifactUrlHandler.class); when(artifactUrlHandlerMock.getUrl(anyString(), any(), anyObject())).thenReturn("http://mockurl"); - this.rabbitTemplate = Mockito.mock(RabbitTemplate.class); - when(rabbitTemplate.getMessageConverter()).thenReturn(messageConverter); - - amqpMessageDispatcherService.setRabbitTemplate(rabbitTemplate); - amqpMessageDispatcherService.setTenantAware(tenantAware); amqpMessageDispatcherService.setArtifactUrlHandler(artifactUrlHandlerMock); + } @Test @Description("Verfies that download and install event with no software modul works") public void testSendDownloadRequesWithEmptySoftwareModules() { final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent = new TargetAssignDistributionSetEvent( - 1L, "default", CONTROLLER_ID, 1l, new ArrayList(), IpUtil.createAmqpUri("mytest")); + 1L, "default", CONTROLLER_ID, 1l, new ArrayList(), + IpUtil.createAmqpUri("vHost", "mytest")); amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent); - final Message sendMessage = createArgumentCapture(targetAssignDistributionSetEvent.getTargetAdress().getHost()); + final Message sendMessage = createArgumentCapture(targetAssignDistributionSetEvent.getTargetAdress()); final DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage); assertTrue("No softwaremmodule should be contained in the request", downloadAndUpdateRequest.getSoftwareModules().isEmpty()); @@ -101,9 +102,9 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement, distributionSetManagement); final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent = new TargetAssignDistributionSetEvent( - 1L, "default", CONTROLLER_ID, 1l, dsA.getModules(), IpUtil.createAmqpUri("mytest")); + 1L, "default", CONTROLLER_ID, 1l, dsA.getModules(), IpUtil.createAmqpUri("vHost", "mytest")); amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent); - final Message sendMessage = createArgumentCapture(targetAssignDistributionSetEvent.getTargetAdress().getHost()); + final Message sendMessage = createArgumentCapture(targetAssignDistributionSetEvent.getTargetAdress()); final DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage); assertEquals("Expecting a size of 3 software modules in the reuqest", 3, downloadAndUpdateRequest.getSoftwareModules().size()); @@ -140,9 +141,9 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit Mockito.when(rabbitTemplate.convertSendAndReceive(any())).thenReturn(receivedList); final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent = new TargetAssignDistributionSetEvent( - 1L, "default", CONTROLLER_ID, 1l, dsA.getModules(), IpUtil.createAmqpUri("mytest")); + 1L, "default", CONTROLLER_ID, 1l, dsA.getModules(), IpUtil.createAmqpUri("vHost", "mytest")); amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent); - final Message sendMessage = createArgumentCapture(targetAssignDistributionSetEvent.getTargetAdress().getHost()); + final Message sendMessage = createArgumentCapture(targetAssignDistributionSetEvent.getTargetAdress()); final DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage); assertEquals("DownloadAndUpdateRequest event should contains 3 software modules", 3, downloadAndUpdateRequest.getSoftwareModules().size()); @@ -159,11 +160,10 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit @Description("Verfies that send cancel event works") public void testSendCancelRequest() { final CancelTargetAssignmentEvent cancelTargetAssignmentDistributionSetEvent = new CancelTargetAssignmentEvent( - 1L, "default", CONTROLLER_ID, 1l, IpUtil.createAmqpUri("mytest")); + 1L, "default", CONTROLLER_ID, 1l, IpUtil.createAmqpUri("vHost", "mytest")); amqpMessageDispatcherService .targetCancelAssignmentToDistributionSet(cancelTargetAssignmentDistributionSetEvent); - final Message sendMessage = createArgumentCapture( - cancelTargetAssignmentDistributionSetEvent.getTargetAdress().getHost()); + final Message sendMessage = createArgumentCapture(cancelTargetAssignmentDistributionSetEvent.getTargetAdress()); assertCancelMessage(sendMessage); } @@ -203,9 +203,9 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit MessageProperties.CONTENT_TYPE_JSON, sendMessage.getMessageProperties().getContentType()); } - protected Message createArgumentCapture(final String exchange) { + protected Message createArgumentCapture(final URI uri) { final ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Message.class); - Mockito.verify(amqpMessageDispatcherService).sendMessage(eq(exchange), argumentCaptor.capture()); + Mockito.verify(senderService).sendMessage(argumentCaptor.capture(), eq(uri)); return argumentCaptor.getValue(); } diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerServiceTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerServiceTest.java index 18f7b853f..9d6ae3ba7 100644 --- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerServiceTest.java +++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerServiceTest.java @@ -68,8 +68,8 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; @RunWith(MockitoJUnitRunner.class) -@Features("AMQP Controller Test") -@Stories("Tests the servcies for message handler and dispatcher") +@Features("Component Tests - Device Management Federation API") +@Stories("AmqpMessage Handler Service Test") public class AmqpMessageHandlerServiceTest { private static final String TENANT = "DEFAULT"; @@ -99,14 +99,15 @@ public class AmqpMessageHandlerServiceTest { @Mock private EventBus eventBus; + @Mock + private RabbitTemplate rabbitTemplate; + @Before public void before() throws Exception { - amqpMessageHandlerService = new AmqpMessageHandlerService(); - amqpMessageHandlerService.setControllerManagement(controllerManagementMock); messageConverter = new Jackson2JsonMessageConverter(); - final RabbitTemplate rabbitTemplate = new RabbitTemplate(); - rabbitTemplate.setMessageConverter(messageConverter); - amqpMessageHandlerService.setRabbitTemplate(rabbitTemplate); + when(rabbitTemplate.getMessageConverter()).thenReturn(messageConverter); + amqpMessageHandlerService = new AmqpMessageHandlerService(rabbitTemplate); + amqpMessageHandlerService.setControllerManagement(controllerManagementMock); amqpMessageHandlerService.setAuthenticationManager(authenticationManagerMock); amqpMessageHandlerService.setArtifactManagement(artifactManagementMock); amqpMessageHandlerService.setCache(cacheMock); @@ -115,14 +116,17 @@ public class AmqpMessageHandlerServiceTest { } - @Test(expected = IllegalArgumentException.class) + @Test @Description("Tests not allowed content-type in message") public void testWrongContentType() { final MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("xml"); final Message message = new Message(new byte[0], messageProperties); - amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT); - fail(); + try { + amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost"); + fail("IllegalArgumentException was excepeted due to worng content type"); + } catch (final IllegalArgumentException e) { + } } @Test @@ -138,10 +142,11 @@ public class AmqpMessageHandlerServiceTest { when(controllerManagementMock.findOrRegisterTargetIfItDoesNotexist(targetIdCaptor.capture(), uriCaptor.capture())).thenReturn(null); - amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT); + amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost"); - assertThat(targetIdCaptor.getValue()).as("Extraxted Thing should be the same").isEqualTo(knownThingId); - assertThat(uriCaptor.getValue().toString()).as("Extraxted Uri should be the same").isEqualTo("amqp://MyTest"); + // verify + assertThat(targetIdCaptor.getValue()).as("Thing id is wrong").isEqualTo(knownThingId); + assertThat(uriCaptor.getValue().toString()).as("Uri is not right").isEqualTo("amqp://vHost/MyTest"); } @@ -153,7 +158,7 @@ public class AmqpMessageHandlerServiceTest { final Message message = messageConverter.toMessage("", messageProperties); try { - amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT); + amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost"); fail("IllegalArgumentException was excepeted since no replyTo header was set"); } catch (final IllegalArgumentException exception) { // test ok - exception was excepted @@ -167,7 +172,7 @@ public class AmqpMessageHandlerServiceTest { final MessageProperties messageProperties = createMessageProperties(MessageType.THING_CREATED); final Message message = messageConverter.toMessage(new byte[0], messageProperties); try { - amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT); + amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost"); fail("IllegalArgumentException was excepeted since no thingID was set"); } catch (final IllegalArgumentException exception) { // test ok - exception was excepted @@ -183,7 +188,7 @@ public class AmqpMessageHandlerServiceTest { final Message message = messageConverter.toMessage(new byte[0], messageProperties); try { - amqpMessageHandlerService.onMessage(message, type, TENANT); + amqpMessageHandlerService.onMessage(message, type, TENANT, "vHost"); fail("IllegalArgumentException was excepeted due to unknown message type"); } catch (final IllegalArgumentException exception) { // test ok - exception was excepted @@ -196,21 +201,21 @@ public class AmqpMessageHandlerServiceTest { final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT); final Message message = new Message(new byte[0], messageProperties); try { - amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT); - fail(); + amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost"); + fail("IllegalArgumentException was excepeted due to unknown message type"); } catch (final IllegalArgumentException e) { } try { messageProperties.setHeader(MessageHeaderKey.TOPIC, "wrongTopic"); - amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT); - fail(); + amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost"); + fail("IllegalArgumentException was excepeted due to unknown topic"); } catch (final IllegalArgumentException e) { } messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.CANCEL_DOWNLOAD.name()); try { - amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT); + amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost"); fail("IllegalArgumentException was excepeted because there was no event topic"); } catch (final IllegalArgumentException exception) { // test ok - exception was excepted @@ -229,7 +234,7 @@ public class AmqpMessageHandlerServiceTest { messageProperties); try { - amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT); + amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost"); fail("IllegalArgumentException was excepeted since no action id was set"); } catch (final IllegalArgumentException exception) { // test ok - exception was excepted @@ -246,7 +251,7 @@ public class AmqpMessageHandlerServiceTest { messageProperties); try { - amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT); + amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost"); fail("IllegalArgumentException was excepeted since no action id was set"); } catch (final IllegalArgumentException exception) { // test ok - exception was excepted @@ -264,7 +269,7 @@ public class AmqpMessageHandlerServiceTest { // test final Message onMessage = amqpMessageHandlerService.onMessage(message, MessageType.AUTHENTIFICATION.name(), - TENANT); + TENANT, "vHost"); // verify final DownloadResponse downloadResponse = (DownloadResponse) messageConverter.fromMessage(onMessage); @@ -288,7 +293,7 @@ public class AmqpMessageHandlerServiceTest { // test final Message onMessage = amqpMessageHandlerService.onMessage(message, MessageType.AUTHENTIFICATION.name(), - TENANT); + TENANT, "vHost"); // verify final DownloadResponse downloadResponse = (DownloadResponse) messageConverter.fromMessage(onMessage); @@ -320,7 +325,7 @@ public class AmqpMessageHandlerServiceTest { // test final Message onMessage = amqpMessageHandlerService.onMessage(message, MessageType.AUTHENTIFICATION.name(), - TENANT); + TENANT, "vHost"); // verify final DownloadResponse downloadResponse = (DownloadResponse) messageConverter.fromMessage(onMessage); @@ -328,7 +333,8 @@ public class AmqpMessageHandlerServiceTest { assertThat(downloadResponse.getResponseCode()).as("Message body response code is wrong") .isEqualTo(HttpStatus.OK.value()); assertThat(downloadResponse.getArtifact().getSize()).as("Wrong artifact size in message body").isEqualTo(1L); - assertThat(downloadResponse.getDownloadUrl()).startsWith("http://localhost/api/v1/downloadserver/downloadId/"); + assertThat(downloadResponse.getDownloadUrl()).as("download url is wrong") + .startsWith("http://localhost/api/v1/downloadserver/downloadId/"); } @Test @@ -355,7 +361,7 @@ public class AmqpMessageHandlerServiceTest { messageProperties); // test - amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT); + amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost"); // verify final ArgumentCaptor captorTargetAssignDistributionSetEvent = ArgumentCaptor diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/BaseAmqpServiceTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/BaseAmqpServiceTest.java new file mode 100644 index 000000000..0bd8c164b --- /dev/null +++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/BaseAmqpServiceTest.java @@ -0,0 +1,103 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.amqp; + +import static org.fest.assertions.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.hawkbit.dmf.json.model.ActionUpdateStatus; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.core.MessageProperties; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; + +import ru.yandex.qatools.allure.annotations.Description; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@RunWith(MockitoJUnitRunner.class) +@Features("Component Tests - Device Management Federation API") +@Stories("Base Amqp Service Test") +public class BaseAmqpServiceTest { + + @Mock + private RabbitTemplate rabbitTemplate; + + private BaseAmqpService baseAmqpService; + + @Before + public void setup() { + when(rabbitTemplate.getMessageConverter()).thenReturn(new Jackson2JsonMessageConverter()); + baseAmqpService = new BaseAmqpService(rabbitTemplate); + + } + + @Test + @Description("Verify that the message conversion works") + public void convertMessageTest() { + final ActionUpdateStatus actionUpdateStatus = new ActionUpdateStatus(); + actionUpdateStatus.setActionId(1L); + actionUpdateStatus.setSoftwareModuleId(2L); + + final Message message = rabbitTemplate.getMessageConverter().toMessage(actionUpdateStatus, + new MessageProperties()); + ActionUpdateStatus convertedActionUpdateStatus = baseAmqpService.convertMessage(message, + ActionUpdateStatus.class); + + assertThat(convertedActionUpdateStatus).as("Converted Action Status is wrong") + .isEqualsToByComparingFields(actionUpdateStatus); + + convertedActionUpdateStatus = baseAmqpService.convertMessage(null, ActionUpdateStatus.class); + assertThat(convertedActionUpdateStatus).as("Converted Object should be null when message is null").isNull(); + + convertedActionUpdateStatus = baseAmqpService.convertMessage(new Message(null, new MessageProperties()), + ActionUpdateStatus.class); + assertThat(convertedActionUpdateStatus).as("Converted Object should be null when message body is null") + .isNull(); + } + + @Test + @Description("Verify that a conversion of a list from a message works") + public void convertMessageListTest() { + final List actionUpdateStatusList = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + final ActionUpdateStatus actionUpdateStatus = new ActionUpdateStatus(); + actionUpdateStatus.setActionId(Long.valueOf(i)); + actionUpdateStatus.setSoftwareModuleId(Long.valueOf(i)); + actionUpdateStatusList.add(actionUpdateStatus); + } + + final Message message = rabbitTemplate.getMessageConverter().toMessage(actionUpdateStatusList, + new MessageProperties()); + List convertedActionUpdateStatus = baseAmqpService.convertMessageList(message, + ActionUpdateStatus.class); + + assertThat(convertedActionUpdateStatus).as("Converted Action Status list is wrong") + .hasSameClassAs(actionUpdateStatusList); + assertThat(convertedActionUpdateStatus).as("Converted Action Status list is wrong") + .hasSameSizeAs(actionUpdateStatusList); + + convertedActionUpdateStatus = baseAmqpService.convertMessageList(null, ActionUpdateStatus.class); + assertThat(convertedActionUpdateStatus).as("Converted list should be empty when message is null").isEmpty(); + + convertedActionUpdateStatus = baseAmqpService.convertMessageList(new Message(null, new MessageProperties()), + ActionUpdateStatus.class); + assertThat(convertedActionUpdateStatus).as("Converted list should be empty when message body is null") + .isEmpty(); + } + +} diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/util/PropertyBasedArtifactUrlHandlerTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/util/PropertyBasedArtifactUrlHandlerTest.java index fcafb23e4..e7ba06d19 100644 --- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/util/PropertyBasedArtifactUrlHandlerTest.java +++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/util/PropertyBasedArtifactUrlHandlerTest.java @@ -11,6 +11,9 @@ package org.eclipse.hawkbit.util; import static org.junit.Assert.assertEquals; import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB; +import org.eclipse.hawkbit.AmqpTestConfiguration; +import org.eclipse.hawkbit.RepositoryApplicationConfiguration; +import org.eclipse.hawkbit.TestConfiguration; import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.dmf.json.model.Artifact; import org.eclipse.hawkbit.repository.model.DistributionSet; @@ -20,6 +23,7 @@ import org.eclipse.hawkbit.tenancy.TenantAware; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.SpringApplicationConfiguration; import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; @@ -31,6 +35,8 @@ import ru.yandex.qatools.allure.annotations.Stories; */ @Features("Component Tests - Artifact URL Handler") @Stories("Test to generate the artifact download URL") +@SpringApplicationConfiguration(classes = { RepositoryApplicationConfiguration.class, TestConfiguration.class, + AmqpTestConfiguration.class }) public class PropertyBasedArtifactUrlHandlerTest extends AbstractIntegrationTestWithMongoDB { @Autowired @@ -50,29 +56,33 @@ public class PropertyBasedArtifactUrlHandlerTest extends AbstractIntegrationTest } @Test - @Description("Tests generate the http download url") + @Description("Tests the generation of http download url.") public void testHttpUrl() { final String url = urlHandlerProperties.getUrl(controllerId, localArtifact, Artifact.UrlProtocol.HTTP); - assertEquals("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/" + controllerId - + "/softwaremodules/" + localArtifact.getSoftwareModule().getId() + "/artifacts/" - + localArtifact.getFilename(), url); + assertEquals("http is build incorrect", + "http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/" + controllerId + + "/softwaremodules/" + localArtifact.getSoftwareModule().getId() + "/artifacts/" + + localArtifact.getFilename(), + url); } @Test - @Description("Tests generate the https download url") + @Description("Tests the generation of https download url.") public void testHttpsUrl() { final String url = urlHandlerProperties.getUrl(controllerId, localArtifact, Artifact.UrlProtocol.HTTPS); - assertEquals("https://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/" + controllerId - + "/softwaremodules/" + localArtifact.getSoftwareModule().getId() + "/artifacts/" - + localArtifact.getFilename(), url); + assertEquals("https is build incorrect", + "https://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/" + controllerId + + "/softwaremodules/" + localArtifact.getSoftwareModule().getId() + "/artifacts/" + + localArtifact.getFilename(), + url); } @Test - @Description("Tests generate the coap download url") + @Description("Tests the generation of coap download url.") public void testCoapUrl() { final String url = urlHandlerProperties.getUrl(controllerId, localArtifact, Artifact.UrlProtocol.COAP); - assertEquals("coap://127.0.0.1:5683/fw/" + tenantAware.getCurrentTenant() + "/" + controllerId + "/sha1/" - + localArtifact.getSha1Hash(), url); + assertEquals("coap is build incorrect", "coap://127.0.0.1:5683/fw/" + tenantAware.getCurrentTenant() + "/" + + controllerId + "/sha1/" + localArtifact.getSha1Hash(), url); } } diff --git a/hawkbit-http-security/src/test/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProviderTest.java b/hawkbit-http-security/src/test/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProviderTest.java index f2ffe5c4c..fb961f9b2 100644 --- a/hawkbit-http-security/src/test/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProviderTest.java +++ b/hawkbit-http-security/src/test/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProviderTest.java @@ -20,7 +20,13 @@ import org.springframework.security.authentication.InsufficientAuthenticationExc import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@Features("Unit Tests - Security") +@Stories("PreAuthToken Source TrustAuthentication Provider Test") @RunWith(MockitoJUnitRunner.class) +// TODO: create description annotations public class PreAuthTokenSourceTrustAuthenticationProviderTest { private static final String REQUEST_SOURCE_IP = "127.0.0.1"; diff --git a/hawkbit-repository/pom.xml b/hawkbit-repository/pom.xml index 62d234ddb..7259262de 100644 --- a/hawkbit-repository/pom.xml +++ b/hawkbit-repository/pom.xml @@ -99,6 +99,11 @@ org.flywaydb flyway-core + + org.springframework.boot + spring-boot-configuration-processor + true + @@ -215,7 +220,7 @@ com.ethlo.persistence.tools eclipselink-maven-plugin - 1.1-SNAPSHOT + 2.6.2 process-classes diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/MultiTenantJpaTransactionManager.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/MultiTenantJpaTransactionManager.java index 2ddbfe870..e19f08b4e 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/MultiTenantJpaTransactionManager.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/MultiTenantJpaTransactionManager.java @@ -48,7 +48,9 @@ public class MultiTenantJpaTransactionManager extends JpaTransactionManager { && !definition.getName().startsWith(SystemManagement.class.getCanonicalName() + ".deleteTenant") && !definition.getName() .startsWith(SystemManagement.class.getCanonicalName() + ".currentTenantKeyGenerator") - && !definition.getName().startsWith(RolloutManagement.class.getCanonicalName() + ".rolloutScheduler")) { + && !definition.getName().startsWith(RolloutManagement.class.getCanonicalName() + ".rolloutScheduler") + && !definition.getName() + .startsWith(SystemManagement.class.getCanonicalName() + ".getOrCreateTenantMetadata")) { final String currentTenant = tenantAware.getCurrentTenant(); if (currentTenant == null) { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java index 16f2bb8ee..bf805f3dd 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java @@ -38,10 +38,6 @@ import org.springframework.validation.beanvalidation.MethodValidationPostProcess /** * General configuration for the SP Repository. * - * - * - * - * */ @EnableJpaRepositories(basePackages = { "org.eclipse.hawkbit.repository" }) @EnableTransactionManagement diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/RolloutProperties.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/RolloutProperties.java new file mode 100644 index 000000000..63e116f47 --- /dev/null +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/RolloutProperties.java @@ -0,0 +1,50 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * Rollout Management properties. + * + */ +@Component +@ConfigurationProperties("hawkbit.rollout") +public class RolloutProperties { + private final Scheduler scheduler = new Scheduler(); + + public Scheduler getScheduler() { + return scheduler; + } + + /** + * Rollout scheduler configuration. + */ + public static class Scheduler { + // used by @Scheduled annotation which needs constant + public static final String PROP_SCHEDULER_DELAY_PLACEHOLDER = "${hawkbit.rollout.scheduler.fixedDelay:30000}"; + + /** + * Schedule where the rollout scheduler looks necessary state changes in + * milliseconds. + */ + private long fixedDelay = 30000L; + + public long getFixedDelay() { + return fixedDelay; + } + + public void setFixedDelay(final long fixedDelay) { + this.fixedDelay = fixedDelay; + } + + } + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionStatusRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionStatusRepository.java index 5e2800755..2705b9ac6 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionStatusRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionStatusRepository.java @@ -21,45 +21,47 @@ import org.springframework.transaction.annotation.Transactional; /** * {@link ActionStatus} repository. * - * - * - * */ @Transactional(readOnly = true) public interface ActionStatusRepository extends BaseEntityRepository, JpaSpecificationExecutor { /** - * @param target + * Counts {@link ActionStatus} entries of given {@link Action} in + * repository. + * * @param action - * @return + * to count status entries + * @return number of actions in repository */ Long countByAction(Action action); /** + * Counts {@link ActionStatus} entries of given {@link Action} with given + * {@link Status} in repository. + * * @param action - * @param retrieved - * @return + * to count status entries + * @param status + * to filter for + * @return number of actions in repository */ - Long countByActionAndStatus(Action action, Status retrieved); + Long countByActionAndStatus(Action action, Status status); /** + * Retrieves all {@link ActionStatus} entries from repository of given + * {@link Action}. + * * @param pageReq + * parameters * @param action - * @return + * of the status entries + * @return pages list of {@link ActionStatus} entries */ Page findByAction(Pageable pageReq, Action action); /** - * @param pageReq - * @param action - * @return - */ - Page findByActionOrderByIdDesc(Pageable pageReq, Action action); - - /** - * Finds all status updates for the defined action and target order by - * {@link ActionStatus#getId()} desc including + * Finds all status updates for the defined action and target including * {@link ActionStatus#getMessages()}. * * @param pageReq @@ -71,6 +73,6 @@ public interface ActionStatusRepository * @return Page with found targets */ @EntityGraph(value = "ActionStatus.withMessages", type = EntityGraphType.LOAD) - Page getByActionOrderByIdDesc(Pageable pageReq, Action action); + Page getByAction(Pageable pageReq, Action action); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java index e4a1e5e6b..b6fbb6010 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java @@ -33,13 +33,11 @@ import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetInfo; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.Target_; +import org.eclipse.hawkbit.security.HawkbitSecurityProperties; import org.hibernate.validator.constraints.NotEmpty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.bind.RelaxedPropertyResolver; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.env.Environment; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Modifying; import org.springframework.security.access.prepost.PreAuthorize; @@ -57,7 +55,7 @@ import org.springframework.validation.annotation.Validated; @Transactional(readOnly = true) @Validated @Service -public class ControllerManagement implements EnvironmentAware { +public class ControllerManagement { private static final Logger LOG = LoggerFactory.getLogger(ControllerManagement.class); private static final Logger LOG_DOS = LoggerFactory.getLogger("server-security.dos"); @@ -85,9 +83,8 @@ public class ControllerManagement implements EnvironmentAware { @Autowired private ActionStatusRepository actionStatusRepository; - private Integer maxCount = 1000; - - private Integer maxAttributes = 100; + @Autowired + private HawkbitSecurityProperties securityProperties; /** * Refreshes the time of the last time the controller has been connected to @@ -379,15 +376,16 @@ public class ControllerManagement implements EnvironmentAware { } private void checkForToManyStatusEntries(final Action action) { - if (maxCount > 0) { + if (securityProperties.getDos().getMaxStatusEntriesPerAction() > 0) { final Long statusCount = actionStatusRepository.countByAction(action); - if (statusCount >= maxCount) { + if (statusCount >= securityProperties.getDos().getMaxStatusEntriesPerAction()) { LOG_DOS.error( "Potential denial of service (DOS) attack identfied. More status entries in the system than permitted ({})!", - maxCount); - throw new ToManyStatusEntriesException(String.valueOf(maxCount)); + securityProperties.getDos().getMaxStatusEntriesPerAction()); + throw new ToManyStatusEntriesException( + String.valueOf(securityProperties.getDos().getMaxStatusEntriesPerAction())); } } } @@ -436,10 +434,12 @@ public class ControllerManagement implements EnvironmentAware { target.getTargetInfo().getControllerAttributes().putAll(data); - if (target.getTargetInfo().getControllerAttributes().size() > maxAttributes) { + if (target.getTargetInfo().getControllerAttributes().size() > securityProperties.getDos() + .getMaxAttributeEntriesPerTarget()) { LOG_DOS.info("Target tries to insert more than the allowed number of entries ({}). DOS attack anticipated!", - maxAttributes); - throw new ToManyAttributeEntriesException(String.valueOf(maxAttributes)); + securityProperties.getDos().getMaxAttributeEntriesPerTarget()); + throw new ToManyAttributeEntriesException( + String.valueOf(securityProperties.getDos().getMaxAttributeEntriesPerTarget())); } target.getTargetInfo().setLastTargetQuery(System.currentTimeMillis()); @@ -447,19 +447,6 @@ public class ControllerManagement implements EnvironmentAware { return targetRepository.save(target); } - /* - * (non-Javadoc) - * - * @see org.springframework.context.EnvironmentAware#setEnvironment(org. - * springframework.core.env. Environment) - */ - @Override - public void setEnvironment(final Environment environment) { - final RelaxedPropertyResolver env = new RelaxedPropertyResolver(environment, "hawkbit.server."); - maxCount = env.getProperty("security.dos.maxStatusEntriesPerAction", Integer.class, 1000); - maxAttributes = env.getProperty("security.dos.maxAttributeEntriesPerTarget", Integer.class, 100); - } - /** * Registers retrieved status for given {@link Target} and {@link Action} if * it does not exist yet. diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java index 236816192..e1976c9a6 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java @@ -365,7 +365,7 @@ public class DeploymentManagement { }).collect(Collectors.toList())).stream() .collect(Collectors.toMap(a -> a.getTarget().getControllerId(), Function.identity())); - // MECS-720 create initial action status when action is created so we + // create initial action status when action is created so we // remember the initial // running status because we will change the status of the action itself // and with this action @@ -925,7 +925,7 @@ public class DeploymentManagement { /** * retrieves all the {@link ActionStatus} entries of the given - * {@link Action} and {@link Target} in the order latest first. + * {@link Action} and {@link Target}. * * @param pageReq * pagination parameter @@ -937,12 +937,12 @@ public class DeploymentManagement { * @return the corresponding {@link Page} of {@link ActionStatus} */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Page findActionStatusMessagesByActionInDescOrder(final Pageable pageReq, final Action action, + public Page findActionStatusByAction(final Pageable pageReq, final Action action, final boolean withMessages) { if (withMessages) { - return actionStatusRepository.getByActionOrderByIdDesc(pageReq, action); + return actionStatusRepository.getByAction(pageReq, action); } else { - return actionStatusRepository.findByActionOrderByIdDesc(pageReq, action); + return actionStatusRepository.findByAction(pageReq, action); } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java index d22a77f75..8b07c9bf8 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java @@ -294,8 +294,7 @@ public class DistributionSetManagement { // hard delete the rest if exixts if (!toHardDelete.isEmpty()) { // don't give the delete statement an empty list, JPA/Oracle cannot - // handle the empty list, - // see MECS-403 + // handle the empty list distributionSetRepository.deleteByIdIn(toHardDelete); } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java index 8f87f9209..eab926b4b 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java @@ -46,7 +46,6 @@ import org.eclipse.hawkbit.repository.model.Target_; import org.eclipse.hawkbit.tenancy.TenantAware; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -55,14 +54,10 @@ import org.springframework.validation.annotation.Validated; /** * Service layer for generating SP reportings. * - * - * - * */ @Transactional(readOnly = true) @Validated @Service -@ConfigurationProperties public class ReportManagement { @Value("${spring.jpa.database}") diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutScheduler.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutScheduler.java index b60d64cc5..24b7c2627 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutScheduler.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutScheduler.java @@ -10,14 +10,13 @@ package org.eclipse.hawkbit.repository; import java.util.List; +import org.eclipse.hawkbit.RolloutProperties; import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.tenancy.TenantAware; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Profile; -import org.springframework.core.env.Environment; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @@ -31,15 +30,10 @@ import org.springframework.stereotype.Component; // don't active the rollout scheduler in test, otherwise it is hard to test // rolloutmanagement and leads weird side-effects maybe. @Profile("!test") -public class RolloutScheduler implements EnvironmentAware { +public class RolloutScheduler { private static final Logger logger = LoggerFactory.getLogger(RolloutScheduler.class); - private static final String PROP_SCHEDULER_DELAY = "hawkbit.rollout.scheduler.fixedDelay"; - private static final long DEFAULT_SCHEDULER_DELAY = 30000L; - private static final String PROP_SCHEDULER_DELAY_PLACEHOLDER = "${" + PROP_SCHEDULER_DELAY + ":" - + DEFAULT_SCHEDULER_DELAY + "}"; - @Autowired private TenantAware tenantAware; @@ -52,7 +46,8 @@ public class RolloutScheduler implements EnvironmentAware { @Autowired private SystemSecurityContext systemSecurityContext; - private long fixedDelay = DEFAULT_SCHEDULER_DELAY; + @Autowired + private RolloutProperties rolloutProperties; /** * Scheduler method called by the spring-async mechanism. Retrieves all @@ -60,7 +55,7 @@ public class RolloutScheduler implements EnvironmentAware { * tenant the {@link RolloutManagement#checkRunningRollouts(long)} in the * {@link SystemSecurityContext}. */ - @Scheduled(initialDelayString = PROP_SCHEDULER_DELAY_PLACEHOLDER, fixedDelayString = PROP_SCHEDULER_DELAY_PLACEHOLDER) + @Scheduled(initialDelayString = RolloutProperties.Scheduler.PROP_SCHEDULER_DELAY_PLACEHOLDER, fixedDelayString = RolloutProperties.Scheduler.PROP_SCHEDULER_DELAY_PLACEHOLDER) public void rolloutScheduler() { logger.debug("rollout schedule checker has been triggered."); // run this code in system code privileged to have the necessary @@ -76,16 +71,11 @@ public class RolloutScheduler implements EnvironmentAware { logger.info("Checking rollouts for {} tenants", tenants.size()); for (final String tenant : tenants) { tenantAware.runAsTenant(tenant, () -> { - rolloutManagement.checkRunningRollouts(fixedDelay); + rolloutManagement.checkRunningRollouts(rolloutProperties.getScheduler().getFixedDelay()); return null; }); } return null; }); } - - @Override - public void setEnvironment(final Environment environment) { - fixedDelay = environment.getProperty(PROP_SCHEDULER_DELAY, Long.class, DEFAULT_SCHEDULER_DELAY); - } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java index 9c00acc7c..77b48a3cd 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java @@ -269,7 +269,7 @@ public class SystemManagement { * @return {@code true} in case the tenant exits or {@code false} if not */ @Cacheable(value = "currentTenant", keyGenerator = "currentTenantKeyGenerator") - // MECS-903 set transaction to not supported, due we call this in + // set transaction to not supported, due we call this in // BaseEntity#prePersist methods // and it seems that JPA committing the transaction when executing this // transactional method, diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java index 945e71c75..706cb4479 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java @@ -17,8 +17,8 @@ import org.eclipse.hawkbit.cache.TenantAwareCacheManager; import org.eclipse.hawkbit.repository.model.helper.EventBusHolder; import org.eclipse.hawkbit.repository.utils.RepositoryDataGenerator; import org.eclipse.hawkbit.repository.utils.RepositoryDataGenerator.DatabaseCleanupUtil; +import org.eclipse.hawkbit.security.DdiSecurityProperties; import org.eclipse.hawkbit.security.SecurityContextTenantAware; -import org.eclipse.hawkbit.security.SecurityProperties; import org.eclipse.hawkbit.security.SpringSecurityAuditorAware; import org.eclipse.hawkbit.tenancy.TenantAware; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; @@ -47,7 +47,7 @@ import com.mongodb.MongoClientOptions; */ @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true, mode = AdviceMode.ASPECTJ, proxyTargetClass = true, securedEnabled = true) -@EnableConfigurationProperties({ SecurityProperties.class, ControllerPollProperties.class }) +@EnableConfigurationProperties({ DdiSecurityProperties.class, ControllerPollProperties.class }) @Profile("test") public class TestConfiguration implements AsyncConfigurer { diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheKeysTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheKeysTest.java index 6c9314d07..b0da78abd 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheKeysTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheKeysTest.java @@ -12,6 +12,11 @@ import static org.fest.assertions.api.Assertions.assertThat; import org.junit.Test; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@Features("Unit Tests - Repository") +@Stories("CacheKeys") public class CacheKeysTest { @Test diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheWriteNotifyTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheWriteNotifyTest.java index 3b69b4fed..c88a3e717 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheWriteNotifyTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheWriteNotifyTest.java @@ -26,6 +26,11 @@ import org.springframework.cache.CacheManager; import com.google.common.eventbus.EventBus; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@Features("Unit Tests - Repository") +@Stories("CacheWriteNotify") @RunWith(MockitoJUnitRunner.class) public class CacheWriteNotifyTest { diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/eventbus/CacheFieldEntityListenerTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/eventbus/CacheFieldEntityListenerTest.java index e80c49b2d..4943ea88a 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/eventbus/CacheFieldEntityListenerTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/eventbus/CacheFieldEntityListenerTest.java @@ -27,6 +27,11 @@ import org.springframework.cache.CacheManager; import org.springframework.cache.support.SimpleValueWrapper; import org.springframework.hateoas.Identifiable; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@Features("Unit Tests - Repository") +@Stories("EventBus") @RunWith(MockitoJUnitRunner.class) public class CacheFieldEntityListenerTest { diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ActionTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ActionTest.java index 0ce7dd677..9bd532b5e 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ActionTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ActionTest.java @@ -14,10 +14,16 @@ import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.ActionType; import org.junit.Test; +import ru.yandex.qatools.allure.annotations.Description; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@Features("Unit Tests - Repository") +@Stories("Deployment Management") public class ActionTest { - // issue MECS-670 timeforced update and eTAG calculation @Test + @Description("Ensures that timeforced moded switch from soft to forces after defined timeframe.") public void timeforcedHitNewHasCodeIsGenerated() throws InterruptedException { final boolean active = true; diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementNoMongoDbTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementNoMongoDbTest.java index e509a3b0c..dd1e171ca 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementNoMongoDbTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementNoMongoDbTest.java @@ -25,9 +25,6 @@ import ru.yandex.qatools.allure.annotations.Stories; /** * Addition tests next to {@link ArtifactManagementTest} with no running MongoDB * - * - * - * */ @Features("Component Tests - Repository") @Stories("Artifact Management") diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ControllerManagementTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ControllerManagementTest.java index 41a7c7848..a3913da2b 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ControllerManagementTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ControllerManagementTest.java @@ -70,8 +70,8 @@ public class ControllerManagementTest extends AbstractIntegrationTest { .isEqualTo(TargetUpdateStatus.IN_SYNC); assertThat(actionStatusRepository.findAll(pageReq).getNumberOfElements()).isEqualTo(3); - assertThat(deploymentManagement.findActionStatusMessagesByActionInDescOrder(pageReq, savedAction, false) - .getNumberOfElements()).isEqualTo(3); + assertThat(deploymentManagement.findActionStatusByAction(pageReq, savedAction, false).getNumberOfElements()) + .isEqualTo(3); } @Test diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DeploymentManagementTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DeploymentManagementTest.java index 985bc6bd9..9530a61c3 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DeploymentManagementTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DeploymentManagementTest.java @@ -50,7 +50,6 @@ import com.google.common.eventbus.Subscribe; import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; -import ru.yandex.qatools.allure.annotations.Issue; import ru.yandex.qatools.allure.annotations.Stories; /** @@ -145,7 +144,6 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { @Test @Description("Test verifies that an assignment with automatic cancelation works correctly even if the update is split into multiple partitions on the database.") - @Issue("MECS-674") public void multiAssigmentHistoryOverMultiplePagesResultsInTwoActiveAction() { final DistributionSet cancelDs = TestDataUtil.generateDistributionSet("Canceled DS", "1.0", softwareManagement, @@ -766,12 +764,13 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { distributionSetManagement.findDistributionSetByIdWithDetails(dsA.getId()).getOptLockRevision()); // verifying that the assignment is correct - assertEquals(1, deploymentManagement.findActiveActionsByTarget(targ).size()); - assertEquals(1, deploymentManagement.findActionsByTarget(targ).size()); - assertEquals(TargetUpdateStatus.PENDING, targ.getTargetInfo().getUpdateStatus()); - assertEquals(dsA, targ.getAssignedDistributionSet()); - assertEquals(dsA, deploymentManagement.findActiveActionsByTarget(targ).get(0).getDistributionSet()); - assertNull(targ.getTargetInfo().getInstalledDistributionSet()); + assertEquals("Active target actions are wrong", 1, deploymentManagement.findActiveActionsByTarget(targ).size()); + assertEquals("Target actions are wrong", 1, deploymentManagement.findActionsByTarget(targ).size()); + assertEquals("Target status is wrong", TargetUpdateStatus.PENDING, targ.getTargetInfo().getUpdateStatus()); + assertEquals("Assigned ds is wrong", dsA, targ.getAssignedDistributionSet()); + assertEquals("Active ds is wrong", dsA, + deploymentManagement.findActiveActionsByTarget(targ).get(0).getDistributionSet()); + assertNull("Installed ds should be null", targ.getTargetInfo().getInstalledDistributionSet()); final Page updAct = actionRepository.findByDistributionSet(pageReq, dsA); final Action action = updAct.getContent().get(0); @@ -781,29 +780,28 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { targ = targetManagement.findTargetByControllerID(targ.getControllerId()); - assertEquals(0, deploymentManagement.findActiveActionsByTarget(targ).size()); - // try { - assertEquals(1, deploymentManagement.findInActiveActionsByTarget(targ).size()); - // } - // catch( final LazyInitializationException ex ) { - // - // } - assertEquals(TargetUpdateStatus.IN_SYNC, targ.getTargetInfo().getUpdateStatus()); - assertEquals(dsA, targ.getAssignedDistributionSet()); - assertEquals(dsA, targ.getTargetInfo().getInstalledDistributionSet()); + assertEquals("active target actions are wrong", 0, deploymentManagement.findActiveActionsByTarget(targ).size()); + assertEquals("active actions are wrong", 1, deploymentManagement.findInActiveActionsByTarget(targ).size()); + + assertEquals("tagret update status is not correct", TargetUpdateStatus.IN_SYNC, + targ.getTargetInfo().getUpdateStatus()); + assertEquals("wrong assigned ds", dsA, targ.getAssignedDistributionSet()); + assertEquals("wrong installed ds", dsA, targ.getTargetInfo().getInstalledDistributionSet()); targs = deploymentManagement.assignDistributionSet(dsB.getId(), new String[] { "target-id-A" }) .getAssignedTargets(); targ = targs.iterator().next(); - assertEquals(1, deploymentManagement.findActiveActionsByTarget(targ).size()); - assertEquals(TargetUpdateStatus.PENDING, + assertEquals("active actions are wrong", 1, deploymentManagement.findActiveActionsByTarget(targ).size()); + assertEquals("target status is wrong", TargetUpdateStatus.PENDING, targetManagement.findTargetByControllerID(targ.getControllerId()).getTargetInfo().getUpdateStatus()); - assertEquals(dsB, targ.getAssignedDistributionSet()); - assertEquals(dsA.getId(), targetManagement.findTargetByControllerIDWithDetails(targ.getControllerId()) - .getTargetInfo().getInstalledDistributionSet().getId()); - assertEquals(dsB, deploymentManagement.findActiveActionsByTarget(targ).get(0).getDistributionSet()); + assertEquals("wrong assigned ds", dsB, targ.getAssignedDistributionSet()); + assertEquals("Installed ds is wrong", dsA.getId(), + targetManagement.findTargetByControllerIDWithDetails(targ.getControllerId()).getTargetInfo() + .getInstalledDistributionSet().getId()); + assertEquals("Active ds is wrong", dsB, + deploymentManagement.findActiveActionsByTarget(targ).get(0).getDistributionSet()); } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TagManagementTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TagManagementTest.java index 9c1a9b66e..eb263b242 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TagManagementTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TagManagementTest.java @@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import java.util.List; @@ -22,6 +23,7 @@ import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.Tag; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetTag; +import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; @@ -34,18 +36,19 @@ import ru.yandex.qatools.allure.annotations.Stories; /** * Test class for {@link TagManagement}. * - * - * */ @Features("Component Tests - Repository") @Stories("Tag Management") -// TODO: fully document tests -> @Description for long text and reasonable -// method name as short text public class TagManagementTest extends AbstractIntegrationTest { public TagManagementTest() { LOG = LoggerFactory.getLogger(TagManagementTest.class); } + @Before + public void setup() { + assertThat(targetTagRepository.findAll()).as("Not tags should be available").isEmpty(); + } + @Test @Description("Full DS tag lifecycle tested. Create tags, assign them to sets and delete the tags.") public void createAndAssignAndDeleteDistributionSetTags() { @@ -92,7 +95,7 @@ public class TagManagementTest extends AbstractIntegrationTest { // search for not deleted distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true) .setTagNames(Lists.newArrayList(tagA.getName())); - assertEquals( + assertEquals("filter works not correct", dsAs.spliterator().getExactSizeIfKnown() + dsABs.spliterator().getExactSizeIfKnown() + dsACs.spliterator().getExactSizeIfKnown() + dsABCs.spliterator().getExactSizeIfKnown(), distributionSetManagement.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()) @@ -100,7 +103,7 @@ public class TagManagementTest extends AbstractIntegrationTest { distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true) .setTagNames(Lists.newArrayList(tagB.getName())); - assertEquals( + assertEquals("filter works not correct", dsBs.spliterator().getExactSizeIfKnown() + dsABs.spliterator().getExactSizeIfKnown() + dsBCs.spliterator().getExactSizeIfKnown() + dsABCs.spliterator().getExactSizeIfKnown(), distributionSetManagement.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()) @@ -108,7 +111,7 @@ public class TagManagementTest extends AbstractIntegrationTest { distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true) .setTagNames(Lists.newArrayList(tagC.getName())); - assertEquals( + assertEquals("filter works not correct", dsCs.spliterator().getExactSizeIfKnown() + dsACs.spliterator().getExactSizeIfKnown() + dsBCs.spliterator().getExactSizeIfKnown() + dsABCs.spliterator().getExactSizeIfKnown(), distributionSetManagement.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()) @@ -116,22 +119,22 @@ public class TagManagementTest extends AbstractIntegrationTest { distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true) .setTagNames(Lists.newArrayList(tagX.getName())); - assertEquals(0, distributionSetManagement + assertEquals("filter works not correct", 0, distributionSetManagement .findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getTotalElements()); - assertEquals(5, distributionSetTagRepository.findAll().spliterator().getExactSizeIfKnown()); + assertEquals("wrong tag size", 5, distributionSetTagRepository.findAll().spliterator().getExactSizeIfKnown()); tagManagement.deleteDistributionSetTag(tagY.getName()); - assertEquals(4, distributionSetTagRepository.findAll().spliterator().getExactSizeIfKnown()); + assertEquals("wrong tag size", 4, distributionSetTagRepository.findAll().spliterator().getExactSizeIfKnown()); tagManagement.deleteDistributionSetTag(tagX.getName()); - assertEquals(3, distributionSetTagRepository.findAll().spliterator().getExactSizeIfKnown()); + assertEquals("wrong tag size", 3, distributionSetTagRepository.findAll().spliterator().getExactSizeIfKnown()); tagManagement.deleteDistributionSetTag(tagB.getName()); - assertEquals(2, distributionSetTagRepository.findAll().spliterator().getExactSizeIfKnown()); + assertEquals("wrong tag size", 2, distributionSetTagRepository.findAll().spliterator().getExactSizeIfKnown()); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE) .setTagNames(Lists.newArrayList(tagA.getName())); - assertEquals( + assertEquals("filter works not correct", dsAs.spliterator().getExactSizeIfKnown() + dsABs.spliterator().getExactSizeIfKnown() + dsACs.spliterator().getExactSizeIfKnown() + dsABCs.spliterator().getExactSizeIfKnown(), distributionSetManagement.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()) @@ -139,12 +142,12 @@ public class TagManagementTest extends AbstractIntegrationTest { distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE) .setTagNames(Lists.newArrayList(tagB.getName())); - assertEquals(0, distributionSetManagement + assertEquals("filter works not correct", 0, distributionSetManagement .findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getTotalElements()); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE) .setTagNames(Lists.newArrayList(tagC.getName())); - assertEquals( + assertEquals("filter works not correct", dsCs.spliterator().getExactSizeIfKnown() + dsACs.spliterator().getExactSizeIfKnown() + dsBCs.spliterator().getExactSizeIfKnown() + dsABCs.spliterator().getExactSizeIfKnown(), distributionSetManagement.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()) @@ -155,45 +158,28 @@ public class TagManagementTest extends AbstractIntegrationTest { return new DistributionSetFilterBuilder(); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.TagManagement#findTargetTag(java.lang.String)} - * . - */ @Test - public void testFindTargetTag() { - assertThat(targetTagRepository.findAll()).isEmpty(); - + @Description("Ensures that all tags are retrieved through repository.") + public void findAllTargetTags() { final List tags = createTargetsWithTags(); assertThat(targetTagRepository.findAll()).isEqualTo(tagManagement.findAllTargetTags()).isEqualTo(tags) - .hasSize(20); + .as("Wrong tag size").hasSize(20); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.TagManagement#createTargetTag(org.eclipse.hawkbit.repository.model.TargetTag)} - * . - */ @Test - public void testCreateTargetTag() { - assertThat(targetTagRepository.findAll()).isEmpty(); - + @Description("Ensures that a created tag is persisted in the repository as defined.") + public void createTargetTag() { final Tag tag = tagManagement.createTargetTag(new TargetTag("kai1", "kai2", "colour")); - assertThat(targetTagRepository.findByNameEquals("kai1").getDescription()).isEqualTo("kai2"); - assertThat(tagManagement.findTargetTag("kai1").getColour()).isEqualTo("colour"); - assertThat(tagManagement.findTargetTagById(tag.getId()).getColour()).isEqualTo("colour"); + assertThat(targetTagRepository.findByNameEquals("kai1").getDescription()).as("wrong tag ed").isEqualTo("kai2"); + assertThat(tagManagement.findTargetTag("kai1").getColour()).as("wrong tag found").isEqualTo("colour"); + assertThat(tagManagement.findTargetTagById(tag.getId()).getColour()).as("wrong tag found").isEqualTo("colour"); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.TagManagement#deleteTargetTag(java.lang.String[])} - * . - */ @Test - public void testDeleteTargetTagsStringArray() { - assertThat(targetTagRepository.findAll()).isEmpty(); + @Description("Ensures that a deleted tag is removed from the repository as defined.") + public void deleteTargetTas() { // create test data final Iterable tags = createTargetsWithTags(); @@ -212,16 +198,13 @@ public class TagManagementTest extends AbstractIntegrationTest { assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).getTags()) .doesNotContain(toDelete); } - assertThat(targetTagRepository.findOne(toDelete.getId())).isNull(); - assertThat(tagManagement.findAllTargetTags()).hasSize(19); + assertThat(targetTagRepository.findOne(toDelete.getId())).as("No tag should be found").isNull(); + assertThat(tagManagement.findAllTargetTags()).as("Wrong target tag size").hasSize(19); } @Test - @Description("Tests the creation of a target tag.") + @Description("Tests the name update of a target tag.") public void updateTargetTag() { - assertThat(targetTagRepository.findAll()).isEmpty(); - - // create test data final List tags = createTargetsWithTags(); // change data @@ -232,91 +215,104 @@ public class TagManagementTest extends AbstractIntegrationTest { tagManagement.updateTargetTag(savedAssigned); // check data - assertThat(tagManagement.findAllTargetTags()).hasSize(tags.size()); - assertThat(targetTagRepository.findOne(savedAssigned.getId()).getName()).isEqualTo("test123"); - assertThat(targetTagRepository.findOne(savedAssigned.getId()).getOptLockRevision()).isEqualTo(2); + assertThat(tagManagement.findAllTargetTags()).as("Wrong target tag size").hasSize(tags.size()); + assertThat(targetTagRepository.findOne(savedAssigned.getId()).getName()).as("wrong target tag is saved") + .isEqualTo("test123"); + assertThat(targetTagRepository.findOne(savedAssigned.getId()).getOptLockRevision()) + .as("wrong target tag is saved").isEqualTo(2); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.TagManagement#createDistributionSetTag(org.eclipse.hawkbit.repository.model.DistributionSetTag)} - * . - */ @Test - public void testCreateDistributionSetTag() { - assertThat(distributionSetTagRepository.findAll()).isEmpty(); - + @Description("Ensures that a created tag is persisted in the repository as defined.") + public void createDistributionSetTag() { final Tag tag = tagManagement.createDistributionSetTag(new DistributionSetTag("kai1", "kai2", "colour")); - assertThat(distributionSetTagRepository.findByNameEquals("kai1").getDescription()).isEqualTo("kai2"); - assertThat(tagManagement.findDistributionSetTag("kai1").getColour()).isEqualTo("colour"); - assertThat(tagManagement.findDistributionSetTagById(tag.getId()).getColour()).isEqualTo("colour"); + assertThat(distributionSetTagRepository.findByNameEquals("kai1").getDescription()).as("wrong tag found") + .isEqualTo("kai2"); + assertThat(tagManagement.findDistributionSetTag("kai1").getColour()).as("wrong tag found").isEqualTo("colour"); + assertThat(tagManagement.findDistributionSetTagById(tag.getId()).getColour()).as("wrong tag found") + .isEqualTo("colour"); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.TagManagement#createDistributionSetTags(java.lang.Iterable)} - * . - */ @Test - public void testCreateDistributionSetTags() { - assertThat(distributionSetTagRepository.findAll()).isEmpty(); - + @Description("Ensures that a created tags are persisted in the repository as defined.") + public void createDistributionSetTags() { final List tags = createDsSetsWithTags(); - assertThat(distributionSetTagRepository.findAll()).hasSize(tags.size()); + assertThat(distributionSetTagRepository.findAll()).as("Wrong size of tags created").hasSize(tags.size()); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.TagManagement#deleteDistributionSetTag(java.lang.String[])} - * . - */ @Test - public void testDeleteDistributionSetTag() { - assertThat(distributionSetTagRepository.findAll()).isEmpty(); - + @Description("Ensures that a deleted tag is removed from the repository as defined.") + public void deleteDistributionSetTag() { // create test data final Iterable tags = createDsSetsWithTags(); final DistributionSetTag toDelete = tags.iterator().next(); for (final DistributionSet set : distributionSetRepository.findAll()) { assertThat(distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).getTags()) - .contains(toDelete); + .as("Wrong tag found").contains(toDelete); } // delete tagManagement.deleteDistributionSetTag(tags.iterator().next().getName()); // check - assertThat(distributionSetTagRepository.findOne(toDelete.getId())).isNull(); - assertThat(tagManagement.findAllDistributionSetTags()).hasSize(19); + assertThat(distributionSetTagRepository.findOne(toDelete.getId())).as("Deleted tag should be null").isNull(); + assertThat(tagManagement.findAllDistributionSetTags()).as("Wrong size of tags after deletion").hasSize(19); for (final DistributionSet set : distributionSetRepository.findAll()) { assertThat(distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).getTags()) - .doesNotContain(toDelete); + .as("Wrong found tags").doesNotContain(toDelete); } } - @Test(expected = EntityAlreadyExistsException.class) - public void testFailedDuplicateTargetTagNameException() { - tagManagement.createTargetTag(new TargetTag("A")); + @Description("Ensures that a tag cannot be created if one exists already with that name (ecpects EntityAlreadyExistsException).") + public void failedDuplicateTargetTagNameException() { tagManagement.createTargetTag(new TargetTag("A")); + try { + tagManagement.createTargetTag(new TargetTag("A")); + fail("Expected EntityAlreadyExistsException"); + } catch (final EntityAlreadyExistsException e) { + } } - @Test(expected = EntityAlreadyExistsException.class) - public void testFailedDuplicateDsTagNameException() { - tagManagement.createDistributionSetTag(new DistributionSetTag("A")); - tagManagement.createDistributionSetTag(new DistributionSetTag("A")); + @Description("Ensures that a tag cannot be updated to a name that already exists on another tag (ecpects EntityAlreadyExistsException).") + public void failedDuplicateTargetTagNameExceptionAfterUpdate() { + tagManagement.createTargetTag(new TargetTag("A")); + final TargetTag tag = tagManagement.createTargetTag(new TargetTag("B")); + tag.setName("A"); + try { + tagManagement.updateTargetTag(tag); + fail("Expected EntityAlreadyExistsException"); + } catch (final EntityAlreadyExistsException e) { + } + } + + @Description("Ensures that a tag cannot be created if one exists already with that name (ecpects EntityAlreadyExistsException).") + public void failedDuplicateDsTagNameException() { + tagManagement.createDistributionSetTag(new DistributionSetTag("A")); + try { + tagManagement.createDistributionSetTag(new DistributionSetTag("A")); + fail("Expected EntityAlreadyExistsException"); + } catch (final EntityAlreadyExistsException e) { + } + } + + @Description("Ensures that a tag cannot be updated to a name that already exists on another tag (ecpects EntityAlreadyExistsException).") + public void failedDuplicateDsTagNameExceptionAfterUpdate() { + tagManagement.createDistributionSetTag(new DistributionSetTag("A")); + final DistributionSetTag tag = tagManagement.createDistributionSetTag(new DistributionSetTag("B")); + tag.setName("A"); + try { + tagManagement.updateDistributionSetTag(tag); + fail("Expected EntityAlreadyExistsException"); + } catch (final EntityAlreadyExistsException e) { + } } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.TagManagement#updateDistributionSetTag(org.eclipse.hawkbit.repository.model.DistributionSetTag)} - * . - */ @Test - public void testUpdateDistributionSetTag() { - assertThat(distributionSetTagRepository.findAll()).isEmpty(); + @Description("Tests the name update of a target tag.") + public void updateDistributionSetTag() { // create test data final List tags = createDsSetsWithTags(); @@ -329,24 +325,19 @@ public class TagManagementTest extends AbstractIntegrationTest { tagManagement.updateDistributionSetTag(savedAssigned); // check data - assertThat(tagManagement.findAllDistributionSetTags()).hasSize(tags.size()); - assertThat(distributionSetTagRepository.findOne(savedAssigned.getId()).getName()).isEqualTo("test123"); + assertThat(tagManagement.findAllDistributionSetTags()).as("Wrong size of ds tags").hasSize(tags.size()); + assertThat(distributionSetTagRepository.findOne(savedAssigned.getId()).getName()).as("Wrong ds tag found") + .isEqualTo("test123"); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.TagManagement#findAllDistributionSetTags()} - * . - */ @Test - public void testFindDistributionSetTagsAll() { - assertThat(distributionSetTagRepository.findAll()).isEmpty(); - + @Description("Ensures that all tags are retrieved through repository.") + public void findDistributionSetTagsAll() { final List tags = createDsSetsWithTags(); // test - assertThat(tagManagement.findAllDistributionSetTags()).hasSize(tags.size()); - assertThat(distributionSetTagRepository.findAll()).hasSize(20); + assertThat(tagManagement.findAllDistributionSetTags()).as("Wrong size of tags").hasSize(tags.size()); + assertThat(distributionSetTagRepository.findAll()).as("Wrong size of tags").hasSize(20); } private List createTargetsWithTags() { diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementSearchTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementSearchTest.java index bd9884e89..34aa223c3 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementSearchTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementSearchTest.java @@ -47,7 +47,7 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { final TargetTag targTagC = tagManagement.createTargetTag(new TargetTag("TargTag-C")); final TargetTag targTagD = tagManagement.createTargetTag(new TargetTag("TargTag-D")); - // TODO kzimmerm: test also installedDS (not only assignedDS) + // TODO kaizimmerm: test also installedDS (not only assignedDS) final DistributionSet setA = TestDataUtil.generateDistributionSet("", softwareManagement, distributionSetManagement); @@ -90,7 +90,7 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { final PageRequest pageReq = new PageRequest(0, 500); // try to find several targets with different filter settings - // TODO kzimmerm: comment and check also the content itself, not only + // TODO kaizimmerm: comment and check also the content itself, not only // the numbers // (containsOnly) assertThat(targetManagement.countTargetsAll()).isEqualTo(400); @@ -185,7 +185,7 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { } - // TODO kzimmerm: add filter tests + // TODO kaizimmerm: add filter tests @Test @Description("Tests the correct order of targets based on selected distribution set. The system expects to have an order based on installed, assigned DS.") public void targetSearchWithVariousFilterCombinationsAndOrderByDistributionSet() { diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementTest.java index cdcaff25e..20dffde29 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementTest.java @@ -96,24 +96,26 @@ public class TargetManagementTest extends AbstractIntegrationTest { final TargetTag targetTag = tagManagement.createTargetTag(new TargetTag("Tag1")); final List assignedTargets = targetManagement.assignTag(assignTarget, targetTag); - assertThat(assignedTargets.size()).isEqualTo(4); + assertThat(assignedTargets.size()).as("Assigned targets are wrong").isEqualTo(4); assignedTargets.forEach(target -> assertThat(target.getTags().size()).isEqualTo(1)); TargetTag findTargetTag = tagManagement.findTargetTag("Tag1"); - assertThat(assignedTargets.size()).isEqualTo(findTargetTag.getAssignedToTargets().size()); + assertThat(assignedTargets.size()).as("Assigned targets are wrong") + .isEqualTo(findTargetTag.getAssignedToTargets().size()); - assertThat(targetManagement.unAssignTag("NotExist", findTargetTag)).isNull(); + assertThat(targetManagement.unAssignTag("NotExist", findTargetTag)).as("Unassign target does not work") + .isNull(); final Target unAssignTarget = targetManagement.unAssignTag("targetId123", findTargetTag); - assertThat(unAssignTarget.getControllerId()).isEqualTo("targetId123"); - assertThat(unAssignTarget.getTags().size()).isEqualTo(0); + assertThat(unAssignTarget.getControllerId()).as("Controller id is wrong").isEqualTo("targetId123"); + assertThat(unAssignTarget.getTags()).as("Tag size is wrong").isEmpty(); findTargetTag = tagManagement.findTargetTag("Tag1"); - assertThat(findTargetTag.getAssignedToTargets().size()).isEqualTo(3); + assertThat(findTargetTag.getAssignedToTargets()).as("Assigned targets are wrong").hasSize(3); final List unAssignTargets = targetManagement.unAssignAllTargetsByTag(findTargetTag); findTargetTag = tagManagement.findTargetTag("Tag1"); - assertThat(findTargetTag.getAssignedToTargets().size()).isEqualTo(0); - assertThat(unAssignTargets.size()).isEqualTo(3); + assertThat(findTargetTag.getAssignedToTargets()).as("Unassigned targets are wrong").isEmpty(); + assertThat(unAssignTargets).as("Unassigned targets are wrong").hasSize(3); unAssignTargets.forEach(target -> assertThat(target.getTags().size()).isEqualTo(0)); } @@ -121,14 +123,14 @@ public class TargetManagementTest extends AbstractIntegrationTest { @Description("Ensures that targets can deleted e.g. test all cascades") public void deleteAndCreateTargets() { Target target = targetManagement.createTarget(new Target("targetId123")); - assertThat(targetManagement.countTargetsAll()).isEqualTo(1); + assertThat(targetManagement.countTargetsAll()).as("target count is wrong").isEqualTo(1); targetManagement.deleteTargets(target.getId()); - assertThat(targetManagement.countTargetsAll()).isEqualTo(0); + assertThat(targetManagement.countTargetsAll()).as("target count is wrong").isEqualTo(0); target = createTargetWithAttributes("4711"); - assertThat(targetManagement.countTargetsAll()).isEqualTo(1); + assertThat(targetManagement.countTargetsAll()).as("target count is wrong").isEqualTo(1); targetManagement.deleteTargets(target.getId()); - assertThat(targetManagement.countTargetsAll()).isEqualTo(0); + assertThat(targetManagement.countTargetsAll()).as("target count is wrong").isEqualTo(0); final List targets = new ArrayList(); for (int i = 0; i < 5; i++) { @@ -136,9 +138,9 @@ public class TargetManagementTest extends AbstractIntegrationTest { targets.add(target.getId()); targets.add(createTargetWithAttributes("" + (i * i + 1000)).getId()); } - assertThat(targetManagement.countTargetsAll()).isEqualTo(10); + assertThat(targetManagement.countTargetsAll()).as("target count is wrong").isEqualTo(10); targetManagement.deleteTargets(targets.toArray(new Long[targets.size()])); - assertThat(targetManagement.countTargetsAll()).isEqualTo(0); + assertThat(targetManagement.countTargetsAll()).as("target count is wrong").isEqualTo(0); } private Target createTargetWithAttributes(final String controllerId) { @@ -150,7 +152,8 @@ public class TargetManagementTest extends AbstractIntegrationTest { target = controllerManagament.updateControllerAttributes(controllerId, testData); target = targetManagement.findTargetByControllerIDWithDetails(controllerId); - assertThat(target.getTargetInfo().getControllerAttributes()).isEqualTo(testData); + assertThat(target.getTargetInfo().getControllerAttributes()).as("Controller Attributes are wrong") + .isEqualTo(testData); return target; } @@ -162,10 +165,14 @@ public class TargetManagementTest extends AbstractIntegrationTest { final DistributionSet set2 = TestDataUtil.generateDistributionSet("test2", softwareManagement, distributionSetManagement); - assertThat(targetManagement.countTargetByAssignedDistributionSet(set.getId())).isEqualTo(0); - assertThat(targetManagement.countTargetByInstalledDistributionSet(set.getId())).isEqualTo(0); - assertThat(targetManagement.countTargetByAssignedDistributionSet(set2.getId())).isEqualTo(0); - assertThat(targetManagement.countTargetByInstalledDistributionSet(set2.getId())).isEqualTo(0); + assertThat(targetManagement.countTargetByAssignedDistributionSet(set.getId())).as("Target count is wrong") + .isEqualTo(0); + assertThat(targetManagement.countTargetByInstalledDistributionSet(set.getId())).as("Target count is wrong") + .isEqualTo(0); + assertThat(targetManagement.countTargetByAssignedDistributionSet(set2.getId())).as("Target count is wrong") + .isEqualTo(0); + assertThat(targetManagement.countTargetByInstalledDistributionSet(set2.getId())).as("Target count is wrong") + .isEqualTo(0); Target target = createTargetWithAttributes("4711"); @@ -183,13 +190,19 @@ public class TargetManagementTest extends AbstractIntegrationTest { target = targetManagement.findTargetByControllerIDWithDetails("4711"); // read data - assertThat(targetManagement.countTargetByAssignedDistributionSet(set.getId())).isEqualTo(0); - assertThat(targetManagement.countTargetByInstalledDistributionSet(set.getId())).isEqualTo(1); - assertThat(targetManagement.countTargetByAssignedDistributionSet(set2.getId())).isEqualTo(1); - assertThat(targetManagement.countTargetByInstalledDistributionSet(set2.getId())).isEqualTo(0); - assertThat(target.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current); - assertThat(target.getAssignedDistributionSet()).isEqualTo(set2); - assertThat(target.getTargetInfo().getInstalledDistributionSet().getId()).isEqualTo(set.getId()); + assertThat(targetManagement.countTargetByAssignedDistributionSet(set.getId())).as("Target count is wrong") + .isEqualTo(0); + assertThat(targetManagement.countTargetByInstalledDistributionSet(set.getId())).as("Target count is wrong") + .isEqualTo(1); + assertThat(targetManagement.countTargetByAssignedDistributionSet(set2.getId())).as("Target count is wrong") + .isEqualTo(1); + assertThat(targetManagement.countTargetByInstalledDistributionSet(set2.getId())).as("Target count is wrong") + .isEqualTo(0); + assertThat(target.getTargetInfo().getLastTargetQuery()).as("Target query is not work") + .isGreaterThanOrEqualTo(current); + assertThat(target.getAssignedDistributionSet()).as("Assigned ds size is wrong").isEqualTo(set2); + assertThat(target.getTargetInfo().getInstalledDistributionSet().getId()).as("Installed ds is wrong") + .isEqualTo(set.getId()); } @@ -373,8 +386,7 @@ public class TargetManagementTest extends AbstractIntegrationTest { assertThat(firstSaved.spliterator().getExactSizeIfKnown() - nr2Del).as("Size of splited list") .isEqualTo(allFound.spliterator().getExactSizeIfKnown()); - // verify that all undeleted are still found - assertThat(allFound).doesNotContain(deletedTargets); + assertThat(allFound).as("Not all undeleted found").doesNotContain(deletedTargets); } @Test @@ -404,7 +416,7 @@ public class TargetManagementTest extends AbstractIntegrationTest { targetInfo = targetInfoRepository.save(targetInfo); } final Query qry = entityManager.createNativeQuery("select * from sp_target_attributes ta"); - final List result = qry.getResultList(); + final List result = qry.getResultList(); assertThat(attribs.size() * ts.spliterator().getExactSizeIfKnown()).as("Amount of all target attributes") .isEqualTo(result.size()); @@ -467,7 +479,8 @@ public class TargetManagementTest extends AbstractIntegrationTest { final Target tNoAttrib = targetManagement.findTargetByControllerID(tNoAttribl.getControllerId()); if (tNoAttrib.getControllerId().equals(target.getControllerId())) { - assertThat(target.getTargetInfo().getControllerAttributes()).isEmpty(); + assertThat(target.getTargetInfo().getControllerAttributes()) + .as("Controller attributes should be empty").isEmpty(); continue restTarget_; } } @@ -479,7 +492,7 @@ public class TargetManagementTest extends AbstractIntegrationTest { if (tNoAttrib.getControllerId().equals(target.getControllerId())) { assertThat(target.getTargetInfo().getControllerAttributes().keySet().toArray()) - .doesNotContain(attribs2Del.toArray()); + .as("Controller attributes are wrong").doesNotContain(attribs2Del.toArray()); continue restTarget_; } } @@ -504,12 +517,14 @@ public class TargetManagementTest extends AbstractIntegrationTest { t2 = targetManagement.createTarget(t2); t1 = targetManagement.findTargetByControllerID(t1.getControllerId()); - assertThat(t1.getTags()).hasSize(noT1Tags).containsAll(t1Tags); - assertThat(t1.getTags()).hasSize(noT1Tags).doesNotContain(Iterables.toArray(t2Tags, TargetTag.class)); + assertThat(t1.getTags()).as("Tag size is wrong").hasSize(noT1Tags).containsAll(t1Tags); + assertThat(t1.getTags()).as("Tag size is wrong").hasSize(noT1Tags) + .doesNotContain(Iterables.toArray(t2Tags, TargetTag.class)); t2 = targetManagement.findTargetByControllerID(t2.getControllerId()); - assertThat(t2.getTags()).hasSize(noT2Tags).containsAll(t2Tags); - assertThat(t2.getTags()).hasSize(noT2Tags).doesNotContain(Iterables.toArray(t1Tags, TargetTag.class)); + assertThat(t2.getTags()).as("Tag size is wrong").hasSize(noT2Tags).containsAll(t2Tags); + assertThat(t2.getTags()).as("Tag size is wrong").hasSize(noT2Tags) + .doesNotContain(Iterables.toArray(t1Tags, TargetTag.class)); } @Test @@ -531,7 +546,7 @@ public class TargetManagementTest extends AbstractIntegrationTest { final TargetTag tagA = tagManagement.createTargetTag(new TargetTag("A")); final TargetTag tagB = tagManagement.createTargetTag(new TargetTag("B")); final TargetTag tagC = tagManagement.createTargetTag(new TargetTag("C")); - final TargetTag tagX = tagManagement.createTargetTag(new TargetTag("X")); + tagManagement.createTargetTag(new TargetTag("X")); // doing different assignments targetManagement.toggleTagAssignment(tagATargets, tagA); @@ -545,7 +560,8 @@ public class TargetManagementTest extends AbstractIntegrationTest { targetManagement.toggleTagAssignment(tagABCTargets, tagB); targetManagement.toggleTagAssignment(tagABCTargets, tagC); - assertThat(targetManagement.countTargetByFilters(null, null, null, Boolean.FALSE, "X")).isEqualTo(0); + assertThat(targetManagement.countTargetByFilters(null, null, null, Boolean.FALSE, "X")) + .as("Target count is wrong").isEqualTo(0); // search for targets with tag tagA final List targetWithTagA = new ArrayList(); @@ -575,11 +591,11 @@ public class TargetManagementTest extends AbstractIntegrationTest { // check again target lists refreshed from DB assertThat(targetManagement.countTargetByFilters(null, null, null, Boolean.FALSE, "A")) - .isEqualTo(targetWithTagA.size()); + .as("Target count is wrong").isEqualTo(targetWithTagA.size()); assertThat(targetManagement.countTargetByFilters(null, null, null, Boolean.FALSE, "B")) - .isEqualTo(targetWithTagB.size()); + .as("Target count is wrong").isEqualTo(targetWithTagB.size()); assertThat(targetManagement.countTargetByFilters(null, null, null, Boolean.FALSE, "C")) - .isEqualTo(targetWithTagC.size()); + .as("Target count is wrong").isEqualTo(targetWithTagC.size()); } @Test @@ -656,14 +672,15 @@ public class TargetManagementTest extends AbstractIntegrationTest { targetManagement.toggleTagAssignment(targAs, targTagA); assertThat(targetManagement.findTargetsByControllerIDsWithTags( - targAs.stream().map(target -> target.getControllerId()).collect(Collectors.toList()))).hasSize(25); + targAs.stream().map(target -> target.getControllerId()).collect(Collectors.toList()))) + .as("Target count is wrong").hasSize(25); // no lazy loading exception and tag correctly assigned assertThat(targetManagement .findTargetsByControllerIDsWithTags( targAs.stream().map(target -> target.getControllerId()).collect(Collectors.toList())) .stream().map(target -> target.getTags().contains(targTagA)).collect(Collectors.toList())) - .containsOnly(true); + .as("Tags not correctly assigned").containsOnly(true); } @Test @@ -678,7 +695,7 @@ public class TargetManagementTest extends AbstractIntegrationTest { final List findAllTargetIds = findAllTargetIdNames.stream().map(TargetIdName::getControllerId) .collect(Collectors.toList()); - assertThat(findAllTargetIds).containsOnly(createdTargetIds); + assertThat(findAllTargetIds).as("Target list has wrong content").containsOnly(createdTargetIds); } @Test diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLActionFieldsTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLActionFieldsTest.java index 139b0a88d..8b20af27d 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLActionFieldsTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLActionFieldsTest.java @@ -26,7 +26,7 @@ import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -@Features("Component Tests - RSQL filtering") +@Features("Component Tests - Repository") @Stories("RSQL filter actions") public class RSQLActionFieldsTest extends AbstractIntegrationTest { diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetFieldTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetFieldTest.java index 6bfdb89aa..ea1db0ed8 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetFieldTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetFieldTest.java @@ -28,7 +28,7 @@ import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -@Features("Component Tests - RSQL filtering") +@Features("Component Tests - Repository") @Stories("RSQL filter distribution set") public class RSQLDistributionSetFieldTest extends AbstractIntegrationTest { @@ -98,7 +98,7 @@ public class RSQLDistributionSetFieldTest extends AbstractIntegrationTest { assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "==true", 4); try { assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "==noExist*", 0); - fail(); + fail("Expected RSQLParameterSyntaxException"); } catch (final RSQLParameterSyntaxException e) { } assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "=in=(true)", 4); @@ -140,7 +140,7 @@ public class RSQLDistributionSetFieldTest extends AbstractIntegrationTest { final Page find = distributionSetManagement.findDistributionSetsAll( RSQLUtility.parse(rsqlParam, DistributionSetFields.class), new PageRequest(0, 100), false); final long countAll = find.getTotalElements(); - assertThat(find).isNotNull(); - assertThat(countAll).isEqualTo(excpectedEntity); + assertThat(find).as("Founded entity is should not be null").isNotNull(); + assertThat(countAll).as("Founded entity size is wrong").isEqualTo(excpectedEntity); } } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetMetadataFieldsTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetMetadataFieldsTest.java index 2d113a0a3..1d1e8b7f3 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetMetadataFieldsTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetMetadataFieldsTest.java @@ -24,7 +24,7 @@ import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -@Features("Component Tests - RSQL filtering") +@Features("Component Tests - Repository") @Stories("RSQL filter distribution set metadata") public class RSQLDistributionSetMetadataFieldsTest extends AbstractIntegrationTest { diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLRolloutGroupFields.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLRolloutGroupFields.java index 05e26293c..78d333826 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLRolloutGroupFields.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLRolloutGroupFields.java @@ -27,7 +27,7 @@ import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -@Features("Component Tests - RSQL filtering") +@Features("Component Tests - Repository") @Stories("RSQL filter rollout group") public class RSQLRolloutGroupFields extends AbstractIntegrationTest { diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleFieldTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleFieldTest.java index 55e4386cd..88f0817f7 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleFieldTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleFieldTest.java @@ -23,7 +23,7 @@ import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -@Features("Component Tests - RSQL filtering") +@Features("Component Tests - Repository") @Stories("RSQL filter software module") public class RSQLSoftwareModuleFieldTest extends AbstractIntegrationTest { diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleMetadataFieldsTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleMetadataFieldsTest.java index f75893b43..c863c1460 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleMetadataFieldsTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleMetadataFieldsTest.java @@ -24,7 +24,7 @@ import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -@Features("Component Tests - RSQL filtering") +@Features("Component Tests - Repository") @Stories("RSQL filter software module metadata") public class RSQLSoftwareModuleMetadataFieldsTest extends AbstractIntegrationTest { diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleTypeFieldsTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleTypeFieldsTest.java index 008de9199..12f4005ac 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleTypeFieldsTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleTypeFieldsTest.java @@ -21,7 +21,7 @@ import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -@Features("Component Tests - RSQL filtering") +@Features("Component Tests - Repository") @Stories("RSQL filter software module test type") public class RSQLSoftwareModuleTypeFieldsTest extends AbstractIntegrationTest { diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLTagFieldsTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLTagFieldsTest.java index e3ab8fc2c..b35ed13d1 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLTagFieldsTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLTagFieldsTest.java @@ -23,7 +23,7 @@ import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -@Features("Component Tests - RSQL filtering") +@Features("Component Tests - Repository") @Stories("RSQL filter target and distribution set tags") public class RSQLTagFieldsTest extends AbstractIntegrationTest { diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLTargetFieldTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLTargetFieldTest.java index 2f77346f2..54efab860 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLTargetFieldTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLTargetFieldTest.java @@ -30,7 +30,7 @@ import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -@Features("Component Tests - RSQL filtering") +@Features("Component Tests - Repository") @Stories("RSQL filter target") public class RSQLTargetFieldTest extends AbstractIntegrationTest { diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLUtilityTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLUtilityTest.java index bcfade8d5..356464bc2 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLUtilityTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLUtilityTest.java @@ -40,7 +40,7 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; @RunWith(MockitoJUnitRunner.class) -@Features("Component Tests - RSQL filtering") +@Features("Component Tests - Repository") @Stories("RSQL search utility") // TODO: fully document tests -> @Description for long text and reasonable // method name as short text diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/tenancy/MultiTenancyEntityTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/tenancy/MultiTenancyEntityTest.java index 51e49ef04..1dd4c9823 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/tenancy/MultiTenancyEntityTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/tenancy/MultiTenancyEntityTest.java @@ -10,8 +10,6 @@ package org.eclipse.hawkbit.tenancy; import static org.fest.assertions.api.Assertions.assertThat; -import java.util.concurrent.Callable; - import org.eclipse.hawkbit.AbstractIntegrationTest; import org.eclipse.hawkbit.WithSpringAuthorityRule; import org.eclipse.hawkbit.WithUser; @@ -31,9 +29,6 @@ import ru.yandex.qatools.allure.annotations.Stories; * CRUD-Operations are tenant aware and cannot access or delete entities not * belonging to the current tenant. * - * - * - * */ @Features("Component Tests - Repository") @Stories("Multi Tenancy") @@ -97,13 +92,9 @@ public class MultiTenancyEntityTest extends AbstractIntegrationTest { // check that the cache is not getting in the way, i.e. "bumlux" results // in bumlux and not // mytenant - assertThat( - securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", "bumlux"), new Callable() { - @Override - public String call() throws Exception { - return systemManagement.getTenantMetadata().getTenant().toUpperCase(); - } - })).isEqualTo("bumlux".toUpperCase()); + assertThat(securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", "bumlux"), + () -> systemManagement.getTenantMetadata().getTenant().toUpperCase())) + .isEqualTo("bumlux".toUpperCase()); } @Test @@ -154,59 +145,38 @@ public class MultiTenancyEntityTest extends AbstractIntegrationTest { } private Target createTargetForTenant(final String controllerId, final String tenant) throws Exception { - return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), new Callable() { - @Override - public Target call() throws Exception { - return targetManagement.createTarget(new Target(controllerId)); - } - }); + return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), + () -> targetManagement.createTarget(new Target(controllerId))); } private Slice findTargetsForTenant(final String tenant) throws Exception { return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), - new Callable>() { - @Override - public Slice call() throws Exception { - return targetManagement.findTargetsAll(pageReq); - } - }); + () -> targetManagement.findTargetsAll(pageReq)); } private void deleteTargetsForTenant(final String tenant, final Long... targetIds) throws Exception { - securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), new Callable() { - @Override - public Void call() throws Exception { - targetManagement.deleteTargets(targetIds); - return null; - } + securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), () -> { + targetManagement.deleteTargets(targetIds); + return null; }); } private DistributionSet createDistributionSetForTenant(final String name, final String version, final String tenant) throws Exception { - return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), - new Callable() { - @Override - public DistributionSet call() throws Exception { - final DistributionSet ds = new DistributionSet(); - ds.setName(name); - ds.setTenant(tenant); - ds.setVersion(version); - ds.setType(distributionSetManagement - .createDistributionSetType(new DistributionSetType("typetest", "test", "foobar"))); - return distributionSetManagement.createDistributionSet(ds); - } - }); + return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), () -> { + final DistributionSet ds = new DistributionSet(); + ds.setName(name); + ds.setTenant(tenant); + ds.setVersion(version); + ds.setType(distributionSetManagement + .createDistributionSetType(new DistributionSetType("typetest", "test", "foobar"))); + return distributionSetManagement.createDistributionSet(ds); + }); } private Page findDistributionSetForTenant(final String tenant) throws Exception { return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), - new Callable>() { - @Override - public Page call() throws Exception { - return distributionSetManagement.findDistributionSetsAll(pageReq, false, false); - } - }); + () -> distributionSetManagement.findDistributionSetsAll(pageReq, false, false)); } } diff --git a/hawkbit-repository/src/test/resources/application-test.properties b/hawkbit-repository/src/test/resources/application-test.properties index 8e8169a64..b1904f911 100644 --- a/hawkbit-repository/src/test/resources/application-test.properties +++ b/hawkbit-repository/src/test/resources/application-test.properties @@ -10,8 +10,8 @@ spring.data.mongodb.uri=mongodb://localhost/spArtifactRepository${random.value} spring.data.mongodb.port=28017 -hawkbit.server.controller.security.authentication.header.enabled=true -hawkbit.server.controller.security.authentication.gatewaytoken.name=TestToken +hawkbit.server.ddi.security.authentication.header.enabled=true +hawkbit.server.ddi.security.authentication.gatewaytoken.name=TestToken hawkbit.server.artifact.repo.upload.maxFileSize=5MB @@ -30,11 +30,6 @@ flyway.initOnMigrate=true flyway.sqlMigrationSuffix=${spring.jpa.database}.sql #spring.jpa.show-sql=true -# SP Controller configuration +# DDI configuration hawkbit.controller.pollingTime=00:01:00 -hawkbit.controller.pollingOverdueTime=00:01:00 - -## Configuration for RabbitMQ integration -hawkbit.dmf.rabbitmq.deadLetterQueue=dmf_connector_deadletter -hawkbit.dmf.rabbitmq.deadLetterExchange=dmf.connector.deadletter -hawkbit.dmf.rabbitmq.receiverQueue=dmf_receiver +hawkbit.controller.pollingOverdueTime=00:01:00 \ No newline at end of file diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/ArtifactStoreController.java b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/ArtifactStoreController.java index 05fd6c492..c2dbd3ba5 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/ArtifactStoreController.java +++ b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/ArtifactStoreController.java @@ -25,13 +25,11 @@ import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.rest.resource.helper.RestResourceConversionHelper; +import org.eclipse.hawkbit.security.HawkbitSecurityProperties; import org.eclipse.hawkbit.util.IpUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.bind.RelaxedPropertyResolver; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.web.bind.annotation.AuthenticationPrincipal; @@ -55,7 +53,7 @@ import org.springframework.web.bind.annotation.RestController; */ @RestController @RequestMapping(ControllerConstants.ARTIFACTS_V1_REQUEST_MAPPING) -public class ArtifactStoreController implements EnvironmentAware { +public class ArtifactStoreController { private static final Logger LOG = LoggerFactory.getLogger(ArtifactStoreController.class); @Autowired @@ -67,14 +65,8 @@ public class ArtifactStoreController implements EnvironmentAware { @Autowired private CacheWriteNotify cacheWriteNotify; - private static final String SP_SERVER_CONFIG_PREFIX = "hawkbit.server."; - private RelaxedPropertyResolver environment; - - @Override - public void setEnvironment(final Environment environment) { - this.environment = new RelaxedPropertyResolver(environment, SP_SERVER_CONFIG_PREFIX); - - } + @Autowired + private HawkbitSecurityProperties securityProperties; /** * Handles GET {@link Artifact} download request. This could be full or @@ -138,8 +130,8 @@ public class ArtifactStoreController implements EnvironmentAware { private Action checkAndReportDownloadByTarget(final HttpServletRequest request, final String targetid, final LocalArtifact artifact) { - final Target target = controllerManagement.updateLastTargetQuery(targetid, IpUtil.getClientIpFromRequest( - request, environment.getProperty("security.rp.remote_ip_header", String.class, "X-Forwarded-For"))); + final Target target = controllerManagement.updateLastTargetQuery(targetid, + IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); final Action action = controllerManagement .getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), artifact.getSoftwareModule()); diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/RootController.java b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/RootController.java index 8246dd430..6928ee7b5 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/RootController.java +++ b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/RootController.java @@ -41,15 +41,13 @@ import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.rest.resource.helper.RestResourceConversionHelper; +import org.eclipse.hawkbit.security.HawkbitSecurityProperties; import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.hawkbit.util.IpUtil; import org.hibernate.validator.constraints.NotEmpty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.bind.RelaxedPropertyResolver; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -74,7 +72,7 @@ import org.springframework.web.bind.annotation.RestController; */ @RestController @RequestMapping(ControllerConstants.BASE_V1_REQUEST_MAPPING) -public class RootController implements EnvironmentAware { +public class RootController { private static final Logger LOG = LoggerFactory.getLogger(RootController.class); private static final String GIVEN_ACTION_IS_NOT_ASSIGNED_TO_GIVEN_TARGET = "given action ({}) is not assigned to given target ({})."; @@ -99,16 +97,8 @@ public class RootController implements EnvironmentAware { @Autowired private TenantAware tenantAware; - private String requestHeader; - - @Override - public void setEnvironment(final Environment environment) { - final RelaxedPropertyResolver relaxedPropertyResolver = new RelaxedPropertyResolver(environment, - SP_SERVER_CONFIG_PREFIX); - - requestHeader = relaxedPropertyResolver.getProperty("security.rp.remote_ip_header", String.class, - "X-Forwarded-For"); - } + @Autowired + private HawkbitSecurityProperties securityProperties; /** * Returns all artifacts of a given software module and target. @@ -155,12 +145,13 @@ public class RootController implements EnvironmentAware { LOG.debug("getControllerBase({})", targetid); final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotexist(targetid, - IpUtil.getClientIpFromRequest(request, requestHeader)); + IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); if (target.getTargetInfo().getUpdateStatus() == TargetUpdateStatus.UNKNOWN) { LOG.debug("target with {} extsisted but was in status UNKNOWN -> REGISTERED)", targetid); controllerManagement.updateTargetStatus(target.getTargetInfo(), TargetUpdateStatus.REGISTERED, - System.currentTimeMillis(), IpUtil.getClientIpFromRequest(request, requestHeader)); + System.currentTimeMillis(), + IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); } return new ResponseEntity<>( @@ -195,7 +186,7 @@ public class RootController implements EnvironmentAware { ResponseEntity result; final Target target = controllerManagement.updateLastTargetQuery(targetid, - IpUtil.getClientIpFromRequest(request, requestHeader)); + IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId); if (checkModule(fileName, module)) { @@ -265,7 +256,8 @@ public class RootController implements EnvironmentAware { public ResponseEntity downloadArtifactMd5(@PathVariable final String targetid, @PathVariable final Long softwareModuleId, @PathVariable final String fileName, final HttpServletResponse response, final HttpServletRequest request) { - controllerManagement.updateLastTargetQuery(targetid, IpUtil.getClientIpFromRequest(request, requestHeader)); + controllerManagement.updateLastTargetQuery(targetid, + IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId); @@ -311,7 +303,7 @@ public class RootController implements EnvironmentAware { LOG.debug("getControllerBasedeploymentAction({},{})", targetid, resource); final Target target = controllerManagement.updateLastTargetQuery(targetid, - IpUtil.getClientIpFromRequest(request, requestHeader)); + IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); final Action action = findActionWithExceptionIfNotFound(actionId); if (!action.getTarget().getId().equals(target.getId())) { @@ -362,7 +354,7 @@ public class RootController implements EnvironmentAware { LOG.debug("provideBasedeploymentActionFeedback for target [{},{}]: {}", targetid, actionId, feedback); final Target target = controllerManagement.updateLastTargetQuery(targetid, - IpUtil.getClientIpFromRequest(request, requestHeader)); + IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); if (!actionId.equals(feedback.getId())) { LOG.warn( @@ -435,8 +427,6 @@ public class RootController implements EnvironmentAware { LOG.debug("Controller reported intermediate status (actionid: {}, targetid: {}) as we got {} report.", actionid, targetid, feedback.getStatus().getExecution()); actionStatus.setStatus(Status.RUNNING); - // MECS-400: we should not use the unstructed message list for - // the server comment on the status. actionStatus.addMessage("Controller reported: " + feedback.getStatus().getExecution()); } @@ -469,7 +459,8 @@ public class RootController implements EnvironmentAware { + ControllerConstants.CONFIG_DATA_ACTION, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity putConfigData(@Valid @RequestBody final ConfigData configData, @PathVariable final String targetid, final HttpServletRequest request) { - controllerManagement.updateLastTargetQuery(targetid, IpUtil.getClientIpFromRequest(request, requestHeader)); + controllerManagement.updateLastTargetQuery(targetid, + IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); controllerManagement.updateControllerAttributes(targetid, configData.getData()); @@ -495,7 +486,7 @@ public class RootController implements EnvironmentAware { LOG.debug("getControllerCancelAction({})", targetid); final Target target = controllerManagement.updateLastTargetQuery(targetid, - IpUtil.getClientIpFromRequest(request, requestHeader)); + IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); final Action action = findActionWithExceptionIfNotFound(actionId); if (!action.getTarget().getId().equals(target.getId())) { @@ -542,7 +533,7 @@ public class RootController implements EnvironmentAware { LOG.debug("provideCancelActionFeedback for target [{}]: {}", targetid, feedback); final Target target = controllerManagement.updateLastTargetQuery(targetid, - IpUtil.getClientIpFromRequest(request, requestHeader)); + IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); if (!actionId.equals(feedback.getId())) { LOG.warn( diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/PagingUtility.java b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/PagingUtility.java index 1503b8bda..4fb854608 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/PagingUtility.java +++ b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/PagingUtility.java @@ -23,11 +23,6 @@ import org.springframework.data.domain.Sort.Direction; /** * Utility class for for paged body generation. * - * - * - * - * - * */ public final class PagingUtility { /* @@ -90,8 +85,9 @@ public final class PagingUtility { if (sortParam != null) { sorting = new Sort(SortUtility.parse(ActionFields.class, sortParam)); } else { - // default sort - sorting = new Sort(Direction.ASC, ActionFields.ID.getFieldName()); + // default sort is DESC in case of action to match behavior + // of management UI (last entry on top) + sorting = new Sort(Direction.DESC, ActionFields.ID.getFieldName()); } return sorting; } @@ -101,8 +97,9 @@ public final class PagingUtility { if (sortParam != null) { sorting = new Sort(SortUtility.parse(ActionStatusFields.class, sortParam)); } else { - // default sort - sorting = new Sort(Direction.ASC, ActionStatusFields.ID.getFieldName()); + // default sort is DESC in case of action status to match behavior + // of management UI (last entry on top) + sorting = new Sort(Direction.DESC, ActionStatusFields.ID.getFieldName()); } return sorting; } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetMapper.java b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetMapper.java index 4f6ddafb8..b6c6c1539 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetMapper.java +++ b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetMapper.java @@ -297,8 +297,8 @@ final public class TargetMapper { final ActionStatusRest result = new ActionStatusRest(); result.setMessages(actionStatus.getMessages()); - result.setReportedAt(action.getCreatedAt()); - result.setStatusId(action.getId()); + result.setReportedAt(actionStatus.getCreatedAt()); + result.setStatusId(actionStatus.getId()); result.setType(getNameOfActionStatusType(actionStatus.getStatus())); return result; diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetResource.java b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetResource.java index 01f018327..69a38f87d 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetResource.java +++ b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetResource.java @@ -235,7 +235,7 @@ public class TargetResource implements TargetRestApi { final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); final Sort sorting = PagingUtility.sanitizeActionStatusSortParam(sortParam); - final Page statusList = this.deploymentManagement.findActionStatusMessagesByActionInDescOrder( + final Page statusList = this.deploymentManagement.findActionStatusByAction( new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting), action, true); return new ResponseEntity<>( diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/ArtifactDownloadTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/ArtifactDownloadTest.java index 2db088e64..b49f34b5f 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/ArtifactDownloadTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/ArtifactDownloadTest.java @@ -60,7 +60,7 @@ import ru.yandex.qatools.allure.annotations.Stories; */ @ActiveProfiles({ "im", "test" }) -@Features("Component Tests - Controller RESTful API") +@Features("Component Tests - Direct Device Integration API") @Stories("Artifact Download Resource") public class ArtifactDownloadTest extends AbstractIntegrationTestWithMongoDB { diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/CancelActionTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/CancelActionTest.java index e7b94cb30..d7e0351cf 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/CancelActionTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/CancelActionTest.java @@ -40,7 +40,7 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; @ActiveProfiles({ "im", "test" }) -@Features("Component Tests - Controller RESTful API") +@Features("Component Tests - Direct Device Integration API") @Stories("Cancel Action Resource") public class CancelActionTest extends AbstractIntegrationTest { diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/ConfigDataTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/ConfigDataTest.java index 4b6a135b2..a2b26c218 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/ConfigDataTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/ConfigDataTest.java @@ -35,7 +35,7 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; @ActiveProfiles({ "im", "test" }) -@Features("Component Tests - Controller RESTful API") +@Features("Component Tests - Direct Device Integration API") @Stories("Config Data Resource") public class ConfigDataTest extends AbstractIntegrationTest { diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/DeploymentBaseTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/DeploymentBaseTest.java index 2aabb0cba..2b2b7e597 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/DeploymentBaseTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/DeploymentBaseTest.java @@ -52,7 +52,7 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; @ActiveProfiles({ "im", "test" }) -@Features("Component Tests - Controller RESTful API") +@Features("Component Tests - Direct Device Integration API") @Stories("Deployment Action Resource") public class DeploymentBaseTest extends AbstractIntegrationTestWithMongoDB { diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/RootControllerTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/RootControllerTest.java index 7dce6dc35..45bf5755b 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/RootControllerTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/RootControllerTest.java @@ -45,13 +45,11 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; @ActiveProfiles({ "im", "test" }) -@Features("Component Tests - Controller RESTful API") +@Features("Component Tests - Direct Device Integration API") @Stories("Root Poll Resource") -// TODO: fully document tests -> @Description for long text and reasonable -// method name as short text public class RootControllerTest extends AbstractIntegrationTestWithMongoDB { - @Test() + @Test @Description("Ensures that targets cannot be created e.g. in plug'n play scenarios when tenant does not exists but can be created if the tenant exists.") @WithUser(tenantId = "tenantDoesNotExists", allSpPermissions = true, authorities = "ROLE_CONTROLLER", autoCreateTenant = false) public void targetCannotBeRegisteredIfTenantDoesNotExistsButWhenExists() throws Exception { @@ -73,6 +71,7 @@ public class RootControllerTest extends AbstractIntegrationTestWithMongoDB { } @Test + @Description("Ensures that target poll request does not change audit data on the entity.") @WithUser(principal = "knownPrincipal", authorities = { SpPermission.READ_TARGET, SpPermission.UPDATE_TARGET, SpPermission.CREATE_TARGET }) public void targetPollDoesNotModifyAuditData() throws Exception { @@ -104,11 +103,13 @@ public class RootControllerTest extends AbstractIntegrationTestWithMongoDB { } @Test + @Description("Ensures that server returns a not found response in case of empty controlloer ID.") public void rootRsWithoutId() throws Exception { mvc.perform(get("/controller/v1/")).andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()); } @Test + @Description("Ensures that the system creates a new target in plug and play manner, i.e. target is authenticated but does not exist yet.") public void rootRsPlugAndPlay() throws Exception { final long current = System.currentTimeMillis(); @@ -133,6 +134,7 @@ public class RootControllerTest extends AbstractIntegrationTestWithMongoDB { } @Test + @Description("Ensures that etag check results in not modified response if provided etag by client is identical to entity in repository.") public void rootRsNotModified() throws Exception { final String etag = mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant())) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) @@ -197,6 +199,8 @@ public class RootControllerTest extends AbstractIntegrationTestWithMongoDB { } @Test + @Description("Ensures that the target state machine of a precomissioned target switches from " + + "UNKNOWN to REGISTERED when the target polls for the first time.") public void rootRsPrecommissioned() throws Exception { final Target target = new Target("4711"); targetManagement.createTarget(target); @@ -219,6 +223,7 @@ public class RootControllerTest extends AbstractIntegrationTestWithMongoDB { } @Test + @Description("Ensures that the source IP address of the polling target is correctly stored in repository") public void rootRsPlugAndPlayIpAddress() throws Exception { // test final String knownControllerId1 = "0815"; diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DistributionSetResourceTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DistributionSetResourceTest.java index 7eccf7196..6254da992 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DistributionSetResourceTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DistributionSetResourceTest.java @@ -47,7 +47,6 @@ import org.eclipse.hawkbit.repository.model.Target; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.junit.Ignore; import org.junit.Test; import org.springframework.context.annotation.Description; import org.springframework.http.MediaType; @@ -59,15 +58,8 @@ import com.jayway.jsonpath.JsonPath; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -/** - * - * - * - */ -@Features("Component Tests - Management RESTful API") +@Features("Component Tests - Management API") @Stories("Distribution Set Resource") -// TODO: fully document tests -> @Description for long text and reasonable -// method name as short text public class DistributionSetResourceTest extends AbstractIntegrationTest { @Test @@ -235,6 +227,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that multi target assignment through API is reflected by the repository.") public void assignMultipleTargetsToDistributionSet() throws Exception { // prepare distribution set final Set createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1); @@ -255,9 +248,13 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { .andExpect(status().isOk()).andExpect(jsonPath("$.assigned", equalTo(knownTargetIds.length - 1))) .andExpect(jsonPath("$.alreadyAssigned", equalTo(1))) .andExpect(jsonPath("$.total", equalTo(knownTargetIds.length))); + + assertThat(targetManagement.findTargetByAssignedDistributionSet(createdDs.getId(), pageReq).getContent()) + .as("Five targets in repository have DS assigned").hasSize(5); } @Test + @Description("Ensures that assigned targets of DS are returned as reflected by the repository.") public void getAssignedTargetsOfDistributionSet() throws Exception { // prepare distribution set final String knownTargetId = "knownTargetId1"; @@ -273,6 +270,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that assigned targets of DS are returned as persisted in the repository.") public void getAssignedTargetsOfDistributionSetIsEmpty() throws Exception { final Set createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1); final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next(); @@ -283,6 +281,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that installed targets of DS are returned as persisted in the repository.") public void getInstalledTargetsOfDistributionSet() throws Exception { // prepare distribution set final String knownTargetId = "knownTargetId1"; @@ -305,46 +304,50 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that DS in repository are listed with proper paging properties.") public void getDistributionSetsWithoutAddtionalRequestParameters() throws Exception { - final int modules = 5; - createDistributionSetsAlphabetical(modules); + final int sets = 5; + createDistributionSetsAlphabetical(sets); mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(modules))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(modules))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(modules))); + .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(sets))) + .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(sets))) + .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(sets))); } @Test + @Description("Ensures that DS in repository are listed with proper paging results with paging limit parameter.") public void getDistributionSetsWithPagingLimitRequestParameter() throws Exception { - final int modules = 5; + final int sets = 5; final int limitSize = 1; - createDistributionSetsAlphabetical(modules); + createDistributionSetsAlphabetical(sets); mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING) .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(modules))) + .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(sets))) .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize))) .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize))); } @Test + @Description("Ensures that DS in repository are listed with proper paging results with paging limit and offset parameter.") public void getDistributionSetsWithPagingLimitAndOffsetRequestParameter() throws Exception { - final int modules = 5; + final int sets = 5; final int offsetParam = 2; - final int expectedSize = modules - offsetParam; - createDistributionSetsAlphabetical(modules); + final int expectedSize = sets - offsetParam; + createDistributionSetsAlphabetical(sets); mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING) .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam)) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(modules))) + .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(sets))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(modules))) + .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(sets))) .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize))) .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize))); } @Test @WithUser(principal = "uploadTester", allSpPermissions = true) + @Description("Ensures that multiple DS requested are listed with expected payload.") public void getDistributionSets() throws Exception { // prepare test data assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0); @@ -389,6 +392,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { @Test @WithUser(principal = "uploadTester", allSpPermissions = true) + @Description("Ensures that single DS requested by ID is listed with expected payload.") public void getDistributionSet() throws Exception { final DistributionSet set = createTestDistributionSet(softwareManagement, distributionSetManagement); @@ -420,6 +424,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { @Test @WithUser(principal = "uploadTester", allSpPermissions = true) + @Description("Ensures that multipe DS posted to API are created in the repository.") public void createDistributionSets() throws JSONException, Exception { assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0); @@ -534,7 +539,8 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test - public void testDeleteUnassignedistributionSet() throws Exception { + @Description("Ensures that DS deletion request to API is reflected by the repository.") + public void deleteUnassignedistributionSet() throws Exception { // prepare test data assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0); @@ -553,7 +559,8 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test - public void testDeleteAssignedDistributionSet() throws Exception { + @Description("Ensures that assigned DS deletion request to API is reflected by the repository by means of deleted flag set.") + public void deleteAssignedDistributionSet() throws Exception { // prepare test data assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0); @@ -574,6 +581,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that DS property update request to API is reflected by the repository.") public void updateDistributionSet() throws Exception { // prepare test data @@ -601,6 +609,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that the server reacts properly to invalid requests (URI, Media Type, Methods) with correct reponses.") public void invalidRequestsOnDistributionSetsResource() throws Exception { final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement, distributionSetManagement); @@ -642,6 +651,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that the metadata creation through API is reflected by the repository.") public void createMetadata() throws Exception { final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement, distributionSetManagement); @@ -674,6 +684,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that a metadata update through API is reflected by the repository.") public void updateMetadata() throws Exception { // prepare and create metadata for update final String knownKey = "knownKey"; @@ -700,6 +711,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that a metadata entry deletion through API is reflected by the repository.") public void deleteMetadata() throws Exception { // prepare and create metadata for deletion final String knownKey = "knownKey"; @@ -722,6 +734,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that a metadata entry selection through API reflectes the repository content.") public void getSingleMetadata() throws Exception { // prepare and create metadata final String knownKey = "knownKey"; @@ -737,6 +750,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that a metadata entry paged list selection through API reflectes the repository content.") public void getPagedListofMetadata() throws Exception { final int totalMetadata = 10; @@ -760,6 +774,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that a DS search with query parameters returns the expected result.") public void searchDistributionSetRsql() throws Exception { final String dsSuffix = "test"; final int amount = 10; @@ -776,11 +791,13 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } - @Ignore @Test + @Description("Ensures that a DS search with complete==true parameter returns only DS that are actually completely filled with mandatory modules.") public void filterDistributionSetComplete() throws Exception { final int amount = 10; TestDataUtil.generateDistributionSets(amount, softwareManagement, distributionSetManagement); + distributionSetManagement.createDistributionSet(new DistributionSet("incomplete", "2", "incomplete", + distributionSetManagement.findDistributionSetTypeByKey("ecl_os"), null)); final String rsqlFindLikeDs1OrDs2 = "complete==" + Boolean.TRUE; @@ -790,6 +807,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that a DS assigned target search with controllerId==1 parameter returns only the target with the given ID.") public void searchDistributionSetAssignedTargetsRsql() throws Exception { // prepare distribution set final Set createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1); @@ -815,6 +833,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that a DS metadata filtered query with value==knownValue1 parameter returns only the metadata entries with that value.") public void searchDistributionSetMetadataRsql() throws Exception { final int totalMetadata = 10; final String knownKeyPrefix = "knownKey"; diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DistributionSetTypeResourceTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DistributionSetTypeResourceTest.java index 266b284ca..78f4f741e 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DistributionSetTypeResourceTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DistributionSetTypeResourceTest.java @@ -46,11 +46,8 @@ import ru.yandex.qatools.allure.annotations.Stories; /** * Test for {@link DistributionSetTypeResource}. * - * - * - * */ -@Features("Component Tests - Management RESTful API") +@Features("Component Tests - Management API") @Stories("Distribution Set Type Resource") public class DistributionSetTypeResourceTest extends AbstractIntegrationTest { diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DownloadResourceTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DownloadResourceTest.java index cc8f4f6b7..ee0fa52fe 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DownloadResourceTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DownloadResourceTest.java @@ -30,11 +30,7 @@ import org.springframework.context.annotation.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -/** - * - * - */ -@Features("Component Tests- Download Restful API") +@Features("Component Tests - Management API") @Stories("Download Resource") public class DownloadResourceTest extends AbstractIntegrationTestWithMongoDB { diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/RolloutResourceTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/RolloutResourceTest.java index ff9f0e7db..29cb4ede0 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/RolloutResourceTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/RolloutResourceTest.java @@ -47,7 +47,7 @@ import ru.yandex.qatools.allure.annotations.Stories; /** * Tests for covering the {@link RolloutResource}. */ -@Features("Component Tests - Management RESTful API") +@Features("Component Tests - Management API") @Stories("Rollout Resource") public class RolloutResourceTest extends AbstractIntegrationTest { @@ -99,7 +99,7 @@ public class RolloutResourceTest extends AbstractIntegrationTest { .andReturn(); } - @Description("TODO") + @Description("Ensures that the repository refuses to create rollout without a defined target filter set.") public void missingTargetFilterQueryInRollout() throws Exception { final String targetFilterQuery = null; @@ -435,7 +435,6 @@ public class RolloutResourceTest extends AbstractIntegrationTest { .andExpect(jsonPath("$content", hasSize(5))).andExpect(jsonPath("$total", equalTo(5))); } - // TODO @Test @Description("Start the rollout in async mode") public void startingRolloutSwitchesIntoRunningStateAsync() throws Exception { @@ -528,7 +527,6 @@ public class RolloutResourceTest extends AbstractIntegrationTest { } - // TODO copied code from sp-bic-test protected T doWithTimeout(final Callable callable, final SuccessCondition successCondition, final long timeout, final long pollInterval) throws Exception // NOPMD { diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SMRessourceMisingMongoDbConnectionTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SMRessourceMisingMongoDbConnectionTest.java index f9be088a4..664dc861c 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SMRessourceMisingMongoDbConnectionTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SMRessourceMisingMongoDbConnectionTest.java @@ -23,13 +23,16 @@ import org.junit.Test; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MvcResult; +import ru.yandex.qatools.allure.annotations.Description; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + /** * Tests {@link SoftwareModuleResource} in case of missing MongoDB connection. * - * - * - * */ +@Features("Component Tests - Management API") +@Stories("Download Resource") public class SMRessourceMisingMongoDbConnectionTest extends AbstractIntegrationTest { @BeforeClass @@ -40,7 +43,8 @@ public class SMRessourceMisingMongoDbConnectionTest extends AbstractIntegrationT } @Test - public void testMissingMongoDbConnection() throws Exception { + @Description("Ensures that the correct error code is returned in case MongoDB unavailable.") + public void missingMongoDbConnectionResultsInErrorAtUpload() throws Exception { assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); assertThat(artifactRepository.findAll()).hasSize(0); diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleResourceTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleResourceTest.java index 8079b5d52..0b8503d6b 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleResourceTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleResourceTest.java @@ -25,6 +25,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -49,6 +50,7 @@ import org.eclipse.hawkbit.rest.resource.model.artifact.ArtifactRest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import org.junit.Before; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.mock.web.MockMultipartFile; @@ -65,10 +67,17 @@ import ru.yandex.qatools.allure.annotations.Stories; * Tests for {@link SoftwareModuleResource} {@link RestController}. * */ -@Features("Component Tests - Management RESTful API") +@Features("Component Tests - Management API") @Stories("Software Module Resource") public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongoDB { + @Before + public void assertPreparationOfRepo() { + assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("no softwaremodule should be founded") + .hasSize(0); + assertThat(artifactRepository.findAll()).as("no artifacts should be founded").hasSize(0); + } + @Test @Description("Tests the update of software module metadata. It is verfied that only the selected fields for the update are really updated and the modification values are filled (i.e. updated by and at).") @WithUser(principal = "smUpdateTester", allSpPermissions = true) @@ -81,18 +90,14 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo final String updateVendor = "newVendor1"; final String updateDescription = "newDescription1"; - final SoftwareModule ah = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); - final SoftwareModule jvm = softwareManagement - .createSoftwareModule(new SoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, "")); - final SoftwareModule os = softwareManagement - .createSoftwareModule(new SoftwareModule(osType, "poky", "3.0.2", null, "")); + softwareManagement.createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + softwareManagement.createSoftwareModule(new SoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, "")); + softwareManagement.createSoftwareModule(new SoftwareModule(osType, "poky", "3.0.2", null, "")); SoftwareModule sm = new SoftwareModule(osType, knownSWName, knownSWVersion, knownSWDescription, knownSWVendor); sm = softwareManagement.createSoftwareModule(sm); - assertThat(sm.getName()).isEqualTo(knownSWName); - assertThat(sm.getName()).isEqualTo(knownSWName); + assertThat(sm.getName()).as("Wrong name of the software module").isEqualTo(knownSWName); final String body = new JSONObject().put("vendor", updateVendor).put("description", updateDescription) .put("name", "nameShouldNotBeChanged").toString(); @@ -112,20 +117,9 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo } - /** - * Test method for - * {@link org.eclipse.hawkbit.rest.resource.SoftwareModuleResource#uploadArtifact(java.lang.Long, org.springframework.web.multipart.MultipartFile)} - * . - * - * @throws Exception - * if test fails - */ @Test @Description("Tests the uppload of an artifact binary. The upload is executed and the content checked in the repository for completenes.") public void uploadArtifact() throws Exception { - // prepare repo - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); - assertThat(artifactRepository.findAll()).hasSize(0); SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null); sm = softwareManagement.createSoftwareModule(sm); assertThat(artifactRepository.findAll()).hasSize(0); @@ -152,36 +146,41 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo .convertArtifactResponse(mvcResult.getResponse().getContentAsString()); final Long artId = ((LocalArtifact) softwareManagement.findSoftwareModuleWithDetails(sm.getId()).getArtifacts() .get(0)).getId(); - assertThat(artResult.getArtifactId()).isEqualTo(artId); + assertThat(artResult.getArtifactId()).as("Wrong artifact id").isEqualTo(artId); assertThat(JsonPath.compile("$_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) + .as("Link contains no self url") .isEqualTo("http://localhost/rest/v1/softwaremodules/" + sm.getId() + "/artifacts/" + artId); assertThat( JsonPath.compile("$_links.download.href").read(mvcResult.getResponse().getContentAsString()).toString()) - .isEqualTo("http://localhost/rest/v1/softwaremodules/" + sm.getId() + "/artifacts/" + artId - + "/download"); + .as("response contains no download url ").isEqualTo("http://localhost/rest/v1/softwaremodules/" + + sm.getId() + "/artifacts/" + artId + "/download"); + assertArtifact(sm, random); + } + + private void assertArtifact(final SoftwareModule sm, final byte[] random) throws IOException { // check result in db... // repo - assertThat(artifactRepository.findAll()).hasSize(1); + assertThat(artifactRepository.findAll()).as("Wrong artifact size").hasSize(1); // binary - assertTrue(IOUtils.contentEquals(new ByteArrayInputStream(random), - artifactManagement - .loadLocalArtifactBinary((LocalArtifact) softwareManagement - .findSoftwareModuleWithDetails(sm.getId()).getArtifacts().get(0)) - .getFileInputStream())); + assertTrue("Wrong artifact content", + IOUtils.contentEquals(new ByteArrayInputStream(random), + artifactManagement + .loadLocalArtifactBinary((LocalArtifact) softwareManagement + .findSoftwareModuleWithDetails(sm.getId()).getArtifacts().get(0)) + .getFileInputStream())); // hashes assertThat(artifactManagement.findLocalArtifactByFilename("origFilename").get(0).getSha1Hash()) - .isEqualTo(HashGeneratorUtils.generateSHA1(random)); + .as("Wrong sha1 hash").isEqualTo(HashGeneratorUtils.generateSHA1(random)); assertThat(artifactManagement.findLocalArtifactByFilename("origFilename").get(0).getMd5Hash()) - .isEqualTo(HashGeneratorUtils.generateMD5(random)); + .as("Wrong md5 hash").isEqualTo(HashGeneratorUtils.generateMD5(random)); // metadata assertThat(((LocalArtifact) softwareManagement.findSoftwareModuleWithDetails(sm.getId()).getArtifacts().get(0)) - .getFilename()).isEqualTo("origFilename"); - + .getFilename()).as("wrong metadata of the filename").isEqualTo("origFilename"); } @Test @@ -203,9 +202,6 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo @Test @Description("Verfies that the system does not accept identical artifacts uploads for the same software module. Expected response: CONFLICT") public void duplicateUploadArtifact() throws Exception { - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); - assertThat(artifactRepository.findAll()).hasSize(0); - SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null); sm = softwareManagement.createSoftwareModule(sm); @@ -228,9 +224,6 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo @Test @Description("verfies that option to upload artifacts with a custom defined by metadata, i.e. not the file name of the binary itself.") public void uploadArtifactWithCustomName() throws Exception { - // prepare repo - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); - assertThat(artifactRepository.findAll()).hasSize(0); SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null); sm = softwareManagement.createSoftwareModule(sm); assertThat(artifactRepository.findAll()).hasSize(0); @@ -245,22 +238,19 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo .andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$providedFilename", equalTo("customFilename"))).andExpect(status().isCreated()); - ; // check result in db... // repo - assertThat(artifactRepository.findAll()).hasSize(1); + assertThat(artifactRepository.findAll()).as("Artifact size is wring").hasSize(1); // hashes - assertThat(artifactManagement.findLocalArtifactByFilename("customFilename")).hasSize(1); + assertThat(artifactManagement.findLocalArtifactByFilename("customFilename")).as("Local artifact is wrong") + .hasSize(1); } @Test @Description("Verfies that the system refuses upload of an artifact where the provided hash sums do not match. Expected result: BAD REQUEST") public void uploadArtifactWithHashCheck() throws Exception { - // prepare repo - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); - assertThat(artifactRepository.findAll()).hasSize(0); SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null); sm = softwareManagement.createSoftwareModule(sm); assertThat(artifactRepository.findAll()).hasSize(0); @@ -280,7 +270,8 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo // check error result ExceptionInfo exceptionInfo = ResourceUtility.convertException(mvcResult.getResponse().getContentAsString()); - assertThat(exceptionInfo.getErrorCode()).isEqualTo(SpServerError.SP_ARTIFACT_UPLOAD_FAILED_SHA1_MATCH.getKey()); + assertThat(exceptionInfo.getErrorCode()).as("Exception contains wrong error code") + .isEqualTo(SpServerError.SP_ARTIFACT_UPLOAD_FAILED_SHA1_MATCH.getKey()); // wrong md5 mvcResult = mvc @@ -290,42 +281,20 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo // check error result exceptionInfo = ResourceUtility.convertException(mvcResult.getResponse().getContentAsString()); - assertThat(exceptionInfo.getErrorCode()).isEqualTo(SpServerError.SP_ARTIFACT_UPLOAD_FAILED_MD5_MATCH.getKey()); + assertThat(exceptionInfo.getErrorCode()).as("Exception contains wrong error code") + .isEqualTo(SpServerError.SP_ARTIFACT_UPLOAD_FAILED_MD5_MATCH.getKey()); mvc.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file) .param("md5sum", md5sum).param("sha1sum", sha1sum)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isCreated()); - // check result... - // repo - assertThat(artifactRepository.findAll()).hasSize(1); - - // binary - assertTrue(IOUtils.contentEquals(new ByteArrayInputStream(random), - artifactManagement - .loadLocalArtifactBinary((LocalArtifact) softwareManagement - .findSoftwareModuleWithDetails(sm.getId()).getArtifacts().get(0)) - .getFileInputStream())); - - // hashes - assertThat(artifactManagement.findLocalArtifactByFilename("origFilename").get(0).getSha1Hash()) - .isEqualTo(HashGeneratorUtils.generateSHA1(random)); - - assertThat(artifactManagement.findLocalArtifactByFilename("origFilename").get(0).getMd5Hash()) - .isEqualTo(md5sum); - - // metadata - assertThat(((LocalArtifact) softwareManagement.findSoftwareModuleWithDetails(sm.getId()).getArtifacts().get(0)) - .getFilename()).isEqualTo("origFilename"); + assertArtifact(sm, random); } @Test @Description("Tests binary download of an artifact including verfication that the downloaded binary is consistent and that the etag header is as expected identical to the SHA1 hash of the file.") public void downloadArtifact() throws Exception { - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); - assertThat(artifactRepository.findAll()).hasSize(0); - SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null); sm = softwareManagement.createSoftwareModule(sm); @@ -342,7 +311,7 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo .andExpect(header().string("ETag", artifact.getSha1Hash())) .andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM)).andReturn(); - assertTrue(Arrays.equals(result.getResponse().getContentAsByteArray(), random)); + assertTrue("Wrong response content", Arrays.equals(result.getResponse().getContentAsByteArray(), random)); final MvcResult result2 = mvc .perform(get("/rest/v1/softwaremodules/{smId}/artifacts/{artId}/download", sm.getId(), @@ -350,19 +319,16 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo .andExpect(header().string("ETag", artifact2.getSha1Hash())) .andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM)).andReturn(); - assertTrue(Arrays.equals(result2.getResponse().getContentAsByteArray(), random)); + assertTrue("Response has wrong response content", + Arrays.equals(result2.getResponse().getContentAsByteArray(), random)); - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(1); - assertThat(artifactRepository.findAll()).hasSize(2); + assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremodule size is wrong").hasSize(1); + assertThat(artifactRepository.findAll()).as("Wrong artifact repostiory").hasSize(2); } @Test @Description("Verifies the listing of one defined artifact assigned to a given software module. That includes the artifact metadata and download links.") public void getArtifact() throws Exception { - // check baseline - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); - assertThat(artifactRepository.findAll()).hasSize(0); - // prepare data for test SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null); sm = softwareManagement.createSoftwareModule(sm); @@ -548,8 +514,6 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo @WithUser(principal = "uploadTester", allSpPermissions = true) @Description("Test retrieval of all software modules the user has access to.") public void getSoftwareModules() throws Exception { - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); - SoftwareModule os = new SoftwareModule(osType, "name1", "version1", "description1", "vendor1"); os = softwareManagement.createSoftwareModule(os); @@ -612,14 +576,12 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo .andExpect(jsonPath("$content.[?(@.id==" + ah.getId() + ")][0]._links.self.href", equalTo("http://localhost/rest/v1/softwaremodules/" + ah.getId()))); - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(3); + assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremodule size is wrong").hasSize(3); } @Test @Description("Test the various filter parameters, e.g. filter by name or type of the module.") public void getSoftwareModulesWithFilterParameters() throws Exception { - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); - SoftwareModule os1 = new SoftwareModule(osType, "osName1", "1.0.0", "description1", "vendor1"); os1 = softwareManagement.createSoftwareModule(os1); @@ -712,8 +674,6 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo @WithUser(principal = "uploadTester", allSpPermissions = true) @Description("Tests GET request on /rest/v1/softwaremodules/{smId}.") public void getSoftareModule() throws Exception { - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); - SoftwareModule os = new SoftwareModule(osType, "name1", "version1", "description1", "vendor1"); os = softwareManagement.createSoftwareModule(os); @@ -771,15 +731,13 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo .andExpect(jsonPath("$_links.artifacts.href", equalTo("http://localhost/rest/v1/softwaremodules/" + ah.getId() + "/artifacts"))); - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(3); + assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremodule size is wrong").hasSize(3); } @Test @WithUser(principal = "uploadTester", allSpPermissions = true) @Description("Verfies that the create request actually results in the creation of the modules in the repository.") public void createSoftwareModules() throws JSONException, Exception { - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); - final SoftwareModule os = new SoftwareModule(osType, "name1", "version1", "description1", "vendor1"); final SoftwareModule jvm = new SoftwareModule(runtimeType, "name2", "version1", "description1", "vendor1"); final SoftwareModule ah = new SoftwareModule(appType, "name3", "version1", "description1", "vendor1"); @@ -824,74 +782,75 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo assertThat( JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) + .as("Response contains invalid self href") .isEqualTo("http://localhost/rest/v1/softwaremodules/" + osCreated.getId()); assertThat(JsonPath.compile("[0]_links.artifacts.href").read(mvcResult.getResponse().getContentAsString()) - .toString()).isEqualTo("http://localhost/rest/v1/softwaremodules/" + osCreated.getId() + "/artifacts"); + .toString()).as("Response contains invalid artifacts href") + .isEqualTo("http://localhost/rest/v1/softwaremodules/" + osCreated.getId() + "/artifacts"); assertThat( JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) + .as("Response contains invalid self href") .isEqualTo("http://localhost/rest/v1/softwaremodules/" + jvmCreated.getId()); assertThat(JsonPath.compile("[1]_links.artifacts.href").read(mvcResult.getResponse().getContentAsString()) - .toString()).isEqualTo("http://localhost/rest/v1/softwaremodules/" + jvmCreated.getId() + "/artifacts"); + .toString()).as("Response contains invalid artfacts href") + .isEqualTo("http://localhost/rest/v1/softwaremodules/" + jvmCreated.getId() + "/artifacts"); assertThat( JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) + .as("Response contains links self href") .isEqualTo("http://localhost/rest/v1/softwaremodules/" + ahCreated.getId()); assertThat(JsonPath.compile("[2]_links.artifacts.href").read(mvcResult.getResponse().getContentAsString()) - .toString()).isEqualTo("http://localhost/rest/v1/softwaremodules/" + ahCreated.getId() + "/artifacts"); + .toString()).as("Response contains invalid artifacts href") + .isEqualTo("http://localhost/rest/v1/softwaremodules/" + ahCreated.getId() + "/artifacts"); - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(3); + assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Wrong softwaremodule size").hasSize(3); assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType).getContent().get(0).getName()) - .isEqualTo(os.getName()); + .as("Softwaremoudle name is wrong").isEqualTo(os.getName()); assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType).getContent().get(0).getCreatedBy()) - .isEqualTo("uploadTester"); + .as("Softwaremoudle created by is wrong").isEqualTo("uploadTester"); assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType).getContent().get(0).getCreatedAt()) - .isGreaterThanOrEqualTo(current); + .as("Softwaremoudle created at is wrong").isGreaterThanOrEqualTo(current); assertThat(softwareManagement.findSoftwareModulesByType(pageReq, runtimeType).getContent().get(0).getName()) - .isEqualTo(jvm.getName()); + .as("Softwaremoudle name is wrong").isEqualTo(jvm.getName()); assertThat(softwareManagement.findSoftwareModulesByType(pageReq, appType).getContent().get(0).getName()) - .isEqualTo(ah.getName()); + .as("Softwaremoudle name is wrong").isEqualTo(ah.getName()); } @Test @Description("Verifies successfull deletion of software modules that are not in use, i.e. assigned to a DS.") public void deleteUnassignedSoftwareModule() throws Exception { - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).isEmpty(); - assertThat(artifactRepository.findAll()).isEmpty(); SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null); sm = softwareManagement.createSoftwareModule(sm); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); - final Artifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm.getId(), - "file1", false); + artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm.getId(), "file1", false); - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(1); - assertThat(artifactRepository.findAll()).hasSize(1); - assertThat(softwareModuleRepository.findAll()).hasSize(1); + assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremoudle size is wrong").hasSize(1); + assertThat(artifactRepository.findAll()).as("artifact site is wrong").hasSize(1); + assertThat(softwareModuleRepository.findAll()).as("Softwaremoudle size is wrong").hasSize(1); mvc.perform(delete("/rest/v1/softwaremodules/{smId}", sm.getId())).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).isEmpty(); - assertThat(softwareModuleRepository.findAll()).isEmpty(); - assertThat(artifactRepository.findAll()).isEmpty(); + assertThat(softwareManagement.findSoftwareModulesAll(pageReq)) + .as("After delete no softwarmodule should be available").isEmpty(); + assertThat(softwareModuleRepository.findAll()).as("After delete no softwarmodule should be available") + .isEmpty(); + assertThat(artifactRepository.findAll()).as("After delete no artifact should be available").isEmpty(); } @Test @Description("Verifies successfull deletion of software modules that are in use, i.e. assigned to a DS which should result in movinf the module to the archive.") public void deleteAssignedSoftwareModule() throws Exception { - // check baseline - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).isEmpty(); - assertThat(artifactRepository.findAll()).isEmpty(); - final DistributionSet ds1 = TestDataUtil.generateDistributionSet("a", softwareManagement, distributionSetManagement); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); - final LocalArtifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), + artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), ds1.findFirstModuleByType(appType).getId(), "file1", false); assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(3); @@ -906,17 +865,17 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); // all 3 are now marked as deleted - assertThat(softwareManagement.findSoftwareModulesAll(pageReq).getNumber()).isEqualTo(0); - assertThat(softwareModuleRepository.findAll()).hasSize(3); - assertThat(artifactRepository.findAll()).hasSize(1); + assertThat(softwareManagement.findSoftwareModulesAll(pageReq).getNumber()) + .as("After delete no softwarmodule should be available").isEqualTo(0); + assertThat(softwareModuleRepository.findAll()).as("After delete no softwarmodule should marked as deleted") + .hasSize(3); + assertThat(artifactRepository.findAll()).as("After delete artifact should available for marked as deleted sm's") + .hasSize(1); } @Test @Description("Tests the deletion of an artifact including verfication that the artifact is actually erased in the repository and removed from the software module.") public void deleteArtifact() throws Exception { - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).isEmpty(); - assertThat(artifactRepository.findAll()).isEmpty(); - // Create 1 SM SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null); sm = softwareManagement.createSoftwareModule(sm); @@ -926,8 +885,7 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo // Create 2 artifacts final LocalArtifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm.getId(), "file1", false); - final LocalArtifact artifact2 = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), - sm.getId(), "file2", false); + artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm.getId(), "file2", false); // check repo before delete assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(1); @@ -940,9 +898,12 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); // check that only one artifact is still alive and still assigned - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(1); - assertThat(artifactRepository.findAll()).hasSize(1); - assertThat(softwareManagement.findSoftwareModuleWithDetails(sm.getId()).getArtifacts()).hasSize(1); + assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("After the sm should be marked as deleted") + .hasSize(1); + assertThat(artifactRepository.findAll()).as("After delete artifact should available for marked as deleted sm's") + .hasSize(1); + assertThat(softwareManagement.findSoftwareModuleWithDetails(sm.getId()).getArtifacts()) + .as("After delete artifact should available for marked as deleted sm's").hasSize(1); } @@ -972,8 +933,8 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo final SoftwareModuleMetadata metaKey1 = softwareManagement.findOne(new SwMetadataCompositeKey(sm, knownKey1)); final SoftwareModuleMetadata metaKey2 = softwareManagement.findOne(new SwMetadataCompositeKey(sm, knownKey2)); - assertThat(metaKey1.getValue()).isEqualTo(knownValue1); - assertThat(metaKey2.getValue()).isEqualTo(knownValue2); + assertThat(metaKey1.getValue()).as("Metadata key is wrong").isEqualTo(knownValue1); + assertThat(metaKey2.getValue()).as("Metadata key is wrong").isEqualTo(knownValue2); } @Test @@ -997,7 +958,7 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo .andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue))); final SoftwareModuleMetadata assertDS = softwareManagement.findOne(new SwMetadataCompositeKey(sm, knownKey)); - assertThat(assertDS.getValue()).isEqualTo(updateValue); + assertThat(assertDS.getValue()).as("Metadata is wrong").isEqualTo(updateValue); } @Test diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleTypeResourceTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleTypeResourceTest.java index c6aedddd4..fefe2a440 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleTypeResourceTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleTypeResourceTest.java @@ -43,11 +43,8 @@ import ru.yandex.qatools.allure.annotations.Stories; /** * Test for {@link SoftwareModuleTypeResource}. * - * - * - * */ -@Features("Component Tests - Management RESTful API") +@Features("Component Tests - Management API") @Stories("Software Module Type Resource") public class SoftwareModuleTypeResourceTest extends AbstractIntegrationTest { diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SortUtilityTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SortUtilityTest.java index d915c4e9e..09a90c39c 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SortUtilityTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SortUtilityTest.java @@ -24,7 +24,7 @@ import ru.yandex.qatools.allure.annotations.Stories; /** * */ -@Features("Component Tests - Management RESTful API") +@Features("Component Tests - Management API") @Stories("Sorting parameter") public class SortUtilityTest { private static final String SORT_PARAM_1 = "NAME:ASC"; diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SystemManagementResourceTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SystemManagementResourceTest.java index 8d8f9a2e4..76cd68d64 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SystemManagementResourceTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SystemManagementResourceTest.java @@ -40,7 +40,7 @@ import ru.yandex.qatools.allure.annotations.Stories; * * */ -@Features("Component Tests - System Management RESTful API") +@Features("Component Tests - Management API") @Stories("System Management Resource") public class SystemManagementResourceTest extends AbstractIntegrationTestWithMongoDB { diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/TargetResourceTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/TargetResourceTest.java index 9db578fe4..a8ebfdd9d 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/TargetResourceTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/TargetResourceTest.java @@ -11,6 +11,7 @@ package org.eclipse.hawkbit.rest.resource; import static org.fest.assertions.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.hasSize; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; @@ -34,6 +35,7 @@ import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.WithUser; import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.im.authentication.SpPermission; +import org.eclipse.hawkbit.repository.ActionFields; import org.eclipse.hawkbit.repository.ActionStatusFields; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.model.Action; @@ -66,16 +68,11 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; /** - * * Spring MVC Tests against the TargetResource. * - * - * */ -@Features("Component Tests - Management RESTful API") +@Features("Component Tests - Management API") @Stories("Target Resource") -// TODO: fully document tests -> @Description for long text and reasonable -// method name as short text public class TargetResourceTest extends AbstractIntegrationTest { private static final String TARGET_DESCRIPTION_TEST = "created in test"; @@ -103,10 +100,8 @@ public class TargetResourceTest extends AbstractIntegrationTest { private static final String JSON_PATH_CONTROLLERID = JSON_PATH_ROOT + JSON_PATH_FIELD_CONTROLLERID; private static final String JSON_PATH_DESCRIPTION = JSON_PATH_ROOT + JSON_PATH_FIELD_DESCRIPTION; - // TODO kzimmerm: test *modified after entity change - @Test - // MECS-1064 + @Description("Ensures that actions list is in exptected order.") public void getActionStatusReturnsCorrectType() throws Exception { final int limitSize = 2; final String knownTargetId = "targetId"; @@ -116,31 +111,29 @@ public class TargetResourceTest extends AbstractIntegrationTest { new ActionStatus(actions.get(0), Status.FINISHED, System.currentTimeMillis(), "testmessage"), actions.get(0)); - final PageRequest pageRequest = new PageRequest(0, 1000, Direction.ASC, ActionStatusFields.ID.getFieldName()); + final PageRequest pageRequest = new PageRequest(0, 1000, Direction.ASC, ActionFields.ID.getFieldName()); + final ActionStatus status = deploymentManagement + .findActionsByTarget(pageRequest, targetManagement.findTargetByControllerID(knownTargetId)).getContent() + .get(0).getActionStatus().stream().sorted((e1, e2) -> Long.compare(e2.getId(), e1.getId())) + .collect(Collectors.toList()).get(0); - // limit to 1 - first page -> standard cancel message - final Long reportAt = deploymentManagement - .findActionsByTarget(pageRequest, targetManagement.findTargetByControllerID(knownTargetId)).getContent() - .get(0).getCreatedAt(); - final Long id = deploymentManagement - .findActionsByTarget(pageRequest, targetManagement.findTargetByControllerID(knownTargetId)).getContent() - .get(0).getId(); mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + RestConstants.TARGET_V1_ACTIONS + "/" + actions.get(0).getId() + "/status") .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)) - .param(RestConstants.REQUEST_PARAMETER_SORTING, "ID:ASC")) + .param(RestConstants.REQUEST_PARAMETER_SORTING, "ID:DESC")) .andExpect(status().isOk()).andDo(MockMvcResultPrinter.print()) .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(3))) .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize))) .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize))) - .andExpect(jsonPath("content.[0].id", equalTo(id.intValue()))) + .andExpect(jsonPath("content.[0].id", equalTo(status.getId().intValue()))) .andExpect(jsonPath("content.[0].type", equalTo("finished"))) .andExpect(jsonPath("content.[0].messages", hasSize(1))) - .andExpect(jsonPath("content.[0].reportedAt", equalTo(reportAt))) + .andExpect(jsonPath("content.[0].reportedAt", equalTo(status.getCreatedAt().longValue()))) .andExpect(jsonPath("content.[1].type", equalTo("canceling"))); } @Test + @Description("Ensures that security token is not returned if user does not have READ_TARGET_SEC_TOKEN permission.") @WithUser(allSpPermissions = false, authorities = { SpPermission.READ_TARGET, SpPermission.CREATE_TARGET }) public void securityTokenIsNotInResponseIfMissingPermission() throws Exception { @@ -152,6 +145,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that security token is returned if user does have READ_TARGET_SEC_TOKEN permission.") @WithUser(allSpPermissions = false, authorities = { SpPermission.READ_TARGET, SpPermission.CREATE_TARGET, SpPermission.READ_TARGET_SEC_TOKEN }) public void securityTokenIsInResponseWithCorrectPermission() throws Exception { @@ -164,6 +158,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that that IP address is in result as stored in the repository.") public void addressAndIpAddressInTargetResult() throws Exception { // prepare targets with IP final String knownControllerId1 = "0815"; @@ -195,6 +190,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that actions history is returned as defined by filter status==pending,status==finished.") public void searchActionsRsql() throws Exception { // prepare test @@ -227,9 +223,10 @@ public class TargetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that a deletion of an active action results in cancelation triggered.") public void cancelActionOK() throws Exception { // prepare test - Target tA = createTargetAndStartAction(); + final Target tA = createTargetAndStartAction(); // test - cancel the active action mvc.perform(delete(RestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}", @@ -250,9 +247,10 @@ public class TargetResourceTest extends AbstractIntegrationTest { } @Test - public void cancelAnCancelActionIsNotAllowed() throws Exception { + @Description("Ensures that method not allowed is returned if cancelation is triggered on already canceled action.") + public void cancelAndCancelActionIsNotAllowed() throws Exception { // prepare test - Target tA = createTargetAndStartAction(); + final Target tA = createTargetAndStartAction(); // cancel the active action deploymentManagement.cancelAction(tA.getActions().get(0), tA); @@ -272,7 +270,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { @Description("Force Quit an Action, which is already canceled. Expected Result is an HTTP response code 204.") public void forceQuitAnCanceledActionReturnsOk() throws Exception { - Target tA = createTargetAndStartAction(); + final Target tA = createTargetAndStartAction(); // cancel the active action deploymentManagement.cancelAction(tA.getActions().get(0), tA); @@ -293,7 +291,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { @Description("Force Quit an Action, which is not canceled. Expected Result is an HTTP response code 405.") public void forceQuitAnNotCanceledActionReturnsMethodNotAllowed() throws Exception { - Target tA = createTargetAndStartAction(); + final Target tA = createTargetAndStartAction(); // test - cancel an cancel action returns forbidden mvc.perform(delete(RestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}?force=true", @@ -302,6 +300,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that deletion is executed if permitted.") public void deleteTargetReturnsOK() throws Exception { final String knownControllerId = "knownControllerIdDelete"; targetManagement.createTarget(new Target(knownControllerId)); @@ -314,6 +313,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that deletion is refused with not found if target does not exist.") public void deleteTargetWhichDoesNotExistsLeadsToEntityNotFound() throws Exception { final String knownControllerId = "knownControllerIdDelete"; @@ -322,6 +322,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that update is refused with not found if target does not exist.") public void updateTargetWhichDoesNotExistsLeadsToEntityNotFound() throws Exception { final String knownControllerId = "knownControllerIdUpdate"; mvc.perform(put(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content("{}") @@ -330,6 +331,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that target update request is reflected by repository.") public void updateTargetDescription() throws Exception { final String knownControllerId = "123"; final String knownNewDescription = "a new desc updated over rest"; @@ -354,6 +356,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that target query returns list of targets in defined format.") public void getTargetWithoutAddtionalRequestParameters() throws Exception { final int knownTargetAmount = 3; final String idA = "a"; @@ -393,6 +396,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { } @Test + @Description("Ensures that target query returns list of targets in defined format in size reduced by given limit parameter.") public void getTargetWithPagingLimitRequestParameter() throws Exception { final int knownTargetAmount = 3; final int limitSize = 1; @@ -413,10 +417,10 @@ public class TargetResourceTest extends AbstractIntegrationTest { .andExpect(jsonPath("$content.[?(@.name==" + idA + ")][0].controllerId", equalTo(idA))) .andExpect(jsonPath("$content.[?(@.name==" + idA + ")][0].createdBy", equalTo("bumlux"))) .andExpect(jsonPath("$content.[?(@.name==" + idA + ")][0].updateStatus", equalTo("unknown"))); - } @Test + @Description("Ensures that target query returns list of targets in defined format in size reduced by given limit and offset parameter.") public void getTargetWithPagingLimitAndOffsetRequestParameter() throws Exception { final int knownTargetAmount = 5; final int offsetParam = 2; @@ -834,7 +838,8 @@ public class TargetResourceTest extends AbstractIntegrationTest { final List actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId); mvc.perform(get( - RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + RestConstants.TARGET_V1_ACTIONS)) + RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + RestConstants.TARGET_V1_ACTIONS) + .param(RestConstants.REQUEST_PARAMETER_SORTING, "ID:ASC")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("content.[1].id", equalTo(actions.get(1).getId().intValue()))) .andExpect(jsonPath("content.[1].type", equalTo("update"))) @@ -851,6 +856,108 @@ public class TargetResourceTest extends AbstractIntegrationTest { .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(2))); } + @Test + @Description("Verfies that the API returns the status list with expected content.") + public void getMultipleActionStatus() throws Exception { + final String knownTargetId = "targetId"; + final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0); + // retrieve list in default descending order for actionstaus entries + final List actionStatus = action.getActionStatus().stream() + .sorted((e1, e2) -> Long.compare(e2.getId(), e1.getId())).collect(Collectors.toList()); + + // sort is default descending order, latest status first + mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + RestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS)) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + .andExpect(jsonPath("content.[0].id", equalTo(actionStatus.get(0).getId().intValue()))) + .andExpect(jsonPath("content.[0].type", equalTo("canceling"))) + .andExpect(jsonPath("content.[0].messages", hasItem("manual cancelation requested"))) + .andExpect(jsonPath("content.[0].reportedAt", equalTo(actionStatus.get(0).getCreatedAt()))) + .andExpect(jsonPath("content.[1].id", equalTo(actionStatus.get(1).getId().intValue()))) + .andExpect(jsonPath("content.[1].type", equalTo("running"))) + .andExpect(jsonPath("content.[1].reportedAt", equalTo(actionStatus.get(1).getCreatedAt()))) + .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(2))) + .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(2))) + .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(2))); + } + + @Test + @Description("Verfies that the API returns the status list with expected content sorted by reportedAt field.") + public void getMultipleActionStatusSortedByReportedAt() throws Exception { + final String knownTargetId = "targetId"; + final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0); + final List actionStatus = action.getActionStatus().stream() + .sorted((e1, e2) -> Long.compare(e1.getId(), e2.getId())).collect(Collectors.toList()); + + // descending order + mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + RestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS) + .param(RestConstants.REQUEST_PARAMETER_SORTING, "REPORTEDAT:DESC")) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + .andExpect(jsonPath("content.[0].id", equalTo(actionStatus.get(1).getId().intValue()))) + .andExpect(jsonPath("content.[0].type", equalTo("canceling"))) + .andExpect(jsonPath("content.[0].messages", hasItem("manual cancelation requested"))) + .andExpect(jsonPath("content.[0].reportedAt", equalTo(actionStatus.get(1).getCreatedAt()))) + .andExpect(jsonPath("content.[1].id", equalTo(actionStatus.get(0).getId().intValue()))) + .andExpect(jsonPath("content.[1].type", equalTo("running"))) + .andExpect(jsonPath("content.[1].reportedAt", equalTo(actionStatus.get(0).getCreatedAt()))) + .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(2))) + .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(2))) + .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(2))); + + // ascending order + mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + RestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS) + .param(RestConstants.REQUEST_PARAMETER_SORTING, "REPORTEDAT:ASC")) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + .andExpect(jsonPath("content.[1].id", equalTo(actionStatus.get(1).getId().intValue()))) + .andExpect(jsonPath("content.[1].type", equalTo("canceling"))) + .andExpect(jsonPath("content.[1].messages", hasItem("manual cancelation requested"))) + .andExpect(jsonPath("content.[1].reportedAt", equalTo(actionStatus.get(1).getCreatedAt()))) + .andExpect(jsonPath("content.[0].id", equalTo(actionStatus.get(0).getId().intValue()))) + .andExpect(jsonPath("content.[0].type", equalTo("running"))) + .andExpect(jsonPath("content.[0].reportedAt", equalTo(actionStatus.get(0).getCreatedAt()))) + .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(2))) + .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(2))) + .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(2))); + } + + @Test + @Description("Verfies that the API returns the status list with expected content split into two pages.") + public void getMultipleActionStatusWithPagingLimitRequestParameter() throws Exception { + final String knownTargetId = "targetId"; + + final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0); + final List actionStatus = action.getActionStatus().stream() + .sorted((e1, e2) -> Long.compare(e1.getId(), e2.getId())).collect(Collectors.toList()); + + // Page 1 + mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + RestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS) + .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(1))) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + .andExpect(jsonPath("content.[0].id", equalTo(actionStatus.get(1).getId().intValue()))) + .andExpect(jsonPath("content.[0].type", equalTo("canceling"))) + .andExpect(jsonPath("content.[0].messages", hasItem("manual cancelation requested"))) + .andExpect(jsonPath("content.[0].reportedAt", equalTo(actionStatus.get(1).getCreatedAt()))) + .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(2))) + .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(1))) + .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(1))); + + // Page 2 + mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + RestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS) + .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(1)) + .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(1))) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + .andExpect(jsonPath("content.[0].id", equalTo(actionStatus.get(0).getId().intValue()))) + .andExpect(jsonPath("content.[0].type", equalTo("running"))) + .andExpect(jsonPath("content.[0].reportedAt", equalTo(actionStatus.get(0).getCreatedAt()))) + .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(2))) + .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(1))) + .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(1))); + } + @Test public void getMultipleActionsWithPagingLimitRequestParameter() throws Exception { final String knownTargetId = "targetId"; @@ -859,7 +966,8 @@ public class TargetResourceTest extends AbstractIntegrationTest { // page 1: one entry mvc.perform(get( RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + RestConstants.TARGET_V1_ACTIONS) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(1))) + .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(1)) + .param(RestConstants.REQUEST_PARAMETER_SORTING, "ID:ASC")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("content.[0].id", equalTo(actions.get(0).getId().intValue()))) .andExpect(jsonPath("content.[0].type", equalTo("cancel"))) @@ -874,7 +982,9 @@ public class TargetResourceTest extends AbstractIntegrationTest { mvc.perform(get( RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + RestConstants.TARGET_V1_ACTIONS) .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(1)) - .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(1))) + .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(1)) + .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(1)) + .param(RestConstants.REQUEST_PARAMETER_SORTING, "ID:ASC")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("content.[0].id", equalTo(actions.get(1).getId().intValue()))) .andExpect(jsonPath("content.[0].type", equalTo("update"))) @@ -902,7 +1012,8 @@ public class TargetResourceTest extends AbstractIntegrationTest { + "?offset=0&limit=50&sort=id:DESC"; } - private List generateTargetWithTwoUpdatesWithOneOverride(final String knownTargetId) { + private List generateTargetWithTwoUpdatesWithOneOverride(final String knownTargetId) + throws InterruptedException { final PageRequest pageRequest = new PageRequest(0, 100, Direction.ASC, ActionStatusFields.ID.getFieldName()); @@ -920,6 +1031,8 @@ public class TargetResourceTest extends AbstractIntegrationTest { final List updatedTargets = deploymentManagement.assignDistributionSet(one, targets) .getAssignedTargets(); // 2nd update + // sleep 10ms to ensure that we can sort by reportedAt + Thread.sleep(10); deploymentManagement.assignDistributionSet(two, updatedTargets); // two updates, one cancelation @@ -946,54 +1059,6 @@ public class TargetResourceTest extends AbstractIntegrationTest { equalTo(generateStatusreferenceLink(knownTargetId, actions.get(1))))); } - @Test - public void getActionStatusWithMultipleResultsWithPagingLimitRequestParameter() throws Exception { - final int limitSize = 1; - final String knownTargetId = "targetId"; - final List actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId); - actions.get(0).setStatus(Status.RUNNING); - controllerManagament.addUpdateActionStatus( - new ActionStatus(actions.get(0), Status.RUNNING, System.currentTimeMillis(), "testmessage"), - actions.get(0)); - - final PageRequest pageRequest = new PageRequest(0, 1000, Direction.ASC, ActionStatusFields.ID.getFieldName()); - - // limit to 1 - first page -> standard cancel message - Long reportAt = deploymentManagement - .findActionsByTarget(pageRequest, targetManagement.findTargetByControllerID(knownTargetId)).getContent() - .get(0).getCreatedAt(); - Long id = deploymentManagement - .findActionsByTarget(pageRequest, targetManagement.findTargetByControllerID(knownTargetId)).getContent() - .get(0).getId(); - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + actions.get(0).getId() + "/status") - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize))) - .andExpect(status().isOk()).andDo(MockMvcResultPrinter.print()) - .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(3))) - .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize))) - .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize))) - .andExpect(jsonPath("content.[0].id", equalTo(id.intValue()))) - .andExpect(jsonPath("content.[0].type", equalTo("running"))) - .andExpect(jsonPath("content.[0].messages", hasSize(1))) - .andExpect(jsonPath("content.[0].reportedAt", equalTo(reportAt))); - - // limit to 1 - first page -> added custom message - reportAt = deploymentManagement - .findActionsByTarget(pageRequest, targetManagement.findTargetByControllerID(knownTargetId)).getContent() - .get(1).getCreatedAt(); - id = deploymentManagement - .findActionsByTarget(pageRequest, targetManagement.findTargetByControllerID(knownTargetId)).getContent() - .get(1).getCreatedAt(); - - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + actions.get(0).getId() + "/status") - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)) - .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(1))) - .andExpect(status().isOk()).andDo(MockMvcResultPrinter.print()) - .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(3))) - .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(1))); - } - @Test public void assignDistributionSetToTarget() throws Exception { @@ -1232,7 +1297,8 @@ public class TargetResourceTest extends AbstractIntegrationTest { // prepare test final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement, distributionSetManagement); - Target tA = targetManagement.createTarget(TestDataUtil.buildTargetFixture("target-id-A", "first description")); + final Target tA = targetManagement + .createTarget(TestDataUtil.buildTargetFixture("target-id-A", "first description")); // assign a distribution set so we get an active update action deploymentManagement.assignDistributionSet(dsA, Lists.newArrayList(tA)); // verify active action diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/model/ExceptionInfoTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/model/ExceptionInfoTest.java index ab5012d73..d240a814b 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/model/ExceptionInfoTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/model/ExceptionInfoTest.java @@ -15,10 +15,17 @@ import java.util.List; import org.junit.Test; +import ru.yandex.qatools.allure.annotations.Description; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@Features("Unit Tests - Management API") +@Stories("Error Handling") public class ExceptionInfoTest { @Test - public void setterAndGetter() { + @Description("Ensures that setters and getters match on teh payload.") + public void setterAndGetterOnExceptionInfo() { final String knownExceptionClass = "hawkbit.test.exception.Class"; final String knownErrorCode = "hawkbit.error.code.Known"; final String knownMessage = "a known message"; diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/model/PagedListTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/model/PagedListTest.java index 0c47856dd..49e13c0b4 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/model/PagedListTest.java +++ b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/model/PagedListTest.java @@ -15,36 +15,46 @@ import java.util.List; import org.junit.Test; +import ru.yandex.qatools.allure.annotations.Description; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@Features("Unit Tests - Management API") +@Stories("Paged List Handling") public class PagedListTest { @Test(expected = NullPointerException.class) + @Description("Ensures that a null payload entitiy throws an exception.") public void createListWithNullContentThrowsException() { new PagedList<>(null, 0); } @Test + @Description("Create list with payload and verify content.") public void createListWithContent() { final long knownTotal = 2; final List knownContentList = new ArrayList<>(); knownContentList.add("content1"); knownContentList.add("content2"); - final PagedList pagedList = new PagedList<>(knownContentList, knownTotal); + assertListSize(knownTotal, knownContentList); + } - assertThat(pagedList.getTotal()).isEqualTo(knownTotal); - assertThat(pagedList.getSize()).isEqualTo(knownContentList.size()); + private void assertListSize(final long knownTotal, final List knownContentList) { + final PagedList pagedList = new PagedList<>(knownContentList, knownTotal); + assertThat(pagedList.getTotal()).as("total size is wrong").isEqualTo(knownTotal); + assertThat(pagedList.getSize()).as("list size is wrong").isEqualTo(knownContentList.size()); } @Test + @Description("Create list with payload and verify size values.") public void createListWithSmallerTotalThanContentSizeIsOk() { final long knownTotal = 0; final List knownContentList = new ArrayList<>(); knownContentList.add("content1"); knownContentList.add("content2"); - final PagedList pagedList = new PagedList<>(knownContentList, knownTotal); - assertThat(pagedList.getTotal()).isEqualTo(knownTotal); - assertThat(pagedList.getSize()).isEqualTo(knownContentList.size()); + assertListSize(knownTotal, knownContentList); } } diff --git a/hawkbit-rest-resource/src/test/resources/application-test.properties b/hawkbit-rest-resource/src/test/resources/application-test.properties index bdd959ca2..92506caa4 100644 --- a/hawkbit-rest-resource/src/test/resources/application-test.properties +++ b/hawkbit-rest-resource/src/test/resources/application-test.properties @@ -24,7 +24,7 @@ hawkbit.server.database=H2 hawkbit.server.database.env=TEST spring.main.show_banner=false -hawkbit.server.controller.security.authentication.header=true +hawkbit.server.ddi.security.authentication.header=true hawkbit.server.artifact.repo.upload.maxFileSize=5MB diff --git a/hawkbit-rest-resource/src/test/resources/log4j2.xml b/hawkbit-rest-resource/src/test/resources/log4j2.xml index 26437af34..98ea99ac9 100644 --- a/hawkbit-rest-resource/src/test/resources/log4j2.xml +++ b/hawkbit-rest-resource/src/test/resources/log4j2.xml @@ -17,7 +17,7 @@ - + diff --git a/hawkbit-security-core/pom.xml b/hawkbit-security-core/pom.xml index 011acc95b..a3b262726 100644 --- a/hawkbit-security-core/pom.xml +++ b/hawkbit-security-core/pom.xml @@ -59,6 +59,11 @@ org.springframework.boot spring-boot + + org.springframework.boot + spring-boot-configuration-processor + true + diff --git a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/DdiSecurityProperties.java b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/DdiSecurityProperties.java new file mode 100644 index 000000000..ce1ff91d8 --- /dev/null +++ b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/DdiSecurityProperties.java @@ -0,0 +1,219 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.security; + +import java.util.List; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * The common properties for DDI security. + */ +@ConfigurationProperties("hawkbit.server.ddi.security") +public class DdiSecurityProperties { + + private final Rp rp = new Rp(); + private final Authentication authentication = new Authentication(); + + public Authentication getAuthentication() { + return authentication; + } + + public Rp getRp() { + return rp; + } + + /** + * Reverse proxy configuration. Defines the security properties for + * authenticating controllers behind a reverse proxy which terminates the + * SSL session at the reverse proxy but adding request header which contains + * the CN of the certificate. + */ + public static class Rp { + + /** + * HTTP header field for common name of a DDI target client certificate. + */ + private String cnHeader = "X-Ssl-Client-Cn"; + + /** + * HTTP header field for issuer hash of a DDI target client certificate. + */ + private String sslIssuerHashHeader = "X-Ssl-Issuer-Hash-%d"; + + /** + * List of trusted (reverse proxy) IP addresses for performing DDI + * client certificate authentication. + */ + private List trustedIPs; + + /** + * @return the cnHeader + */ + public String getCnHeader() { + return cnHeader; + } + + /** + * @param cnHeader + * the cnHeader to set + */ + public void setCnHeader(final String cnHeader) { + this.cnHeader = cnHeader; + } + + /** + * @return the sslIssuerHashHeader + */ + public String getSslIssuerHashHeader() { + return sslIssuerHashHeader; + } + + /** + * @param sslIssuerHashHeader + * the sslIssuerHashHeader to set + */ + public void setSslIssuerHashHeader(final String sslIssuerHashHeader) { + this.sslIssuerHashHeader = sslIssuerHashHeader; + } + + /** + * @return the trustedIPs + */ + public List getTrustedIPs() { + return trustedIPs; + } + + /** + * @param trustedIPs + * the trustedIPs to set + */ + public void setTrustedIPs(final List trustedIPs) { + this.trustedIPs = trustedIPs; + } + + } + + /** + * DDI Authentication options. + */ + public static class Authentication { + private final Anonymous anonymous = new Anonymous(); + private final Targettoken targettoken = new Targettoken(); + private final Gatewaytoken gatewaytoken = new Gatewaytoken(); + + public Anonymous getAnonymous() { + return anonymous; + } + + public Gatewaytoken getGatewaytoken() { + return gatewaytoken; + } + + public Targettoken getTargettoken() { + return targettoken; + } + + /** + * Target token authentication. Tokens are defined per target. + * + */ + public static class Targettoken { + /** + * Set to true to enable target token authentication. + */ + private boolean enabled = false; + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(final boolean enabled) { + this.enabled = enabled; + } + + } + + /** + * Gateway token authentication. Tokens are defined per tenant. Use with + * care! + * + */ + public static class Gatewaytoken { + + /** + * Gateway token based authentication enabled. + */ + private boolean enabled = false; + + /** + * Default gateway token name. + */ + private String name = ""; + + /** + * Default gateway token itself. + */ + private String key = ""; + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(final boolean enabled) { + this.enabled = enabled; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getKey() { + return key; + } + + public void setKey(final String key) { + this.key = key; + } + + } + + /** + * Anonymous authentication. + */ + public static class Anonymous { + + /** + * Set to true to enable anonymous DDI client authentication. + */ + private boolean enabled = false; + + /** + * @param enabled + * the enabled to set + */ + public void setEnabled(final boolean enabled) { + this.enabled = enabled; + } + + /** + * @return the enabled + */ + public boolean isEnabled() { + return enabled; + } + } + + } + +} diff --git a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/HawkbitSecurityProperties.java b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/HawkbitSecurityProperties.java new file mode 100644 index 000000000..7b157da65 --- /dev/null +++ b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/HawkbitSecurityProperties.java @@ -0,0 +1,191 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.security; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * Security related hawkbit configuration. + * + */ +@Component +@ConfigurationProperties("hawkbit.server.security") +public class HawkbitSecurityProperties { + + private final Clients clients = new Clients(); + private final Dos dos = new Dos(); + private final Xframe xframe = new Xframe(); + + public Dos getDos() { + return dos; + } + + public Clients getClients() { + return clients; + } + + public Xframe getXframe() { + return xframe; + } + + /** + * Defines the XFrameOption policy. + * + */ + public static class Xframe { + + /** + * XFrame option. Allowed values: SAMEORIGIN, DENY, ALLOW-FROM + */ + private String option = "DENY"; + + /** + * ALLOW-FROM defined URL, has to be filled in case ALLOW-FROM option is + * selected. + */ + private String allowfrom = ""; + + public String getOption() { + return option; + } + + public void setOption(final String option) { + this.option = option; + } + + public String getAllowfrom() { + return allowfrom; + } + + public void setAllowfrom(final String allowfrom) { + this.allowfrom = allowfrom; + } + + } + + /** + * Security configuration related to clients. + * + */ + public static class Clients { + + /** + * Blacklisted client (IP addresses) for for DDI and Management API. + */ + private String blacklist = ""; + + /** + * Name of the http header from which the remote ip is extracted. + */ + private String remoteIpHeader = "X-Forwarded-For"; + + public String getBlacklist() { + return blacklist; + } + + public void setBlacklist(final String blacklist) { + this.blacklist = blacklist; + } + + public String getRemoteIpHeader() { + return remoteIpHeader; + } + + public void setRemoteIpHeader(final String remoteIpHeader) { + this.remoteIpHeader = remoteIpHeader; + } + } + + /** + * Denial of service protection related properties. + * + */ + public static class Dos { + + /** + * Maximum number of status updates that the controller can report for + * an action (0 to disable). + */ + private int maxStatusEntriesPerAction = 1000; + + /** + * Maximum number of attributes that the controller can report; + */ + private int maxAttributeEntriesPerTarget = 100; + + private final Filter filter = new Filter(); + + public Filter getFilter() { + return filter; + } + + public int getMaxStatusEntriesPerAction() { + return maxStatusEntriesPerAction; + } + + public void setMaxStatusEntriesPerAction(final int maxStatusEntriesPerAction) { + this.maxStatusEntriesPerAction = maxStatusEntriesPerAction; + } + + public int getMaxAttributeEntriesPerTarget() { + return maxAttributeEntriesPerTarget; + } + + public void setMaxAttributeEntriesPerTarget(final int maxAttributeEntriesPerTarget) { + this.maxAttributeEntriesPerTarget = maxAttributeEntriesPerTarget; + } + + public static class Filter { + + /** + * White list of peer IP addresses for DOS filter (regular + * expression). + */ + private String whitelist = "10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|192\\.168\\.\\d{1,3}\\.\\d{1,3}|169\\.254\\.\\d{1,3}\\.\\d{1,3}|127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}"; + + /** + * # Maximum number of allowed REST read/GET requests per second per + * client. + */ + int maxRead = 200; + + /** + * Maximum number of allowed REST write/(PUT/POST/etc.) requests per + * second per client. + */ + int maxWrite = 50; + + public String getWhitelist() { + return whitelist; + } + + public void setWhitelist(final String whitelist) { + this.whitelist = whitelist; + } + + public int getMaxRead() { + return maxRead; + } + + public void setMaxRead(final int maxRead) { + this.maxRead = maxRead; + } + + public int getMaxWrite() { + return maxWrite; + } + + public void setMaxWrite(final int maxWrite) { + this.maxWrite = maxWrite; + } + + } + } +} diff --git a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SecurityProperties.java b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SecurityProperties.java deleted file mode 100644 index 8cc056f15..000000000 --- a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SecurityProperties.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - */ -package org.eclipse.hawkbit.security; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -/** - * The common properties for security. - * - * - * - */ -@ConfigurationProperties -public class SecurityProperties { - - /** - * Inner class for reverse proxy configuration. - */ - @Component - @ConfigurationProperties("hawkbit.server.controller.security.rp") - public static class RpProperties { - private String cnHeader = "X-Ssl-Client-Cn"; - private String sslIssuerHashHeader = "X-Ssl-Issuer-Hash-%d"; - private List trustedIPs; - - /** - * @return the cnHeader - */ - public String getCnHeader() { - return cnHeader; - } - - /** - * @param cnHeader - * the cnHeader to set - */ - public void setCnHeader(final String cnHeader) { - this.cnHeader = cnHeader; - } - - /** - * @return the sslIssuerHashHeader - */ - public String getSslIssuerHashHeader() { - return sslIssuerHashHeader; - } - - /** - * @param sslIssuerHashHeader - * the sslIssuerHashHeader to set - */ - public void setSslIssuerHashHeader(final String sslIssuerHashHeader) { - this.sslIssuerHashHeader = sslIssuerHashHeader; - } - - /** - * @return the trustedIPs - */ - public List getTrustedIPs() { - return trustedIPs; - } - - /** - * @param trustedIPs - * the trustedIPs to set - */ - public void setTrustedIPs(final List trustedIPs) { - this.trustedIPs = trustedIPs; - } - - } - - /** - * Inner class for anonymous enable configuration. - */ - @Component - @ConfigurationProperties("hawkbit.server.controller.security.authentication.anonymous") - public static class AnoymousAuthenticationProperties { - private Boolean enabled = Boolean.FALSE; - - /** - * @param enabled - * the enabled to set - */ - public void setEnabled(final Boolean enabled) { - this.enabled = enabled; - } - - /** - * @return the enabled - */ - public Boolean getEnabled() { - return enabled; - } - - } - - @Autowired - private RpProperties rppProperties; - - @Autowired - private AnoymousAuthenticationProperties authenticationsProperties; - - public String getRpCnHeader() { - return rppProperties.getCnHeader(); - } - - public String getRpSslIssuerHashHeader() { - return rppProperties.getSslIssuerHashHeader(); - } - - public List getRpTrustedIPs() { - return rppProperties.getTrustedIPs(); - } - - public Boolean getAnonymousEnabled() { - return authenticationsProperties.getEnabled(); - } - -} diff --git a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SystemSecurityContext.java b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SystemSecurityContext.java index 334065a10..b22b54e39 100644 --- a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SystemSecurityContext.java +++ b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SystemSecurityContext.java @@ -15,7 +15,6 @@ import java.util.concurrent.Callable; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; import org.eclipse.hawkbit.tenancy.TenantAware; -import org.eclipse.hawkbit.tenancy.TenantAware.TenantRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -30,8 +29,7 @@ import org.springframework.stereotype.Service; import com.google.common.base.Throwables; /** - * @author Michael Hirsch - * + * */ @Service public class SystemSecurityContext { @@ -55,15 +53,12 @@ public class SystemSecurityContext { final SecurityContext oldContext = SecurityContextHolder.getContext(); try { logger.debug("entering system code execution"); - return tenantAware.runAsTenant(tenantAware.getCurrentTenant(), new TenantRunner() { - @Override - public T run() { - try { - setSystemContext(); - return callable.call(); - } catch (final Exception e) { - throw Throwables.propagate(e); - } + return tenantAware.runAsTenant(tenantAware.getCurrentTenant(), () -> { + try { + setSystemContext(); + return callable.call(); + } catch (final Exception e) { + throw Throwables.propagate(e); } }); @@ -116,7 +111,8 @@ public class SystemSecurityContext { } @Override - public void setAuthenticated(final boolean isAuthenticated) throws IllegalArgumentException { + public void setAuthenticated(final boolean isAuthenticated) { + // not needed } } } diff --git a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/util/IpUtil.java b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/util/IpUtil.java index 0068fd0c8..4e08d8bfe 100644 --- a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/util/IpUtil.java +++ b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/util/IpUtil.java @@ -20,9 +20,6 @@ import com.google.common.net.HttpHeaders; /** * A utility which determines the correct IP of a connected {@link Target}. E.g * from a {@link HttpServletRequest}. - * - * - * * */ public final class IpUtil { @@ -95,7 +92,6 @@ public final class IpUtil { if (isIpV6) { return URI.create(scheme + SCHEME_SEPERATOR + "[" + host + "]"); } - return URI.create(scheme + SCHEME_SEPERATOR + host); } @@ -104,12 +100,14 @@ public final class IpUtil { * * @param host * the host + * @param exchange + * the exchange will store in the path * @return the {@link URI} * @throws IllegalArgumentException * If the given string not parsable */ - public static URI createAmqpUri(final String host) { - return createUri(AMPQP_SCHEME, host); + public static URI createAmqpUri(final String host, final String exchange) { + return createUri(AMPQP_SCHEME, host).resolve("/" + exchange); } /** diff --git a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/util/SPInfo.java b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/util/SPInfo.java index 3a2a696df..feb94c0d7 100644 --- a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/util/SPInfo.java +++ b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/util/SPInfo.java @@ -11,90 +11,24 @@ package org.eclipse.hawkbit.util; import javax.servlet.MultipartConfigElement; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; /** * Bean which contains all informations about the SP software, e.g. like * version, built time etc. from the environment. * - * - * - * */ @Component -public class SPInfo implements EnvironmentAware { +public class SPInfo { // package private for testing purposes static final String UNKNOWN_VERSION = "unknown"; static final String UNKNOWN_CREDENTIAL = "unknown credential"; - private Environment environmentData; - @Autowired private MultipartConfigElement configElement; - /* - * (non-Javadoc) - * - * @see org.springframework.context.EnvironmentAware#setEnvironment(org. - * springframework.core.env. Environment) - */ - @Override - public void setEnvironment(final Environment environment) { - this.environmentData = environment; - } - - /** - * @return the version in string format, e.g. 1.0.0 or {@code "UNKNOWN"} in - * case the SP version info cannot be determined. - */ - public String getVersion() { - if (environmentData != null) { - return environmentData.getProperty("info.build.version", UNKNOWN_VERSION); - } - return UNKNOWN_VERSION; - } - - public String getSupportEmail() { - if (environmentData != null) { - return environmentData.getProperty("hawkbit.server.email.support"); - } - return ""; - } - - public String getRequestAccountEmail() { - if (environmentData != null) { - return environmentData.getProperty("hawkbit.server.email.request.account"); - } - return ""; - } - - public String getDemoTenant() { - if (environmentData != null) { - return environmentData.getProperty("hawkbit.server.demo.tenant"); - } - return UNKNOWN_CREDENTIAL; - } - - public String getDemoUser() { - if (environmentData != null) { - return environmentData.getProperty("hawkbit.server.demo.user"); - } - return UNKNOWN_CREDENTIAL; - - } - - public String getDemoPassword() { - if (environmentData != null) { - return environmentData.getProperty("hawkbit.server.demo.password"); - } - return UNKNOWN_CREDENTIAL; - - } - /** * @return the max file size to upload artifact files in bytes which has * been configured. diff --git a/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/ExcludePathAwareShallowETagFilterTest.java b/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/ExcludePathAwareShallowETagFilterTest.java index d3dc066f1..0b2c0b116 100644 --- a/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/ExcludePathAwareShallowETagFilterTest.java +++ b/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/ExcludePathAwareShallowETagFilterTest.java @@ -28,6 +28,11 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@Features("Unit Tests - Security") +@Stories("Exclude path aware shallow ETag filter") @RunWith(MockitoJUnitRunner.class) public class ExcludePathAwareShallowETagFilterTest { diff --git a/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/security/SecurityTokenGeneratorTest.java b/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/security/SecurityTokenGeneratorTest.java index 405d6d010..b83b81df7 100644 --- a/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/security/SecurityTokenGeneratorTest.java +++ b/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/security/SecurityTokenGeneratorTest.java @@ -13,8 +13,14 @@ import java.security.NoSuchAlgorithmException; import org.junit.Test; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@Features("Unit Tests - Security") +@Stories("SecurityToken Generator Test") public class SecurityTokenGeneratorTest { + // FIXME: figure what is this all about?? @Test public void test() throws NoSuchAlgorithmException, UnsupportedEncodingException { final SecurityTokenGenerator securityTokenGenerator = new SecurityTokenGenerator(); diff --git a/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/util/IpUtilTest.java b/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/util/IpUtilTest.java index d56c59252..9eb83d2a9 100644 --- a/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/util/IpUtilTest.java +++ b/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/util/IpUtilTest.java @@ -33,8 +33,8 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; @RunWith(MockitoJUnitRunner.class) -@Features("IpUtil Test") -@Stories("Tests the created uris") +@Features("Unit Tests - Security") +@Stories("IP Util Test") public class IpUtilTest { @Mock @@ -106,23 +106,24 @@ public class IpUtilTest { @Description("Tests create amqp uri ipv4 and ipv6") public void testCreateAmqpUri() { final String ipv4 = "10.99.99.1"; - URI amqpUri = IpUtil.createAmqpUri(ipv4); + URI amqpUri = IpUtil.createAmqpUri(ipv4, "path"); assertAmqpUri(ipv4, amqpUri); final String host = "myhost"; - amqpUri = IpUtil.createAmqpUri(host); + amqpUri = IpUtil.createAmqpUri(host, "path"); assertAmqpUri(host, amqpUri); final String ipv6 = "0:0:0:0:0:0:0:1"; - amqpUri = IpUtil.createAmqpUri(ipv6); + amqpUri = IpUtil.createAmqpUri(ipv6, "path"); assertAmqpUri("[" + ipv6 + "]", amqpUri); } - private void assertAmqpUri(final String host, final URI httpUri) { - assertTrue("The given URI is an AMQP scheme", IpUtil.isAmqpUri(httpUri)); - assertFalse("The given URI is not an HTTP scheme", IpUtil.isHttpUri(httpUri)); - assertEquals("The given host matches the URI host", host, httpUri.getHost()); - assertEquals("The given URI has an AMQP scheme", "amqp", httpUri.getScheme()); + private void assertAmqpUri(final String host, final URI amqpUri) { + assertTrue("The given URI is an AMQP scheme", IpUtil.isAmqpUri(amqpUri)); + assertFalse("The given URI is not an HTTP scheme", IpUtil.isHttpUri(amqpUri)); + assertEquals("The given host matches the URI host", host, amqpUri.getHost()); + assertEquals("The given URI has an AMQP scheme", "amqp", amqpUri.getScheme()); + assertEquals("The given URI has an AMQP path", "/path", amqpUri.getRawPath()); } @Test diff --git a/hawkbit-test-report/pom.xml b/hawkbit-test-report/pom.xml index 6e58cb61a..3e9182f0a 100644 --- a/hawkbit-test-report/pom.xml +++ b/hawkbit-test-report/pom.xml @@ -18,7 +18,7 @@ 0.2.0-SNAPSHOT hawkbit-test-report - Hawkbit :: Test Report + hawkBit :: Test Report pom @@ -75,8 +75,7 @@ - - + \ No newline at end of file diff --git a/hawkbit-ui/pom.xml b/hawkbit-ui/pom.xml index 0bd083e36..2c7e65638 100644 --- a/hawkbit-ui/pom.xml +++ b/hawkbit-ui/pom.xml @@ -58,26 +58,6 @@ - - net.alchim31.maven - yuicompressor-maven-plugin - 1.5.0 - - - - compress - - - - - - **/*.css - - true - ${basedir}/src/main/resources/VAADIN/themes/hawkbit/styles.css - true - - @@ -115,7 +95,7 @@ com.vaadin vaadin-maven-plugin - [7.5.2,) + [7.6.3,) compile-theme @@ -213,7 +193,6 @@ org.vaadin.addons tokenfield - org.vaadin.alump.distributionbar dbar-addon @@ -222,7 +201,11 @@ org.vaadin.addons contextmenu - + + org.springframework.boot + spring-boot-configuration-processor + true + diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/HawkbitUI.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/HawkbitUI.java index d352211f6..2be62db1d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/HawkbitUI.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/HawkbitUI.java @@ -14,12 +14,11 @@ import java.util.Set; import javax.servlet.http.Cookie; -import org.eclipse.hawkbit.eventbus.event.EntityEvent; -import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails; import org.eclipse.hawkbit.ui.components.SPUIErrorHandler; import org.eclipse.hawkbit.ui.menu.DashboardEvent.PostViewChangeEvent; import org.eclipse.hawkbit.ui.menu.DashboardMenu; import org.eclipse.hawkbit.ui.menu.DashboardMenuItem; +import org.eclipse.hawkbit.ui.push.EventPushStrategy; import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SpringContextHelper; @@ -28,14 +27,8 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.io.Resource; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.vaadin.spring.events.EventBus; -import org.vaadin.spring.events.EventBus.SessionEventBus; -import com.google.common.eventbus.AllowConcurrentEvents; -import com.google.common.eventbus.Subscribe; import com.vaadin.annotations.Title; import com.vaadin.navigator.Navigator; import com.vaadin.navigator.View; @@ -45,9 +38,6 @@ import com.vaadin.server.ClientConnector.DetachListener; import com.vaadin.server.Responsive; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinService; -import com.vaadin.server.VaadinSession; -import com.vaadin.server.VaadinSession.State; -import com.vaadin.server.WrappedSession; import com.vaadin.spring.navigator.SpringViewProvider; import com.vaadin.ui.Component; import com.vaadin.ui.CssLayout; @@ -71,6 +61,8 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener { private static final String EMPTY_VIEW = ""; + private EventPushStrategy pushStrategy; + @Autowired private SpringViewProvider viewProvider; @@ -92,69 +84,37 @@ public class HawkbitUI extends DefaultHawkbitUI implements DetachListener { protected transient EventBus.SessionEventBus eventBus; /** - * An {@link com.google.common.eventbus.EventBus} subscriber which - * subscribes {@link EntityEvent} from the repository to dispatch these - * events to the UI {@link SessionEventBus}. - * - * @param event - * the entity event which has been published from the repository + * Default constructor. */ - @Subscribe - @AllowConcurrentEvents - public void dispatch(final org.eclipse.hawkbit.eventbus.event.Event event) { - final VaadinSession session = getSession(); - if (session == null || session.getState() != State.OPEN) { - return; - } - - final WrappedSession wrappedSession = session.getSession(); - if (wrappedSession == null) { - return; - } - - final SecurityContext userContext = (SecurityContext) wrappedSession - .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); - if (!eventSecurityCheck(userContext, event)) { - return; - } - - final SecurityContext oldContext = SecurityContextHolder.getContext(); - try { - access(new DispatcherRunnable(eventBus, session, userContext, event)); - } finally { - SecurityContextHolder.setContext(oldContext); - } - + public HawkbitUI() { + // is empty, is ok. } - protected boolean eventSecurityCheck(final SecurityContext userContext, - final org.eclipse.hawkbit.eventbus.event.Event event) { - if (userContext != null && userContext.getAuthentication() != null) { - final Object tenantAuthenticationDetails = userContext.getAuthentication().getDetails(); - if (tenantAuthenticationDetails instanceof TenantAwareAuthenticationDetails) { - return ((TenantAwareAuthenticationDetails) tenantAuthenticationDetails).getTenant() - .equalsIgnoreCase(event.getTenant()); - } - } - return false; + /** + * Constructor taking the push strategy. + * + * @param pushStrategy + * the strategy to push events from the backend to the UI + */ + public HawkbitUI(final EventPushStrategy pushStrategy) { + this.pushStrategy = pushStrategy; } - /* - * (non-Javadoc) - * - * @see - * com.vaadin.server.ClientConnector.DetachListener#detach(com.vaadin.server - * .ClientConnector. DetachEvent) - */ @Override public void detach(final DetachEvent event) { LOG.info("ManagementUI is detached uiid - {}", getUIId()); - + eventBus.unsubscribe(this); + if (pushStrategy != null) { + pushStrategy.clean(); + } } @Override protected void init(final VaadinRequest vaadinRequest) { LOG.info("ManagementUI init starts uiid - {}", getUI().getUIId()); + if (pushStrategy != null) { + pushStrategy.init(getUI()); + } addDetachListener(this); SpringContextHelper.setContext(context); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/UiProperties.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/UiProperties.java new file mode 100644 index 000000000..b23935826 --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/UiProperties.java @@ -0,0 +1,162 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.ui; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * Properties for Management UI customization. + * + */ +@Component +@ConfigurationProperties("hawkbit.server.ui") +public class UiProperties { + + private final Links links = new Links(); + private final Login login = new Login(); + private final Demo demo = new Demo(); + + public Login getLogin() { + return login; + } + + public Links getLinks() { + return links; + } + + public Demo getDemo() { + return demo; + } + + /** + * Demo account login information. + * + */ + public static class Demo { + + /** + * Demo tenant. + */ + private String tenant = "DEFAULT"; + /** + * Demo user name. + */ + private String user = "admin"; + + /** + * Demo user password. + */ + private String password = "admin"; + + public String getTenant() { + return tenant; + } + + public void setTenant(final String tenant) { + this.tenant = tenant; + } + + public String getUser() { + return user; + } + + public void setUser(final String user) { + this.user = user; + } + + public String getPassword() { + return password; + } + + public void setPassword(final String password) { + this.password = password; + } + + } + + /** + * Links to potentially other systems (e.g. support, user management etc.). + * + */ + public static class Links { + /** + * Link to product support. + */ + private String support = ""; + + /** + * Link to request a system account, access. + */ + private String requestAccount = ""; + + /** + * Link to user management. + */ + private String userManagement = ""; + + public String getSupport() { + return support; + } + + public void setSupport(final String support) { + this.support = support; + } + + public String getRequestAccount() { + return requestAccount; + } + + public void setRequestAccount(final String requestAccount) { + this.requestAccount = requestAccount; + } + + public String getUserManagement() { + return userManagement; + } + + public void setUserManagement(final String userManagement) { + this.userManagement = userManagement; + } + + } + + /** + * Configuration of login view. + * + */ + public static class Login { + + private final Cookie cookie = new Cookie(); + + public Cookie getCookie() { + return cookie; + } + + /** + * Cookie configuration for login credential cookie. + * + */ + public static class Cookie { + /** + * Secure cookie enabled. + */ + private boolean secure = true; + + public boolean isSecure() { + return secure; + } + + public void setSecure(final boolean secure) { + this.secure = secure; + } + } + } + +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/CreateUpdateSoftwareTypeLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/CreateUpdateSoftwareTypeLayout.java index b79b53ae0..dc6d1081e 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/CreateUpdateSoftwareTypeLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/CreateUpdateSoftwareTypeLayout.java @@ -438,17 +438,17 @@ public class CreateUpdateSoftwareTypeLayout extends CustomComponent implements C if (permChecker.hasUpdateDistributionPermission()) { optionValues.add(updateType.getValue()); } - createOptionGroup(optionValues); + createOptionGroupByValues(optionValues); } private void singleMultiOptionGroup() { final List optionValues = new ArrayList<>(); optionValues.add(singleAssign.getValue()); optionValues.add(multiAssign.getValue()); - assignOptionGroup(optionValues); + assignOptionGroupByValues(optionValues); } - private void createOptionGroup(final List tagOptions) { + private void createOptionGroupByValues(final List tagOptions) { createOptiongroup = new OptionGroup("", tagOptions); createOptiongroup.setStyleName(ValoTheme.OPTIONGROUP_SMALL); createOptiongroup.addStyleName("custom-option-group"); @@ -458,7 +458,7 @@ public class CreateUpdateSoftwareTypeLayout extends CustomComponent implements C } } - private void assignOptionGroup(final List tagOptions) { + private void assignOptionGroupByValues(final List tagOptions) { assignOptiongroup = new OptionGroup("", tagOptions); assignOptiongroup.setStyleName(ValoTheme.OPTIONGROUP_SMALL); assignOptiongroup.addStyleName("custom-option-group"); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java index 62a09c83b..a502b341c 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java @@ -50,9 +50,9 @@ public class ArtifactUploadState implements Serializable { private boolean swTypeFilterClosed = Boolean.FALSE; - private boolean isSwModuleTableMaximized = Boolean.FALSE; + private boolean swModuleTableMaximized = Boolean.FALSE; - private boolean isArtifactDetailsMaximized = Boolean.FALSE; + private boolean artifactDetailsMaximized = Boolean.FALSE; private final Set selectedDeleteSWModuleTypes = new HashSet<>(); @@ -152,15 +152,15 @@ public class ArtifactUploadState implements Serializable { * @return the isSwModuleTableMaximized */ public boolean isSwModuleTableMaximized() { - return isSwModuleTableMaximized; + return swModuleTableMaximized; } /** * @param isSwModuleTableMaximized * the isSwModuleTableMaximized to set */ - public void setSwModuleTableMaximized(final boolean isSwModuleTableMaximized) { - this.isSwModuleTableMaximized = isSwModuleTableMaximized; + public void setSwModuleTableMaximized(final boolean swModuleTableMaximized) { + this.swModuleTableMaximized = swModuleTableMaximized; } public Set getSelectedDeleteSWModuleTypes() { @@ -171,15 +171,15 @@ public class ArtifactUploadState implements Serializable { * @return the isArtifactDetailsMaximized */ public boolean isArtifactDetailsMaximized() { - return isArtifactDetailsMaximized; + return artifactDetailsMaximized; } /** * @param isArtifactDetailsMaximized * the isArtifactDetailsMaximized to set */ - public void setArtifactDetailsMaximized(final boolean isArtifactDetailsMaximized) { - this.isArtifactDetailsMaximized = isArtifactDetailsMaximized; + public void setArtifactDetailsMaximized(final boolean artifactDetailsMaximized) { + this.artifactDetailsMaximized = artifactDetailsMaximized; } /** diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java index 1610a2de8..8982be759 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java @@ -78,7 +78,7 @@ public class TargetTagToken extends AbstractTargetTagToken { } private TargetTagAssigmentResult toggleAssignment(final String tagNameSelected) { - final Set targetList = new HashSet(); + final Set targetList = new HashSet<>(); targetList.add(selectedTarget.getControllerId()); final TargetTagAssigmentResult result = targetManagement.toggleTagAssignment(targetList, tagNameSelected); uinotification.displaySuccess(HawkbitCommonUtil.getTargetTagAssigmentMsg(tagNameSelected, result, i18n)); @@ -102,7 +102,7 @@ public class TargetTagToken extends AbstractTargetTagToken { /* To Be Done : this implementation will vary in views */ private List getClickedTagList() { - return new ArrayList(); + return new ArrayList<>(); } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTarget.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTarget.java index 9a374f980..d85b2bc71 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTarget.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTarget.java @@ -38,11 +38,9 @@ public class ProxyTarget extends Target { private TargetIdName targetIdName; - private Long createdAt; + private String assignedDistNameVersion; - private String assignedDistNameVersion = null; - - private String installedDistNameVersion = null; + private String installedDistNameVersion; private String pollStatusToolTip; @@ -251,22 +249,6 @@ public class ProxyTarget extends Target { this.installedDistributionSet = installedDistributionSet; } - /** - * @return the createdAt - */ - @Override - public Long getCreatedAt() { - return createdAt; - } - - /** - * @param createdAt - * the createdAt to set - */ - public void setCreatedAt(final Long createdAt) { - this.createdAt = createdAt; - } - /** * @return the targetIdName */ diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java index 4fed0dd4b..8d609f628 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java @@ -555,10 +555,10 @@ public class CreateUpdateDistSetTypeLayout extends CustomComponent implements Co if (permChecker.hasUpdateDistributionPermission()) { optionValues.add(updateDistType.getValue()); } - createOptionGroup(optionValues); + createOptionGroupByValues(optionValues); } - private void createOptionGroup(final List typeOptions) { + private void createOptionGroupByValues(final List typeOptions) { createOptiongroup = new OptionGroup("", typeOptions); createOptiongroup.setId(SPUIDefinitions.CREATE_OPTION_GROUP_DISTRIBUTION_SET_TYPE_ID); createOptiongroup.addStyleName(ValoTheme.OPTIONGROUP_SMALL); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java index 7e06a4171..ce31f649b 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java @@ -62,9 +62,9 @@ public class ManageDistUIState implements Serializable { private final Map deleteSofwareModulesList = new HashMap<>(); - private boolean isSwModuleTableMaximized = Boolean.FALSE; + private boolean swModuleTableMaximized = Boolean.FALSE; - private boolean isDsTableMaximized = Boolean.FALSE; + private boolean dsTableMaximized = Boolean.FALSE; private final Map assignedSoftwareModuleDetails = new HashMap<>(); @@ -219,7 +219,7 @@ public class ManageDistUIState implements Serializable { * @return boolean */ public boolean isDsTableMaximized() { - return isDsTableMaximized; + return dsTableMaximized; } /*** @@ -227,8 +227,8 @@ public class ManageDistUIState implements Serializable { * * @param isDsModuleTableMaximized */ - public void setDsTableMaximized(final boolean isDsModuleTableMaximized) { - isDsTableMaximized = isDsModuleTableMaximized; + public void setDsTableMaximized(final boolean dsModuleTableMaximized) { + dsTableMaximized = dsModuleTableMaximized; } public Map getAssignedSoftwareModuleDetails() { @@ -239,15 +239,15 @@ public class ManageDistUIState implements Serializable { * @return the isSwModuleTableMaximized */ public boolean isSwModuleTableMaximized() { - return isSwModuleTableMaximized; + return swModuleTableMaximized; } /** * @param isSwModuleTableMaximized * the isSwModuleTableMaximized to set */ - public void setSwModuleTableMaximized(final boolean isSwModuleTableMaximized) { - this.isSwModuleTableMaximized = isSwModuleTableMaximized; + public void setSwModuleTableMaximized(final boolean swModuleTableMaximized) { + this.swModuleTableMaximized = swModuleTableMaximized; } /** diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/login/LoginView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/login/LoginView.java index 9beeff56a..484333219 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/login/LoginView.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/login/LoginView.java @@ -15,16 +15,14 @@ import javax.servlet.http.Cookie; import org.eclipse.hawkbit.im.authentication.MultitenancyIndicator; import org.eclipse.hawkbit.im.authentication.TenantUserPasswordAuthenticationToken; +import org.eclipse.hawkbit.ui.UiProperties; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.documentation.DocumentationPageLink; import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; -import org.eclipse.hawkbit.util.SPInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.env.Environment; import org.springframework.security.authentication.CredentialsExpiredException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.AuthenticationException; @@ -61,7 +59,7 @@ import com.vaadin.ui.themes.ValoTheme; */ @SpringView(name = "") @UIScope -public class LoginView extends VerticalLayout implements View, EnvironmentAware { +public class LoginView extends VerticalLayout implements View { private static final String LOGIN_TEXTFIELD = "login-textfield"; private static final long serialVersionUID = 1L; private static final Logger LOGGER = LoggerFactory.getLogger(LoginView.class); @@ -76,7 +74,7 @@ public class LoginView extends VerticalLayout implements View, EnvironmentAware private I18N i18n; @Autowired - private transient SPInfo spInfo; + private transient UiProperties uiProperties; @Autowired private transient MultitenancyIndicator multiTenancyIndicator; @@ -86,9 +84,6 @@ public class LoginView extends VerticalLayout implements View, EnvironmentAware private PasswordField password; private Button signin; - private Boolean secureCookie = Boolean.TRUE; - private String userManagementLoginUrl; - void loginAuthenticationFailedNotification() { final Notification notification = new Notification(i18n.get("notification.login.failed.title")); notification.setDescription(i18n.get("notification.login.failed.description")); @@ -119,7 +114,8 @@ public class LoginView extends VerticalLayout implements View, EnvironmentAware final URI spURI = Page.getCurrent().getLocation(); final String lookForDemoFragment = spURI.toString(); if (lookForDemoFragment.contains("?demo")) { - login(spInfo.getDemoTenant(), spInfo.getDemoUser(), spInfo.getDemoPassword(), false); + login(uiProperties.getDemo().getTenant(), uiProperties.getDemo().getUser(), + uiProperties.getDemo().getPassword(), false); } final Component loginForm = buildLoginForm(); @@ -243,18 +239,18 @@ public class LoginView extends VerticalLayout implements View, EnvironmentAware links.addComponent(demoLink); demoLink.addStyleName(ValoTheme.LINK_SMALL); - if (spInfo.getRequestAccountEmail() != null) { + if (!uiProperties.getLinks().getRequestAccount().isEmpty()) { final Link requestAccountLink = SPUIComponentProvider.getLink(SPUIComponetIdProvider.LINK_REQUESTACCOUNT, - i18n.get("link.requestaccount.name"), spInfo.getRequestAccountEmail(), FontAwesome.SHOPPING_CART, - "", linkStyle, true); + i18n.get("link.requestaccount.name"), uiProperties.getLinks().getRequestAccount(), + FontAwesome.SHOPPING_CART, "", linkStyle, true); links.addComponent(requestAccountLink); requestAccountLink.addStyleName(ValoTheme.LINK_SMALL); } - if (userManagementLoginUrl != null) { + if (!uiProperties.getLinks().getUserManagement().isEmpty()) { final Link userManagementLink = SPUIComponentProvider.getLink(SPUIComponetIdProvider.LINK_USERMANAGEMENT, - i18n.get("link.usermanagement.name"), userManagementLoginUrl, FontAwesome.USERS, "_blank", - linkStyle, true); + i18n.get("link.usermanagement.name"), uiProperties.getLinks().getUserManagement(), + FontAwesome.USERS, "_blank", linkStyle, true); links.addComponent(userManagementLink); userManagementLink.addStyleName(ValoTheme.LINK_SMALL); } @@ -315,7 +311,7 @@ public class LoginView extends VerticalLayout implements View, EnvironmentAware // 100 days tenantCookie.setMaxAge(3600 * 24 * 100); tenantCookie.setHttpOnly(true); - tenantCookie.setSecure(secureCookie); + tenantCookie.setSecure(uiProperties.getLogin().getCookie().isSecure()); VaadinService.getCurrentResponse().addCookie(tenantCookie); } @@ -324,7 +320,7 @@ public class LoginView extends VerticalLayout implements View, EnvironmentAware // 100 days usernameCookie.setMaxAge(3600 * 24 * 100); usernameCookie.setHttpOnly(true); - usernameCookie.setSecure(secureCookie); + usernameCookie.setSecure(uiProperties.getLogin().getCookie().isSecure()); VaadinService.getCurrentResponse().addCookie(usernameCookie); } @@ -368,16 +364,4 @@ public class LoginView extends VerticalLayout implements View, EnvironmentAware loginAuthenticationFailedNotification(); } } - - /* - * (non-Javadoc) - * - * @see org.springframework.context.EnvironmentAware#setEnvironment(org. - * springframework.core.env. Environment) - */ - @Override - public void setEnvironment(final Environment environment) { - secureCookie = environment.getProperty("hawkbit.server.ui.login.cookie.secure", Boolean.class, Boolean.TRUE); - userManagementLoginUrl = environment.getProperty("hawkbit.server.im.login.url", String.class); - } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java index df9d8a60d..f8d53b1bf 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java @@ -16,6 +16,7 @@ import java.util.StringJoiner; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; +import org.eclipse.hawkbit.repository.ActionStatusFields; import org.eclipse.hawkbit.repository.DeploymentManagement; import org.eclipse.hawkbit.repository.exception.CancelActionNotAllowedException; import org.eclipse.hawkbit.repository.model.Action; @@ -43,6 +44,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -417,10 +420,10 @@ public class ActionHistoryTable extends TreeTable implements Handler { final org.eclipse.hawkbit.repository.model.Action action = deploymentManagement .findActionWithDetails(actionId); - final Pageable pageReq = new PageRequest(0, 1000); - final Page actionStatusList = deploymentManagement - .findActionStatusMessagesByActionInDescOrder(pageReq, action, - managementUIState.isActionHistoryMaximized()); + final Pageable pageReq = new PageRequest(0, 1000, + new Sort(Direction.DESC, ActionStatusFields.ID.getFieldName())); + final Page actionStatusList = deploymentManagement.findActionStatusByAction(pageReq, action, + managementUIState.isActionHistoryMaximized()); final List content = actionStatusList.getContent(); /* * Since the recent action status and messages are already diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java index dfdbcd9de..9bbc1c05d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java @@ -94,8 +94,8 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { @Autowired private transient TenantMetaDataRepository tenantMetaDataRepository; - private Button saveDistribution; - private Button discardDistribution; + private Button saveDistributionBtn; + private Button discardDistributionBtn; private TextField distNameTextField; private TextField distVersionTextField; private Label madatoryLabel; @@ -103,7 +103,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { private CheckBox reqMigStepCheckbox; private ComboBox distsetTypeNameComboBox; private boolean editDistribution = Boolean.FALSE; - private Long editDistId = null; + private Long editDistId; private Window addDistributionWindow; private String originalDistName; private String originalDistVersion; @@ -131,9 +131,9 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { final HorizontalLayout buttonsLayout = new HorizontalLayout(); buttonsLayout.setSizeFull(); buttonsLayout.setStyleName("dist-buttons-horz-layout"); - buttonsLayout.addComponents(saveDistribution, discardDistribution); - buttonsLayout.setComponentAlignment(saveDistribution, Alignment.BOTTOM_LEFT); - buttonsLayout.setComponentAlignment(discardDistribution, Alignment.BOTTOM_RIGHT); + buttonsLayout.addComponents(saveDistributionBtn, discardDistributionBtn); + buttonsLayout.setComponentAlignment(saveDistributionBtn, Alignment.BOTTOM_LEFT); + buttonsLayout.setComponentAlignment(discardDistributionBtn, Alignment.BOTTOM_RIGHT); buttonsLayout.addStyleName("window-style"); /* @@ -186,14 +186,14 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { reqMigStepCheckbox.setId(SPUIComponetIdProvider.DIST_ADD_MIGRATION_CHECK); /* save or update button */ - saveDistribution = SPUIComponentProvider.getButton(SPUIComponetIdProvider.DIST_ADD_SAVE, "", "", "", true, + saveDistributionBtn = SPUIComponentProvider.getButton(SPUIComponetIdProvider.DIST_ADD_SAVE, "", "", "", true, FontAwesome.SAVE, SPUIButtonStyleSmallNoBorder.class); - saveDistribution.addClickListener(event -> saveDistribution()); + saveDistributionBtn.addClickListener(event -> saveDistribution()); /* close button */ - discardDistribution = SPUIComponentProvider.getButton(SPUIComponetIdProvider.DIST_ADD_DISCARD, "", "", "", true, - FontAwesome.TIMES, SPUIButtonStyleSmallNoBorder.class); - discardDistribution.addClickListener(event -> discardDistribution()); + discardDistributionBtn = SPUIComponentProvider.getButton(SPUIComponetIdProvider.DIST_ADD_DISCARD, "", "", "", + true, FontAwesome.TIMES, SPUIButtonStyleSmallNoBorder.class); + discardDistributionBtn.addClickListener(event -> discardDistribution()); } /** @@ -216,7 +216,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { } private void enableSaveButton() { - saveDistribution.setEnabled(true); + saveDistributionBtn.setEnabled(true); } private DistributionSetType getDefaultDistributionSetType() { @@ -226,7 +226,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { } private void disableSaveButton() { - saveDistribution.setEnabled(false); + saveDistributionBtn.setEnabled(false); } private void saveDistribution() { @@ -415,7 +415,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { distsetTypeNameComboBox.removeStyleName(SPUIStyleDefinitions.SP_COMBOFIELD_ERROR); descTextArea.clear(); reqMigStepCheckbox.clear(); - saveDistribution.setEnabled(true); + saveDistributionBtn.setEnabled(true); removeListeners(); changedComponents.clear(); } @@ -497,7 +497,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { public void populateValuesOfDistribution(final Long editDistId) { this.editDistId = editDistId; editDistribution = Boolean.TRUE; - saveDistribution.setEnabled(false); + saveDistributionBtn.setEnabled(false); final DistributionSet distSet = distributionSetManagement.findDistributionSetByIdWithDetails(editDistId); if (distSet != null) { distNameTextField.setValue(distSet.getName()); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java index 8f91bf336..c0f681c7a 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java @@ -107,32 +107,15 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin super.inittialize(); } - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.ui.common.confirmwindow.layout. - * AbstractConfirmationWindowLayout# getConfimrationTabs() - */ @Override protected Map getConfimrationTabs() { - final Map tabs = new HashMap(); - /** - * create tab for deleted distribution. - */ - - /* Create tab for SW Module Type delete */ + final Map tabs = new HashMap<>(); if (!managementUIState.getDeletedDistributionList().isEmpty()) { tabs.put(i18n.get("caption.delete.dist.accordion.tab"), createDeletedDistributionTab()); } - /** - * create tab for deleted target. - */ if (!managementUIState.getDeletedTargetList().isEmpty()) { tabs.put(i18n.get("caption.delete.target.accordion.tab"), createDeletedTargetTab()); } - /** - * create tab for assignment. - */ if (!managementUIState.getAssignedList().isEmpty()) { tabs.put(i18n.get("caption.assign.dist.accordion.tab"), createAssignmentTab()); } @@ -196,8 +179,8 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin private void saveAllAssignments(final ConfirmationTab tab) { final Set itemIds = managementUIState.getAssignedList().keySet(); Long distId; - List targetIdSetList = null; - List tempIdList = null; + List targetIdSetList; + List tempIdList; final ActionType actionType = ((ActionTypeOptionGroupLayout.ActionTypeOption) actionTypeOptionGroupLayout .getActionTypeOptionGroup().getValue()).getActionType(); final long forcedTimeStamp = (((ActionTypeOptionGroupLayout.ActionTypeOption) actionTypeOptionGroupLayout @@ -205,7 +188,7 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin ? actionTypeOptionGroupLayout.getForcedTimeDateField().getValue().getTime() : Action.NO_FORCE_TIME; - final Map> saveAssignedList = new HashMap>(); + final Map> saveAssignedList = new HashMap<>(); int successAssignmentCount = 0; int duplicateAssignmentCount = 0; @@ -216,7 +199,7 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin if (saveAssignedList.containsKey(distId)) { targetIdSetList = saveAssignedList.get(distId); } else { - targetIdSetList = new ArrayList(); + targetIdSetList = new ArrayList<>(); } targetIdSetList.add(itemId); saveAssignedList.put(distId, (ArrayList) targetIdSetList); @@ -275,15 +258,13 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin } private String getAssigmentSuccessMessage(final int assignedCount) { - final String assignment = FontAwesome.TASKS.getHtml() + SPUILabelDefinitions.HTML_SPACE + return FontAwesome.TASKS.getHtml() + SPUILabelDefinitions.HTML_SPACE + i18n.get("message.target.assignment", new Object[] { assignedCount }); - return assignment; } private String getDuplicateAssignmentMessage(final int alreadyAssignedCount) { - final String alreadyAssigned = FontAwesome.TASKS.getHtml() + SPUILabelDefinitions.HTML_SPACE + return FontAwesome.TASKS.getHtml() + SPUILabelDefinitions.HTML_SPACE + i18n.get("message.target.alreadyAssigned", new Object[] { alreadyAssignedCount }); - return alreadyAssigned; } private void discardAllAssignments(final ConfirmationTab tab) { @@ -456,7 +437,7 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin } private void deleteAllDistributions(final ConfirmationTab tab) { - final Set deletedIds = new HashSet(); + final Set deletedIds = new HashSet<>(); managementUIState.getDeletedDistributionList().forEach(distIdName -> deletedIds.add(distIdName.getId())); distributionSetManagement.deleteDistributionSet(deletedIds.toArray(new Long[deletedIds.size()])); addToConsolitatedMsg(FontAwesome.TRASH_O.getHtml() + SPUILabelDefinitions.HTML_SPACE @@ -516,7 +497,7 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin final IndexedContainer contactContainer = new IndexedContainer(); contactContainer.addContainerProperty(TARGET_ID, String.class, ""); contactContainer.addContainerProperty(TARGET_NAME, String.class, ""); - Item item = null; + Item item; for (final TargetIdName targteId : managementUIState.getDeletedTargetList()) { item = contactContainer.addItem(targteId); item.getItemProperty(TARGET_ID).setValue(targteId.getControllerId()); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java index 28fb4635f..3184bf923 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java @@ -62,20 +62,20 @@ public class ManagementUIState implements Serializable { private boolean distTagFilterClosed = true; - private Long targetsTruncated = null; + private Long targetsTruncated; private final AtomicLong targetsCountAll = new AtomicLong(); - private boolean isDsTableMaximized = Boolean.FALSE; + private boolean dsTableMaximized = Boolean.FALSE; // Contains ID and NAme of last selected target private DistributionSetIdName lastSelectedDsIdName; // Contains list of ID and Names of all the selected Targets private Set selectedDsIdName = Collections.emptySet(); - private boolean isTargetTableMaximized = Boolean.FALSE; + private boolean targetTableMaximized = Boolean.FALSE; - private boolean isActionHistoryMaximized = Boolean.FALSE; + private boolean actionHistoryMaximized = Boolean.FALSE; private boolean noDataAvilableTarget = Boolean.FALSE; @@ -255,11 +255,11 @@ public class ManagementUIState implements Serializable { } public boolean isDsTableMaximized() { - return isDsTableMaximized; + return dsTableMaximized; } public void setDsTableMaximized(final boolean isDsTableMaximized) { - this.isDsTableMaximized = isDsTableMaximized; + this.dsTableMaximized = isDsTableMaximized; } public DistributionSetIdName getLastSelectedDsIdName() { @@ -282,7 +282,7 @@ public class ManagementUIState implements Serializable { * @return the isTargetTableMaximized */ public boolean isTargetTableMaximized() { - return isTargetTableMaximized; + return targetTableMaximized; } /** @@ -290,14 +290,14 @@ public class ManagementUIState implements Serializable { * the isTargetTableMaximized to set */ public void setTargetTableMaximized(final boolean isTargetTableMaximized) { - this.isTargetTableMaximized = isTargetTableMaximized; + this.targetTableMaximized = isTargetTableMaximized; } /** * @return the isActionHistoryMaximized */ public boolean isActionHistoryMaximized() { - return isActionHistoryMaximized; + return actionHistoryMaximized; } /** @@ -305,7 +305,7 @@ public class ManagementUIState implements Serializable { * the isActionHistoryMaximized to set */ public void setActionHistoryMaximized(final boolean isActionHistoryMaximized) { - this.isActionHistoryMaximized = isActionHistoryMaximized; + this.actionHistoryMaximized = isActionHistoryMaximized; } /** diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/menu/DashboardMenu.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/menu/DashboardMenu.java index 44ec9ea40..beff0e6b9 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/menu/DashboardMenu.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/menu/DashboardMenu.java @@ -18,17 +18,16 @@ import java.util.List; import java.util.Optional; import java.util.stream.Collectors; +import org.eclipse.hawkbit.HawkbitServerProperties; import org.eclipse.hawkbit.im.authentication.PermissionService; import org.eclipse.hawkbit.im.authentication.UserPrincipal; +import org.eclipse.hawkbit.ui.UiProperties; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.documentation.DocumentationPageLink; import org.eclipse.hawkbit.ui.menu.DashboardEvent.PostViewChangeEvent; import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; -import org.eclipse.hawkbit.util.SPInfo; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.env.Environment; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; @@ -42,7 +41,6 @@ import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.UIScope; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Component; import com.vaadin.ui.CustomComponent; @@ -50,7 +48,6 @@ import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Link; import com.vaadin.ui.MenuBar; -import com.vaadin.ui.MenuBar.Command; import com.vaadin.ui.MenuBar.MenuItem; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.ValoTheme; @@ -61,11 +58,17 @@ import com.vaadin.ui.themes.ValoTheme; */ @SpringComponent @UIScope -public final class DashboardMenu extends CustomComponent implements EnvironmentAware { +public final class DashboardMenu extends CustomComponent { @Autowired private I18N i18n; + @Autowired + private transient UiProperties uiProperties; + + @Autowired + private transient HawkbitServerProperties serverProperties; + private static final long serialVersionUID = 5394474618559481462L; public static final String ID = "dashboard-menu"; @@ -74,16 +77,12 @@ public final class DashboardMenu extends CustomComponent implements EnvironmentA private static final String STYLE_VISIBLE = "valo-menu-visible"; // this should be resolved when we introduce event bus on UI to just inform - // the buttons directly - // via events + // the buttons directly via events private final List menuButtons = new ArrayList<>(); @Autowired private transient PermissionService permissionService; - @Autowired - private transient SPInfo spInfo; - @Autowired private final List dashboardVaadinViews = new ArrayList<>(); @@ -91,12 +90,10 @@ public final class DashboardMenu extends CustomComponent implements EnvironmentA private boolean accessibleViewsEmpty; - private String userManagementLoginUrl; - /** * initializing the view and creating the layout, cannot be done in the - * custructor because the constructor will be called by spring and the - * dashabord must be initialized when the dashboard UI is creating. + * constructor because the constructor will be called by spring and the + * dashboard must be initialized when the dashboard UI is creating. */ public void init() { initialViewName = ""; @@ -162,20 +159,20 @@ public final class DashboardMenu extends CustomComponent implements EnvironmentA links.addComponent(docuLink); links.setComponentAlignment(docuLink, Alignment.BOTTOM_CENTER); - if (userManagementLoginUrl != null) { + if (!uiProperties.getLinks().getUserManagement().isEmpty()) { final Link userManagementLink = SPUIComponentProvider.getLink(SPUIComponetIdProvider.LINK_USERMANAGEMENT, - i18n.get("link.usermanagement.name"), userManagementLoginUrl, FontAwesome.USERS, "_blank", - linkStyle, true); + i18n.get("link.usermanagement.name"), uiProperties.getLinks().getUserManagement(), + FontAwesome.USERS, "_blank", linkStyle, true); userManagementLink.setDescription(i18n.get("link.usermanagement.name")); links.addComponent(userManagementLink); userManagementLink.setSizeFull(); links.setComponentAlignment(userManagementLink, Alignment.BOTTOM_CENTER); } - if (spInfo.getSupportEmail() != null) { + if (!uiProperties.getLinks().getSupport().isEmpty()) { final Link supportLink = SPUIComponentProvider.getLink(SPUIComponetIdProvider.LINK_SUPPORT, - i18n.get("link.support.name"), spInfo.getSupportEmail(), FontAwesome.ENVELOPE_O, "", linkStyle, - true); + i18n.get("link.support.name"), uiProperties.getLinks().getSupport(), FontAwesome.ENVELOPE_O, "", + linkStyle, true); supportLink.setDescription(i18n.get("link.support.name")); supportLink.setSizeFull(); links.addComponent(supportLink); @@ -222,12 +219,7 @@ public final class DashboardMenu extends CustomComponent implements EnvironmentA settingsItem.setDescription(user.getUsername()); } - settingsItem.addItem("Sign Out", new Command() { - @Override - public void menuSelected(final MenuItem selectedItem) { - Page.getCurrent().setLocation("/UI/logout"); - } - }); + settingsItem.addItem("Sign Out", selectedItem -> Page.getCurrent().setLocation("/UI/logout")); return settings; } @@ -254,14 +246,11 @@ public final class DashboardMenu extends CustomComponent implements EnvironmentA } private Component buildToggleButton() { - final Button valoMenuToggleButton = new Button("Menu", new ClickListener() { - @Override - public void buttonClick(final ClickEvent event) { - if (getCompositionRoot().getStyleName().contains(STYLE_VISIBLE)) { - getCompositionRoot().removeStyleName(STYLE_VISIBLE); - } else { - getCompositionRoot().addStyleName(STYLE_VISIBLE); - } + final Button valoMenuToggleButton = new Button("Menu", (ClickListener) event -> { + if (getCompositionRoot().getStyleName().contains(STYLE_VISIBLE)) { + getCompositionRoot().removeStyleName(STYLE_VISIBLE); + } else { + getCompositionRoot().addStyleName(STYLE_VISIBLE); } }); valoMenuToggleButton.setIcon(FontAwesome.LIST); @@ -307,7 +296,7 @@ public final class DashboardMenu extends CustomComponent implements EnvironmentA final Label label = new Label(); label.setSizeFull(); label.setStyleName("version-layout"); - label.setValue(spInfo.getVersion()); + label.setValue(serverProperties.getBuild().getVersion()); return label; } @@ -341,11 +330,6 @@ public final class DashboardMenu extends CustomComponent implements EnvironmentA menuButtons.forEach(button -> button.postViewChange(event)); } - @Override - public void setEnvironment(final Environment environment) { - userManagementLoginUrl = environment.getProperty("hawkbit.server.im.login.url", String.class); - } - /** * Returns the dashboard view type by a given view name. * @@ -411,12 +395,7 @@ public final class DashboardMenu extends CustomComponent implements EnvironmentA setDescription(view.getDashboardCaptionLong()); /* Avoid double click */ setDisableOnClick(true); - addClickListener(new ClickListener() { - @Override - public void buttonClick(final ClickEvent event) { - event.getComponent().getUI().getNavigator().navigateTo(view.getViewName()); - } - }); + addClickListener(event -> event.getComponent().getUI().getNavigator().navigateTo(view.getViewName())); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/DelayedEventBusPushStrategy.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/DelayedEventBusPushStrategy.java new file mode 100644 index 000000000..87fcbe922 --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/DelayedEventBusPushStrategy.java @@ -0,0 +1,244 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.ui.push; + +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.BlockingDeque; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import org.eclipse.hawkbit.eventbus.event.DistributionSetTagCreatedBulkEvent; +import org.eclipse.hawkbit.eventbus.event.EntityEvent; +import org.eclipse.hawkbit.eventbus.event.RolloutChangeEvent; +import org.eclipse.hawkbit.eventbus.event.RolloutGroupChangeEvent; +import org.eclipse.hawkbit.eventbus.event.TargetCreatedEvent; +import org.eclipse.hawkbit.eventbus.event.TargetDeletedEvent; +import org.eclipse.hawkbit.eventbus.event.TargetInfoUpdateEvent; +import org.eclipse.hawkbit.eventbus.event.TargetTagCreatedBulkEvent; +import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.context.HttpSessionSecurityContextRepository; +import org.vaadin.spring.events.EventBus; +import org.vaadin.spring.events.EventBus.SessionEventBus; + +import com.google.common.collect.Sets; +import com.google.common.eventbus.AllowConcurrentEvents; +import com.google.common.eventbus.Subscribe; +import com.vaadin.server.VaadinSession; +import com.vaadin.server.VaadinSession.State; +import com.vaadin.server.WrappedSession; +import com.vaadin.ui.UI; + +/** + * A {@link EventPushStrategy} implementation which retrieves events from + * {@link com.google.common.eventbus.EventBus} and store them first in an queue + * where they will dispatched every 2 seconds to the {@link EventBus} in a + * Vaadin access thread {@link UI#access(Runnable)}. + * + * This strategy avoids blocking UIs when too many events are fired and + * dispatched to the UI thread. The UI will freeze in the time. To avoid that + * all events are collected first and same events are merged to a list of events + * before they dispatched to the UI thread. + * + * The strategy also verifies the current tenant in the session with the tenant + * in the event and only forwards event from the right tenant to the UI. + * + */ +public class DelayedEventBusPushStrategy implements EventPushStrategy { + + private static final Logger LOG = LoggerFactory.getLogger(DelayedEventBusPushStrategy.class); + + private static final int BLOCK_SIZE = 10_000; + private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + private final BlockingDeque queue = new LinkedBlockingDeque<>(BLOCK_SIZE); + private final EventBus.SessionEventBus eventBus; + private final com.google.common.eventbus.EventBus systemEventBus; + + private ScheduledFuture jobHandle; + + /** + * only events defined in the set are dispatched to the session event bus. + */ + private static final Set> UI_EVENTS = Sets.newHashSet(TargetInfoUpdateEvent.class, + TargetCreatedEvent.class, TargetDeletedEvent.class, RolloutChangeEvent.class, RolloutGroupChangeEvent.class, + TargetTagCreatedBulkEvent.class, DistributionSetTagCreatedBulkEvent.class); + + /** + * Constructor. + * + * @param eventBus + * the session event bus to where the events should be dispatched + * @param systemEventBus + * the system event bus where to retrieve the events from the + * back-end + */ + public DelayedEventBusPushStrategy(final SessionEventBus eventBus, + final com.google.common.eventbus.EventBus systemEventBus) { + this.eventBus = eventBus; + this.systemEventBus = systemEventBus; + } + + /** + * An {@link com.google.common.eventbus.EventBus} subscriber which + * subscribes {@link EntityEvent} from the repository to dispatch these + * events to the UI {@link SessionEventBus}. + * + * @param event + * the entity event which has been published from the repository + */ + @Subscribe + @AllowConcurrentEvents + public void dispatch(final org.eclipse.hawkbit.eventbus.event.Event event) { + // to dispatch too many events which are not interested on the UI + if (UI_EVENTS.contains(event.getClass()) && !queue.offer(event)) { + LOG.warn("Deque limit is reached, cannot add more events!!! Dropped event is {}", event); + return; + } + } + + @Override + public void init(final UI vaadinUI) { + LOG.debug("Initialize delayed event push strategy"); + jobHandle = executorService.scheduleWithFixedDelay(new DispatchRunnable(vaadinUI, vaadinUI.getSession()), 500, + 2000, TimeUnit.MILLISECONDS); + systemEventBus.register(this); + } + + @Override + public void clean() { + LOG.debug("Cleanup resources"); + jobHandle.cancel(true); + systemEventBus.unregister(this); + executorService.shutdownNow(); + queue.clear(); + } + + /** + * Checks if the tenant within the event is equal with the current tenant in + * the context. + * + * @param userContext + * the security context of the current session + * @param event + * the event to dispatch to the UI + * @return {@code true} if the event can be dispatched to the UI otherwise + * {@code false} + */ + protected boolean eventSecurityCheck(final SecurityContext userContext, + final org.eclipse.hawkbit.eventbus.event.Event event) { + if (userContext == null || userContext.getAuthentication() == null) { + return false; + } + final Object tenantAuthenticationDetails = userContext.getAuthentication().getDetails(); + if (tenantAuthenticationDetails instanceof TenantAwareAuthenticationDetails) { + return ((TenantAwareAuthenticationDetails) tenantAuthenticationDetails).getTenant() + .equalsIgnoreCase(event.getTenant()); + } + return false; + } + + private final class DispatchRunnable implements Runnable { + + private final UI vaadinUI; + private final VaadinSession vaadinSession; + + private DispatchRunnable(final UI ui, final VaadinSession session) { + vaadinUI = ui; + vaadinSession = session; + } + + @Override + public void run() { + LOG.debug("UI EventBus aggregator started"); + final long timestamp = System.currentTimeMillis(); + final List events = new LinkedList<>(); + for (int i = 0; i < BLOCK_SIZE; i++) { + final org.eclipse.hawkbit.eventbus.event.Event pollEvent = queue.poll(); + if (pollEvent == null) { + continue; + } + events.add(pollEvent); + } + + if (events.isEmpty()) { + return; + } + + if (vaadinSession == null) { + return; + } + + LOG.debug("UI EventBus aggregator session: {}", vaadinSession); + + final WrappedSession wrappedSession = vaadinSession.getSession(); + if (wrappedSession == null) { + return; + } + + final int eventsSize = events.size(); + + doDispatch(events, wrappedSession); + + LOG.debug("UI EventBus aggregator done with sending {} events in {} ms", eventsSize, + System.currentTimeMillis() - timestamp); + + } + + private void doDispatch(final List events, + final WrappedSession wrappedSession) { + final SecurityContext userContext = (SecurityContext) wrappedSession + .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); + final SecurityContext oldContext = SecurityContextHolder.getContext(); + try { + SecurityContextHolder.setContext(userContext); + vaadinUI.access(() -> { + if (vaadinSession.getState() != State.OPEN) { + return; + } + fowardEvents(events, userContext); + + // send a list of events, because ui performance issues + publishEventAsList(events, userContext, TargetInfoUpdateEvent.class); + publishEventAsList(events, userContext, TargetCreatedEvent.class); + publishEventAsList(events, userContext, TargetDeletedEvent.class); + }); + } finally { + SecurityContextHolder.setContext(oldContext); + } + } + + private void publishEventAsList(final List events, + final SecurityContext userContext, final Class eventType) { + final List bulkEvents = events.stream() + .filter(event -> DelayedEventBusPushStrategy.this.eventSecurityCheck(userContext, event) + && eventType.isInstance(event)) + .collect(Collectors.toList()); + if (bulkEvents.isEmpty()) { + return; + } + eventBus.publish(vaadinUI, bulkEvents); + } + + private void fowardEvents(final List events, + final SecurityContext userContext) { + events.stream().filter(event -> DelayedEventBusPushStrategy.this.eventSecurityCheck(userContext, event)) + .forEach(event -> eventBus.publish(vaadinUI, event)); + } + } + +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/EventPushStrategy.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/EventPushStrategy.java new file mode 100644 index 000000000..504dece60 --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/EventPushStrategy.java @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.ui.push; + +import com.vaadin.ui.UI; + +/** + * Interface declaring a strategy to push events from the back-end to the UI. + * + */ +public interface EventPushStrategy { + + /** + * Initialize the event push strategy, this is bound to the life-cycle of + * the {@link UI} so the strategy can be initialized based a {@link UI}. + * + * @param vaadinUI + * the {@link UI} + */ + void init(UI vaadinUI); + + /** + * Cleans up resources when the strategy is not be used anymore e.g. + * {@link UI#detach()}. + */ + void clean(); +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/AddUpdateRolloutWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/AddUpdateRolloutWindowLayout.java index d0cddfb19..cdcbbcede 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/AddUpdateRolloutWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/AddUpdateRolloutWindowLayout.java @@ -128,9 +128,9 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { private TextArea description; - private Button saveRollout; + private Button saveRolloutBtn; - private Button discardRolllout; + private Button discardRollloutBtn; private OptionGroup errorThresholdOptionGroup; @@ -138,7 +138,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { private Window addUpdateRolloutWindow; - private Boolean editRollout; + private Boolean editRolloutEnabled; private Rollout rolloutForEdit; @@ -167,7 +167,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { * Reset the field values. */ public void resetComponents() { - editRollout = Boolean.FALSE; + editRolloutEnabled = Boolean.FALSE; rolloutName.clear(); targetFilterQuery.clear(); resetFields(); @@ -212,7 +212,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { final HorizontalLayout groupLayout = new HorizontalLayout(); groupLayout.setSizeFull(); groupLayout.addComponents(noOfGroups, groupSizeLabel); - groupLayout.setExpandRatio(noOfGroups, 1.0f); + groupLayout.setExpandRatio(noOfGroups, 1.0F); groupLayout.setComponentAlignment(groupSizeLabel, Alignment.MIDDLE_LEFT); return groupLayout; } @@ -221,7 +221,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { final HorizontalLayout errorThresoldLayout = new HorizontalLayout(); errorThresoldLayout.setSizeFull(); errorThresoldLayout.addComponents(errorThreshold, errorThresholdOptionGroup); - errorThresoldLayout.setExpandRatio(errorThreshold, 1.0f); + errorThresoldLayout.setExpandRatio(errorThreshold, 1.0F); return errorThresoldLayout; } @@ -229,9 +229,9 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { final HorizontalLayout targetFilterLayout = new HorizontalLayout(); targetFilterLayout.setSizeFull(); targetFilterLayout.addComponents(targetFilterQueryCombo, targetFilterQuery, totalTargetsLabel); - targetFilterLayout.setExpandRatio(targetFilterQueryCombo, 0.71f); - targetFilterLayout.setExpandRatio(targetFilterQuery, 0.70f); - targetFilterLayout.setExpandRatio(totalTargetsLabel, 0.29f); + targetFilterLayout.setExpandRatio(targetFilterQueryCombo, 0.71F); + targetFilterLayout.setExpandRatio(targetFilterQuery, 0.70F); + targetFilterLayout.setExpandRatio(totalTargetsLabel, 0.29F); targetFilterLayout.setComponentAlignment(totalTargetsLabel, Alignment.MIDDLE_LEFT); return targetFilterLayout; } @@ -240,7 +240,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { final HorizontalLayout triggerThresholdLayout = new HorizontalLayout(); triggerThresholdLayout.setSizeFull(); triggerThresholdLayout.addComponents(triggerThreshold, getPercentHintLabel()); - triggerThresholdLayout.setExpandRatio(triggerThreshold, 1.0f); + triggerThresholdLayout.setExpandRatio(triggerThreshold, 1.0F); return triggerThresholdLayout; } @@ -254,9 +254,9 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { private HorizontalLayout getSaveDiscardButtonLayout() { final HorizontalLayout buttonsLayout = new HorizontalLayout(); buttonsLayout.setSizeFull(); - buttonsLayout.addComponents(saveRollout, discardRolllout); - buttonsLayout.setComponentAlignment(saveRollout, Alignment.BOTTOM_LEFT); - buttonsLayout.setComponentAlignment(discardRolllout, Alignment.BOTTOM_RIGHT); + buttonsLayout.addComponents(saveRolloutBtn, discardRollloutBtn); + buttonsLayout.setComponentAlignment(saveRolloutBtn, Alignment.BOTTOM_LEFT); + buttonsLayout.setComponentAlignment(discardRollloutBtn, Alignment.BOTTOM_RIGHT); buttonsLayout.addStyleName("window-style"); return buttonsLayout; } @@ -277,8 +277,8 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { description = createDescription(); errorThresholdOptionGroup = createErrorThresholdOptionGroup(); setDefaultSaveStartGroupOption(); - saveRollout = createSaveButton(); - discardRolllout = createDiscardButton(); + saveRolloutBtn = createSaveButton(); + discardRollloutBtn = createDiscardButton(); actionTypeOptionGroupLayout.selectDefaultOption(); totalTargetsLabel = createTotalTargetsLabel(); @@ -383,8 +383,9 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { private Container createTargetFilterComboContainer() { final BeanQueryFactory targetFilterQF = new BeanQueryFactory<>( TargetFilterBeanQuery.class); - return new LazyQueryContainer(new LazyQueryDefinition(true, SPUIDefinitions.PAGE_SIZE, - SPUILabelDefinitions.VAR_NAME), targetFilterQF); + return new LazyQueryContainer( + new LazyQueryDefinition(true, SPUIDefinitions.PAGE_SIZE, SPUILabelDefinitions.VAR_NAME), + targetFilterQF); } @@ -410,7 +411,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { } private void onRolloutSave() { - if (editRollout) { + if (editRolloutEnabled) { editRollout(); } else { createRollout(); @@ -422,8 +423,8 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { rolloutForEdit.setName(rolloutName.getValue()); rolloutForEdit.setDescription(description.getValue()); final DistributionSetIdName distributionSetIdName = (DistributionSetIdName) distributionSet.getValue(); - rolloutForEdit.setDistributionSet(distributionSetManagement.findDistributionSetById(distributionSetIdName - .getId())); + rolloutForEdit.setDistributionSet( + distributionSetManagement.findDistributionSetById(distributionSetIdName.getId())); rolloutForEdit.setActionType(getActionType()); rolloutForEdit.setForcedTime(getForcedTimeStamp()); final int amountGroup = Integer.parseInt(noOfGroups.getValue()); @@ -453,8 +454,9 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { private long getForcedTimeStamp() { return (((ActionTypeOptionGroupLayout.ActionTypeOption) actionTypeOptionGroupLayout.getActionTypeOptionGroup() - .getValue()) == ActionTypeOption.AUTO_FORCED) ? actionTypeOptionGroupLayout.getForcedTimeDateField() - .getValue().getTime() : Action.NO_FORCE_TIME; + .getValue()) == ActionTypeOption.AUTO_FORCED) + ? actionTypeOptionGroupLayout.getForcedTimeDateField().getValue().getTime() + : Action.NO_FORCE_TIME; } private ActionType getActionType() { @@ -487,8 +489,8 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { rolloutToCreate.setName(rolloutName.getValue()); rolloutToCreate.setDescription(description.getValue()); rolloutToCreate.setTargetFilterQuery(targetFilter); - rolloutToCreate.setDistributionSet(distributionSetManagement.findDistributionSetById(distributionSetIdName - .getId())); + rolloutToCreate + .setDistributionSet(distributionSetManagement.findDistributionSetById(distributionSetIdName.getId())); rolloutToCreate.setActionType(getActionType()); rolloutToCreate.setForcedTime(getForcedTimeStamp()); @@ -499,8 +501,8 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { private String getTargetFilterQuery() { if (null != targetFilterQueryCombo.getValue() && HawkbitCommonUtil.trimAndNullIfEmpty((String) targetFilterQueryCombo.getValue()) != null) { - final Item filterItem = targetFilterQueryCombo.getContainerDataSource().getItem( - targetFilterQueryCombo.getValue()); + final Item filterItem = targetFilterQueryCombo.getContainerDataSource() + .getItem(targetFilterQueryCombo.getValue()); return (String) filterItem.getItemProperty("query").getValue(); } return null; @@ -568,8 +570,8 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { private boolean duplicateCheck() { if (rolloutManagement.findRolloutByName(getRolloutName()) != null) { - uiNotification.displayValidationError(i18n.get("message.rollout.duplicate.check", - new Object[] { getRolloutName() })); + uiNotification.displayValidationError( + i18n.get("message.rollout.duplicate.check", new Object[] { getRolloutName() })); return false; } return true; @@ -580,9 +582,8 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { } private TextArea createDescription() { - final TextArea descriptionField = SPUIComponentProvider.getTextArea("text-area-style", - ValoTheme.TEXTFIELD_TINY, false, null, i18n.get("textfield.description"), - SPUILabelDefinitions.TEXT_AREA_MAX_LENGTH); + final TextArea descriptionField = SPUIComponentProvider.getTextArea("text-area-style", ValoTheme.TEXTFIELD_TINY, + false, null, i18n.get("textfield.description"), SPUILabelDefinitions.TEXT_AREA_MAX_LENGTH); descriptionField.setId(SPUIComponetIdProvider.ROLLOUT_DESCRIPTION_ID); descriptionField.setNullRepresentation(HawkbitCommonUtil.SP_STRING_EMPTY); descriptionField.setSizeFull(); @@ -647,8 +648,9 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { private Container createDsComboContainer() { final BeanQueryFactory distributionQF = new BeanQueryFactory<>(DistBeanQuery.class); - return new LazyQueryContainer(new LazyQueryDefinition(true, SPUIDefinitions.PAGE_SIZE, - SPUILabelDefinitions.VAR_DIST_ID_NAME), distributionQF); + return new LazyQueryContainer( + new LazyQueryDefinition(true, SPUIDefinitions.PAGE_SIZE, SPUILabelDefinitions.VAR_DIST_ID_NAME), + distributionQF); } @@ -682,8 +684,8 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { try { if (HawkbitCommonUtil.trimAndNullIfEmpty(noOfGroups.getValue()) == null || HawkbitCommonUtil.trimAndNullIfEmpty((String) targetFilterQueryCombo.getValue()) == null) { - uiNotification.displayValidationError(i18n - .get("message.rollout.noofgroups.or.targetfilter.missing")); + uiNotification + .displayValidationError(i18n.get("message.rollout.noofgroups.or.targetfilter.missing")); } else { new RegexpValidator(NUMBER_REGEXP, i18n.get(MESSAGE_ENTER_NUMBER)).validate(value); final int groupSize = getGroupSize(); @@ -708,8 +710,8 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { public void validate(final Object value) { try { new RegexpValidator(NUMBER_REGEXP, i18n.get(MESSAGE_ENTER_NUMBER)).validate(value); - new IntegerRangeValidator(i18n.get(MESSAGE_ROLLOUT_FIELD_VALUE_RANGE, 0, 100), 0, 100).validate(Integer - .valueOf(value.toString())); + new IntegerRangeValidator(i18n.get(MESSAGE_ROLLOUT_FIELD_VALUE_RANGE, 0, 100), 0, 100) + .validate(Integer.valueOf(value.toString())); } catch (final InvalidValueException ex) { throw ex; } @@ -723,8 +725,8 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { public void validate(final Object value) { try { new RegexpValidator(NUMBER_REGEXP, i18n.get(MESSAGE_ENTER_NUMBER)).validate(value); - new IntegerRangeValidator(i18n.get(MESSAGE_ROLLOUT_FIELD_VALUE_RANGE, 0, 500), 0, 500).validate(Integer - .valueOf(value.toString())); + new IntegerRangeValidator(i18n.get(MESSAGE_ROLLOUT_FIELD_VALUE_RANGE, 0, 500), 0, 500) + .validate(Integer.valueOf(value.toString())); } catch (final InvalidValueException ex) { throw ex; } @@ -740,7 +742,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { */ public void populateData(final Long rolloutId) { resetComponents(); - editRollout = Boolean.TRUE; + editRolloutEnabled = Boolean.TRUE; rolloutForEdit = rolloutManagement.findRolloutById(rolloutId); rolloutName.setValue(rolloutForEdit.getName()); description.setValue(rolloutForEdit.getDescription()); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/GatewaySecurityTokenAuthenticationConfigurationItem.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/GatewaySecurityTokenAuthenticationConfigurationItem.java index 0d3f496ba..fa1ca9271 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/GatewaySecurityTokenAuthenticationConfigurationItem.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/GatewaySecurityTokenAuthenticationConfigurationItem.java @@ -83,10 +83,9 @@ public class GatewaySecurityTokenAuthenticationConfigurationItem extends Abstrac gatewayTokenNameTextField = SPUIComponentProvider.getTextField("", ValoTheme.TEXTFIELD_TINY, false, null, "", true, SPUILabelDefinitions.TEXT_FIELD_MAX_LENGTH); gatewayTokenNameTextField.setImmediate(true); - // hide text field until we support multiple gateway tokens for a tenant - // MECS-830 + // hide text field until we support multiple gateway tokens for a tenan gatewayTokenNameTextField.setVisible(false); - gatewayTokenNameTextField.addTextChangeListener(event -> keyNameChanged()); + gatewayTokenNameTextField.addTextChangeListener(event -> doKeyNameChanged()); final Button gatewaytokenBtn = SPUIComponentProvider.getButton("TODO-ID", "Regenerate Key", "", ValoTheme.BUTTON_TINY + " " + "redicon", true, null, SPUIButtonStyleSmall.class); @@ -116,10 +115,7 @@ public class GatewaySecurityTokenAuthenticationConfigurationItem extends Abstrac } } - /** - * @return - */ - private void keyNameChanged() { + private void doKeyNameChanged() { keyNameChanged = true; notifyConfigurationChanged(); } diff --git a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/push/SpringSecurityAtmosphereInterceptorTest.java b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/push/SpringSecurityAtmosphereInterceptorTest.java index 84b48a004..bcf0dcf72 100644 --- a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/push/SpringSecurityAtmosphereInterceptorTest.java +++ b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/push/SpringSecurityAtmosphereInterceptorTest.java @@ -25,7 +25,13 @@ import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@Features("Unit Tests - Management UI") +@Stories("Push Security") @RunWith(MockitoJUnitRunner.class) +// TODO: create description annotations public class SpringSecurityAtmosphereInterceptorTest { @Mock diff --git a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/utils/NamingThreadFactoryTest.java b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/utils/NamingThreadFactoryTest.java index 1ff1b3d33..d91d4cba2 100644 --- a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/utils/NamingThreadFactoryTest.java +++ b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/utils/NamingThreadFactoryTest.java @@ -24,7 +24,7 @@ import org.springframework.context.annotation.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -@Features("Component Tests - UI") +@Features("Unit Tests - Management UI") @Stories("Threads with NamingThreadFactory") @RunWith(MockitoJUnitRunner.class) public class NamingThreadFactoryTest { diff --git a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/utils/SPUIComponentProviderTest.java b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/utils/SPUIComponentProviderTest.java index 1f4798ad5..f818bc15d 100644 --- a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/utils/SPUIComponentProviderTest.java +++ b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/utils/SPUIComponentProviderTest.java @@ -19,12 +19,15 @@ import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.Button; import com.vaadin.ui.Label; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + /** * Unit Test block for UI Component provider. Dynamic Factory Testing. * - * - * */ +@Features("Unit Tests - Management UI") +@Stories("UI components") public class SPUIComponentProviderTest { /** * Test case for check button factory. diff --git a/pom.xml b/pom.xml index d481a56fb..fffce192a 100644 --- a/pom.xml +++ b/pom.xml @@ -74,7 +74,7 @@ 1.0.0 0.0.6.RELEASE - 7.5.10 + 7.6.3 ${vaadin.version} 7.4.0.1 2.2.0 @@ -86,7 +86,7 @@ 1.4 2.0M10 - 1.4.15 + 1.4.22 2.6.2 1.5.4 1.0.2 @@ -559,7 +559,6 @@ org.json json ${json.version} - test de.flapdoodle.embed