From c737614e9b6aed1dc45dd3d9441112f218900c4c Mon Sep 17 00:00:00 2001 From: SirWayne Date: Mon, 15 Feb 2016 08:55:44 +0100 Subject: [PATCH 01/58] Add sender service to customize sending messages Signed-off-by: SirWayne --- .../hawkbit/amqp/AmqpConfiguration.java | 12 ++- .../amqp/AmqpMessageDispatcherService.java | 62 +++++--------- .../amqp/AmqpMessageHandlerService.java | 80 ++++++++----------- .../hawkbit/amqp/AmqpSenderService.java | 24 ++++++ .../eclipse/hawkbit/amqp/BaseAmqpService.java | 60 ++++++++++++++ .../amqp/DefaultAmqpSenderService.java | 29 +++++++ .../AmqpControllerAuthentficationTest.java | 6 +- .../AmqpMessageDispatcherServiceTest.java | 21 ++--- .../amqp/AmqpMessageHandlerServiceTest.java | 10 +-- .../java/org/eclipse/hawkbit/util/IpUtil.java | 6 +- .../org/eclipse/hawkbit/util/IpUtilTest.java | 17 ++-- 11 files changed, 205 insertions(+), 122 deletions(-) create mode 100644 hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpSenderService.java create mode 100644 hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/BaseAmqpService.java create mode 100644 hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/DefaultAmqpSenderService.java 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..7ad557717 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 @@ -125,7 +125,17 @@ public class AmqpConfiguration { */ @Bean public AmqpMessageHandlerService amqpMessageHandlerService() { - return new AmqpMessageHandlerService(); + return new AmqpMessageHandlerService(jsonMessageConverter(), rabbitTemplate); + } + + /** + * Create amqp handler service bean. + * + * @return + */ + @Bean + public AmqpSenderService amqpSenderServiceBean() { + return new DefaultAmqpSenderService(rabbitTemplate); } /** 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..06809d47e 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,13 +25,12 @@ 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.amqp.support.converter.MessageConverter; import org.springframework.beans.factory.annotation.Autowired; import com.google.common.eventbus.Subscribe; @@ -43,17 +42,19 @@ import com.google.common.eventbus.Subscribe; * */ @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; + + @Autowired + public AmqpMessageDispatcherService(final MessageConverter messageConverter, final RabbitTemplate defaultTemplate) { + super(messageConverter, defaultTemplate); + } + /** * Method to send a message to a RabbitMQ Exchange after the Distribution * set has been assign to a Target. @@ -79,11 +80,9 @@ public class AmqpMessageDispatcherService { downloadAndUpdateRequest.addSoftwareModule(amqpSoftwareModule); } - final Message message = rabbitTemplate.getMessageConverter().toMessage( - downloadAndUpdateRequest, - createConnectorMessageProperties(targetAssignDistributionSetEvent.getTenant(), controllerId, - EventTopic.DOWNLOAD_AND_INSTALL)); - sendMessage(targetAdress.getHost(), message); + final Message message = messageConverter.toMessage(downloadAndUpdateRequest, createConnectorMessageProperties( + targetAssignDistributionSetEvent.getTenant(), controllerId, EventTopic.DOWNLOAD_AND_INSTALL)); + amqpSenderService.sendMessage(message, targetAdress); } /** @@ -98,29 +97,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 = messageConverter.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 +138,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,14 +157,6 @@ 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; } 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..5eed2945c 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 @@ -50,7 +50,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; @@ -78,13 +77,10 @@ import com.google.common.eventbus.EventBus; * * */ -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; @@ -104,6 +100,14 @@ public class AmqpMessageHandlerService { @Autowired private HostnameResolver hostnameResolver; + /** + * @param messageConverter + */ + @Autowired + public AmqpMessageHandlerService(final MessageConverter messageConverter, final RabbitTemplate defaultTemplate) { + super(messageConverter, defaultTemplate); + } + /** * /** Method to handle all incoming amqp messages. * @@ -153,8 +157,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 +181,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 +200,7 @@ public class AmqpMessageHandlerService { authentificationResponse.setMessage(errorMessage); } - return rabbitTemplate.getMessageConverter().toMessage(authentificationResponse, messageProperties); + return messageConverter.toMessage(authentificationResponse, messageProperties); } private static Artifact convertDbArtifact(final DbArtifact dbArtifact) { @@ -219,9 +223,9 @@ 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); } @@ -250,7 +254,8 @@ public class AmqpMessageHandlerService { 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(getVirtualHost(message), replyTo); final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotexist(thingId, amqpUri); LOG.debug("Target {} reported online state.", thingId); @@ -267,8 +272,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 +286,10 @@ 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."); } /** @@ -356,8 +358,8 @@ public class AmqpMessageHandlerService { */ 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 +368,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,27 +383,11 @@ 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. * @@ -428,12 +414,12 @@ public class AmqpMessageHandlerService { this.hostnameResolver = hostnameResolver; } - void setRabbitTemplate(final RabbitTemplate rabbitTemplate) { - this.rabbitTemplate = rabbitTemplate; + void setMessageConverter(final MessageConverter messageConverter) { + this.messageConverter = messageConverter; } MessageConverter getMessageConverter() { - return rabbitTemplate.getMessageConverter(); + return messageConverter; } void setAuthenticationManager(final AmqpControllerAuthentfication authenticationManager) { 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..b7d8ed4e7 --- /dev/null +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpSenderService.java @@ -0,0 +1,24 @@ +package org.eclipse.hawkbit.amqp; + +import java.net.URI; + +import org.springframework.amqp.core.Message; + +/** + * Copyright (c) 2011-2016 Bosch Software Innovations GmbH, Germany. All rights reserved. + */ + +/** + * + */ +@FunctionalInterface +public interface AmqpSenderService { + + /** + * + * @param message + * @param uri + */ + void sendMessage(Message message, URI uri); + +} 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..8371a0586 --- /dev/null +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/BaseAmqpService.java @@ -0,0 +1,60 @@ +/** + * Copyright (c) 2011-2016 Bosch Software Innovations GmbH, Germany. All rights reserved. + */ +package org.eclipse.hawkbit.amqp; + +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; +import org.springframework.beans.factory.annotation.Autowired; + +/** + * @author Dennis Melzer + * + */ +public class BaseAmqpService { + + protected static final String VIRTUAL_HOST_MESSAGE_HEADER = "VHOST_HEADER"; + + protected MessageConverter messageConverter; + + protected RabbitTemplate spInternalConnectorTemplate; + + @Autowired + public BaseAmqpService(final MessageConverter messageConverter, final RabbitTemplate defaultTemplate) { + this.messageConverter = messageConverter; + spInternalConnectorTemplate = defaultTemplate; + } + + protected String getVirtualHost(final Message message) { + final Object virtualHost = message.getMessageProperties().getHeaders().get(VIRTUAL_HOST_MESSAGE_HEADER); + + if (virtualHost == null) { + return spInternalConnectorTemplate.getConnectionFactory().getVirtualHost(); + } + return virtualHost.toString(); + } + + protected void cleanMessage(final Message message) { + message.getMessageProperties().getHeaders().remove(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME); + message.getMessageProperties().getHeaders().remove(VIRTUAL_HOST_MESSAGE_HEADER); + } + + /** + * 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") + protected T convertMessage(final Message message, final Class clazz) { + message.getMessageProperties().getHeaders().put(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME, + clazz.getTypeName()); + return (T) messageConverter.fromMessage(message); + } + +} 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..5a51f9b9f --- /dev/null +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/DefaultAmqpSenderService.java @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2011-2016 Bosch Software Innovations GmbH, Germany. All rights reserved. + */ +package org.eclipse.hawkbit.amqp; + +import java.net.URI; + +import org.springframework.amqp.core.Message; +import org.springframework.amqp.rabbit.core.RabbitTemplate; + +/** + * + */ +public class DefaultAmqpSenderService extends BaseAmqpService implements AmqpSenderService { + + /** + * @param messageConverter + * @param defaultTemplate + */ + public DefaultAmqpSenderService(final RabbitTemplate defaultTemplate) { + super(defaultTemplate.getMessageConverter(), defaultTemplate); + } + + @Override + public void sendMessage(final Message message, final URI uri) { + spInternalConnectorTemplate.send(uri.getPath(), message); + } + +} 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/AmqpControllerAuthentficationTest.java index 5a77c5fce..f5102c3c3 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/AmqpControllerAuthentficationTest.java @@ -60,11 +60,8 @@ 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); + amqpMessageHandlerService = new AmqpMessageHandlerService(messageConverter, mock(RabbitTemplate.class)); authenticationManager = new AmqpControllerAuthentfication(); authenticationManager.setControllerManagement(mock(ControllerManagement.class)); @@ -78,7 +75,6 @@ public class AmqpControllerAuthentficationTest { final ControllerManagement controllerManagement = mock(ControllerManagement.class); when(controllerManagement.getSecurityTokenByControllerId(anyString())).thenReturn(CONTROLLLER_ID); authenticationManager.setControllerManagement(controllerManagement); - amqpMessageHandlerService.setArtifactManagement(mock(ArtifactManagement.class)); authenticationManager.setTenantAware(new SecurityContextTenantAware()); 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 348e8dea4..dc9cd8e01 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 @@ -15,7 +15,6 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; @@ -59,6 +58,8 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit private AmqpMessageDispatcherService amqpMessageDispatcherService; + private AmqpSenderService senderService; + private MessageConverter messageConverter; private RabbitTemplate rabbitTemplate; @@ -68,7 +69,7 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit @Override public void before() throws Exception { super.before(); - amqpMessageDispatcherService = new AmqpMessageDispatcherService(); + amqpMessageDispatcherService = new AmqpMessageDispatcherService(messageConverter, rabbitTemplate); amqpMessageDispatcherService = spy(amqpMessageDispatcherService); messageConverter = new Jackson2JsonMessageConverter(); @@ -78,16 +79,17 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit this.rabbitTemplate = Mockito.mock(RabbitTemplate.class); when(rabbitTemplate.getMessageConverter()).thenReturn(messageConverter); - amqpMessageDispatcherService.setRabbitTemplate(rabbitTemplate); - amqpMessageDispatcherService.setTenantAware(tenantAware); amqpMessageDispatcherService.setArtifactUrlHandler(artifactUrlHandlerMock); + + senderService = new DefaultAmqpSenderService(rabbitTemplate); } @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 DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage); @@ -100,7 +102,7 @@ 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 DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage); @@ -134,7 +136,7 @@ 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 DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage); @@ -152,7 +154,7 @@ 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( @@ -194,7 +196,8 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit protected Message createArgumentCapture(final String exchange) { final ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Message.class); - Mockito.verify(amqpMessageDispatcherService).sendMessage(eq(exchange), argumentCaptor.capture()); + // Mockito.verify(senderService).sendMessage(argumentCaptor.capture(), + // eq(exchange)); 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 bea75e9d6..189d79487 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 @@ -99,14 +99,14 @@ 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); + amqpMessageHandlerService = new AmqpMessageHandlerService(messageConverter, rabbitTemplate); + amqpMessageHandlerService.setControllerManagement(controllerManagementMock); amqpMessageHandlerService.setAuthenticationManager(authenticationManagerMock); amqpMessageHandlerService.setArtifactManagement(artifactManagementMock); amqpMessageHandlerService.setCache(cacheMock); 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..79285dfd6 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 @@ -95,7 +95,6 @@ public final class IpUtil { if (isIpV6) { return URI.create(scheme + SCHEME_SEPERATOR + "[" + host + "]"); } - return URI.create(scheme + SCHEME_SEPERATOR + host); } @@ -108,8 +107,9 @@ public final class IpUtil { * @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 virtualHost, final String exchange) { + // TODO check + return createUri(AMPQP_SCHEME, virtualHost).resolve(exchange); } /** 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 e1e809ab8..30aa161ad 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 @@ -104,23 +104,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(IpUtil.isAmqpUri(httpUri)); - assertFalse(IpUtil.isHttpUri(httpUri)); - assertEquals(host, httpUri.getHost()); - assertEquals("amqp", httpUri.getScheme()); + private void assertAmqpUri(final String host, final URI amqpUri) { + assertTrue(IpUtil.isAmqpUri(amqpUri)); + assertFalse(IpUtil.isHttpUri(amqpUri)); + assertEquals(host, amqpUri.getHost()); + assertEquals("amqp", amqpUri.getScheme()); + assertEquals("path", amqpUri.getPath()); } @Test(expected = IllegalArgumentException.class) From 5d7ade1cf2de189f94aec645002935da26e7d100 Mon Sep 17 00:00:00 2001 From: SirWayne Date: Mon, 15 Feb 2016 16:20:45 +0100 Subject: [PATCH 02/58] Add create tenant Signed-off-by: SirWayne --- .../hawkbit/cache/TenantAwareCacheManager.java | 14 ++++++++++++-- .../eclipse/hawkbit/amqp/AmqpConfiguration.java | 2 ++ .../org/eclipse/hawkbit/amqp/BaseAmqpService.java | 2 -- .../hawkbit/MultiTenantJpaTransactionManager.java | 4 +++- 4 files changed, 17 insertions(+), 5 deletions(-) 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-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 7ad557717..42b91e89b 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; @@ -134,6 +135,7 @@ public class AmqpConfiguration { * @return */ @Bean + @ConditionalOnMissingBean public AmqpSenderService amqpSenderServiceBean() { return new DefaultAmqpSenderService(rabbitTemplate); } 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 index 8371a0586..adc5b43f6 100644 --- 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 @@ -7,7 +7,6 @@ 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; -import org.springframework.beans.factory.annotation.Autowired; /** * @author Dennis Melzer @@ -21,7 +20,6 @@ public class BaseAmqpService { protected RabbitTemplate spInternalConnectorTemplate; - @Autowired public BaseAmqpService(final MessageConverter messageConverter, final RabbitTemplate defaultTemplate) { this.messageConverter = messageConverter; spInternalConnectorTemplate = defaultTemplate; 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) { From 91dfbbd3a6128ec3ba6089519e41c9633fa266ba Mon Sep 17 00:00:00 2001 From: SirWayne Date: Mon, 15 Feb 2016 16:48:02 +0100 Subject: [PATCH 03/58] Extract exchange from URI Signed-off-by: SirWayne --- .../main/java/org/eclipse/hawkbit/amqp/BaseAmqpService.java | 6 ++++++ .../org/eclipse/hawkbit/amqp/DefaultAmqpSenderService.java | 2 +- .../src/main/java/org/eclipse/hawkbit/util/IpUtil.java | 3 +-- .../src/test/java/org/eclipse/hawkbit/util/IpUtilTest.java | 2 +- 4 files changed, 9 insertions(+), 4 deletions(-) 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 index adc5b43f6..faed3eb74 100644 --- 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 @@ -3,6 +3,8 @@ */ package org.eclipse.hawkbit.amqp; +import java.net.URI; + import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.support.converter.AbstractJavaTypeMapper; @@ -55,4 +57,8 @@ public class BaseAmqpService { return (T) messageConverter.fromMessage(message); } + protected String getExchangeFromAmqpUri(final URI amqpUri) { + return amqpUri.getPath().substring(1); + } + } 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 index 5a51f9b9f..1b962da19 100644 --- 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 @@ -23,7 +23,7 @@ public class DefaultAmqpSenderService extends BaseAmqpService implements AmqpSen @Override public void sendMessage(final Message message, final URI uri) { - spInternalConnectorTemplate.send(uri.getPath(), message); + spInternalConnectorTemplate.send(getExchangeFromAmqpUri(uri), message); } } 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 79285dfd6..07c22e796 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 @@ -108,8 +108,7 @@ public final class IpUtil { * If the given string not parsable */ public static URI createAmqpUri(final String virtualHost, final String exchange) { - // TODO check - return createUri(AMPQP_SCHEME, virtualHost).resolve(exchange); + return createUri(AMPQP_SCHEME, virtualHost).resolve("/" + exchange); } /** 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 30aa161ad..47e9bfe9a 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 @@ -121,7 +121,7 @@ public class IpUtilTest { assertFalse(IpUtil.isHttpUri(amqpUri)); assertEquals(host, amqpUri.getHost()); assertEquals("amqp", amqpUri.getScheme()); - assertEquals("path", amqpUri.getPath()); + assertEquals("/path", amqpUri.getRawPath()); } @Test(expected = IllegalArgumentException.class) From be68ad32f521e1c00b1ec6d919802ed24524faa9 Mon Sep 17 00:00:00 2001 From: SirWayne Date: Tue, 16 Feb 2016 09:22:54 +0100 Subject: [PATCH 04/58] Add JavaDoc and refactor staff for clean code convention Signed-off-by: SirWayne --- .../amqp/AmqpMessageHandlerService.java | 21 ++----------------- .../eclipse/hawkbit/amqp/AmqpProperties.java | 4 ++-- .../eclipse/hawkbit/amqp/BaseAmqpService.java | 19 ++++++++++++++++- 3 files changed, 22 insertions(+), 22 deletions(-) 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 5eed2945c..539d652b6 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; @@ -71,10 +70,8 @@ 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 extends BaseAmqpService { @@ -211,11 +208,6 @@ public class AmqpMessageHandlerService extends BaseAmqpService { 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); @@ -230,15 +222,6 @@ public class AmqpMessageHandlerService extends BaseAmqpService { 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. * 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..2c3477c1f 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 @@ -22,8 +22,8 @@ import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("hawkbit.dmf.rabbitmq") public class AmqpProperties { - private String deadLetterQueue = "dmf_connector_deadletter"; - private String deadLetterExchange = "dmf.connector.deadletter"; + private String deadLetterQueue = "dmf_receiver_deadletter"; + private String deadLetterExchange = "dmf.receiver.deadletter"; private String receiverQueue = "dmf_receiver"; private boolean missingQueuesFatal = false; 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 index faed3eb74..9b0702d41 100644 --- 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 @@ -4,18 +4,21 @@ package org.eclipse.hawkbit.amqp; import java.net.URI; +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; /** - * @author Dennis Melzer * */ public class BaseAmqpService { + private static final Logger LOGGER = LoggerFactory.getLogger(BaseAmqpService.class); protected static final String VIRTUAL_HOST_MESSAGE_HEADER = "VHOST_HEADER"; protected MessageConverter messageConverter; @@ -61,4 +64,18 @@ public class BaseAmqpService { return amqpUri.getPath().substring(1); } + protected 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(); + } + + protected void logAndThrowMessageError(final Message message, final String error) { + LOGGER.error("Error \"{}\" reported by message {}", error, message.getMessageProperties().getMessageId()); + throw new IllegalArgumentException(error); + } + } From b4421e7e4419c6b68f1a41e2f0a8b5e03f297742 Mon Sep 17 00:00:00 2001 From: SirWayne Date: Tue, 16 Feb 2016 12:24:33 +0100 Subject: [PATCH 05/58] Add JavaDoc, refactor staff for clean code convention and modify unit tests Signed-off-by: SirWayne --- .../hawkbit/amqp/AmqpConfiguration.java | 4 +- .../amqp/AmqpControllerAuthentfication.java | 5 +- .../amqp/AmqpMessageDispatcherService.java | 12 +++-- .../amqp/AmqpMessageHandlerService.java | 42 ++++++++++------ .../eclipse/hawkbit/amqp/AmqpProperties.java | 37 -------------- .../hawkbit/amqp/AmqpSenderService.java | 30 ++++++++++-- .../eclipse/hawkbit/amqp/BaseAmqpService.java | 30 ++++-------- .../amqp/DefaultAmqpSenderService.java | 27 +++++++---- .../hawkbit/AmqpTestConfiguration.java | 48 +++++++++++++++++++ .../AmqpControllerAuthentficationTest.java | 6 +-- .../AmqpMessageDispatcherServiceTest.java | 36 +++++++------- .../amqp/AmqpMessageHandlerServiceTest.java | 30 ++++++------ .../PropertyBasedArtifactUrlHandlerTest.java | 6 +++ .../security/SystemSecurityContext.java | 22 ++++----- .../java/org/eclipse/hawkbit/util/IpUtil.java | 9 ++-- 15 files changed, 194 insertions(+), 150 deletions(-) create mode 100644 hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/AmqpTestConfiguration.java 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 42b91e89b..ad106c0bd 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 @@ -130,9 +130,9 @@ public class AmqpConfiguration { } /** - * Create amqp handler service bean. + * Create default amqp sender service bean. * - * @return + * @return the default amqp sender service bean */ @Bean @ConditionalOnMissingBean 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 dd36ef1fd..9b98cadfa 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 @@ -127,10 +127,7 @@ 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) { 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 06809d47e..a2ffd06e3 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 @@ -36,9 +36,11 @@ 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 @@ -160,4 +162,8 @@ public class AmqpMessageDispatcherService extends BaseAmqpService { 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 539d652b6..33ca6837e 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 @@ -98,15 +98,25 @@ public class AmqpMessageHandlerService extends BaseAmqpService { private HostnameResolver hostnameResolver; /** + * Constructor. + * * @param messageConverter + * the message converter. + * @param defaultTemplate + * the configured amqp template. */ - @Autowired public AmqpMessageHandlerService(final MessageConverter messageConverter, final RabbitTemplate defaultTemplate) { super(messageConverter, 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, internalAmqpTemplate.getConnectionFactory().getVirtualHost()); + } + /** - * /** Method to handle all incoming amqp messages. + * Method to handle all incoming amqp messages. * * @param message * incoming message @@ -116,11 +126,11 @@ public class AmqpMessageHandlerService extends BaseAmqpService { * 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 { @@ -128,7 +138,7 @@ public class AmqpMessageHandlerService extends BaseAmqpService { switch (messageType) { case THING_CREATED: setTenantSecurityContext(tenant); - registerTarget(message); + registerTarget(message, virtualHost); break; case EVENT: setTenantSecurityContext(tenant); @@ -230,7 +240,7 @@ public class AmqpMessageHandlerService extends BaseAmqpService { * @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(); @@ -238,7 +248,7 @@ public class AmqpMessageHandlerService extends BaseAmqpService { logAndThrowMessageError(message, "No ReplyTo was set for the createThing Event."); } - final URI amqpUri = IpUtil.createAmqpUri(getVirtualHost(message), replyTo); + final URI amqpUri = IpUtil.createAmqpUri(virtualHost, replyTo); final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotexist(thingId, amqpUri); LOG.debug("Target {} reported online state.", thingId); @@ -271,6 +281,7 @@ public class AmqpMessageHandlerService extends BaseAmqpService { private void handleIncomingEvent(final Message message, final EventTopic topic) { if (EventTopic.UPDATE_ACTION_STATUS.equals(topic)) { updateActionStatus(message); + return; } logAndThrowMessageError(message, "Got event without appropriate topic."); } @@ -321,19 +332,20 @@ public class AmqpMessageHandlerService extends BaseAmqpService { 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()); } } + 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); + } + /** * @param message * @param actionUpdateStatus 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 2c3477c1f..c3a807f48 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 @@ -8,15 +8,11 @@ */ package org.eclipse.hawkbit.amqp; -import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Bean which holds the necessary properties for configuring the AMQP * connection. - * - * - * * */ @ConfigurationProperties("hawkbit.dmf.rabbitmq") @@ -27,59 +23,26 @@ public class AmqpProperties { private String receiverQueue = "dmf_receiver"; private boolean missingQueuesFatal = false; - /** - * Is missingQueuesFatal enabled - * - * @see SimpleMessageListenerContainer#setMissingQueuesFatal - * @return the missingQueuesFatal enabled disabled - */ public boolean isMissingQueuesFatal() { return missingQueuesFatal; } - /** - * @param missingQueuesFatal - * the missingQueuesFatal to set. - * @see SimpleMessageListenerContainer#setMissingQueuesFatal - */ public void setMissingQueuesFatal(final boolean missingQueuesFatal) { this.missingQueuesFatal = missingQueuesFatal; } - /** - * Returns the dead letter exchange. - * - * @return dead letter exchange - */ public String getDeadLetterExchange() { return deadLetterExchange; } - /** - * Sets the dead letter exchange. - * - * @param deadLetterExchange - * the deadLetterExchange to be set - */ public void setDeadLetterExchange(final String deadLetterExchange) { this.deadLetterExchange = deadLetterExchange; } - /** - * Returns the dead letter queue. - * - * @return the dead letter queue - */ public String getDeadLetterQueue() { return deadLetterQueue; } - /** - * Sets the dead letter queue. - * - * @param deadLetterQueue - * the deadLetterQueue ro be set - */ public void setDeadLetterQueue(final String deadLetterQueue) { this.deadLetterQueue = deadLetterQueue; } 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 index b7d8ed4e7..936495aba 100644 --- 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 @@ -1,3 +1,11 @@ +/** + * 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; @@ -5,20 +13,32 @@ import java.net.URI; import org.springframework.amqp.core.Message; /** - * Copyright (c) 2011-2016 Bosch Software Innovations GmbH, Germany. All rights reserved. - */ - -/** - * + * 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. * * @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 index 9b0702d41..f7702e3a6 100644 --- 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 @@ -1,9 +1,13 @@ /** - * Copyright (c) 2011-2016 Bosch Software Innovations GmbH, Germany. All rights reserved. + * 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 java.util.Map; import org.slf4j.Logger; @@ -14,34 +18,22 @@ 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); - protected static final String VIRTUAL_HOST_MESSAGE_HEADER = "VHOST_HEADER"; - protected MessageConverter messageConverter; - protected RabbitTemplate spInternalConnectorTemplate; + protected RabbitTemplate internalAmqpTemplate; public BaseAmqpService(final MessageConverter messageConverter, final RabbitTemplate defaultTemplate) { this.messageConverter = messageConverter; - spInternalConnectorTemplate = defaultTemplate; - } - - protected String getVirtualHost(final Message message) { - final Object virtualHost = message.getMessageProperties().getHeaders().get(VIRTUAL_HOST_MESSAGE_HEADER); - - if (virtualHost == null) { - return spInternalConnectorTemplate.getConnectionFactory().getVirtualHost(); - } - return virtualHost.toString(); + internalAmqpTemplate = defaultTemplate; } protected void cleanMessage(final Message message) { message.getMessageProperties().getHeaders().remove(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME); - message.getMessageProperties().getHeaders().remove(VIRTUAL_HOST_MESSAGE_HEADER); } /** @@ -60,10 +52,6 @@ public class BaseAmqpService { return (T) messageConverter.fromMessage(message); } - protected String getExchangeFromAmqpUri(final URI amqpUri) { - return amqpUri.getPath().substring(1); - } - protected String getStringHeaderKey(final Message message, final String key, final String errorMessageIfNull) { final Map header = message.getMessageProperties().getHeaders(); final Object value = header.get(key); 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 index 1b962da19..3dad77f43 100644 --- 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 @@ -1,5 +1,10 @@ /** - * Copyright (c) 2011-2016 Bosch Software Innovations GmbH, Germany. All rights reserved. + * 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; @@ -9,21 +14,27 @@ 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 extends BaseAmqpService implements AmqpSenderService { +public class DefaultAmqpSenderService implements AmqpSenderService { + + private final RabbitTemplate internalAmqpTemplate; /** - * @param messageConverter - * @param defaultTemplate + * Constructor. + * + * @param internalAmqpTemplate + * the amqp template */ - public DefaultAmqpSenderService(final RabbitTemplate defaultTemplate) { - super(defaultTemplate.getMessageConverter(), defaultTemplate); + public DefaultAmqpSenderService(final RabbitTemplate internalAmqpTemplate) { + this.internalAmqpTemplate = internalAmqpTemplate; } @Override public void sendMessage(final Message message, final URI uri) { - spInternalConnectorTemplate.send(getExchangeFromAmqpUri(uri), message); + internalAmqpTemplate.send(extractExchange(uri), 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/AmqpControllerAuthentficationTest.java index f5102c3c3..9d41df1ad 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/AmqpControllerAuthentficationTest.java @@ -125,7 +125,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); @@ -147,7 +147,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); @@ -169,7 +169,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 dc9cd8e01..4e6e74ea6 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 @@ -15,9 +15,11 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; +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; @@ -44,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; @@ -58,30 +59,29 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit private AmqpMessageDispatcherService amqpMessageDispatcherService; - private AmqpSenderService senderService; - - 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(messageConverter, rabbitTemplate); + this.rabbitTemplate = Mockito.mock(RabbitTemplate.class); + when(rabbitTemplate.getMessageConverter()).thenReturn(new Jackson2JsonMessageConverter()); + amqpMessageDispatcherService = new AmqpMessageDispatcherService(new Jackson2JsonMessageConverter(), + 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.setArtifactUrlHandler(artifactUrlHandlerMock); - senderService = new DefaultAmqpSenderService(rabbitTemplate); } @Test @@ -91,7 +91,7 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit 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(downloadAndUpdateRequest.getSoftwareModules().isEmpty()); } @@ -104,7 +104,7 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent = new TargetAssignDistributionSetEvent( 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(3, downloadAndUpdateRequest.getSoftwareModules().size()); for (final org.eclipse.hawkbit.dmf.json.model.SoftwareModule softwareModule : downloadAndUpdateRequest @@ -138,7 +138,7 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent = new TargetAssignDistributionSetEvent( 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(3, downloadAndUpdateRequest.getSoftwareModules().size()); for (final org.eclipse.hawkbit.dmf.json.model.SoftwareModule softwareModule : downloadAndUpdateRequest @@ -157,8 +157,7 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit 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); } @@ -194,10 +193,9 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit assertEquals(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(senderService).sendMessage(argumentCaptor.capture(), - // eq(exchange)); + 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 189d79487..860403f0c 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 @@ -121,7 +121,7 @@ public class AmqpMessageHandlerServiceTest { 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); + amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost"); fail(); } @@ -140,11 +140,11 @@ public class AmqpMessageHandlerServiceTest { uriCaptor.capture())).thenReturn(null); // test - amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT); + amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost"); // verify assertThat(targetIdCaptor.getValue()).isEqualTo(knownThingId); - assertThat(uriCaptor.getValue().toString()).isEqualTo("amqp://MyTest"); + assertThat(uriCaptor.getValue().toString()).isEqualTo("amqp://vHost/MyTest"); } @@ -156,7 +156,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 @@ -170,7 +170,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 @@ -186,7 +186,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 @@ -199,21 +199,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); + amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost"); fail(); } catch (final IllegalArgumentException e) { } try { messageProperties.setHeader(MessageHeaderKey.TOPIC, "wrongTopic"); - amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT); + amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost"); fail(); } 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 @@ -232,7 +232,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 @@ -249,7 +249,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 @@ -267,7 +267,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); @@ -290,7 +290,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); @@ -321,7 +321,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); @@ -355,7 +355,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/util/PropertyBasedArtifactUrlHandlerTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/util/PropertyBasedArtifactUrlHandlerTest.java index fcafb23e4..772b9f261 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 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 7e3dc8de7..c1125667e 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 { @@ -45,15 +43,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); } }); @@ -106,7 +101,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 07c22e796..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 { @@ -103,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 virtualHost, final String exchange) { - return createUri(AMPQP_SCHEME, virtualHost).resolve("/" + exchange); + public static URI createAmqpUri(final String host, final String exchange) { + return createUri(AMPQP_SCHEME, host).resolve("/" + exchange); } /** From f42fbe32b37c0bfe08313a43ebcbe8308e9a80d9 Mon Sep 17 00:00:00 2001 From: SirWayne Date: Wed, 17 Feb 2016 15:16:24 +0100 Subject: [PATCH 06/58] Add null check in convert methode Signed-off-by: SirWayne --- .../main/java/org/eclipse/hawkbit/amqp/BaseAmqpService.java | 3 +++ 1 file changed, 3 insertions(+) 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 index f7702e3a6..c3811626e 100644 --- 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 @@ -47,6 +47,9 @@ public class BaseAmqpService { */ @SuppressWarnings("unchecked") protected T convertMessage(final Message message, final Class clazz) { + if (message == null) { + return null; + } message.getMessageProperties().getHeaders().put(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME, clazz.getTypeName()); return (T) messageConverter.fromMessage(message); From cfaf02779fb4e7c2b70e58d093c1387920398679 Mon Sep 17 00:00:00 2001 From: SirWayne Date: Wed, 17 Feb 2016 23:43:52 +0100 Subject: [PATCH 07/58] Convert Json List Signed-off-by: SirWayne --- .../eclipse/hawkbit/amqp/BaseAmqpService.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) 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 index c3811626e..d9af2b533 100644 --- 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 @@ -8,6 +8,9 @@ */ 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; @@ -55,6 +58,27 @@ public class BaseAmqpService { return (T) messageConverter.fromMessage(message); } + /** + * 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") + protected List convertMessageList(final Message message, final Class clazz) { + if (message == null) { + return Collections.emptyList(); + } + message.getMessageProperties().getHeaders().put(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME, + ArrayList.class); + message.getMessageProperties().getHeaders().put(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, + clazz.getTypeName()); + return (List) messageConverter.fromMessage(message); + } + protected String getStringHeaderKey(final Message message, final String key, final String errorMessageIfNull) { final Map header = message.getMessageProperties().getHeaders(); final Object value = header.get(key); From 031be3e8cb6ae6651e70c7c84c847bd0b4606523 Mon Sep 17 00:00:00 2001 From: SirWayne Date: Thu, 18 Feb 2016 00:26:45 +0100 Subject: [PATCH 08/58] Convert Json List Signed-off-by: SirWayne --- .../main/java/org/eclipse/hawkbit/amqp/BaseAmqpService.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 index d9af2b533..ca0a04485 100644 --- 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 @@ -54,7 +54,7 @@ public class BaseAmqpService { return null; } message.getMessageProperties().getHeaders().put(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME, - clazz.getTypeName()); + clazz.getName()); return (T) messageConverter.fromMessage(message); } @@ -73,9 +73,9 @@ public class BaseAmqpService { return Collections.emptyList(); } message.getMessageProperties().getHeaders().put(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME, - ArrayList.class); + ArrayList.class.getName()); message.getMessageProperties().getHeaders().put(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, - clazz.getTypeName()); + clazz.getName()); return (List) messageConverter.fromMessage(message); } From 661d3e2d417727867e78d17b8fa5cc002c41e352 Mon Sep 17 00:00:00 2001 From: SirWayne Date: Thu, 18 Feb 2016 10:27:58 +0100 Subject: [PATCH 09/58] Add JavaDoc Signed-off-by: SirWayne --- .../main/java/org/eclipse/hawkbit/amqp/BaseAmqpService.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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 index ca0a04485..6cfa89358 100644 --- 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 @@ -59,12 +59,13 @@ public class BaseAmqpService { } /** - * Is needed to convert a incoming message to is originally object type. + * 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 originally object. + * the class of the list content. * @return */ @SuppressWarnings("unchecked") From 94db219bcb87e2fbba75c0f69cc74fdeea0e79c8 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Mon, 22 Feb 2016 14:17:13 +0100 Subject: [PATCH 10/58] Completed DDI API --- .../hawkbit/controller/ArtifactDownloadTest.java | 2 +- .../hawkbit/controller/CancelActionTest.java | 2 +- .../eclipse/hawkbit/controller/ConfigDataTest.java | 2 +- .../hawkbit/controller/DeploymentBaseTest.java | 2 +- .../hawkbit/controller/RootControllerTest.java | 13 +++++++++---- 5 files changed, 13 insertions(+), 8 deletions(-) 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"; From 22fb4bcb136186065bfee22ba6f87140f06980bd Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Mon, 22 Feb 2016 17:21:59 +0100 Subject: [PATCH 11/58] Harmonised test descriptions for mgmt. API --- .../resource/DistributionSetResourceTest.java | 69 ++++++++++++------- .../DistributionSetTypeResourceTest.java | 2 +- .../rest/resource/DownloadResourceTest.java | 2 +- .../rest/resource/RolloutResourceTest.java | 2 +- ...MRessourceMisingMongoDbConnectionTest.java | 12 ++-- .../resource/SoftwareModuleResourceTest.java | 2 +- .../SoftwareModuleTypeResourceTest.java | 5 +- .../rest/resource/SortUtilityTest.java | 2 +- .../SystemManagementResourceTest.java | 2 +- .../rest/resource/TargetResourceTest.java | 13 ++-- .../resource/model/ExceptionInfoTest.java | 9 ++- .../rest/resource/model/PagedListTest.java | 9 +++ 12 files changed, 83 insertions(+), 46 deletions(-) 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..3ca25132a 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 @@ -50,7 +50,7 @@ import ru.yandex.qatools.allure.annotations.Stories; * * */ -@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..6c33b0eea 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 @@ -34,7 +34,7 @@ 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..cb4fc9f4a 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 { 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..5b6923686 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 @@ -65,7 +65,7 @@ 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 { 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..d1dd4d6ed 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 @@ -72,7 +72,7 @@ import ru.yandex.qatools.allure.annotations.Stories; * * */ -@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 @@ -229,7 +229,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { @Test 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}", @@ -252,7 +252,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { @Test public void cancelAnCancelActionIsNotAllowed() throws Exception { // prepare test - Target tA = createTargetAndStartAction(); + final Target tA = createTargetAndStartAction(); // cancel the active action deploymentManagement.cancelAction(tA.getActions().get(0), tA); @@ -272,7 +272,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 +293,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", @@ -1232,7 +1232,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 e9601d693..a1df7f298 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("Junit 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..9c5a5ac12 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,14 +15,22 @@ 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("Junit 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<>(); @@ -36,6 +44,7 @@ public class PagedListTest { } @Test + @Description("Create list with payload and verify size values.") public void createListWithSmallerTotalThanContentSizeIsOk() { final long knownTotal = 0; final List knownContentList = new ArrayList<>(); From a9f91e90da42202bba9bba79a42e80e9597a6c50 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Mon, 22 Feb 2016 20:13:45 +0100 Subject: [PATCH 12/58] Removed old issue numbers. Further documentation --- .../repository/DeploymentManagement.java | 2 +- .../repository/DistributionSetManagement.java | 3 +-- .../hawkbit/repository/SystemManagement.java | 2 +- .../hawkbit/repository/ActionTest.java | 8 ++++++- .../ArtifactManagementNoMongoDbTest.java | 3 --- .../repository/DeploymentManagementTest.java | 1 - .../hawkbit/controller/RootController.java | 2 -- .../DistributionSetTypeResourceTest.java | 3 --- .../rest/resource/DownloadResourceTest.java | 4 ---- .../rest/resource/RolloutResourceTest.java | 2 +- .../resource/SoftwareModuleResourceTest.java | 8 ------- .../rest/resource/TargetResourceTest.java | 22 +++++++++++++------ ...yTokenAuthenticationConfigurationItem.java | 3 +-- 13 files changed, 27 insertions(+), 36 deletions(-) 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 560549e7e..c0319a069 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 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/SystemManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java index 09b6025d3..aac5db7f5 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 @@ -280,7 +280,7 @@ public class SystemManagement implements EnvironmentAware { * @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/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/DeploymentManagementTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DeploymentManagementTest.java index 693a67082..0db3325aa 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 @@ -140,7 +140,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, 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..2b0ac810e 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 @@ -435,8 +435,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()); } 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 3ca25132a..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,9 +46,6 @@ import ru.yandex.qatools.allure.annotations.Stories; /** * Test for {@link DistributionSetTypeResource}. * - * - * - * */ @Features("Component Tests - Management API") @Stories("Distribution Set Type Resource") 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 6c33b0eea..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,10 +30,6 @@ import org.springframework.context.annotation.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -/** - * - * - */ @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 cb4fc9f4a..afa12b7af 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 @@ -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; 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 5b6923686..0587a305c 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 @@ -112,14 +112,6 @@ 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 { 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 d1dd4d6ed..3ae423448 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 @@ -74,8 +74,6 @@ import ru.yandex.qatools.allure.annotations.Stories; */ @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 +101,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"; @@ -141,6 +137,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { } @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 +149,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 +162,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 +194,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,6 +227,7 @@ 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 final Target tA = createTargetAndStartAction(); @@ -250,7 +251,8 @@ 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 final Target tA = createTargetAndStartAction(); @@ -302,6 +304,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 +317,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 +326,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 +335,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 +360,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 +400,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 +421,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; 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 6ae002263..790f219d8 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 @@ -84,8 +84,7 @@ 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()); From 7f2a9d1ed2913af56b28f143771b2dfa3bd8b3bd Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Tue, 23 Feb 2016 09:57:18 +0100 Subject: [PATCH 13/58] Features harmonised, more test descriptions --- .../repository/ArtifactStoreTest.java | 5 + .../cache/eventbus/EventDistributorTest.java | 5 + .../cache/redis/RedisPropertiesTest.java | 5 + .../EventBusSubscriberProcessorTest.java | 5 + .../AmqpControllerAuthentficationTest.java | 4 +- .../AmqpMessageDispatcherServiceTest.java | 4 +- .../amqp/AmqpMessageHandlerServiceTest.java | 4 +- ...SourceTrustAuthenticationProviderTest.java | 5 + .../eclipse/hawkbit/cache/CacheKeysTest.java | 5 + .../hawkbit/cache/CacheWriteNotifyTest.java | 5 + .../CacheFieldEntityListenerTest.java | 5 + .../hawkbit/repository/TagManagementTest.java | 94 ++++++++----------- .../TargetManagementSearchTest.java | 6 +- .../repository/rsql/RSQLActionFieldsTest.java | 2 +- .../rsql/RSQLDistributionSetFieldTest.java | 2 +- ...RSQLDistributionSetMetadataFieldsTest.java | 2 +- .../rsql/RSQLRolloutGroupFields.java | 2 +- .../rsql/RSQLSoftwareModuleFieldTest.java | 2 +- .../RSQLSoftwareModuleMetadataFieldsTest.java | 2 +- .../RSQLSoftwareModuleTypeFieldsTest.java | 2 +- .../repository/rsql/RSQLTagFieldsTest.java | 2 +- .../repository/rsql/RSQLTargetFieldTest.java | 2 +- .../repository/rsql/RSQLUtilityTest.java | 2 +- .../tenancy/MultiTenancyEntityTest.java | 68 ++++---------- .../rest/resource/RolloutResourceTest.java | 2 - .../rest/resource/TargetResourceTest.java | 3 - .../security/SecurityTokenGeneratorTest.java | 5 + .../org/eclipse/hawkbit/util/IpUtilTest.java | 4 +- 28 files changed, 124 insertions(+), 130 deletions(-) diff --git a/hawkbit-artifact-repository-mongo/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactStoreTest.java b/hawkbit-artifact-repository-mongo/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactStoreTest.java index 2a8441ee6..c53447a6c 100644 --- a/hawkbit-artifact-repository-mongo/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactStoreTest.java +++ b/hawkbit-artifact-repository-mongo/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactStoreTest.java @@ -34,6 +34,11 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.google.common.io.BaseEncoding; import com.mongodb.gridfs.GridFSDBFile; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@Features("Component Tests - Repository") +@Stories("Artifact Store MongoDB") @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = { ArtifactStoreAutoConfiguration.class, TestConfiguration.class }) public class ArtifactStoreTest { 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..fb657638e 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,6 +29,11 @@ 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) public class EventDistributorTest { 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/src/test/java/org/eclipse/hawkbit/eventbus/EventBusSubscriberProcessorTest.java b/hawkbit-core/src/test/java/org/eclipse/hawkbit/eventbus/EventBusSubscriberProcessorTest.java index ac02aaad1..2925ba878 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,6 +21,11 @@ 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) public class EventBusSubscriberProcessorTest { 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/AmqpControllerAuthentficationTest.java index 1d962907b..d44bee337 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/AmqpControllerAuthentficationTest.java @@ -47,8 +47,8 @@ import ru.yandex.qatools.allure.annotations.Stories; * * Test Amqp controller authentfication. */ -@Features("AMQP Authenfication Test") -@Stories("Tests the authenfication") +@Features("Component Tests - Device Management Federation API") +@Stories("AmqpController Authentfication Test") public class AmqpControllerAuthentficationTest { private static final String TENANT = "DEFAULT"; 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 348e8dea4..6584d9349 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 @@ -53,8 +53,8 @@ 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; 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 bea75e9d6..4a05e96ff 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"; 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..a5b02ffb1 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,6 +20,11 @@ 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) public class PreAuthTokenSourceTrustAuthenticationProviderTest { 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/TagManagementTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TagManagementTest.java index 9c1a9b66e..b8a4db598 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 @@ -34,13 +34,9 @@ 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); @@ -155,13 +151,9 @@ 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() { + @Description("Ensures that all tags are retrieved through repository.") + public void findAllTargetTags() { assertThat(targetTagRepository.findAll()).isEmpty(); final List tags = createTargetsWithTags(); @@ -170,13 +162,9 @@ public class TagManagementTest extends AbstractIntegrationTest { .hasSize(20); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.TagManagement#createTargetTag(org.eclipse.hawkbit.repository.model.TargetTag)} - * . - */ @Test - public void testCreateTargetTag() { + @Description("Ensures that a created tag is persisted in the repository as defined.") + public void createTargetTag() { assertThat(targetTagRepository.findAll()).isEmpty(); final Tag tag = tagManagement.createTargetTag(new TargetTag("kai1", "kai2", "colour")); @@ -186,13 +174,9 @@ public class TagManagementTest extends AbstractIntegrationTest { assertThat(tagManagement.findTargetTagById(tag.getId()).getColour()).isEqualTo("colour"); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.TagManagement#deleteTargetTag(java.lang.String[])} - * . - */ @Test - public void testDeleteTargetTagsStringArray() { + @Description("Ensures that a deleted tag is removed from the repository as defined.") + public void deleteTargetTas() { assertThat(targetTagRepository.findAll()).isEmpty(); // create test data @@ -217,7 +201,7 @@ public class TagManagementTest extends AbstractIntegrationTest { } @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(); @@ -237,13 +221,9 @@ public class TagManagementTest extends AbstractIntegrationTest { assertThat(targetTagRepository.findOne(savedAssigned.getId()).getOptLockRevision()).isEqualTo(2); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.TagManagement#createDistributionSetTag(org.eclipse.hawkbit.repository.model.DistributionSetTag)} - * . - */ @Test - public void testCreateDistributionSetTag() { + @Description("Ensures that a created tag is persisted in the repository as defined.") + public void createDistributionSetTag() { assertThat(distributionSetTagRepository.findAll()).isEmpty(); final Tag tag = tagManagement.createDistributionSetTag(new DistributionSetTag("kai1", "kai2", "colour")); @@ -253,13 +233,9 @@ public class TagManagementTest extends AbstractIntegrationTest { assertThat(tagManagement.findDistributionSetTagById(tag.getId()).getColour()).isEqualTo("colour"); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.TagManagement#createDistributionSetTags(java.lang.Iterable)} - * . - */ @Test - public void testCreateDistributionSetTags() { + @Description("Ensures that a created tags are persisted in the repository as defined.") + public void createDistributionSetTags() { assertThat(distributionSetTagRepository.findAll()).isEmpty(); final List tags = createDsSetsWithTags(); @@ -267,13 +243,9 @@ public class TagManagementTest extends AbstractIntegrationTest { assertThat(distributionSetTagRepository.findAll()).hasSize(tags.size()); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.TagManagement#deleteDistributionSetTag(java.lang.String[])} - * . - */ @Test - public void testDeleteDistributionSetTag() { + @Description("Ensures that a deleted tag is removed from the repository as defined.") + public void deleteDistributionSetTag() { assertThat(distributionSetTagRepository.findAll()).isEmpty(); // create test data @@ -298,24 +270,40 @@ public class TagManagementTest extends AbstractIntegrationTest { } @Test(expected = EntityAlreadyExistsException.class) - public void testFailedDuplicateTargetTagNameException() { + @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")); tagManagement.createTargetTag(new TargetTag("A")); } @Test(expected = EntityAlreadyExistsException.class) - public void testFailedDuplicateDsTagNameException() { + @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"); + tagManagement.updateTargetTag(tag); + } + + @Test(expected = EntityAlreadyExistsException.class) + @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")); tagManagement.createDistributionSetTag(new DistributionSetTag("A")); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.TagManagement#updateDistributionSetTag(org.eclipse.hawkbit.repository.model.DistributionSetTag)} - * . - */ + @Test(expected = EntityAlreadyExistsException.class) + @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"); + tagManagement.updateDistributionSetTag(tag); + } + @Test - public void testUpdateDistributionSetTag() { + @Description("Tests the name update of a target tag.") + public void updateDistributionSetTag() { assertThat(distributionSetTagRepository.findAll()).isEmpty(); // create test data @@ -333,13 +321,9 @@ public class TagManagementTest extends AbstractIntegrationTest { assertThat(distributionSetTagRepository.findOne(savedAssigned.getId()).getName()).isEqualTo("test123"); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.TagManagement#findAllDistributionSetTags()} - * . - */ @Test - public void testFindDistributionSetTagsAll() { + @Description("Ensures that all tags are retrieved through repository.") + public void findDistributionSetTagsAll() { assertThat(distributionSetTagRepository.findAll()).isEmpty(); final List tags = createDsSetsWithTags(); 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/rsql/RSQLActionFieldsTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLActionFieldsTest.java index 71cf511ae..0c4a3aadd 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..0c316f918 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 { 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 3b923d167..1e58b2f8c 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-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 afa12b7af..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 @@ -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/TargetResourceTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/TargetResourceTest.java index 3ae423448..e9b0bd60a 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 @@ -66,11 +66,8 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; /** - * * Spring MVC Tests against the TargetResource. * - * - * */ @Features("Component Tests - Management API") @Stories("Target Resource") 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..9228e700c 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,6 +13,11 @@ 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 { @Test 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 e1e809ab8..25e1c974b 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 From ac9547e04c5c766d1e923a9ea82c5d5d6d549fd5 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Tue, 23 Feb 2016 20:01:50 +0100 Subject: [PATCH 14/58] Completed test docs on artefact repo --- .../hawkbit/artifact/repository/ArtifactStoreTest.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/hawkbit-artifact-repository-mongo/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactStoreTest.java b/hawkbit-artifact-repository-mongo/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactStoreTest.java index c53447a6c..c5aca8e1a 100644 --- a/hawkbit-artifact-repository-mongo/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactStoreTest.java +++ b/hawkbit-artifact-repository-mongo/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactStoreTest.java @@ -34,6 +34,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.google.common.io.BaseEncoding; import com.mongodb.gridfs.GridFSDBFile; +import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; @@ -53,6 +54,7 @@ public class ArtifactStoreTest { private GridFsOperations gridFs; @Test + @Description("Ensures that storage in MongoDB is correctly executed.s") public void storeArtifactInMongoDB() { final int filelengthBytes = 128; final String filename = "testfile.json"; @@ -65,6 +67,7 @@ public class ArtifactStoreTest { } @Test + @Description("Ensures that search by SHA1 hash (which is used by hawkBit as artifact ID) finds the expected results.") public void findArtifactBySHA1Hash() throws NoSuchAlgorithmException { final int filelengthBytes = 128; final String filename = "testfile.json"; @@ -77,6 +80,7 @@ public class ArtifactStoreTest { } @Test + @Description("Ensures that search by MD5 hash finds the expected results.") public void findArtifactByMD5Hash() throws NoSuchAlgorithmException { final int filelengthBytes = 128; final String filename = "testfile.json"; @@ -89,6 +93,7 @@ public class ArtifactStoreTest { } @Test + @Description("Ensures that artifact content can be read through InputStream.") public void getInputStreamFromArtifact() throws IOException { final int filelengthBytes = 128; final String filename = "testfile.json"; @@ -108,7 +113,8 @@ public class ArtifactStoreTest { } @Test - public void deleteArtifactWithOnlyOneTenantLast() throws NoSuchAlgorithmException { + @Description("Ensures that artifact delete actually results in deletion from database.") + public void deleteArtifact() throws NoSuchAlgorithmException { final int filelengthBytes = 128; final String filename = "testfile.json"; final String contentType = "application/json"; From 204fe1fd18920fd5c8dda2fcc1acb3355077acde Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Tue, 23 Feb 2016 20:53:21 +0100 Subject: [PATCH 15/58] Created TODOs for missing descriptions --- .../hawkbit/cache/eventbus/EventDistributorTest.java | 1 + .../hawkbit/eventbus/EventBusSubscriberProcessorTest.java | 1 + .../PreAuthTokenSourceTrustAuthenticationProviderTest.java | 1 + .../hawkbit/security/SecurityTokenGeneratorTest.java | 1 + .../push/SpringSecurityAtmosphereInterceptorTest.java | 6 ++++++ .../eclipse/hawkbit/ui/utils/NamingThreadFactoryTest.java | 2 +- .../hawkbit/ui/utils/SPUIComponentProviderTest.java | 7 +++++-- 7 files changed, 16 insertions(+), 3 deletions(-) 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 fb657638e..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 @@ -35,6 +35,7 @@ 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-core/src/test/java/org/eclipse/hawkbit/eventbus/EventBusSubscriberProcessorTest.java b/hawkbit-core/src/test/java/org/eclipse/hawkbit/eventbus/EventBusSubscriberProcessorTest.java index 2925ba878..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 @@ -27,6 +27,7 @@ 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-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 a5b02ffb1..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 @@ -26,6 +26,7 @@ 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-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 9228e700c..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 @@ -20,6 +20,7 @@ import ru.yandex.qatools.allure.annotations.Stories; @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-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. From ecdf38b4f980372a80a89d9d6fe178aceea40adb Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Tue, 23 Feb 2016 22:12:29 +0100 Subject: [PATCH 16/58] Fixed typo --- ...ationTest.java => AmqpControllerAuthenticationTest.java} | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) rename hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/{AmqpControllerAuthentficationTest.java => AmqpControllerAuthenticationTest.java} (98%) 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 98% 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 d44bee337..d6c63b83b 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 @@ -45,11 +45,11 @@ import ru.yandex.qatools.allure.annotations.Stories; /** * - * Test Amqp controller authentfication. + * Test Amqp controller authentication. */ @Features("Component Tests - Device Management Federation API") -@Stories("AmqpController Authentfication Test") -public class AmqpControllerAuthentficationTest { +@Stories("AmqpController Authentication Test") +public class AmqpControllerAuthenticationTest { private static final String TENANT = "DEFAULT"; private static String CONTROLLLER_ID = "123"; From 623c980b7b3217cf5580248c2ba3384be5f4ed40 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Wed, 24 Feb 2016 08:31:05 +0100 Subject: [PATCH 17/58] Completed feature stories annotations --- .../hawkbit/rest/resource/model/ExceptionInfoTest.java | 2 +- .../hawkbit/ExcludePathAwareShallowETagFilterTest.java | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) 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 a1df7f298..a74d89179 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 @@ -19,7 +19,7 @@ import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -@Features("Junit Tests - Management API") +@Features("Unit Tests - Management API") @Stories("Error Handling") public class ExceptionInfoTest { 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 ce663fbfb..c5830f016 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 { From c99ad7c59625bd0051cc8ffe4e8015ad4496c56b Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Wed, 24 Feb 2016 08:31:20 +0100 Subject: [PATCH 18/58] Upgrade Allure --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index aa188e76a..0613e30f0 100644 --- a/pom.xml +++ b/pom.xml @@ -79,7 +79,7 @@ 1.4 2.0M10 1.8 - 1.4.15 + 1.4.22 2.6.0 1.5.4 1.0.2 From e1a48c9b7d9b3e7054c9eca76aba197ea72fe42a Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Wed, 24 Feb 2016 10:20:33 +0100 Subject: [PATCH 19/58] Documented usage of annotations --- CONTRUBUTING.md | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/CONTRUBUTING.md b/CONTRUBUTING.md index bc04d2abd..516c63a68 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,32 @@ 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 + +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. From 5248e70db9c652f5813460ecf5cf35f4231dfe45 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Wed, 24 Feb 2016 10:21:35 +0100 Subject: [PATCH 20/58] Added example --- CONTRUBUTING.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CONTRUBUTING.md b/CONTRUBUTING.md index 516c63a68..626e7f0f1 100644 --- a/CONTRUBUTING.md +++ b/CONTRUBUTING.md @@ -45,6 +45,11 @@ Examples for hawkBit components: * 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 From 0b8e693cec47e8f1156509b5119b08224789ebf5 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Thu, 25 Feb 2016 11:36:21 +0100 Subject: [PATCH 21/58] Migrated environment aware to property annotation mechanism, documented properties. --- .../simulator/amqp/AmqpProperties.java | 16 +- .../client/ClientConfigurationProperties.java | 11 + .../AsyncConfigurerThreadpoolProperties.java | 14 +- .../scheduling/ExecutorAutoConfiguration.java | 5 +- .../security/SecurityAutoConfiguration.java | 4 +- .../SecurityManagedConfiguration.java | 50 ++-- ...ertyHostnameResolverAutoConfiguration.java | 1 + .../autoconfigure/url/ServerProperties.java | 30 --- .../hawkbit/cache/RedisConfiguration.java | 2 - .../hawkbit/cache/RedisProperties.java | 10 +- .../hawkbit/ControllerPollProperties.java | 9 + .../org/eclipse/hawkbit/ServerProperties.java | 97 ++++++++ .../amqp/AmqpControllerAuthentfication.java | 6 +- .../eclipse/hawkbit/amqp/AmqpProperties.java | 19 +- .../AmqpControllerAuthentficationTest.java | 4 +- .../RepositoryApplicationConfiguration.java | 4 - .../repository/ControllerManagement.java | 41 ++-- .../hawkbit/repository/ReportManagement.java | 5 - .../eclipse/hawkbit/TestConfiguration.java | 4 +- .../security/DdiSecurityProperties.java | 147 +++++++++++ .../hawkbit/security/SecurityProperties.java | 231 +++++++++++------- .../java/org/eclipse/hawkbit/util/SPInfo.java | 68 +----- .../org/eclipse/hawkbit/ui/UiProperties.java | 152 ++++++++++++ .../eclipse/hawkbit/ui/login/LoginView.java | 42 +--- .../hawkbit/ui/menu/DashboardMenu.java | 67 ++--- 25 files changed, 688 insertions(+), 351 deletions(-) delete mode 100644 hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/url/ServerProperties.java create mode 100644 hawkbit-core/src/main/java/org/eclipse/hawkbit/ServerProperties.java create mode 100644 hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/DdiSecurityProperties.java create mode 100644 hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/UiProperties.java 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..9aa37e719 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 @@ -14,16 +14,28 @@ import org.springframework.boot.context.properties.ConfigurationProperties; * Bean which holds the necessary properties for configuring the AMQP * connection. * - * - * */ @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-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/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/AsyncConfigurerThreadpoolProperties.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/AsyncConfigurerThreadpoolProperties.java index f7f18f1b0..35996a114 100644 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/AsyncConfigurerThreadpoolProperties.java +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/AsyncConfigurerThreadpoolProperties.java @@ -13,17 +13,29 @@ import org.springframework.boot.context.properties.ConfigurationProperties; /** * Properties for the async configurer. * - * */ @ConfigurationProperties("hawkbit.threadpool") public class AsyncConfigurerThreadpoolProperties { + /** + * Max queue size for central event executor. + */ private Integer queuesize = 250; + /** + * Core processing threads for central event executor. + */ private Integer corethreads = 5; + /** + * Maximum thread pool size for central event executor. + */ private Integer maxthreads = 50; + /** + * When the number of threads is greater than the core, this is the maximum + * time that excess idle threads will wait for new tasks before terminating. + */ private Long idletimeout = 10000L; public Integer getQueuesize() { diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/ExecutorAutoConfiguration.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/ExecutorAutoConfiguration.java index f8a86d1bc..43a096e7d 100644 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/ExecutorAutoConfiguration.java +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/ExecutorAutoConfiguration.java @@ -26,10 +26,9 @@ import org.springframework.security.concurrent.DelegatingSecurityContextExecutor import com.google.common.util.concurrent.ThreadFactoryBuilder; /** - * + * Central event processors inside update server. * */ - @Configuration @EnableConfigurationProperties(AsyncConfigurerThreadpoolProperties.class) public class ExecutorAutoConfiguration { @@ -40,7 +39,7 @@ public class ExecutorAutoConfiguration { private AsyncConfigurerThreadpoolProperties asyncConfigurerProperties; /** - * @return ExecutorService for general pupose multi threaded operations + * @return ExecutorService for general purpose multi threaded operations */ @Bean @ConditionalOnMissingBean diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityAutoConfiguration.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityAutoConfiguration.java index 326ff4774..8a3a50ad2 100644 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityAutoConfiguration.java +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityAutoConfiguration.java @@ -20,7 +20,7 @@ import org.eclipse.hawkbit.im.authentication.SpPermission; import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails; import org.eclipse.hawkbit.im.authentication.UserAuthenticationFilter; import org.eclipse.hawkbit.security.SecurityContextTenantAware; -import org.eclipse.hawkbit.security.SecurityProperties; +import org.eclipse.hawkbit.security.DdiSecurityProperties; import org.eclipse.hawkbit.security.SpringSecurityAuditorAware; import org.eclipse.hawkbit.tenancy.TenantAware; import org.slf4j.Logger; @@ -53,7 +53,7 @@ import org.springframework.security.web.authentication.www.BasicAuthenticationFi * */ @Configuration -@EnableConfigurationProperties(SecurityProperties.class) +@EnableConfigurationProperties(DdiSecurityProperties.class) public class SecurityAutoConfiguration { /** diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java index ca55f1711..b6a46737e 100644 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java @@ -31,6 +31,7 @@ import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.SystemManagement; import org.eclipse.hawkbit.rest.resource.RestConstants; import org.eclipse.hawkbit.security.ControllerTenantAwareAuthenticationDetailsSource; +import org.eclipse.hawkbit.security.DdiSecurityProperties; import org.eclipse.hawkbit.security.DosFilter; import org.eclipse.hawkbit.security.HttpControllerPreAuthenticateSecurityTokenFilter; import org.eclipse.hawkbit.security.HttpControllerPreAuthenticatedGatewaySecurityTokenFilter; @@ -43,17 +44,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.boot.context.embedded.ServletListenerRegistrationBean; import org.springframework.cache.Cache; -import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.AdviceMode; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; -import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -94,17 +92,11 @@ import org.vaadin.spring.security.web.authentication.VaadinUrlAuthenticationSucc @EnableGlobalMethodSecurity(prePostEnabled = true, mode = AdviceMode.ASPECTJ, proxyTargetClass = true, securedEnabled = true) @EnableWebMvcSecurity @Order(value = Ordered.HIGHEST_PRECEDENCE) -public class SecurityManagedConfiguration implements EnvironmentAware { +public class SecurityManagedConfiguration { private static final Logger LOG = LoggerFactory.getLogger(SecurityManagedConfiguration.class); - 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 SecurityProperties securityProperties; /** * {@link WebSecurityConfigurer} for the internal SP controller API. @@ -123,7 +115,7 @@ public class SecurityManagedConfiguration implements EnvironmentAware { @Autowired private TenantAware tenantAware; @Autowired - private SecurityProperties securityConfiguration; + private DdiSecurityProperties securityConfiguration; @Autowired private org.springframework.boot.autoconfigure.security.SecurityProperties springSecurityProperties; @@ -204,13 +196,9 @@ public class SecurityManagedConfiguration implements EnvironmentAware { public FilterRegistrationBean dosFilter() { final FilterRegistrationBean filterRegBean = new FilterRegistrationBean(); - filterRegBean - .setFilter( - new DosFilter(environment.getProperty("security.dos.filter.maxRead", Integer.class, 200), - environment.getProperty("security.dos.filter.maxWrite", Integer.class, 50), - environment.getProperty("security.dos.filter.whitelist"), environment - .getProperty("security.clients.blacklist"), - environment.getProperty("security.rp.remote_ip_header", String.class, "X-Forwarded-For"))); + filterRegBean.setFilter(new DosFilter(securityProperties.getDos().getFilter().getMaxRead(), + securityProperties.getDos().getFilter().getMaxWrite(), securityProperties.getDos().getWhitelist(), + securityProperties.getClients().getBlacklist(), securityProperties.getClients().getRemoteIpHeader())); filterRegBean.addUrlPatterns("/{tenant}/controller/v1/*", "/rest/*"); return filterRegBean; } @@ -310,8 +298,7 @@ public class SecurityManagedConfiguration implements EnvironmentAware { @Configuration @Order(400) @EnableVaadinSecurity - public static class UISecurityConfigurationAdapter extends WebSecurityConfigurerAdapter - implements EnvironmentAware { + public static class UISecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { private static final String XFRAME_OPTION_DENY = "DENY"; private static final String XFRAME_OPTION_SAMEORIGIN = "SAMEORIGIN"; @@ -320,13 +307,8 @@ public class SecurityManagedConfiguration implements EnvironmentAware { private VaadinSecurityContext vaadinSecurityContext; @Autowired private org.springframework.boot.autoconfigure.security.SecurityProperties springSecurityProperties; - - private RelaxedPropertyResolver environment; - - @Override - public void setEnvironment(final Environment environment) { - this.environment = new RelaxedPropertyResolver(environment, SP_SERVER_CONFIG_PREFIX); - } + @Autowired + private SecurityProperties securityProperties; /** * post construct for setting the authentication success handler for the @@ -379,13 +361,13 @@ public class SecurityManagedConfiguration implements EnvironmentAware { protected void configure(final HttpSecurity http) throws Exception { // configuration xframe-option - final String confXframeOption = environment.getProperty("security.xframe.option", XFRAME_OPTION_DENY); - final String confAllowFromUri = environment.getProperty("security.xframe.option.allowfrom"); - if (confXframeOption.equals(XFAME_OPTION_ALLOW_FROM) && confAllowFromUri == null) { + final String confXframeOption = securityProperties.getXframe().getOption(); + final String confAllowFromUri = securityProperties.getXframe().getAllowfrom(); + if (confXframeOption.equals(XFAME_OPTION_ALLOW_FROM) && confAllowFromUri.isEmpty()) { // if allow-from option is specified but no allowFromUri throw // exception throw new IllegalStateException("hawkbit.server.security.xframe.option has been specified as ALLOW-FROM" - + " but no hawkbit.server.security.xframe.option.allowfrom has been set, " + + " but no hawkbit.server.security.xframe.allowfrom has been set, " + "please ensure to set allow from URIs"); } @@ -461,7 +443,7 @@ public class SecurityManagedConfiguration implements EnvironmentAware { public static class IdRestSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { @Autowired - private SecurityProperties securityConfiguration; + private DdiSecurityProperties securityConfiguration; @Autowired @Qualifier(CacheConstants.DOWNLOAD_ID_CACHE) diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/url/PropertyHostnameResolverAutoConfiguration.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/url/PropertyHostnameResolverAutoConfiguration.java index eb925e281..a8fc609ef 100644 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/url/PropertyHostnameResolverAutoConfiguration.java +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/url/PropertyHostnameResolverAutoConfiguration.java @@ -11,6 +11,7 @@ package org.eclipse.hawkbit.autoconfigure.url; import java.net.MalformedURLException; import java.net.URL; +import org.eclipse.hawkbit.ServerProperties; import org.eclipse.hawkbit.api.HostnameResolver; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/url/ServerProperties.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/url/ServerProperties.java deleted file mode 100644 index 24c9dfb0e..000000000 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/url/ServerProperties.java +++ /dev/null @@ -1,30 +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.autoconfigure.url; - -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 ServerProperties { - - private String url = "http://localhost:8080"; - - public String getUrl() { - return url; - } - - public void setUrl(final String url) { - this.url = url; - } -} 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 2d1b99c98..5dc069f8a 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-core/src/main/java/org/eclipse/hawkbit/ControllerPollProperties.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/ControllerPollProperties.java index 694d5c016..fad0f78ec 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/ControllerPollProperties.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/ControllerPollProperties.java @@ -20,7 +20,16 @@ import org.springframework.boot.context.properties.ConfigurationProperties; @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"; public String getPollingTime() { diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/ServerProperties.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/ServerProperties.java new file mode 100644 index 000000000..b48949a31 --- /dev/null +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/ServerProperties.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 ServerProperties { + /** + * 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. Influeneced 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-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 dd36ef1fd..67ae1c8fb 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 @@ -23,7 +23,7 @@ import org.eclipse.hawkbit.security.ControllerPreAuthenticatedGatewaySecurityTok import org.eclipse.hawkbit.security.ControllerPreAuthenticatedSecurityHeaderFilter; import org.eclipse.hawkbit.security.PreAuthTokenSourceTrustAuthenticationProvider; import org.eclipse.hawkbit.security.PreAuthenficationFilter; -import org.eclipse.hawkbit.security.SecurityProperties; +import org.eclipse.hawkbit.security.DdiSecurityProperties; import org.eclipse.hawkbit.tenancy.TenantAware; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,7 +55,7 @@ public class AmqpControllerAuthentfication { private TenantAware tenantAware; @Autowired - private SecurityProperties secruityProperties; + private DdiSecurityProperties secruityProperties; /** * Constructor. @@ -137,7 +137,7 @@ public class AmqpControllerAuthentfication { this.controllerManagement = controllerManagement; } - public void setSecruityProperties(final SecurityProperties secruityProperties) { + public void setSecruityProperties(final DdiSecurityProperties secruityProperties) { this.secruityProperties = secruityProperties; } 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..5bb3dbd5d 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,29 @@ 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, see + * {@link SimpleMessageListenerContainer#setMissingQueuesFatal(boolean)}. + */ private boolean missingQueuesFatal = false; /** 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/AmqpControllerAuthentficationTest.java index 1d962907b..68b7b59ff 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/AmqpControllerAuthentficationTest.java @@ -24,7 +24,7 @@ import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.SystemManagement; import org.eclipse.hawkbit.security.SecurityContextTenantAware; -import org.eclipse.hawkbit.security.SecurityProperties; +import org.eclipse.hawkbit.security.DdiSecurityProperties; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; import org.junit.Before; import org.junit.Test; @@ -68,7 +68,7 @@ public class AmqpControllerAuthentficationTest { authenticationManager = new AmqpControllerAuthentfication(); authenticationManager.setControllerManagement(mock(ControllerManagement.class)); - final SecurityProperties secruityProperties = mock(SecurityProperties.class); + final DdiSecurityProperties secruityProperties = mock(DdiSecurityProperties.class); when(secruityProperties.getRpSslIssuerHashHeader()).thenReturn("X-Ssl-Issuer-Hash-%d"); authenticationManager.setSecruityProperties(secruityProperties); systemManagement = mock(SystemManagement.class); 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 e2d31a04c..84d1d9b60 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java @@ -40,10 +40,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/repository/ControllerManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java index e4a1e5e6b..5b31f4934 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.SecurityProperties; 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 SecurityProperties 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/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/test/java/org/eclipse/hawkbit/TestConfiguration.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java index 945e71c75..0667c6e08 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java @@ -18,7 +18,7 @@ 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.SecurityContextTenantAware; -import org.eclipse.hawkbit.security.SecurityProperties; +import org.eclipse.hawkbit.security.DdiSecurityProperties; 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-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..8a8e38fdc --- /dev/null +++ b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/DdiSecurityProperties.java @@ -0,0 +1,147 @@ +/** + * 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 DDI security. + */ +@ConfigurationProperties("hawkbit.server.ddi.security") +public class DdiSecurityProperties { + + /** + * Inner class for 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. + */ + @Component + @ConfigurationProperties("hawkbit.server.ddi.security.rp") + public static class RpProperties { + + /** + * 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; + } + + } + + /** + * Inner class for anonymous enable configuration. + */ + @Component + @ConfigurationProperties("hawkbit.server.ddi.security.authentication.anonymous") + public static class AnoymousAuthenticationProperties { + + /** + * Set to true to enable anonymous DDI client authentication. + */ + 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/SecurityProperties.java b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SecurityProperties.java index 8cc056f15..08c7f2132 100644 --- 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 @@ -1,130 +1,181 @@ -/** - * 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. - * - * + * Security related hawkbit configuration. * */ -@ConfigurationProperties +@ConfigurationProperties("hawkbit.server.security") public class SecurityProperties { + 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; + } + /** - * Inner class for reverse proxy configuration. + * Defines the XFrameOption policy. + * */ - @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; + public static class Xframe { /** - * @return the cnHeader + * XFrame option. Allowed values: SAMEORIGIN, DENY, ALLOW-FROM */ - public String getCnHeader() { - return cnHeader; + 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; } - /** - * @param cnHeader - * the cnHeader to set - */ - public void setCnHeader(final String cnHeader) { - this.cnHeader = cnHeader; + public void setOption(final String option) { + this.option = option; } - /** - * @return the sslIssuerHashHeader - */ - public String getSslIssuerHashHeader() { - return sslIssuerHashHeader; + public String getAllowfrom() { + return allowfrom; } - /** - * @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; + public void setAllowfrom(final String allowfrom) { + this.allowfrom = allowfrom; } } /** - * Inner class for anonymous enable configuration. + * Security configuration related to clients. + * */ - @Component - @ConfigurationProperties("hawkbit.server.controller.security.authentication.anonymous") - public static class AnoymousAuthenticationProperties { - private Boolean enabled = Boolean.FALSE; + public static class Clients { /** - * @param enabled - * the enabled to set + * Blacklisted client (IP addresses) for for DDI and Management API. */ - public void setEnabled(final Boolean enabled) { - this.enabled = enabled; - } + private String blacklist = ""; /** - * @return the enabled + * Name of the http header from which the remote ip is extracted. */ - public Boolean getEnabled() { - return enabled; + 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; + } } - @Autowired - private RpProperties rppProperties; + /** + * Denial of service protection related properties. + * + */ + public static class Dos { - @Autowired - private AnoymousAuthenticationProperties authenticationsProperties; + /** + * 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}"; - public String getRpCnHeader() { - return rppProperties.getCnHeader(); + /** + * 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 String getWhitelist() { + return whitelist; + } + + public void setWhitelist(final String whitelist) { + this.whitelist = whitelist; + } + + 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 { + + /** + * # 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 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; + } + + } } - - 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/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-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..22a8d8d23 --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/UiProperties.java @@ -0,0 +1,152 @@ +package org.eclipse.hawkbit.ui; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * Properties for Management UI customization. + * + */ +@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/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/menu/DashboardMenu.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/menu/DashboardMenu.java index 44ec9ea40..9dd207565 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.ServerProperties; 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 ServerProperties serverProperties; + private static final long serialVersionUID = 5394474618559481462L; public static final String ID = "dashboard-menu"; @@ -81,8 +84,8 @@ public final class DashboardMenu extends CustomComponent implements EnvironmentA @Autowired private transient PermissionService permissionService; - @Autowired - private transient SPInfo spInfo; + // @Autowired + // private transient SPInfo spInfo; @Autowired private final List dashboardVaadinViews = new ArrayList<>(); @@ -91,8 +94,6 @@ 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 @@ -162,20 +163,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 +223,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 +250,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 +300,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 +334,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 +399,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())); } From ab18e12b69c90e88564dbe71106dd37a09f48146 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Thu, 25 Feb 2016 17:59:46 +0100 Subject: [PATCH 22/58] Completed migration to ConfigurationProperties annotation. Added boot metadata generation to build. --- .gitignore | 3 +- MIGRATION.md | 9 + examples/hawkbit-device-simulator/pom.xml | 6 +- .../simulator/amqp/AmqpProperties.java | 2 + .../src/main/resources/application.properties | 25 ++- examples/hawkbit-mgmt-api-client/pom.xml | 5 + .../client/ClientConfigurationProperties.java | 2 + .../src/main/resources/application.properties | 2 +- hawkbit-autoconfigure/pom.xml | 5 + .../conf/ControllerPollAutoConfiguration.java | 27 --- .../AsyncConfigurerThreadpoolProperties.java | 2 + .../SecurityManagedConfiguration.java | 19 ++- ...ertyHostnameResolverAutoConfiguration.java | 6 +- hawkbit-cache-redis/pom.xml | 5 + .../hawkbit/cache/RedisProperties.java | 2 + hawkbit-core/pom.xml | 5 + .../hawkbit/ControllerPollProperties.java | 5 +- ...ties.java => HawkbitServerProperties.java} | 4 +- .../configuration/TenantConfigurationKey.java | 12 +- hawkbit-dmf-amqp/pom.xml | 5 + .../amqp/AmqpControllerAuthentfication.java | 6 +- .../eclipse/hawkbit/amqp/AmqpProperties.java | 2 + .../AmqpControllerAuthentficationTest.java | 8 +- hawkbit-repository/pom.xml | 5 + .../eclipse/hawkbit/RolloutProperties.java | 50 ++++++ .../repository/ControllerManagement.java | 4 +- .../hawkbit/repository/RolloutScheduler.java | 22 +-- .../eclipse/hawkbit/TestConfiguration.java | 5 +- .../resources/application-test.properties | 11 +- .../controller/ArtifactStoreController.java | 20 +-- .../hawkbit/controller/RootController.java | 39 ++--- .../resources/application-test.properties | 2 +- hawkbit-security-core/pom.xml | 5 + .../security/DdiSecurityProperties.java | 156 +++++++++++++----- ...es.java => HawkbitSecurityProperties.java} | 40 +++-- hawkbit-ui/pom.xml | 7 +- .../org/eclipse/hawkbit/ui/UiProperties.java | 10 ++ .../hawkbit/ui/menu/DashboardMenu.java | 4 +- pom.xml | 1 - 39 files changed, 348 insertions(+), 200 deletions(-) create mode 100644 MIGRATION.md delete mode 100644 hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/conf/ControllerPollAutoConfiguration.java rename hawkbit-core/src/main/java/org/eclipse/hawkbit/{ServerProperties.java => HawkbitServerProperties.java} (95%) create mode 100644 hawkbit-repository/src/main/java/org/eclipse/hawkbit/RolloutProperties.java rename hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/{SecurityProperties.java => HawkbitSecurityProperties.java} (79%) diff --git a/.gitignore b/.gitignore index ba9cf4617..fcd017f64 100644 --- a/.gitignore +++ b/.gitignore @@ -16,13 +16,12 @@ *.jar *.war -###################### # Sonar -###################### .sonar_lock # Eclipse IDE +.factorypath *.pydevproject .project .metadata 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..94749789c 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,6 +115,11 @@ com.jayway.jsonpath json-path + + org.springframework.boot + spring-boot-configuration-processor + true + 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 9aa37e719..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,12 +9,14 @@ 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 { 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 68f35b550..ead019247 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 @@ -9,12 +9,14 @@ package org.eclipse.hawkbit.mgmt.client; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; /** * Configuration bean which holds the configuration of the client e.g. the base * URL of the hawkbit-server and the credentials to use the RESTful Management * API. */ +@Component @ConfigurationProperties(prefix = "hawkbit") public class ClientConfigurationProperties { 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/hawkbit-autoconfigure/pom.xml b/hawkbit-autoconfigure/pom.xml index 11a106a4b..7670da406 100644 --- a/hawkbit-autoconfigure/pom.xml +++ b/hawkbit-autoconfigure/pom.xml @@ -72,5 +72,10 @@ org.springframework spring-context-support + + org.springframework.boot + spring-boot-configuration-processor + true + diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/conf/ControllerPollAutoConfiguration.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/conf/ControllerPollAutoConfiguration.java deleted file mode 100644 index bcbc5ec16..000000000 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/conf/ControllerPollAutoConfiguration.java +++ /dev/null @@ -1,27 +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.autoconfigure.conf; - -import org.eclipse.hawkbit.ControllerPollProperties; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -/** - * Enable the Controlle Poll. - * - * - * - */ -@Configuration -@ConditionalOnClass(ControllerPollProperties.class) -@EnableConfigurationProperties(ControllerPollProperties.class) -public class ControllerPollAutoConfiguration { - -} diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/AsyncConfigurerThreadpoolProperties.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/AsyncConfigurerThreadpoolProperties.java index 35996a114..2e7c6406e 100644 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/AsyncConfigurerThreadpoolProperties.java +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/AsyncConfigurerThreadpoolProperties.java @@ -9,11 +9,13 @@ package org.eclipse.hawkbit.autoconfigure.scheduling; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; /** * Properties for the async configurer. * */ +@Component @ConfigurationProperties("hawkbit.threadpool") public class AsyncConfigurerThreadpoolProperties { diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java index b6a46737e..c337b8e94 100644 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java @@ -33,12 +33,12 @@ import org.eclipse.hawkbit.rest.resource.RestConstants; import org.eclipse.hawkbit.security.ControllerTenantAwareAuthenticationDetailsSource; import org.eclipse.hawkbit.security.DdiSecurityProperties; import org.eclipse.hawkbit.security.DosFilter; +import org.eclipse.hawkbit.security.HawkbitSecurityProperties; import org.eclipse.hawkbit.security.HttpControllerPreAuthenticateSecurityTokenFilter; import org.eclipse.hawkbit.security.HttpControllerPreAuthenticatedGatewaySecurityTokenFilter; import org.eclipse.hawkbit.security.HttpControllerPreAuthenticatedSecurityHeaderFilter; import org.eclipse.hawkbit.security.HttpDownloadAuthenticationFilter; import org.eclipse.hawkbit.security.PreAuthTokenSourceTrustAuthenticationProvider; -import org.eclipse.hawkbit.security.SecurityProperties; import org.eclipse.hawkbit.tenancy.TenantAware; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -96,7 +96,7 @@ public class SecurityManagedConfiguration { private static final Logger LOG = LoggerFactory.getLogger(SecurityManagedConfiguration.class); @Autowired - private SecurityProperties securityProperties; + private HawkbitSecurityProperties securityProperties; /** * {@link WebSecurityConfigurer} for the internal SP controller API. @@ -124,7 +124,7 @@ public class SecurityManagedConfiguration { final ControllerTenantAwareAuthenticationDetailsSource authenticationDetailsSource = new ControllerTenantAwareAuthenticationDetailsSource(); final HttpControllerPreAuthenticatedSecurityHeaderFilter securityHeaderFilter = new HttpControllerPreAuthenticatedSecurityHeaderFilter( - securityConfiguration.getRpCnHeader(), securityConfiguration.getRpSslIssuerHashHeader(), + securityConfiguration.getRp().getCnHeader(), securityConfiguration.getRp().getSslIssuerHashHeader(), systemManagement, tenantAware); securityHeaderFilter.setAuthenticationManager(authenticationManager()); securityHeaderFilter.setCheckForPrincipalChanges(true); @@ -150,7 +150,7 @@ public class SecurityManagedConfiguration { httpSec = httpSec.requiresChannel().anyRequest().requiresSecure().and(); } - if (securityConfiguration.getAnonymousEnabled()) { + if (securityConfiguration.getAuthentication().getAnonymous().isEnabled()) { LOG.info( "******************\n** Anonymous controller security enabled, should only use for developing purposes **\n******************"); final AnonymousAuthenticationFilter anoymousFilter = new AnonymousAuthenticationFilter( @@ -181,7 +181,7 @@ public class SecurityManagedConfiguration { @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider( - new PreAuthTokenSourceTrustAuthenticationProvider(securityConfiguration.getRpTrustedIPs())); + new PreAuthTokenSourceTrustAuthenticationProvider(securityConfiguration.getRp().getTrustedIPs())); } } @@ -197,8 +197,9 @@ public class SecurityManagedConfiguration { final FilterRegistrationBean filterRegBean = new FilterRegistrationBean(); filterRegBean.setFilter(new DosFilter(securityProperties.getDos().getFilter().getMaxRead(), - securityProperties.getDos().getFilter().getMaxWrite(), securityProperties.getDos().getWhitelist(), - securityProperties.getClients().getBlacklist(), securityProperties.getClients().getRemoteIpHeader())); + securityProperties.getDos().getFilter().getMaxWrite(), + securityProperties.getDos().getFilter().getWhitelist(), securityProperties.getClients().getBlacklist(), + securityProperties.getClients().getRemoteIpHeader())); filterRegBean.addUrlPatterns("/{tenant}/controller/v1/*", "/rest/*"); return filterRegBean; } @@ -308,7 +309,7 @@ public class SecurityManagedConfiguration { @Autowired private org.springframework.boot.autoconfigure.security.SecurityProperties springSecurityProperties; @Autowired - private SecurityProperties securityProperties; + private HawkbitSecurityProperties securityProperties; /** * post construct for setting the authentication success handler for the @@ -466,7 +467,7 @@ public class SecurityManagedConfiguration { @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider( - new PreAuthTokenSourceTrustAuthenticationProvider(securityConfiguration.getRpTrustedIPs())); + new PreAuthTokenSourceTrustAuthenticationProvider(securityConfiguration.getRp().getTrustedIPs())); } } diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/url/PropertyHostnameResolverAutoConfiguration.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/url/PropertyHostnameResolverAutoConfiguration.java index a8fc609ef..0bd4a8240 100644 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/url/PropertyHostnameResolverAutoConfiguration.java +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/url/PropertyHostnameResolverAutoConfiguration.java @@ -11,7 +11,7 @@ package org.eclipse.hawkbit.autoconfigure.url; import java.net.MalformedURLException; import java.net.URL; -import org.eclipse.hawkbit.ServerProperties; +import org.eclipse.hawkbit.HawkbitServerProperties; import org.eclipse.hawkbit.api.HostnameResolver; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -28,11 +28,11 @@ import com.google.common.base.Throwables; * */ @Configuration -@EnableConfigurationProperties(ServerProperties.class) +@EnableConfigurationProperties(HawkbitServerProperties.class) public class PropertyHostnameResolverAutoConfiguration { @Autowired - private ServerProperties serverProperties; + private HawkbitServerProperties serverProperties; /** * @return the default autoconfigure hostname resolver implementation which diff --git a/hawkbit-cache-redis/pom.xml b/hawkbit-cache-redis/pom.xml index 99c8328b5..09567291b 100644 --- a/hawkbit-cache-redis/pom.xml +++ b/hawkbit-cache-redis/pom.xml @@ -37,6 +37,11 @@ redis.clients jedis + + org.springframework.boot + spring-boot-configuration-processor + true + 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 ab409bbf5..fcd5a1d3d 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 @@ -9,12 +9,14 @@ package org.eclipse.hawkbit.cache; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; /** * Bean which holds the necessary properties for configuring the Redis * connection. * */ +@Component @ConfigurationProperties("hawkbit.server.redis") public class RedisProperties { 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 fad0f78ec..4e176d258 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/ControllerPollProperties.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/ControllerPollProperties.java @@ -9,14 +9,13 @@ 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 { diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/ServerProperties.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java similarity index 95% rename from hawkbit-core/src/main/java/org/eclipse/hawkbit/ServerProperties.java rename to hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java index b48949a31..e36c9dfdb 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/ServerProperties.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java @@ -9,13 +9,15 @@ package org.eclipse.hawkbit; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; /** * Properties for the server e.g. the server's URL which must be configured. * */ +@Component @ConfigurationProperties("hawkbit.server") -public class ServerProperties { +public class HawkbitServerProperties { /** * Defines under which URI the update server can be reached. Used to * calculate download URLs for DMF transmitted update actions. 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 477cd654e..ec5c5ec40 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 @@ -22,35 +22,35 @@ public enum TenantConfigurationKey { * boolean value {@code true} {@code false}. */ AUTHENTICATION_MODE_HEADER_ENABLED("authentication.header.enabled", - "hawkbit.server.controller.security.authentication.header.enabled", Boolean.FALSE.toString()), + "hawkbit.server.ddi.security.authentication.header.enabled", Boolean.FALSE.toString()), /** * */ AUTHENTICATION_MODE_HEADER_AUTHORITY_NAME("authentication.header.authority", - "hawkbit.server.controller.security.authentication.header.authority", Boolean.FALSE.toString()), + "hawkbit.server.ddi.security.authentication.header.authority", Boolean.FALSE.toString()), /** * boolean value {@code true} {@code false}. */ AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED("authentication.targettoken.enabled", - "hawkbit.server.controller.security.authentication.targettoken.enabled", Boolean.FALSE.toString()), + "hawkbit.server.ddi.security.authentication.targettoken.enabled", Boolean.FALSE.toString()), /** * boolean value {@code true} {@code false}. */ AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_ENABLED("authentication.gatewaytoken.enabled", - "hawkbit.server.controller.security.authentication.gatewaytoken.enabled", Boolean.FALSE.toString()), + "hawkbit.server.ddi.security.authentication.gatewaytoken.enabled", Boolean.FALSE.toString()), /** * 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", null), + "hawkbit.server.ddi.security.authentication.gatewaytoken.name", null), /** * string value which holds the actual security-key of the gateway security * token. */ AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY("authentication.gatewaytoken.key", - "hawkbit.server.controller.security.authentication.gatewaytoken.key", null); + "hawkbit.server.ddi.security.authentication.gatewaytoken.key", null); private final String keyName; private final String defaultKeyName; 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/AmqpControllerAuthentfication.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthentfication.java index 67ae1c8fb..227933b33 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.DdiSecurityProperties; import org.eclipse.hawkbit.tenancy.TenantAware; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -78,8 +78,8 @@ public class AmqpControllerAuthentfication { filterChain.add(gatewaySecurityTokenFilter); final ControllerPreAuthenticatedSecurityHeaderFilter securityHeaderFilter = new ControllerPreAuthenticatedSecurityHeaderFilter( - secruityProperties.getRpCnHeader(), secruityProperties.getRpSslIssuerHashHeader(), systemManagement, - tenantAware); + secruityProperties.getRp().getCnHeader(), secruityProperties.getRp().getSslIssuerHashHeader(), + systemManagement, tenantAware); filterChain.add(securityHeaderFilter); final ControllerPreAuthenticateSecurityTokenFilter securityTokenFilter = new ControllerPreAuthenticateSecurityTokenFilter( 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 5bb3dbd5d..669d72e3f 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 @@ -10,12 +10,14 @@ package org.eclipse.hawkbit.amqp; import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; 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.dmf.rabbitmq") public class AmqpProperties { 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/AmqpControllerAuthentficationTest.java index 68b7b59ff..39ff3b049 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/AmqpControllerAuthentficationTest.java @@ -23,8 +23,9 @@ import org.eclipse.hawkbit.dmf.json.model.TenantSecruityToken; import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.SystemManagement; -import org.eclipse.hawkbit.security.SecurityContextTenantAware; import org.eclipse.hawkbit.security.DdiSecurityProperties; +import org.eclipse.hawkbit.security.DdiSecurityProperties.Rp; +import org.eclipse.hawkbit.security.SecurityContextTenantAware; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; import org.junit.Before; import org.junit.Test; @@ -68,8 +69,11 @@ public class AmqpControllerAuthentficationTest { authenticationManager = new AmqpControllerAuthentfication(); authenticationManager.setControllerManagement(mock(ControllerManagement.class)); + final DdiSecurityProperties secruityProperties = mock(DdiSecurityProperties.class); - when(secruityProperties.getRpSslIssuerHashHeader()).thenReturn("X-Ssl-Issuer-Hash-%d"); + final Rp rp = mock(Rp.class); + when(secruityProperties.getRp()).thenReturn(rp); + when(rp.getSslIssuerHashHeader()).thenReturn("X-Ssl-Issuer-Hash-%d"); authenticationManager.setSecruityProperties(secruityProperties); systemManagement = mock(SystemManagement.class); authenticationManager.setSystemManagement(systemManagement); diff --git a/hawkbit-repository/pom.xml b/hawkbit-repository/pom.xml index 62d234ddb..01b58dabb 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 + 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/ControllerManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java index 5b31f4934..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,7 +33,7 @@ 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.SecurityProperties; +import org.eclipse.hawkbit.security.HawkbitSecurityProperties; import org.hibernate.validator.constraints.NotEmpty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -84,7 +84,7 @@ public class ControllerManagement { private ActionStatusRepository actionStatusRepository; @Autowired - private SecurityProperties securityProperties; + private HawkbitSecurityProperties securityProperties; /** * Refreshes the time of the last time the controller has been connected to 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/test/java/org/eclipse/hawkbit/TestConfiguration.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java index 0667c6e08..e6887a976 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java @@ -18,12 +18,10 @@ 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.SecurityContextTenantAware; -import org.eclipse.hawkbit.security.DdiSecurityProperties; import org.eclipse.hawkbit.security.SpringSecurityAuditorAware; import org.eclipse.hawkbit.tenancy.TenantAware; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cache.Cache; import org.springframework.cache.guava.GuavaCacheManager; import org.springframework.context.annotation.AdviceMode; @@ -47,7 +45,8 @@ import com.mongodb.MongoClientOptions; */ @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true, mode = AdviceMode.ASPECTJ, proxyTargetClass = true, securedEnabled = true) -@EnableConfigurationProperties({ DdiSecurityProperties.class, ControllerPollProperties.class }) +// @EnableConfigurationProperties({ DdiSecurityProperties.class, +// ControllerPollProperties.class }) @Profile("test") public class TestConfiguration implements AsyncConfigurer { diff --git a/hawkbit-repository/src/test/resources/application-test.properties b/hawkbit-repository/src/test/resources/application-test.properties index e5fb04a21..dc7549fcb 100644 --- a/hawkbit-repository/src/test/resources/application-test.properties +++ b/hawkbit-repository/src/test/resources/application-test.properties @@ -10,7 +10,7 @@ spring.data.mongodb.uri=mongodb://localhost/spArtifactRepository${random.value} spring.data.mongodb.port=28017 -hawkbit.server.controller.security.authentication.header.enabled=true +hawkbit.server.ddi.security.authentication.header.enabled=true hawkbit.server.artifact.repo.upload.maxFileSize=5MB @@ -29,11 +29,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..a8d17e1b3 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( @@ -469,7 +461,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 +488,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 +535,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/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-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 index 8a8e38fdc..cb95975e5 100644 --- 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 @@ -10,25 +10,34 @@ 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 DDI security. */ +@Component @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; + } + /** - * Inner class for 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. + * 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. */ - @Component - @ConfigurationProperties("hawkbit.server.ddi.security.rp") - public static class RpProperties { + public static class Rp { /** * HTTP header field for common name of a DDI target client certificate. @@ -94,54 +103,119 @@ public class DdiSecurityProperties { } /** - * Inner class for anonymous enable configuration. + * DDI Authentication options. */ - @Component - @ConfigurationProperties("hawkbit.server.ddi.security.authentication.anonymous") - public static class AnoymousAuthenticationProperties { + public static class Authentication { + private final Anonymous anonymous = new Anonymous(); + private final Targettoken targettoken = new Targettoken(); + private final Gatewaytoken gatewaytoken = new Gatewaytoken(); - /** - * Set to true to enable anonymous DDI client authentication. - */ - private Boolean enabled = Boolean.FALSE; + public Anonymous getAnonymous() { + return anonymous; + } - /** - * @param enabled - * the enabled to set - */ - public void setEnabled(final Boolean enabled) { - this.enabled = enabled; + public Gatewaytoken getGatewaytoken() { + return gatewaytoken; + } + + public Targettoken getTargettoken() { + return targettoken; } /** - * @return the enabled + * Target token authentication. Tokens are defined per target. + * */ - public Boolean getEnabled() { - return enabled; + 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 { - @Autowired - private RpProperties rppProperties; + /** + * Gateway token based authentication enabled. + */ + private boolean enabled = false; - @Autowired - private AnoymousAuthenticationProperties authenticationsProperties; + /** + * Default gateway token name. + */ + private String name = ""; - public String getRpCnHeader() { - return rppProperties.getCnHeader(); - } + /** + * Default gateway token itself. + */ + private String key = ""; - public String getRpSslIssuerHashHeader() { - return rppProperties.getSslIssuerHashHeader(); - } + public boolean isEnabled() { + return enabled; + } - public List getRpTrustedIPs() { - return rppProperties.getTrustedIPs(); - } + 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; + } + } - public Boolean getAnonymousEnabled() { - return authenticationsProperties.getEnabled(); } } 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/HawkbitSecurityProperties.java similarity index 79% rename from hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SecurityProperties.java rename to hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/HawkbitSecurityProperties.java index 08c7f2132..7b157da65 100644 --- a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SecurityProperties.java +++ b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/HawkbitSecurityProperties.java @@ -1,16 +1,25 @@ +/** + * 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 SecurityProperties { +public class HawkbitSecurityProperties { private final Clients clients = new Clients(); - private final Dos dos = new Dos(); private final Xframe xframe = new Xframe(); @@ -100,11 +109,6 @@ public class SecurityProperties { */ public static class Dos { - /** - * 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 status updates that the controller can report for * an action (0 to disable). @@ -122,14 +126,6 @@ public class SecurityProperties { return filter; } - public String getWhitelist() { - return whitelist; - } - - public void setWhitelist(final String whitelist) { - this.whitelist = whitelist; - } - public int getMaxStatusEntriesPerAction() { return maxStatusEntriesPerAction; } @@ -148,6 +144,12 @@ public class SecurityProperties { 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. @@ -160,6 +162,14 @@ public class SecurityProperties { */ int maxWrite = 50; + public String getWhitelist() { + return whitelist; + } + + public void setWhitelist(final String whitelist) { + this.whitelist = whitelist; + } + public int getMaxRead() { return maxRead; } diff --git a/hawkbit-ui/pom.xml b/hawkbit-ui/pom.xml index 0bd083e36..c9bd54b01 100644 --- a/hawkbit-ui/pom.xml +++ b/hawkbit-ui/pom.xml @@ -213,7 +213,6 @@ org.vaadin.addons tokenfield - org.vaadin.alump.distributionbar dbar-addon @@ -222,7 +221,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/UiProperties.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/UiProperties.java index 22a8d8d23..b23935826 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/UiProperties.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/UiProperties.java @@ -1,11 +1,21 @@ +/** + * 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 { 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 9dd207565..191ae1078 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,7 +18,7 @@ import java.util.List; import java.util.Optional; import java.util.stream.Collectors; -import org.eclipse.hawkbit.ServerProperties; +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; @@ -67,7 +67,7 @@ public final class DashboardMenu extends CustomComponent { private transient UiProperties uiProperties; @Autowired - private transient ServerProperties serverProperties; + private transient HawkbitServerProperties serverProperties; private static final long serialVersionUID = 5394474618559481462L; diff --git a/pom.xml b/pom.xml index d481a56fb..bf38d3b14 100644 --- a/pom.xml +++ b/pom.xml @@ -559,7 +559,6 @@ org.json json ${json.version} - test de.flapdoodle.embed From 7692a299185a084b9a32d1f9f6c2ffb48f2f1ebb Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Thu, 25 Feb 2016 20:36:17 +0100 Subject: [PATCH 23/58] Fixed property bean setup --- .../AsyncConfigurerThreadpoolProperties.java | 2 -- .../security/SecurityManagedConfiguration.java | 12 ++++++------ .../src/main/resources/META-INF/spring.factories | 1 - .../src/main/resources/hawkbitdefaults.properties | 5 ++--- .../org/eclipse/hawkbit/HawkbitServerProperties.java | 4 +--- .../hawkbit/amqp/AmqpControllerAuthentfication.java | 6 +++--- .../util/PropertyBasedArtifactUrlHandlerTest.java | 6 +++--- .../java/org/eclipse/hawkbit/TestConfiguration.java | 5 +++-- .../hawkbit/security/DdiSecurityProperties.java | 2 -- 9 files changed, 18 insertions(+), 25 deletions(-) diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/AsyncConfigurerThreadpoolProperties.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/AsyncConfigurerThreadpoolProperties.java index 2e7c6406e..35996a114 100644 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/AsyncConfigurerThreadpoolProperties.java +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/scheduling/AsyncConfigurerThreadpoolProperties.java @@ -9,13 +9,11 @@ package org.eclipse.hawkbit.autoconfigure.scheduling; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; /** * Properties for the async configurer. * */ -@Component @ConfigurationProperties("hawkbit.threadpool") public class AsyncConfigurerThreadpoolProperties { diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java index c337b8e94..b27e76a28 100644 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java @@ -115,7 +115,7 @@ public class SecurityManagedConfiguration { @Autowired private TenantAware tenantAware; @Autowired - private DdiSecurityProperties securityConfiguration; + private DdiSecurityProperties ddiSecurityConfiguration; @Autowired private org.springframework.boot.autoconfigure.security.SecurityProperties springSecurityProperties; @@ -124,7 +124,7 @@ public class SecurityManagedConfiguration { final ControllerTenantAwareAuthenticationDetailsSource authenticationDetailsSource = new ControllerTenantAwareAuthenticationDetailsSource(); final HttpControllerPreAuthenticatedSecurityHeaderFilter securityHeaderFilter = new HttpControllerPreAuthenticatedSecurityHeaderFilter( - securityConfiguration.getRp().getCnHeader(), securityConfiguration.getRp().getSslIssuerHashHeader(), + ddiSecurityConfiguration.getRp().getCnHeader(), ddiSecurityConfiguration.getRp().getSslIssuerHashHeader(), systemManagement, tenantAware); securityHeaderFilter.setAuthenticationManager(authenticationManager()); securityHeaderFilter.setCheckForPrincipalChanges(true); @@ -150,7 +150,7 @@ public class SecurityManagedConfiguration { httpSec = httpSec.requiresChannel().anyRequest().requiresSecure().and(); } - if (securityConfiguration.getAuthentication().getAnonymous().isEnabled()) { + if (ddiSecurityConfiguration.getAuthentication().getAnonymous().isEnabled()) { LOG.info( "******************\n** Anonymous controller security enabled, should only use for developing purposes **\n******************"); final AnonymousAuthenticationFilter anoymousFilter = new AnonymousAuthenticationFilter( @@ -181,7 +181,7 @@ public class SecurityManagedConfiguration { @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider( - new PreAuthTokenSourceTrustAuthenticationProvider(securityConfiguration.getRp().getTrustedIPs())); + new PreAuthTokenSourceTrustAuthenticationProvider(ddiSecurityConfiguration.getRp().getTrustedIPs())); } } @@ -444,7 +444,7 @@ public class SecurityManagedConfiguration { public static class IdRestSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { @Autowired - private DdiSecurityProperties securityConfiguration; + private DdiSecurityProperties ddiSecurityConfiguration; @Autowired @Qualifier(CacheConstants.DOWNLOAD_ID_CACHE) @@ -467,7 +467,7 @@ public class SecurityManagedConfiguration { @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider( - new PreAuthTokenSourceTrustAuthenticationProvider(securityConfiguration.getRp().getTrustedIPs())); + new PreAuthTokenSourceTrustAuthenticationProvider(ddiSecurityConfiguration.getRp().getTrustedIPs())); } } diff --git a/hawkbit-autoconfigure/src/main/resources/META-INF/spring.factories b/hawkbit-autoconfigure/src/main/resources/META-INF/spring.factories index 5d8d005d9..335054585 100644 --- a/hawkbit-autoconfigure/src/main/resources/META-INF/spring.factories +++ b/hawkbit-autoconfigure/src/main/resources/META-INF/spring.factories @@ -11,5 +11,4 @@ org.eclipse.hawkbit.autoconfigure.eventbus.EventBusAutoConfiguration,\ org.eclipse.hawkbit.autoconfigure.scheduling.AsyncConfigurerAutoConfiguration,\ org.eclipse.hawkbit.autoconfigure.cache.RedisAutoConfiguration,\ org.eclipse.hawkbit.autoconfigure.scheduling.ExecutorAutoConfiguration,\ -org.eclipse.hawkbit.autoconfigure.conf.ControllerPollAutoConfiguration,\ org.eclipse.hawkbit.autoconfigure.amqp.AmqpAutoConfiguration diff --git a/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties b/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties index 98749a384..5e1f6e680 100644 --- a/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties +++ b/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties @@ -29,11 +29,10 @@ flyway.initOnMigrate=true flyway.sqlMigrationSuffix=${spring.jpa.database}.sql # Vaadin Servlet -vaadin.static.servlet.productionMode=true vaadin.servlet.productionMode=true vaadin.servlet.urlMapping=/UI/* -vaadin.servlet.params.heartbeatInterval=60 -vaadin.servlet.params.closeIdleSessions=false +vaadin.servlet.heartbeatInterval=60 +vaadin.servlet.closeIdleSessions=false # Spring MVC spring.mvc.favicon.enabled=false diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java index e36c9dfdb..878965102 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/HawkbitServerProperties.java @@ -9,13 +9,11 @@ package org.eclipse.hawkbit; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; /** * Properties for the server e.g. the server's URL which must be configured. * */ -@Component @ConfigurationProperties("hawkbit.server") public class HawkbitServerProperties { /** @@ -31,7 +29,7 @@ public class HawkbitServerProperties { } /** - * Build information of the hawkBit instance. Influeneced by maven. + * Build information of the hawkBit instance. Influenced by maven. * */ public static class Build { 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 227933b33..20a663387 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 @@ -55,7 +55,7 @@ public class AmqpControllerAuthentfication { private TenantAware tenantAware; @Autowired - private DdiSecurityProperties secruityProperties; + private DdiSecurityProperties ddiSecruityProperties; /** * Constructor. @@ -78,7 +78,7 @@ public class AmqpControllerAuthentfication { filterChain.add(gatewaySecurityTokenFilter); final ControllerPreAuthenticatedSecurityHeaderFilter securityHeaderFilter = new ControllerPreAuthenticatedSecurityHeaderFilter( - secruityProperties.getRp().getCnHeader(), secruityProperties.getRp().getSslIssuerHashHeader(), + ddiSecruityProperties.getRp().getCnHeader(), ddiSecruityProperties.getRp().getSslIssuerHashHeader(), systemManagement, tenantAware); filterChain.add(securityHeaderFilter); @@ -138,7 +138,7 @@ public class AmqpControllerAuthentfication { } public void setSecruityProperties(final DdiSecurityProperties secruityProperties) { - this.secruityProperties = secruityProperties; + this.ddiSecruityProperties = secruityProperties; } public void setSystemManagement(final SystemManagement systemManagement) { 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..31901ae9e 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 @@ -50,7 +50,7 @@ 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 @@ -59,7 +59,7 @@ public class PropertyBasedArtifactUrlHandlerTest extends AbstractIntegrationTest } @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 @@ -68,7 +68,7 @@ public class PropertyBasedArtifactUrlHandlerTest extends AbstractIntegrationTest } @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); 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 e6887a976..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,11 +17,13 @@ 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.SpringSecurityAuditorAware; import org.eclipse.hawkbit.tenancy.TenantAware; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cache.Cache; import org.springframework.cache.guava.GuavaCacheManager; import org.springframework.context.annotation.AdviceMode; @@ -45,8 +47,7 @@ import com.mongodb.MongoClientOptions; */ @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true, mode = AdviceMode.ASPECTJ, proxyTargetClass = true, securedEnabled = true) -// @EnableConfigurationProperties({ DdiSecurityProperties.class, -// ControllerPollProperties.class }) +@EnableConfigurationProperties({ DdiSecurityProperties.class, ControllerPollProperties.class }) @Profile("test") public class TestConfiguration implements AsyncConfigurer { 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 index cb95975e5..ce1ff91d8 100644 --- 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 @@ -11,12 +11,10 @@ package org.eclipse.hawkbit.security; import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; /** * The common properties for DDI security. */ -@Component @ConfigurationProperties("hawkbit.server.ddi.security") public class DdiSecurityProperties { From c221da7d64ff48a77d195d33ac2a33e0ba9105d7 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Thu, 25 Feb 2016 21:26:04 +0100 Subject: [PATCH 24/58] Removed unnecessary property definitions --- .../src/main/resources/hawkbitdefaults.properties | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties b/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties index 5e1f6e680..5e767726a 100644 --- a/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties +++ b/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties @@ -7,12 +7,6 @@ # http://www.eclipse.org/legal/epl-v10.html # -# Tomcat / Server -server.tomcat.compression=on -spring.http.gzip.mime-types=text/html,text/xml,text/plain,application/json,application/javascript,text/css,application/x-javascript,text/javascript,application/vnd.ms-fontobject,application/x-font-opentype,application/x-font-truetype,application/x-font-ttf,application/xml,font/eot,font/opentype,font/otf,image/svg+xml,image/vnd.microsoft.icon -server.tomcat.compressable-mime-types=${spring.http.gzip.mime-types} -spring.http.gzip.min-gzip-size=256 - # JPA / Datasource spring.jpa.eclipselink.eclipselink.weaving=false spring.jpa.database=H2 @@ -21,7 +15,6 @@ spring.datasource.driverClassName=org.h2.Driver # MongoDB for artifact-repository spring.data.mongodb.uri=mongodb://localhost/artifactrepo -spring.data.mongo.repositories.enabled=true # Flyway DDL flyway.enabled=true @@ -34,10 +27,6 @@ vaadin.servlet.urlMapping=/UI/* vaadin.servlet.heartbeatInterval=60 vaadin.servlet.closeIdleSessions=false -# Spring MVC -spring.mvc.favicon.enabled=false - - # Defines the thread pool executor hawkbit.threadpool.corethreads=5 hawkbit.threadpool.maxthreads=20 From c9c36ea435c2fe2da6c5710f2de794eaad78858b Mon Sep 17 00:00:00 2001 From: SirWayne Date: Mon, 29 Feb 2016 15:34:07 +0100 Subject: [PATCH 25/58] Add description for asserts in test cases Signed-off-by: SirWayne --- .../SoftwareModuleAssigmentBuilder.java | 2 +- .../amqp/AmqpMessageHandlerServiceTest.java | 15 +- .../PropertyBasedArtifactUrlHandlerTest.java | 20 +- .../repository/DeploymentManagementTest.java | 31 ++- .../repository/TargetManagementTest.java | 103 +++++---- .../rsql/RSQLDistributionSetFieldTest.java | 4 +- .../resource/SoftwareModuleResourceTest.java | 203 ++++++++---------- .../rest/resource/model/PagedListTest.java | 13 +- .../ui/common/tagdetails/TargetTagToken.java | 4 +- .../ManangementConfirmationWindowLayout.java | 37 +--- 10 files changed, 203 insertions(+), 229 deletions(-) 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/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..cf6c26590 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 @@ -115,14 +115,16 @@ public class AmqpMessageHandlerServiceTest { } - @Test(expected = IllegalArgumentException.class) @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); + fail("IllegalArgumentException was excepeted due to worng content type"); + } catch (final IllegalArgumentException e) { + } } @Test @@ -197,14 +199,14 @@ public class AmqpMessageHandlerServiceTest { final Message message = new Message(new byte[0], messageProperties); try { amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT); - fail(); + 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(); + fail("IllegalArgumentException was excepeted due to unknown topic"); } catch (final IllegalArgumentException e) { } @@ -328,7 +330,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 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..2f3a8e21b 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 @@ -53,18 +53,22 @@ public class PropertyBasedArtifactUrlHandlerTest extends AbstractIntegrationTest @Description("Tests generate the 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") 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 @@ -72,7 +76,7 @@ public class PropertyBasedArtifactUrlHandlerTest extends AbstractIntegrationTest 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-repository/src/test/java/org/eclipse/hawkbit/repository/DeploymentManagementTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DeploymentManagementTest.java index 985bc6bd9..a3071d756 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 @@ -766,12 +766,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); @@ -782,12 +783,8 @@ 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()); @@ -797,13 +794,15 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { 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("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/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/RSQLDistributionSetFieldTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetFieldTest.java index 6bfdb89aa..f72c3a968 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 @@ -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-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..3a0cc3e94 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; @@ -69,6 +71,13 @@ import ru.yandex.qatools.allure.annotations.Stories; @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(); @@ -123,9 +128,6 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo @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 +154,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 +210,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 +232,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 +246,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 +278,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 +289,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); @@ -350,19 +327,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 +522,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 +584,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 +682,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 +739,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 +790,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 +873,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 +893,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 +906,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 +941,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 +966,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/model/PagedListTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/model/PagedListTest.java index 0c47856dd..4a88bf43e 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 @@ -29,10 +29,13 @@ public class PagedListTest { 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 @@ -42,9 +45,7 @@ public class PagedListTest { 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-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/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()); From 5973413cbeba331a97f39490f7510b2a4adae793 Mon Sep 17 00:00:00 2001 From: SirWayne Date: Tue, 1 Mar 2016 08:37:50 +0100 Subject: [PATCH 26/58] Add Javadoc and remove message converter from base class Signed-off-by: SirWayne --- .../hawkbit/amqp/AmqpConfiguration.java | 4 +-- .../amqp/AmqpMessageDispatcherService.java | 11 ++++-- .../amqp/AmqpMessageHandlerService.java | 35 ++++--------------- .../hawkbit/amqp/AmqpSenderService.java | 2 +- .../eclipse/hawkbit/amqp/BaseAmqpService.java | 33 +++++++++++------ .../AmqpControllerAuthentficationTest.java | 4 ++- .../AmqpMessageDispatcherServiceTest.java | 3 +- .../amqp/AmqpMessageHandlerServiceTest.java | 3 +- 8 files changed, 46 insertions(+), 49 deletions(-) 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 ad106c0bd..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 @@ -122,11 +122,11 @@ public class AmqpConfiguration { /** * Create amqp handler service bean. * - * @return + * @return handler service bean */ @Bean public AmqpMessageHandlerService amqpMessageHandlerService() { - return new AmqpMessageHandlerService(jsonMessageConverter(), rabbitTemplate); + return new AmqpMessageHandlerService(rabbitTemplate); } /** 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 a2ffd06e3..8681d3a7a 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 @@ -29,7 +29,6 @@ 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.MessageConverter; import org.springframework.beans.factory.annotation.Autowired; @@ -52,9 +51,15 @@ public class AmqpMessageDispatcherService extends BaseAmqpService { @Autowired private AmqpSenderService amqpSenderService; + /** + * Constructor. + * + * @param messageConverter + * message converter + */ @Autowired - public AmqpMessageDispatcherService(final MessageConverter messageConverter, final RabbitTemplate defaultTemplate) { - super(messageConverter, defaultTemplate); + public AmqpMessageDispatcherService(final MessageConverter messageConverter) { + super(messageConverter); } /** 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 33ca6837e..66de7ada0 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 @@ -49,7 +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.MessageConverter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.Cache; @@ -97,16 +96,17 @@ public class AmqpMessageHandlerService extends BaseAmqpService { @Autowired private HostnameResolver hostnameResolver; + private final RabbitTemplate internalAmqpTemplate; + /** * Constructor. * - * @param messageConverter - * the message converter. * @param defaultTemplate * the configured amqp template. */ - public AmqpMessageHandlerService(final MessageConverter messageConverter, final RabbitTemplate defaultTemplate) { - super(messageConverter, defaultTemplate); + public AmqpMessageHandlerService(final RabbitTemplate defaultTemplate) { + super(defaultTemplate.getMessageConverter()); + this.internalAmqpTemplate = defaultTemplate; } @RabbitListener(queues = "${hawkbit.dmf.rabbitmq.receiverQueue}", containerFactory = "listenerContainerFactory") @@ -346,11 +346,6 @@ public class AmqpMessageHandlerService extends BaseAmqpService { return controllerManagement.addUpdateActionStatus(actionStatus, action); } - /** - * @param message - * @param actionUpdateStatus - * @return - */ private Action checkActionExist(final Message message, final ActionUpdateStatus actionUpdateStatus) { final Long actionId = actionUpdateStatus.getActionId(); LOG.debug("Target notifies intermediate about action {} with status {}.", actionId, @@ -383,17 +378,7 @@ public class AmqpMessageHandlerService extends BaseAmqpService { } } - /** - * 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; @@ -409,14 +394,6 @@ public class AmqpMessageHandlerService extends BaseAmqpService { this.hostnameResolver = hostnameResolver; } - void setMessageConverter(final MessageConverter messageConverter) { - this.messageConverter = messageConverter; - } - - MessageConverter getMessageConverter() { - return messageConverter; - } - void setAuthenticationManager(final AmqpControllerAuthentfication authenticationManager) { this.authenticationManager = authenticationManager; } 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 index 936495aba..6cb3dd9be 100644 --- 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 @@ -20,7 +20,7 @@ public interface AmqpSenderService { /** * Send the given message to the given uri. The uri contains the (virtual) - * host and exchange. + * host and exchange e.g amqp://host/exchange. * * @param message * the amqp message 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 index 6cfa89358..5ad27c041 100644 --- 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 @@ -16,7 +16,6 @@ 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; @@ -28,14 +27,23 @@ public class BaseAmqpService { private static final Logger LOGGER = LoggerFactory.getLogger(BaseAmqpService.class); protected MessageConverter messageConverter; - protected RabbitTemplate internalAmqpTemplate; - - public BaseAmqpService(final MessageConverter messageConverter, final RabbitTemplate defaultTemplate) { + /** + * Constructor. + * + * @param messageConverter + * the message messageConverter. + */ + public BaseAmqpService(final MessageConverter messageConverter) { this.messageConverter = messageConverter; - internalAmqpTemplate = defaultTemplate; } - protected void cleanMessage(final Message message) { + /** + * 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); } @@ -46,7 +54,7 @@ public class BaseAmqpService { * the message to convert. * @param clazz * the class of the originally object. - * @return + * @return the converted object */ @SuppressWarnings("unchecked") protected T convertMessage(final Message message, final Class clazz) { @@ -66,7 +74,7 @@ public class BaseAmqpService { * the message to convert. * @param clazz * the class of the list content. - * @return + * @return the list of converted objects */ @SuppressWarnings("unchecked") protected List convertMessageList(final Message message, final Class clazz) { @@ -80,7 +88,12 @@ public class BaseAmqpService { return (List) messageConverter.fromMessage(message); } - protected String getStringHeaderKey(final Message message, final String key, final String errorMessageIfNull) { + public MessageConverter getMessageConverter() { + return messageConverter; + } + + 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) { @@ -89,7 +102,7 @@ public class BaseAmqpService { return value.toString(); } - protected void logAndThrowMessageError(final Message message, final String error) { + protected final void logAndThrowMessageError(final Message message, final String error) { LOGGER.error("Error \"{}\" reported by message {}", error, message.getMessageProperties().getMessageId()); throw new IllegalArgumentException(error); } 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/AmqpControllerAuthentficationTest.java index e8b8a089b..ce2db47d5 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/AmqpControllerAuthentficationTest.java @@ -61,7 +61,9 @@ public class AmqpControllerAuthentficationTest { @Before public void before() throws Exception { messageConverter = new Jackson2JsonMessageConverter(); - amqpMessageHandlerService = new AmqpMessageHandlerService(messageConverter, mock(RabbitTemplate.class)); + final RabbitTemplate rabbitTemplate = mock(RabbitTemplate.class); + when(rabbitTemplate.getMessageConverter()).thenReturn(messageConverter); + amqpMessageHandlerService = new AmqpMessageHandlerService(rabbitTemplate); authenticationManager = new AmqpControllerAuthentfication(); authenticationManager.setControllerManagement(mock(ControllerManagement.class)); 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 4c8300bfd..5967976ca 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 @@ -70,8 +70,7 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit super.before(); this.rabbitTemplate = Mockito.mock(RabbitTemplate.class); when(rabbitTemplate.getMessageConverter()).thenReturn(new Jackson2JsonMessageConverter()); - amqpMessageDispatcherService = new AmqpMessageDispatcherService(new Jackson2JsonMessageConverter(), - rabbitTemplate); + amqpMessageDispatcherService = new AmqpMessageDispatcherService(new Jackson2JsonMessageConverter()); amqpMessageDispatcherService = spy(amqpMessageDispatcherService); senderService = Mockito.mock(DefaultAmqpSenderService.class); 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 9bc2f2da7..582a1857b 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 @@ -105,7 +105,8 @@ public class AmqpMessageHandlerServiceTest { @Before public void before() throws Exception { messageConverter = new Jackson2JsonMessageConverter(); - amqpMessageHandlerService = new AmqpMessageHandlerService(messageConverter, rabbitTemplate); + when(rabbitTemplate.getMessageConverter()).thenReturn(messageConverter); + amqpMessageHandlerService = new AmqpMessageHandlerService(rabbitTemplate); amqpMessageHandlerService.setControllerManagement(controllerManagementMock); amqpMessageHandlerService.setAuthenticationManager(authenticationManagerMock); amqpMessageHandlerService.setArtifactManagement(artifactManagementMock); From 229e7c54af239fb1b7476ec1b7dce14e63bb023d Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Wed, 2 Mar 2016 07:33:22 +0100 Subject: [PATCH 27/58] introduce a push strategy to the HawkbitUI and a delayed push implementation to avoid UI freezes when too many events are dispatched to the UI Signed-off-by: Michael Hirsch --- .../java/org/eclipse/hawkbit/app/MyUI.java | 50 +--- .../org/eclipse/hawkbit/ui/HawkbitUI.java | 82 ++---- .../ui/push/DelayedEventBusPushStrategy.java | 245 ++++++++++++++++++ .../hawkbit/ui/push/EventPushStrategy.java | 35 +++ 4 files changed, 307 insertions(+), 105 deletions(-) create mode 100644 hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/DelayedEventBusPushStrategy.java create mode 100644 hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/EventPushStrategy.java 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/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/push/DelayedEventBusPushStrategy.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/DelayedEventBusPushStrategy.java new file mode 100644 index 000000000..d54bce409 --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/DelayedEventBusPushStrategy.java @@ -0,0 +1,245 @@ +/** + * 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. + * + * @author Michael Hirsch + * + */ +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) { + 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..55e3b367d --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/EventPushStrategy.java @@ -0,0 +1,35 @@ +/** + * 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. + * + * @author Michael Hirsch + * + */ +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(); +} From 5efcc295bce4fa8720bea7387374a019584d45b2 Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Wed, 2 Mar 2016 09:00:10 +0100 Subject: [PATCH 28/58] clean code do early return. Signed-off-by: Michael Hirsch --- .../ui/push/DelayedEventBusPushStrategy.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) 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 index d54bce409..9ebfcdefd 100644 --- 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 @@ -143,12 +143,13 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { */ 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()); - } + 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; } From 6f39769692bb42a3576e593e2030f01083d82eb1 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Wed, 2 Mar 2016 10:20:47 +0100 Subject: [PATCH 29/58] Removed out commented code. Signed-off-by: Kai Zimmermann --- .../org/eclipse/hawkbit/ui/menu/DashboardMenu.java | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) 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 191ae1078..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 @@ -77,16 +77,12 @@ public final class DashboardMenu extends CustomComponent { 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<>(); @@ -96,8 +92,8 @@ public final class DashboardMenu extends CustomComponent { /** * 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 = ""; From 22f94da9eb66cc55d188b912f63d18525c74385c Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Wed, 2 Mar 2016 10:22:27 +0100 Subject: [PATCH 30/58] Commented new factorypath entry --- .gitignore | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index fcd017f64..8cd3d476e 100644 --- a/.gitignore +++ b/.gitignore @@ -19,9 +19,10 @@ # Sonar .sonar_lock -# Eclipse IDE - +# Created by spring-boot-configuration-processor .factorypath + +# Eclipse IDE *.pydevproject .project .metadata From d28ea67e89ff34dca8748575a853c60625c9bc13 Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Wed, 2 Mar 2016 11:25:43 +0100 Subject: [PATCH 31/58] remove author tag from javadoc Signed-off-by: Michael Hirsch --- .../eclipse/hawkbit/ui/push/DelayedEventBusPushStrategy.java | 2 -- .../java/org/eclipse/hawkbit/ui/push/EventPushStrategy.java | 2 -- 2 files changed, 4 deletions(-) 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 index 9ebfcdefd..87fcbe922 100644 --- 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 @@ -58,8 +58,6 @@ import com.vaadin.ui.UI; * 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. * - * @author Michael Hirsch - * */ public class DelayedEventBusPushStrategy implements EventPushStrategy { 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 index 55e3b367d..504dece60 100644 --- 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 @@ -12,8 +12,6 @@ import com.vaadin.ui.UI; /** * Interface declaring a strategy to push events from the back-end to the UI. - * - * @author Michael Hirsch * */ public interface EventPushStrategy { From d014e81b738644cbfd8a8b1377fc45de29e3b6ac Mon Sep 17 00:00:00 2001 From: Dennis Melzer Date: Wed, 2 Mar 2016 12:50:00 +0100 Subject: [PATCH 32/58] Update AmqpMessageHandlerService.java --- .../org/eclipse/hawkbit/amqp/AmqpMessageHandlerService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 66de7ada0..ae1926331 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 @@ -374,7 +374,7 @@ public class AmqpMessageHandlerService extends BaseAmqpService { } else { logAndThrowMessageError(message, - "Cancel Recjected message is not allowed, if action is on state: " + action.getStatus()); + "Cancel recjected message is not allowed, if action is on state: " + action.getStatus()); } } From fbff46c7bd88a9e70e9756bc53a6aa17a9e548ee Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Wed, 2 Mar 2016 12:57:51 +0100 Subject: [PATCH 33/58] Removed component --- .../main/java/org/eclipse/hawkbit/cache/RedisProperties.java | 2 -- 1 file changed, 2 deletions(-) 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 fcd5a1d3d..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 @@ -9,14 +9,12 @@ package org.eclipse.hawkbit.cache; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; /** * Bean which holds the necessary properties for configuring the Redis * connection. * */ -@Component @ConfigurationProperties("hawkbit.server.redis") public class RedisProperties { From 8c4b7e1750dc494e913cb1611e620dbe5a9054bd Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Thu, 3 Mar 2016 10:35:09 +0100 Subject: [PATCH 34/58] Upgraded eclipse link weave to 2.6.2 --- hawkbit-repository/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hawkbit-repository/pom.xml b/hawkbit-repository/pom.xml index 62d234ddb..981da979e 100644 --- a/hawkbit-repository/pom.xml +++ b/hawkbit-repository/pom.xml @@ -215,7 +215,7 @@ com.ethlo.persistence.tools eclipselink-maven-plugin - 1.1-SNAPSHOT + 2.6.2 process-classes From e731543313b663ae02327882897134aa1822c78f Mon Sep 17 00:00:00 2001 From: Jonathan Philip Knoblauch Date: Thu, 3 Mar 2016 10:52:55 +0100 Subject: [PATCH 35/58] Fix for sonar rule: Fields and methods should not have conflicting names Signed-off-by: Jonathan Philip Knoblauch --- .../CreateUpdateSoftwareTypeLayout.java | 8 +- .../artifacts/state/ArtifactUploadState.java | 16 ++-- .../CreateUpdateDistSetTypeLayout.java | 4 +- .../state/ManageDistUIState.java | 16 ++-- .../DistributionAddUpdateWindowLayout.java | 30 ++++---- .../management/state/ManagementUIState.java | 20 ++--- .../rollout/AddUpdateRolloutWindowLayout.java | 76 ++++++++++--------- ...yTokenAuthenticationConfigurationItem.java | 7 +- 8 files changed, 88 insertions(+), 89 deletions(-) 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/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/management/dstable/DistributionAddUpdateWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java index dfdbcd9de..21914778e 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 saveDistributionButton; + private Button discardDistributionButton; 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(saveDistributionButton, discardDistributionButton); + buttonsLayout.setComponentAlignment(saveDistributionButton, Alignment.BOTTOM_LEFT); + buttonsLayout.setComponentAlignment(discardDistributionButton, 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, + saveDistributionButton = SPUIComponentProvider.getButton(SPUIComponetIdProvider.DIST_ADD_SAVE, "", "", "", true, FontAwesome.SAVE, SPUIButtonStyleSmallNoBorder.class); - saveDistribution.addClickListener(event -> saveDistribution()); + saveDistributionButton.addClickListener(event -> saveDistribution()); /* close button */ - discardDistribution = SPUIComponentProvider.getButton(SPUIComponetIdProvider.DIST_ADD_DISCARD, "", "", "", true, - FontAwesome.TIMES, SPUIButtonStyleSmallNoBorder.class); - discardDistribution.addClickListener(event -> discardDistribution()); + discardDistributionButton = SPUIComponentProvider.getButton(SPUIComponetIdProvider.DIST_ADD_DISCARD, "", "", "", + true, FontAwesome.TIMES, SPUIButtonStyleSmallNoBorder.class); + discardDistributionButton.addClickListener(event -> discardDistribution()); } /** @@ -216,7 +216,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { } private void enableSaveButton() { - saveDistribution.setEnabled(true); + saveDistributionButton.setEnabled(true); } private DistributionSetType getDefaultDistributionSetType() { @@ -226,7 +226,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { } private void disableSaveButton() { - saveDistribution.setEnabled(false); + saveDistributionButton.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); + saveDistributionButton.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); + saveDistributionButton.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/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/rollout/AddUpdateRolloutWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/AddUpdateRolloutWindowLayout.java index d0cddfb19..3a1deaf65 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,7 +128,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { private TextArea description; - private Button saveRollout; + private Button saveRolloutBtn; private Button discardRolllout; @@ -138,7 +138,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { private Window addUpdateRolloutWindow; - private Boolean editRollout; + private Boolean editRolloutBtn; private Rollout rolloutForEdit; @@ -167,7 +167,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { * Reset the field values. */ public void resetComponents() { - editRollout = Boolean.FALSE; + editRolloutBtn = 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,8 +254,8 @@ 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.addComponents(saveRolloutBtn, discardRolllout); + buttonsLayout.setComponentAlignment(saveRolloutBtn, Alignment.BOTTOM_LEFT); buttonsLayout.setComponentAlignment(discardRolllout, Alignment.BOTTOM_RIGHT); buttonsLayout.addStyleName("window-style"); return buttonsLayout; @@ -277,7 +277,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { description = createDescription(); errorThresholdOptionGroup = createErrorThresholdOptionGroup(); setDefaultSaveStartGroupOption(); - saveRollout = createSaveButton(); + saveRolloutBtn = createSaveButton(); discardRolllout = createDiscardButton(); actionTypeOptionGroupLayout.selectDefaultOption(); @@ -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 (editRolloutBtn) { 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; + editRolloutBtn = 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 6ae002263..20865494b 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 @@ -87,7 +87,7 @@ public class GatewaySecurityTokenAuthenticationConfigurationItem extends Abstrac // hide text field until we support multiple gateway tokens for a tenant // MECS-830 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); @@ -117,10 +117,7 @@ public class GatewaySecurityTokenAuthenticationConfigurationItem extends Abstrac } } - /** - * @return - */ - private void keyNameChanged() { + private void doKeyNameChanged() { keyNameChanged = true; notifyConfigurationChanged(); } From 74731d39ce96756f728bf7905c6675dc0bbf42b4 Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Thu, 3 Mar 2016 10:57:57 +0100 Subject: [PATCH 36/58] fix retrieving the wrong message converter for converting messages over amqp Signed-off-by: Michael Hirsch --- .../amqp/AmqpMessageDispatcherService.java | 13 ++++++------ .../amqp/AmqpMessageHandlerService.java | 9 +++------ .../eclipse/hawkbit/amqp/BaseAmqpService.java | 20 +++++++++++-------- .../AmqpMessageDispatcherServiceTest.java | 2 +- 4 files changed, 23 insertions(+), 21 deletions(-) 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 8681d3a7a..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 @@ -29,7 +29,7 @@ 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.support.converter.MessageConverter; +import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import com.google.common.eventbus.Subscribe; @@ -58,8 +58,8 @@ public class AmqpMessageDispatcherService extends BaseAmqpService { * message converter */ @Autowired - public AmqpMessageDispatcherService(final MessageConverter messageConverter) { - super(messageConverter); + public AmqpMessageDispatcherService(final RabbitTemplate rabbitTemplate) { + super(rabbitTemplate); } /** @@ -87,8 +87,9 @@ public class AmqpMessageDispatcherService extends BaseAmqpService { downloadAndUpdateRequest.addSoftwareModule(amqpSoftwareModule); } - final Message message = messageConverter.toMessage(downloadAndUpdateRequest, createConnectorMessageProperties( - targetAssignDistributionSetEvent.getTenant(), controllerId, EventTopic.DOWNLOAD_AND_INSTALL)); + final Message message = getMessageConverter().toMessage(downloadAndUpdateRequest, + createConnectorMessageProperties(targetAssignDistributionSetEvent.getTenant(), controllerId, + EventTopic.DOWNLOAD_AND_INSTALL)); amqpSenderService.sendMessage(message, targetAdress); } @@ -104,7 +105,7 @@ public class AmqpMessageDispatcherService extends BaseAmqpService { final CancelTargetAssignmentEvent cancelTargetAssignmentDistributionSetEvent) { final String controllerId = cancelTargetAssignmentDistributionSetEvent.getControllerId(); final Long actionId = cancelTargetAssignmentDistributionSetEvent.getActionId(); - final Message message = messageConverter.toMessage(actionId, createConnectorMessageProperties( + final Message message = getMessageConverter().toMessage(actionId, createConnectorMessageProperties( cancelTargetAssignmentDistributionSetEvent.getTenant(), controllerId, EventTopic.CANCEL_DOWNLOAD)); amqpSenderService.sendMessage(message, cancelTargetAssignmentDistributionSetEvent.getTargetAdress()); 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 ae1926331..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 @@ -96,8 +96,6 @@ public class AmqpMessageHandlerService extends BaseAmqpService { @Autowired private HostnameResolver hostnameResolver; - private final RabbitTemplate internalAmqpTemplate; - /** * Constructor. * @@ -105,14 +103,13 @@ public class AmqpMessageHandlerService extends BaseAmqpService { * the configured amqp template. */ public AmqpMessageHandlerService(final RabbitTemplate defaultTemplate) { - super(defaultTemplate.getMessageConverter()); - this.internalAmqpTemplate = 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, internalAmqpTemplate.getConnectionFactory().getVirtualHost()); + return onMessage(message, type, tenant, getRabbitTemplate().getConnectionFactory().getVirtualHost()); } /** @@ -207,7 +204,7 @@ public class AmqpMessageHandlerService extends BaseAmqpService { authentificationResponse.setMessage(errorMessage); } - return messageConverter.toMessage(authentificationResponse, messageProperties); + return getMessageConverter().toMessage(authentificationResponse, messageProperties); } private static Artifact convertDbArtifact(final DbArtifact dbArtifact) { 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 index 5ad27c041..f418937e3 100644 --- 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 @@ -16,6 +16,7 @@ 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; @@ -25,16 +26,16 @@ import org.springframework.amqp.support.converter.MessageConverter; public class BaseAmqpService { private static final Logger LOGGER = LoggerFactory.getLogger(BaseAmqpService.class); - protected MessageConverter messageConverter; + private final RabbitTemplate rabbitTemplate; /** * Constructor. * - * @param messageConverter - * the message messageConverter. + * @param rabbitTemplate + * the rabbit template. */ - public BaseAmqpService(final MessageConverter messageConverter) { - this.messageConverter = messageConverter; + public BaseAmqpService(final RabbitTemplate rabbitTemplate) { + this.rabbitTemplate = rabbitTemplate; } /** @@ -63,7 +64,7 @@ public class BaseAmqpService { } message.getMessageProperties().getHeaders().put(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME, clazz.getName()); - return (T) messageConverter.fromMessage(message); + return (T) rabbitTemplate.getMessageConverter().fromMessage(message); } /** @@ -85,11 +86,11 @@ public class BaseAmqpService { ArrayList.class.getName()); message.getMessageProperties().getHeaders().put(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, clazz.getName()); - return (List) messageConverter.fromMessage(message); + return (List) rabbitTemplate.getMessageConverter().fromMessage(message); } public MessageConverter getMessageConverter() { - return messageConverter; + return rabbitTemplate.getMessageConverter(); } protected final String getStringHeaderKey(final Message message, final String key, @@ -107,4 +108,7 @@ public class BaseAmqpService { throw new IllegalArgumentException(error); } + protected RabbitTemplate getRabbitTemplate() { + return rabbitTemplate; + } } 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 5967976ca..f8ac2a027 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 @@ -70,7 +70,7 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit super.before(); this.rabbitTemplate = Mockito.mock(RabbitTemplate.class); when(rabbitTemplate.getMessageConverter()).thenReturn(new Jackson2JsonMessageConverter()); - amqpMessageDispatcherService = new AmqpMessageDispatcherService(new Jackson2JsonMessageConverter()); + amqpMessageDispatcherService = new AmqpMessageDispatcherService(rabbitTemplate); amqpMessageDispatcherService = spy(amqpMessageDispatcherService); senderService = Mockito.mock(DefaultAmqpSenderService.class); From 8b1816f42273911250d41da6c99bd10f630ee5ab Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Thu, 3 Mar 2016 17:06:58 +0100 Subject: [PATCH 37/58] Fixed wrong status content generation in mgmt API. Signed-off-by: Kai Zimmermann --- .../hawkbit/rest/resource/TargetMapper.java | 4 +- .../rest/resource/TargetResourceTest.java | 79 +++++++++++++++++-- 2 files changed, 76 insertions(+), 7 deletions(-) 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/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..5001bf00a 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; @@ -229,7 +230,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { @Test 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}", @@ -252,7 +253,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { @Test public void cancelAnCancelActionIsNotAllowed() throws Exception { // prepare test - Target tA = createTargetAndStartAction(); + final Target tA = createTargetAndStartAction(); // cancel the active action deploymentManagement.cancelAction(tA.getActions().get(0), tA); @@ -272,7 +273,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 +294,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", @@ -851,6 +852,72 @@ 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 List actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId); + + mvc.perform(get( + RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + RestConstants.TARGET_V1_ACTIONS + + "/" + actions.get(0).getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS)) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + .andExpect( + jsonPath("content.[0].id", equalTo(actions.get(0).getActionStatus().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(actions.get(0).getActionStatus().get(1).getCreatedAt()))) + .andExpect( + jsonPath("content.[1].id", equalTo(actions.get(0).getActionStatus().get(0).getId().intValue()))) + .andExpect(jsonPath("content.[1].type", equalTo("running"))) + .andExpect(jsonPath("content.[1].reportedAt", + equalTo(actions.get(0).getActionStatus().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 resturns the status list with expected content split into two pages.") + public void getMultipleActionStatusWithPagingLimitRequestParameter() throws Exception { + final String knownTargetId = "targetId"; + + final List actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId); + + // Page 1 + mvc.perform(get( + RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + RestConstants.TARGET_V1_ACTIONS + + "/" + actions.get(0).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(actions.get(0).getActionStatus().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(actions.get(0).getActionStatus().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 + + "/" + actions.get(0).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(actions.get(0).getActionStatus().get(0).getId().intValue()))) + .andExpect(jsonPath("content.[0].type", equalTo("running"))) + .andExpect(jsonPath("content.[0].reportedAt", + equalTo(actions.get(0).getActionStatus().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"; @@ -874,6 +941,7 @@ 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))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("content.[0].id", equalTo(actions.get(1).getId().intValue()))) @@ -1232,7 +1300,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 From 3e158deb6b433b803987b4a8498b577f2156df27 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Thu, 3 Mar 2016 17:09:09 +0100 Subject: [PATCH 38/58] Fixed typo. Signed-off-by: Kai Zimmermann --- .../org/eclipse/hawkbit/rest/resource/TargetResourceTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 5001bf00a..7f718b7ca 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 @@ -879,7 +879,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { } @Test - @Description("Verfies that the API resturns the status list with expected content split into two pages.") + @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"; From 19fe7e5a46d56699e5f578fc205a544e8cda7066 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Thu, 3 Mar 2016 17:46:14 +0100 Subject: [PATCH 39/58] Fixed ordering problem. Signed-off-by: Kai Zimmermann --- .../rest/resource/TargetResourceTest.java | 53 ++++++++----------- .../src/test/resources/log4j2.xml | 2 +- 2 files changed, 24 insertions(+), 31 deletions(-) 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 7f718b7ca..fa5935b0e 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 @@ -856,23 +856,20 @@ public class TargetResourceTest extends AbstractIntegrationTest { @Description("Verfies that the API returns the status list with expected content.") public void getMultipleActionStatus() throws Exception { final String knownTargetId = "targetId"; - final List actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId); + 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()); - mvc.perform(get( - RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + RestConstants.TARGET_V1_ACTIONS - + "/" + actions.get(0).getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS)) + 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(actions.get(0).getActionStatus().get(1).getId().intValue()))) + .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(actions.get(0).getActionStatus().get(1).getCreatedAt()))) - .andExpect( - jsonPath("content.[1].id", equalTo(actions.get(0).getActionStatus().get(0).getId().intValue()))) + .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(actions.get(0).getActionStatus().get(0).getCreatedAt()))) + .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))); @@ -883,36 +880,32 @@ public class TargetResourceTest extends AbstractIntegrationTest { public void getMultipleActionStatusWithPagingLimitRequestParameter() throws Exception { final String knownTargetId = "targetId"; - final List actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId); + 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 - + "/" + actions.get(0).getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(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(actions.get(0).getActionStatus().get(1).getId().intValue()))) + .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(actions.get(0).getActionStatus().get(1).getCreatedAt()))) + .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 - + "/" + actions.get(0).getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(1)) - .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(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)) + .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(1))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect( - jsonPath("content.[0].id", equalTo(actions.get(0).getActionStatus().get(0).getId().intValue()))) + .andExpect(jsonPath("content.[0].id", equalTo(actionStatus.get(0).getId().intValue()))) .andExpect(jsonPath("content.[0].type", equalTo("running"))) - .andExpect(jsonPath("content.[0].reportedAt", - equalTo(actions.get(0).getActionStatus().get(0).getCreatedAt()))) + .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))); 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 @@ - + From e7173aa84681d4b494090fcfbeb646b3fd9ed1e3 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Thu, 3 Mar 2016 18:54:50 +0100 Subject: [PATCH 40/58] Cleanup messed up actionstatus sorting. We used sort param but had hardcoded sorting in the reposirory. I added also reportAt based sorting. Signed-off-by: Kai Zimmermann --- .../repository/ActionStatusFields.java | 7 +- .../repository/ActionStatusRepository.java | 9 +- .../repository/DeploymentManagement.java | 8 +- .../repository/ControllerManagementTest.java | 4 +- .../hawkbit/rest/resource/PagingUtility.java | 2 +- .../hawkbit/rest/resource/TargetResource.java | 2 +- .../rest/resource/TargetResourceTest.java | 118 +++++++++--------- .../actionhistory/ActionHistoryTable.java | 7 +- 8 files changed, 77 insertions(+), 80 deletions(-) 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..c5830256a 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. + */ + REPORTED_AT("createdAt"); private final String fieldName; 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..c2cb84939 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 @@ -50,13 +50,6 @@ public interface ActionStatusRepository */ 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 @@ -71,6 +64,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/DeploymentManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java index 236816192..ac989e277 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 @@ -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/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-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..9d3f43545 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 @@ -102,7 +102,7 @@ public final class PagingUtility { sorting = new Sort(SortUtility.parse(ActionStatusFields.class, sortParam)); } else { // default sort - sorting = new Sort(Direction.ASC, ActionStatusFields.ID.getFieldName()); + sorting = new Sort(Direction.DESC, ActionStatusFields.ID.getFieldName()); } return sorting; } 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/rest/resource/TargetResourceTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/TargetResourceTest.java index fa5935b0e..33dd1357a 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 @@ -35,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; @@ -117,27 +118,24 @@ 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"))); } @@ -855,13 +853,40 @@ public class TargetResourceTest extends AbstractIntegrationTest { @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)) + + RestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS) + .param(RestConstants.REQUEST_PARAMETER_SORTING, "REPORTED_AT: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"))) @@ -873,6 +898,22 @@ public class TargetResourceTest extends AbstractIntegrationTest { .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, "REPORTED_AT: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 @@ -963,7 +1004,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()); @@ -981,6 +1023,8 @@ public class TargetResourceTest extends AbstractIntegrationTest { final List updatedTargets = deploymentManagement.assignDistributionSet(one, targets) .getAssignedTargets(); // 2nd update + // sleep 1ms to ensure that we can sort by reportedAt + Thread.sleep(1); deploymentManagement.assignDistributionSet(two, updatedTargets); // two updates, one cancelation @@ -1007,54 +1051,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 { 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..ca0317695 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,9 +420,9 @@ 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 Pageable pageReq = new PageRequest(0, 1000, new Sort(Direction.ASC, ActionStatusFields.ID.getFieldName())); final Page actionStatusList = deploymentManagement - .findActionStatusMessagesByActionInDescOrder(pageReq, action, + .findActionStatusByAction(pageReq, action, managementUIState.isActionHistoryMaximized()); final List content = actionStatusList.getContent(); /* From 794db1867377226faf34b74d5fe26c604df3a754 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Thu, 3 Mar 2016 20:46:50 +0100 Subject: [PATCH 41/58] Added comments and changed default sorting for actions. --- .../repository/ActionStatusRepository.java | 31 ++++++++++++------- .../hawkbit/rest/resource/PagingUtility.java | 13 +++----- .../rest/resource/TargetResourceTest.java | 9 ++++-- 3 files changed, 31 insertions(+), 22 deletions(-) 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 c2cb84939..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,38 +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); /** - * 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 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 9d3f43545..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,7 +97,8 @@ public final class PagingUtility { if (sortParam != null) { sorting = new Sort(SortUtility.parse(ActionStatusFields.class, sortParam)); } else { - // default sort + // 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/test/java/org/eclipse/hawkbit/rest/resource/TargetResourceTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/TargetResourceTest.java index 33dd1357a..7a0c01768 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 @@ -833,7 +833,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"))) @@ -960,7 +961,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"))) @@ -976,7 +978,8 @@ public class TargetResourceTest extends AbstractIntegrationTest { 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"))) From 8c5945badd8825b8ee96b7569f1c769144190ca7 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Thu, 3 Mar 2016 20:53:54 +0100 Subject: [PATCH 42/58] Fixed sort order in UI --- .../ui/management/actionhistory/ActionHistoryTable.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) 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 ca0317695..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 @@ -420,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, new Sort(Direction.ASC, ActionStatusFields.ID.getFieldName())); - final Page actionStatusList = deploymentManagement - .findActionStatusByAction(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 From f17f58f78a907979f467ac8a2973a639fb60af83 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Thu, 3 Mar 2016 21:24:39 +0100 Subject: [PATCH 43/58] Fixed typo. --- .../org/eclipse/hawkbit/rest/resource/model/PagedListTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 b4a11412c..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 @@ -19,7 +19,7 @@ import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -@Features("Junit Tests - Management API") +@Features("Unit Tests - Management API") @Stories("Paged List Handling") public class PagedListTest { From 3b74db0cac9236b2a63cae32a109f6ec979b1e54 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Fri, 4 Mar 2016 08:40:47 +0100 Subject: [PATCH 44/58] Sleep raised to 10ms as stem.currentMillis is not updated every millisecond. Signed-off-by: Kai Zimmermann --- .../org/eclipse/hawkbit/rest/resource/TargetResourceTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 7a0c01768..a99e6d8f7 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 @@ -1026,8 +1026,8 @@ public class TargetResourceTest extends AbstractIntegrationTest { final List updatedTargets = deploymentManagement.assignDistributionSet(one, targets) .getAssignedTargets(); // 2nd update - // sleep 1ms to ensure that we can sort by reportedAt - Thread.sleep(1); + // sleep 10ms to ensure that we can sort by reportedAt + Thread.sleep(10); deploymentManagement.assignDistributionSet(two, updatedTargets); // two updates, one cancelation From 0fc63a452ffebabf7c3430dbd19c575f1d130b99 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Fri, 4 Mar 2016 08:59:17 +0100 Subject: [PATCH 45/58] Switched to REPORTEDAT to be more consitend with other fields. Signed-off-by: Kai Zimmermann --- .../org/eclipse/hawkbit/repository/ActionStatusFields.java | 2 +- .../org/eclipse/hawkbit/rest/resource/TargetResourceTest.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) 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 c5830256a..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 @@ -25,7 +25,7 @@ public enum ActionStatusFields implements FieldNameProvider { /** * The reportedAt field. */ - REPORTED_AT("createdAt"); + REPORTEDAT("createdAt"); private final String fieldName; 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 a99e6d8f7..1ec4d5d16 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 @@ -887,7 +887,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { // 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, "REPORTED_AT:DESC")) + .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"))) @@ -903,7 +903,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { // 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, "REPORTED_AT:ASC")) + .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"))) From 7fe6804045433e44930ed9a051574872e8c2e24c Mon Sep 17 00:00:00 2001 From: asharani-murugesh Date: Fri, 4 Mar 2016 10:05:41 +0100 Subject: [PATCH 46/58] Upgrade vaadin to version 7.6.3 Signed-off-by: asharani-murugesh --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d481a56fb..8f61a0554 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 From a227ede0e020370b211d2cd67ae7ad38a6072aa6 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Fri, 4 Mar 2016 12:21:38 +0100 Subject: [PATCH 47/58] Completed merge --- .../src/main/resources/hawkbitdefaults.properties | 4 ++-- .../main/java/org/eclipse/hawkbit/amqp/AmqpProperties.java | 7 +++---- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties b/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties index 5e767726a..8f7ab288a 100644 --- a/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties +++ b/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties @@ -38,6 +38,6 @@ hawkbit.controller.pollingTime=00:05:00 hawkbit.controller.pollingOverdueTime=00:05:00 ## Configuration for RabbitMQ integration -hawkbit.dmf.rabbitmq.deadLetterQueue=dmf_connector_deadletter -hawkbit.dmf.rabbitmq.deadLetterExchange=dmf.connector.deadletter +hawkbit.dmf.rabbitmq.deadLetterQueue=dmf_receiver_deadletter +hawkbit.dmf.rabbitmq.deadLetterExchange=dmf.receiver.deadletter hawkbit.dmf.rabbitmq.receiverQueue=dmf_receiver 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 5a9c18f05..4b33a59b8 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 @@ -23,12 +23,12 @@ public class AmqpProperties { /** * DMF API dead letter queue. */ - private String deadLetterQueue = "dmf_connector_deadletter"; + private String deadLetterQueue = "dmf_receiver_deadletter"; /** * DMF API dead letter exchange. */ - private String deadLetterExchange = "dmf.connector.deadletter"; + private String deadLetterExchange = "dmf.receiver.deadletter"; /** * DMF API receiving queue. @@ -36,8 +36,7 @@ public class AmqpProperties { private String receiverQueue = "dmf_receiver"; /** - * Missing queue fatal, see - * {@link SimpleMessageListenerContainer#setMissingQueuesFatal(boolean)}. + * Missing queue fatal. */ private boolean missingQueuesFatal = false; From 54b29ea446ac5c6bb503eabe61e2b622745126d2 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Fri, 4 Mar 2016 21:38:57 +0100 Subject: [PATCH 48/58] Remove broken css compressor --- hawkbit-ui/pom.xml | 22 +--------------------- 1 file changed, 1 insertion(+), 21 deletions(-) diff --git a/hawkbit-ui/pom.xml b/hawkbit-ui/pom.xml index c9bd54b01..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 From fb9454d840631cebc2bd7e52387250a382ab5d8a Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Sat, 5 Mar 2016 11:21:25 +0100 Subject: [PATCH 49/58] update vaadin-bom to 7.6.3 version because 7.5 version is not working with updated vaadin 7.6 in hawkbit Signed-off-by: Michael Hirsch --- examples/hawkbit-device-simulator/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/hawkbit-device-simulator/pom.xml b/examples/hawkbit-device-simulator/pom.xml index 94749789c..a2575e9db 100644 --- a/examples/hawkbit-device-simulator/pom.xml +++ b/examples/hawkbit-device-simulator/pom.xml @@ -126,7 +126,7 @@ com.vaadin vaadin-bom - 7.5.5 + 7.6.3 pom import From ff156234fa6452c2bc5a4a27616e7f9d404cbb70 Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Sat, 5 Mar 2016 14:11:37 +0100 Subject: [PATCH 50/58] Annotation component must be removed because bean will otherwise registered twice because of EnableAutoConfiguration in the AmqpConfiguration Signed-off-by: Michael Hirsch --- .../src/main/java/org/eclipse/hawkbit/amqp/AmqpProperties.java | 2 -- 1 file changed, 2 deletions(-) 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 4b33a59b8..985424d7d 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 @@ -10,14 +10,12 @@ package org.eclipse.hawkbit.amqp; import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; 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.dmf.rabbitmq") public class AmqpProperties { /** From da9124cecdcff22e6a00423767f1163239c15d54 Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Sat, 5 Mar 2016 17:43:39 +0100 Subject: [PATCH 51/58] use correct method to send the message to rabbitMQ, exchange was not used from parameter Signed-off-by: Michael Hirsch --- .../java/org/eclipse/hawkbit/amqp/DefaultAmqpSenderService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 index 3dad77f43..9586633bf 100644 --- 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 @@ -34,7 +34,7 @@ public class DefaultAmqpSenderService implements AmqpSenderService { @Override public void sendMessage(final Message message, final URI uri) { - internalAmqpTemplate.send(extractExchange(uri), message); + internalAmqpTemplate.send(extractExchange(uri), null, message); } } From 52be35c7ff8d9cf1cb5bc8e22f7c29f56de8f85c Mon Sep 17 00:00:00 2001 From: SirWayne Date: Mon, 7 Mar 2016 10:02:00 +0100 Subject: [PATCH 52/58] Rename deadletter queue and exchange Signed-off-by: SirWayne --- .../src/main/resources/hawkbitdefaults.properties | 4 ++-- .../main/java/org/eclipse/hawkbit/amqp/AmqpProperties.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties b/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties index 8f7ab288a..5e767726a 100644 --- a/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties +++ b/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties @@ -38,6 +38,6 @@ hawkbit.controller.pollingTime=00:05:00 hawkbit.controller.pollingOverdueTime=00:05:00 ## Configuration for RabbitMQ integration -hawkbit.dmf.rabbitmq.deadLetterQueue=dmf_receiver_deadletter -hawkbit.dmf.rabbitmq.deadLetterExchange=dmf.receiver.deadletter +hawkbit.dmf.rabbitmq.deadLetterQueue=dmf_connector_deadletter +hawkbit.dmf.rabbitmq.deadLetterExchange=dmf.connector.deadletter hawkbit.dmf.rabbitmq.receiverQueue=dmf_receiver 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 985424d7d..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 @@ -21,12 +21,12 @@ public class AmqpProperties { /** * DMF API dead letter queue. */ - private String deadLetterQueue = "dmf_receiver_deadletter"; + private String deadLetterQueue = "dmf_connector_deadletter"; /** * DMF API dead letter exchange. */ - private String deadLetterExchange = "dmf.receiver.deadletter"; + private String deadLetterExchange = "dmf.connector.deadletter"; /** * DMF API receiving queue. From 7fec5c8407683f240aeb758d4dcc560e84732a6f Mon Sep 17 00:00:00 2001 From: Jonathan Philip Knoblauch Date: Mon, 7 Mar 2016 10:07:06 +0100 Subject: [PATCH 53/58] Changed name saveDistributionButton to saveDistributionBtn and discardDistributionButton to discardDistributionBtn for consistency Signed-off-by: Jonathan Philip Knoblauch --- .../DistributionAddUpdateWindowLayout.java | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) 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 21914778e..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 saveDistributionButton; - private Button discardDistributionButton; + private Button saveDistributionBtn; + private Button discardDistributionBtn; private TextField distNameTextField; private TextField distVersionTextField; private Label madatoryLabel; @@ -131,9 +131,9 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { final HorizontalLayout buttonsLayout = new HorizontalLayout(); buttonsLayout.setSizeFull(); buttonsLayout.setStyleName("dist-buttons-horz-layout"); - buttonsLayout.addComponents(saveDistributionButton, discardDistributionButton); - buttonsLayout.setComponentAlignment(saveDistributionButton, Alignment.BOTTOM_LEFT); - buttonsLayout.setComponentAlignment(discardDistributionButton, 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 */ - saveDistributionButton = SPUIComponentProvider.getButton(SPUIComponetIdProvider.DIST_ADD_SAVE, "", "", "", true, + saveDistributionBtn = SPUIComponentProvider.getButton(SPUIComponetIdProvider.DIST_ADD_SAVE, "", "", "", true, FontAwesome.SAVE, SPUIButtonStyleSmallNoBorder.class); - saveDistributionButton.addClickListener(event -> saveDistribution()); + saveDistributionBtn.addClickListener(event -> saveDistribution()); /* close button */ - discardDistributionButton = SPUIComponentProvider.getButton(SPUIComponetIdProvider.DIST_ADD_DISCARD, "", "", "", + discardDistributionBtn = SPUIComponentProvider.getButton(SPUIComponetIdProvider.DIST_ADD_DISCARD, "", "", "", true, FontAwesome.TIMES, SPUIButtonStyleSmallNoBorder.class); - discardDistributionButton.addClickListener(event -> discardDistribution()); + discardDistributionBtn.addClickListener(event -> discardDistribution()); } /** @@ -216,7 +216,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { } private void enableSaveButton() { - saveDistributionButton.setEnabled(true); + saveDistributionBtn.setEnabled(true); } private DistributionSetType getDefaultDistributionSetType() { @@ -226,7 +226,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { } private void disableSaveButton() { - saveDistributionButton.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(); - saveDistributionButton.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; - saveDistributionButton.setEnabled(false); + saveDistributionBtn.setEnabled(false); final DistributionSet distSet = distributionSetManagement.findDistributionSetByIdWithDetails(editDistId); if (distSet != null) { distNameTextField.setValue(distSet.getName()); From f4791743ce51d6684c9326e39f57310d217848db Mon Sep 17 00:00:00 2001 From: SirWayne Date: Mon, 7 Mar 2016 12:18:18 +0100 Subject: [PATCH 54/58] Add test case description Signed-off-by: SirWayne --- .../eclipse/hawkbit/amqp/BaseAmqpService.java | 1 + .../repository/DeploymentManagementTest.java | 14 +- .../hawkbit/repository/TagManagementTest.java | 124 ++++++++++-------- .../rsql/RSQLDistributionSetFieldTest.java | 2 +- .../resource/SoftwareModuleResourceTest.java | 2 +- .../hawkbit/ui/components/ProxyTarget.java | 22 +--- 6 files changed, 79 insertions(+), 86 deletions(-) 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 index f418937e3..897f1ae62 100644 --- 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 @@ -99,6 +99,7 @@ public class BaseAmqpService { final Object value = header.get(key); if (value == null) { logAndThrowMessageError(message, errorMessageIfNull); + return null; } return value.toString(); } 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 6427ca8a2..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; /** @@ -781,12 +780,13 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { targ = targetManagement.findTargetByControllerID(targ.getControllerId()); - assertEquals(0, deploymentManagement.findActiveActionsByTarget(targ).size()); - assertEquals(1, deploymentManagement.findInActiveActionsByTarget(targ).size()); + assertEquals("active target actions are wrong", 0, deploymentManagement.findActiveActionsByTarget(targ).size()); + assertEquals("active actions are wrong", 1, deploymentManagement.findInActiveActionsByTarget(targ).size()); - assertEquals(TargetUpdateStatus.IN_SYNC, targ.getTargetInfo().getUpdateStatus()); - assertEquals(dsA, targ.getAssignedDistributionSet()); - assertEquals(dsA, targ.getTargetInfo().getInstalledDistributionSet()); + 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(); @@ -796,7 +796,7 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { 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("wrong assigned ds", dsB, targ.getAssignedDistributionSet()); assertEquals("Installed ds is wrong", dsA.getId(), targetManagement.findTargetByControllerIDWithDetails(targ.getControllerId()).getTargetInfo() .getInstalledDistributionSet().getId()); 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 b8a4db598..b1c2cf3e3 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; @@ -42,6 +44,11 @@ public class TagManagementTest extends AbstractIntegrationTest { 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() { @@ -88,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()) @@ -96,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()) @@ -104,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()) @@ -112,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()) @@ -135,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()) @@ -154,30 +161,27 @@ public class TagManagementTest extends AbstractIntegrationTest { @Test @Description("Ensures that all tags are retrieved through repository.") public void findAllTargetTags() { - assertThat(targetTagRepository.findAll()).isEmpty(); - final List tags = createTargetsWithTags(); assertThat(targetTagRepository.findAll()).isEqualTo(tagManagement.findAllTargetTags()).isEqualTo(tags) - .hasSize(20); + .as("Wrong tag size").hasSize(20); } @Test @Description("Ensures that a created tag is persisted in the repository as defined.") public void createTargetTag() { - assertThat(targetTagRepository.findAll()).isEmpty(); - 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 founded") + .isEqualTo("kai2"); + assertThat(tagManagement.findTargetTag("kai1").getColour()).as("wrong tag founded").isEqualTo("colour"); + assertThat(tagManagement.findTargetTagById(tag.getId()).getColour()).as("wrong tag founded") + .isEqualTo("colour"); } @Test @Description("Ensures that a deleted tag is removed from the repository as defined.") public void deleteTargetTas() { - assertThat(targetTagRepository.findAll()).isEmpty(); // create test data final Iterable tags = createTargetsWithTags(); @@ -196,16 +200,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 founded").isNull(); + assertThat(tagManagement.findAllTargetTags()).as("Wrong target tag size").hasSize(19); } @Test @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 @@ -216,95 +217,105 @@ 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 @Description("Ensures that a created tag is persisted in the repository as defined.") public void createDistributionSetTag() { - assertThat(distributionSetTagRepository.findAll()).isEmpty(); - 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 founded") + .isEqualTo("kai2"); + assertThat(tagManagement.findDistributionSetTag("kai1").getColour()).as("wrong tag founded") + .isEqualTo("colour"); + assertThat(tagManagement.findDistributionSetTagById(tag.getId()).getColour()).as("wrong tag founded") + .isEqualTo("colour"); } @Test @Description("Ensures that a created tags are persisted in the repository as defined.") public void createDistributionSetTags() { - assertThat(distributionSetTagRepository.findAll()).isEmpty(); - final List tags = createDsSetsWithTags(); - assertThat(distributionSetTagRepository.findAll()).hasSize(tags.size()); + assertThat(distributionSetTagRepository.findAll()).as("Wrong size of tags created").hasSize(tags.size()); } @Test @Description("Ensures that a deleted tag is removed from the repository as defined.") public void deleteDistributionSetTag() { - assertThat(distributionSetTagRepository.findAll()).isEmpty(); - // 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 founded").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 founded tags").doesNotContain(toDelete); } } - @Test(expected = EntityAlreadyExistsException.class) @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")); - tagManagement.createTargetTag(new TargetTag("A")); + try { + tagManagement.createTargetTag(new TargetTag("A")); + fail("Excpeted EntityAlreadyExistsException"); + } catch (final EntityAlreadyExistsException e) { + } } - @Test(expected = EntityAlreadyExistsException.class) @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"); - tagManagement.updateTargetTag(tag); + try { + tagManagement.updateTargetTag(tag); + fail("Excpeted EntityAlreadyExistsException"); + } catch (final EntityAlreadyExistsException e) { + } } - @Test(expected = EntityAlreadyExistsException.class) @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")); - tagManagement.createDistributionSetTag(new DistributionSetTag("A")); + try { + tagManagement.createDistributionSetTag(new DistributionSetTag("A")); + fail("Excpeted EntityAlreadyExistsException"); + } catch (final EntityAlreadyExistsException e) { + } } - @Test(expected = EntityAlreadyExistsException.class) @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"); - tagManagement.updateDistributionSetTag(tag); + try { + tagManagement.updateDistributionSetTag(tag); + fail("Excpeted EntityAlreadyExistsException"); + } catch (final EntityAlreadyExistsException e) { + } } @Test @Description("Tests the name update of a target tag.") public void updateDistributionSetTag() { - assertThat(distributionSetTagRepository.findAll()).isEmpty(); // create test data final List tags = createDsSetsWithTags(); @@ -317,20 +328,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 founded") + .isEqualTo("test123"); } @Test @Description("Ensures that all tags are retrieved through repository.") public void findDistributionSetTagsAll() { - assertThat(distributionSetTagRepository.findAll()).isEmpty(); - 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/rsql/RSQLDistributionSetFieldTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetFieldTest.java index 40d757d15..add5419ee 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 @@ -98,7 +98,7 @@ public class RSQLDistributionSetFieldTest extends AbstractIntegrationTest { assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "==true", 4); try { assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "==noExist*", 0); - fail(); + fail("Excepted RSQLParameterSyntaxException"); } catch (final RSQLParameterSyntaxException e) { } assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "=in=(true)", 4); 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 cf93fcba7..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 @@ -311,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(), 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 */ From cf48ef215a0f81a8744e63c22531691f8fefcbe8 Mon Sep 17 00:00:00 2001 From: Jonathan Philip Knoblauch Date: Mon, 7 Mar 2016 13:14:40 +0100 Subject: [PATCH 55/58] Changed names for editRollout boolean and discardRolllout Button Signed-off-by: Jonathan Philip Knoblauch --- .../ui/rollout/AddUpdateRolloutWindowLayout.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) 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 3a1deaf65..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 @@ -130,7 +130,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { 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 editRolloutBtn; + private Boolean editRolloutEnabled; private Rollout rolloutForEdit; @@ -167,7 +167,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { * Reset the field values. */ public void resetComponents() { - editRolloutBtn = Boolean.FALSE; + editRolloutEnabled = Boolean.FALSE; rolloutName.clear(); targetFilterQuery.clear(); resetFields(); @@ -254,9 +254,9 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { private HorizontalLayout getSaveDiscardButtonLayout() { final HorizontalLayout buttonsLayout = new HorizontalLayout(); buttonsLayout.setSizeFull(); - buttonsLayout.addComponents(saveRolloutBtn, discardRolllout); + buttonsLayout.addComponents(saveRolloutBtn, discardRollloutBtn); buttonsLayout.setComponentAlignment(saveRolloutBtn, Alignment.BOTTOM_LEFT); - buttonsLayout.setComponentAlignment(discardRolllout, Alignment.BOTTOM_RIGHT); + buttonsLayout.setComponentAlignment(discardRollloutBtn, Alignment.BOTTOM_RIGHT); buttonsLayout.addStyleName("window-style"); return buttonsLayout; } @@ -278,7 +278,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { errorThresholdOptionGroup = createErrorThresholdOptionGroup(); setDefaultSaveStartGroupOption(); saveRolloutBtn = createSaveButton(); - discardRolllout = createDiscardButton(); + discardRollloutBtn = createDiscardButton(); actionTypeOptionGroupLayout.selectDefaultOption(); totalTargetsLabel = createTotalTargetsLabel(); @@ -411,7 +411,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { } private void onRolloutSave() { - if (editRolloutBtn) { + if (editRolloutEnabled) { editRollout(); } else { createRollout(); @@ -742,7 +742,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { */ public void populateData(final Long rolloutId) { resetComponents(); - editRolloutBtn = Boolean.TRUE; + editRolloutEnabled = Boolean.TRUE; rolloutForEdit = rolloutManagement.findRolloutById(rolloutId); rolloutName.setValue(rolloutForEdit.getName()); description.setValue(rolloutForEdit.getDescription()); From 43d01da309f2d81b62fc29a46cb7ccfa00e3317d Mon Sep 17 00:00:00 2001 From: SirWayne Date: Mon, 7 Mar 2016 13:35:26 +0100 Subject: [PATCH 56/58] Fix typo after pull request review Signed-off-by: SirWayne --- .../hawkbit/repository/TagManagementTest.java | 31 +++++++++---------- .../rsql/RSQLDistributionSetFieldTest.java | 2 +- 2 files changed, 15 insertions(+), 18 deletions(-) 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 b1c2cf3e3..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 @@ -172,11 +172,9 @@ public class TagManagementTest extends AbstractIntegrationTest { public void createTargetTag() { final Tag tag = tagManagement.createTargetTag(new TargetTag("kai1", "kai2", "colour")); - assertThat(targetTagRepository.findByNameEquals("kai1").getDescription()).as("wrong tag founded") - .isEqualTo("kai2"); - assertThat(tagManagement.findTargetTag("kai1").getColour()).as("wrong tag founded").isEqualTo("colour"); - assertThat(tagManagement.findTargetTagById(tag.getId()).getColour()).as("wrong tag founded") - .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 @@ -200,7 +198,7 @@ public class TagManagementTest extends AbstractIntegrationTest { assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).getTags()) .doesNotContain(toDelete); } - assertThat(targetTagRepository.findOne(toDelete.getId())).as("No tag should be founded").isNull(); + assertThat(targetTagRepository.findOne(toDelete.getId())).as("No tag should be found").isNull(); assertThat(tagManagement.findAllTargetTags()).as("Wrong target tag size").hasSize(19); } @@ -229,11 +227,10 @@ public class TagManagementTest extends AbstractIntegrationTest { public void createDistributionSetTag() { final Tag tag = tagManagement.createDistributionSetTag(new DistributionSetTag("kai1", "kai2", "colour")); - assertThat(distributionSetTagRepository.findByNameEquals("kai1").getDescription()).as("wrong tag founded") + assertThat(distributionSetTagRepository.findByNameEquals("kai1").getDescription()).as("wrong tag found") .isEqualTo("kai2"); - assertThat(tagManagement.findDistributionSetTag("kai1").getColour()).as("wrong tag founded") - .isEqualTo("colour"); - assertThat(tagManagement.findDistributionSetTagById(tag.getId()).getColour()).as("wrong tag founded") + assertThat(tagManagement.findDistributionSetTag("kai1").getColour()).as("wrong tag found").isEqualTo("colour"); + assertThat(tagManagement.findDistributionSetTagById(tag.getId()).getColour()).as("wrong tag found") .isEqualTo("colour"); } @@ -254,7 +251,7 @@ public class TagManagementTest extends AbstractIntegrationTest { for (final DistributionSet set : distributionSetRepository.findAll()) { assertThat(distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).getTags()) - .as("Wrong tag founded").contains(toDelete); + .as("Wrong tag found").contains(toDelete); } // delete @@ -265,7 +262,7 @@ public class TagManagementTest extends AbstractIntegrationTest { assertThat(tagManagement.findAllDistributionSetTags()).as("Wrong size of tags after deletion").hasSize(19); for (final DistributionSet set : distributionSetRepository.findAll()) { assertThat(distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).getTags()) - .as("Wrong founded tags").doesNotContain(toDelete); + .as("Wrong found tags").doesNotContain(toDelete); } } @@ -274,7 +271,7 @@ public class TagManagementTest extends AbstractIntegrationTest { tagManagement.createTargetTag(new TargetTag("A")); try { tagManagement.createTargetTag(new TargetTag("A")); - fail("Excpeted EntityAlreadyExistsException"); + fail("Expected EntityAlreadyExistsException"); } catch (final EntityAlreadyExistsException e) { } } @@ -286,7 +283,7 @@ public class TagManagementTest extends AbstractIntegrationTest { tag.setName("A"); try { tagManagement.updateTargetTag(tag); - fail("Excpeted EntityAlreadyExistsException"); + fail("Expected EntityAlreadyExistsException"); } catch (final EntityAlreadyExistsException e) { } } @@ -296,7 +293,7 @@ public class TagManagementTest extends AbstractIntegrationTest { tagManagement.createDistributionSetTag(new DistributionSetTag("A")); try { tagManagement.createDistributionSetTag(new DistributionSetTag("A")); - fail("Excpeted EntityAlreadyExistsException"); + fail("Expected EntityAlreadyExistsException"); } catch (final EntityAlreadyExistsException e) { } } @@ -308,7 +305,7 @@ public class TagManagementTest extends AbstractIntegrationTest { tag.setName("A"); try { tagManagement.updateDistributionSetTag(tag); - fail("Excpeted EntityAlreadyExistsException"); + fail("Expected EntityAlreadyExistsException"); } catch (final EntityAlreadyExistsException e) { } } @@ -329,7 +326,7 @@ public class TagManagementTest extends AbstractIntegrationTest { // check data assertThat(tagManagement.findAllDistributionSetTags()).as("Wrong size of ds tags").hasSize(tags.size()); - assertThat(distributionSetTagRepository.findOne(savedAssigned.getId()).getName()).as("Wrong ds tag founded") + assertThat(distributionSetTagRepository.findOne(savedAssigned.getId()).getName()).as("Wrong ds tag found") .isEqualTo("test123"); } 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 add5419ee..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 @@ -98,7 +98,7 @@ public class RSQLDistributionSetFieldTest extends AbstractIntegrationTest { assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "==true", 4); try { assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "==noExist*", 0); - fail("Excepted RSQLParameterSyntaxException"); + fail("Expected RSQLParameterSyntaxException"); } catch (final RSQLParameterSyntaxException e) { } assertRSQLQuery(DistributionSetFields.COMPLETE.name() + "=in=(true)", 4); From 6c74c1186dbd95bc57ac1661ffc3e863d81c1b9f Mon Sep 17 00:00:00 2001 From: SirWayne Date: Tue, 8 Mar 2016 12:23:31 +0100 Subject: [PATCH 57/58] Create unit test for the json amqp message conversion Signed-off-by: SirWayne --- .../eclipse/hawkbit/amqp/BaseAmqpService.java | 8 +- .../amqp/AmqpMessageHandlerServiceTest.java | 1 + .../hawkbit/amqp/BaseAmqpServiceTest.java | 103 ++++++++++++++++++ 3 files changed, 108 insertions(+), 4 deletions(-) create mode 100644 hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/BaseAmqpServiceTest.java 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 index 897f1ae62..8a054165b 100644 --- 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 @@ -58,8 +58,8 @@ public class BaseAmqpService { * @return the converted object */ @SuppressWarnings("unchecked") - protected T convertMessage(final Message message, final Class clazz) { - if (message == null) { + 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, @@ -78,8 +78,8 @@ public class BaseAmqpService { * @return the list of converted objects */ @SuppressWarnings("unchecked") - protected List convertMessageList(final Message message, final Class clazz) { - if (message == null) { + 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, 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 79a39a40a..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 @@ -116,6 +116,7 @@ public class AmqpMessageHandlerServiceTest { } + @Test @Description("Tests not allowed content-type in message") public void testWrongContentType() { final MessageProperties messageProperties = new MessageProperties(); 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(); + } + +} From dd7f7d2a9dc8224943502338d09cf6b6e1a52ca8 Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Tue, 8 Mar 2016 17:39:24 +0100 Subject: [PATCH 58/58] fix mgmt client startup with xml problem and not unique bean exception Signed-off-by: Michael Hirsch --- .../hawkbit/mgmt/client/ClientConfigurationProperties.java | 2 -- .../hawkbit-mgmt-api-client/src/main/resources/logback.xml | 3 --- 2 files changed, 5 deletions(-) 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 ead019247..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 @@ -9,14 +9,12 @@ package org.eclipse.hawkbit.mgmt.client; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; /** * Configuration bean which holds the configuration of the client e.g. the base * URL of the hawkbit-server and the credentials to use the RESTful Management * API. */ -@Component @ConfigurationProperties(prefix = "hawkbit") public class ClientConfigurationProperties { 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 @@ -