From a3295b518d5b60c158359c88370c9af3ae66e1c5 Mon Sep 17 00:00:00 2001 From: Jonathan Philip Knoblauch Date: Tue, 22 Mar 2016 17:01:24 +0100 Subject: [PATCH 01/31] Added tenant configuration for anyonmous download and UI element to allow to configure anonymous download Signed-off-by: Jonathan Philip Knoblauch --- .../configuration/TenantConfigurationKey.java | 7 +- .../DownloadAnonymousConfigurationView.java | 121 ++++++++++++++++++ .../TenantConfigurationDashboardView.java | 4 + .../src/main/resources/messages.properties | 2 + .../src/main/resources/messages_de.properties | 2 + .../src/main/resources/messages_en.properties | 2 + 6 files changed, 137 insertions(+), 1 deletion(-) create mode 100644 hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java 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 c83f24dc2..32a7a8376 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 @@ -63,7 +63,12 @@ public enum TenantConfigurationKey { /** * string value which holds the polling time interval in the format HH:mm:ss */ - POLLING_OVERDUE_TIME_INTERVAL("pollingTime", "hawkbit.controller.pollingTime", String.class, null, TenantConfigurationPollingDurationValidator.class); + POLLING_OVERDUE_TIME_INTERVAL("pollingTime", "hawkbit.controller.pollingTime", String.class, null, TenantConfigurationPollingDurationValidator.class), + + /** + * boolean value {@code true} {@code false}. + */ + ANONYMOUS_DOWNLOAD_MODE_ENABLED("anonymous.download.enabled", "hawkbit.server.download.anonymous.enabled", Boolean.class, Boolean.FALSE.toString(), TenantConfigurationBooleanValidator.class); private final String keyName; private final String defaultKeyName; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java new file mode 100644 index 000000000..7366a251f --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java @@ -0,0 +1,121 @@ +/** + * 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.tenantconfiguration; + +import javax.annotation.PostConstruct; + +import org.eclipse.hawkbit.repository.TenantConfigurationManagement; +import org.eclipse.hawkbit.repository.model.TenantConfigurationValue; +import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; +import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; +import org.eclipse.hawkbit.ui.utils.I18N; +import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; +import org.springframework.beans.factory.annotation.Autowired; + +import com.vaadin.spring.annotation.SpringComponent; +import com.vaadin.spring.annotation.ViewScope; +import com.vaadin.ui.Alignment; +import com.vaadin.ui.CheckBox; +import com.vaadin.ui.GridLayout; +import com.vaadin.ui.Label; +import com.vaadin.ui.Panel; +import com.vaadin.ui.VerticalLayout; + +/** + * @author Jonathan Knoblauch + * + */ + +@SpringComponent +@ViewScope +public class DownloadAnonymousConfigurationView extends BaseConfigurationView + implements ConfigurationItem.ConfigurationItemChangeListener { + + private static final String DIST_CHECKBOX_STYLE = "dist-checkbox-style"; + + private static final long serialVersionUID = 1L; + + @Autowired + private I18N i18n; // TODO + + @Autowired + private transient TenantConfigurationManagement tenantConfigurationManagement; + + boolean anonymousDownloadEnabled; + + private CheckBox downloadAnonymousCheckBox; + + /** + * Initialize Default Distribution Set layout. + */ + @PostConstruct + public void init() { + + final TenantConfigurationValue value = tenantConfigurationManagement + .getConfigurationValue(TenantConfigurationKey.ANONYMOUS_DOWNLOAD_MODE_ENABLED, Boolean.class); + anonymousDownloadEnabled = value.getValue(); + + final Panel rootPanel = new Panel(); + rootPanel.setSizeFull(); + rootPanel.addStyleName("config-panel"); + + final VerticalLayout vLayout = new VerticalLayout(); + vLayout.setMargin(true); + vLayout.setSizeFull(); + + final Label headerDisSetType = new Label(i18n.get("enonymous.download.title")); + headerDisSetType.addStyleName("config-panel-header"); + vLayout.addComponent(headerDisSetType); + + final GridLayout gridLayout = new GridLayout(2, 1); + gridLayout.setSpacing(true); + gridLayout.setImmediate(true); + gridLayout.setColumnExpandRatio(1, 1.0F); + gridLayout.setSizeFull(); + + downloadAnonymousCheckBox = SPUIComponentProvider.getCheckBox("", DIST_CHECKBOX_STYLE, null, false, ""); + downloadAnonymousCheckBox.setValue(anonymousDownloadEnabled); + downloadAnonymousCheckBox.setId("TODO"); + downloadAnonymousCheckBox.addValueChangeListener(event -> configurationHasChanged()); + gridLayout.addComponent(downloadAnonymousCheckBox); + + final Label configurationLabel = SPUIComponentProvider.getLabel(i18n.get("enonymous.download.label"), + SPUILabelDefinitions.SP_LABEL_SIMPLE); + gridLayout.addComponent(configurationLabel); + gridLayout.setComponentAlignment(configurationLabel, Alignment.MIDDLE_LEFT); + + vLayout.addComponent(gridLayout); + + rootPanel.setContent(vLayout); + setCompositionRoot(rootPanel); + + } + + @Override + public void configurationHasChanged() { + anonymousDownloadEnabled = downloadAnonymousCheckBox.getValue(); + notifyConfigurationChanged(); + } + + @Override + public void save() { + tenantConfigurationManagement.addOrUpdateConfiguration(TenantConfigurationKey.ANONYMOUS_DOWNLOAD_MODE_ENABLED, + downloadAnonymousCheckBox.getValue()); + // TODO notification Download server + } + + @Override + public void undo() { + anonymousDownloadEnabled = tenantConfigurationManagement + .getGlobalConfigurationValue(TenantConfigurationKey.ANONYMOUS_DOWNLOAD_MODE_ENABLED, Boolean.class); + downloadAnonymousCheckBox.setValue(anonymousDownloadEnabled); + + } + +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/TenantConfigurationDashboardView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/TenantConfigurationDashboardView.java index 8a22064ab..0349ba867 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/TenantConfigurationDashboardView.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/TenantConfigurationDashboardView.java @@ -58,6 +58,9 @@ public class TenantConfigurationDashboardView extends CustomComponent implements @Autowired private PollingConfigurationView pollingConfigurationView; + @Autowired + private DownloadAnonymousConfigurationView downloadAnonymousConfigurationView; + @Autowired private I18N i18n; @@ -80,6 +83,7 @@ public class TenantConfigurationDashboardView extends CustomComponent implements configurationViews.add(defaultDistributionSetTypeLayout); configurationViews.add(authenticationConfigurationView); configurationViews.add(pollingConfigurationView); + configurationViews.add(downloadAnonymousConfigurationView); } @Override diff --git a/hawkbit-ui/src/main/resources/messages.properties b/hawkbit-ui/src/main/resources/messages.properties index 27103a0b9..ebdcfa76f 100644 --- a/hawkbit-ui/src/main/resources/messages.properties +++ b/hawkbit-ui/src/main/resources/messages.properties @@ -401,6 +401,8 @@ configuration.polling.title=Polling Configuration configuration.polling.time=Polling Time configuration.polling.overduetime=Polling Overdue Time configuration.polling.custom.value=use a custom value +enonymous.download.title=Anonymous download +enonymous.download.label=Allow anonymous download. If you enable this option the download server will accept anonymous download requests. #Calendar calendar.year=year diff --git a/hawkbit-ui/src/main/resources/messages_de.properties b/hawkbit-ui/src/main/resources/messages_de.properties index 9ff2e5e75..47cb36f31 100644 --- a/hawkbit-ui/src/main/resources/messages_de.properties +++ b/hawkbit-ui/src/main/resources/messages_de.properties @@ -389,6 +389,8 @@ configuration.defaultdistributionset.select.label=Wahl des default Distribution configuration.savebutton.tooltip=Konfigurationen speichern configuration.cancellbutton.tooltip=Konfigurationen zur�cksetzen configuration.authentication.title=Authentifikationseinstellungen +enonymous.download.title=Anonymes herunterladen +enonymous.download.label=Erlaube anonymes herunterladen. When diese option aktivert ist, wird der download server anonyme download anfragen erlauben. #Calendar calendar.year=Jahr calendar.years=Jahre diff --git a/hawkbit-ui/src/main/resources/messages_en.properties b/hawkbit-ui/src/main/resources/messages_en.properties index 74f50f378..50c04ad46 100644 --- a/hawkbit-ui/src/main/resources/messages_en.properties +++ b/hawkbit-ui/src/main/resources/messages_en.properties @@ -383,6 +383,8 @@ configuration.authentication.title=Authentication Configuration controller.polling.title=Polling Configuration controller.polling.time=Polling Time controller.polling.overduetime=Polling Overdue Time +enonymous.download.title=Anonymous download +enonymous.download.label=Allow anonymous download. If you enable this option the download server will accept anonymous download requests. #Calendar calendar.year=year From cdac7185c47dc9c8b9288d669a89d57950cf0548 Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Wed, 23 Mar 2016 10:23:35 +0100 Subject: [PATCH 02/31] fix typo of class TenantSecurityToken and handle authentication message based on FileResource not only on SHA1 hash Signed-off-by: Michael Hirsch --- .../amqp/AmqpControllerAuthentfication.java | 6 +- .../amqp/AmqpMessageHandlerService.java | 52 ++++-- .../AmqpControllerAuthenticationTest.java | 29 +-- .../amqp/AmqpMessageHandlerServiceTest.java | 9 +- .../dmf/json/model/TenantSecruityToken.java | 94 ---------- .../dmf/json/model/TenantSecurityToken.java | 176 ++++++++++++++++++ ...actHttpControllerAuthenticationFilter.java | 15 +- .../repository/ArtifactManagement.java | 3 +- ...bstractControllerAuthenticationFilter.java | 8 +- .../CoapAnonymousPreAuthenticatedFilter.java | 16 +- ...lerPreAuthenticateSecurityTokenFilter.java | 8 +- ...thenticatedGatewaySecurityTokenFilter.java | 8 +- ...rPreAuthenticatedSecurityHeaderFilter.java | 10 +- .../security/PreAuthenficationFilter.java | 8 +- 14 files changed, 279 insertions(+), 163 deletions(-) delete mode 100644 hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecruityToken.java create mode 100644 hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecurityToken.java 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 8f19d9f02..3fa7979b9 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 @@ -13,7 +13,7 @@ import java.util.List; import javax.annotation.PostConstruct; -import org.eclipse.hawkbit.dmf.json.model.TenantSecruityToken; +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails; import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; @@ -100,7 +100,7 @@ public class AmqpControllerAuthentfication { * the authentication request object * @return the authentfication object */ - public Authentication doAuthenticate(final TenantSecruityToken secruityToken) { + public Authentication doAuthenticate(final TenantSecurityToken secruityToken) { PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(null, null); for (final PreAuthenficationFilter filter : filterChain) { final PreAuthenticatedAuthenticationToken authenticationRest = createAuthentication(filter, secruityToken); @@ -115,7 +115,7 @@ public class AmqpControllerAuthentfication { } private static PreAuthenticatedAuthenticationToken createAuthentication(final PreAuthenficationFilter filter, - final TenantSecruityToken secruityToken) { + final TenantSecurityToken secruityToken) { if (!filter.isEnable(secruityToken)) { return null; 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 cfd5485a6..71b8f8db8 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 @@ -27,8 +27,9 @@ import org.eclipse.hawkbit.dmf.amqp.api.MessageType; import org.eclipse.hawkbit.dmf.json.model.ActionUpdateStatus; import org.eclipse.hawkbit.dmf.json.model.Artifact; import org.eclipse.hawkbit.dmf.json.model.ArtifactHash; +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken.FileResource; import org.eclipse.hawkbit.dmf.json.model.DownloadResponse; -import org.eclipse.hawkbit.dmf.json.model.TenantSecruityToken; import org.eclipse.hawkbit.eventbus.event.TargetAssignDistributionSetEvent; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails; @@ -157,25 +158,29 @@ public class AmqpMessageHandlerService extends BaseAmqpService { private Message handleAuthentifiactionMessage(final Message message) { final DownloadResponse authentificationResponse = new DownloadResponse(); final MessageProperties messageProperties = message.getMessageProperties(); - final TenantSecruityToken secruityToken = convertMessage(message, TenantSecruityToken.class); - final String sha1 = secruityToken.getSha1(); + final TenantSecurityToken secruityToken = convertMessage(message, + TenantSecurityToken.class); + final FileResource fileResource = secruityToken.getFileResource(); try { SecurityContextHolder.getContext().setAuthentication(authenticationManager.doAuthenticate(secruityToken)); - final LocalArtifact localArtifact = artifactManagement - .findFirstLocalArtifactsBySHA1(secruityToken.getSha1()); + + final LocalArtifact localArtifact = findLocalArtifactByFileResource(fileResource); + if (localArtifact == null) { throw new EntityNotFoundException(); } // check action for this download purposes, the method will throw an // EntityNotFoundException in case the controller is not allowed to - // download this file - // because it's not assigned to an action and not assigned to this - // controller. - final Action action = controllerManagement.getActionForDownloadByTargetAndSoftwareModule( - secruityToken.getControllerId(), localArtifact.getSoftwareModule()); - LOG.info("Found action for download authentication request action: {}, sha1: {}", action, - secruityToken.getSha1()); + // download this file because it's not assigned to an action and not + // assigned to this controller. Otherwise no controllerId is set = + // anonymous download + if (secruityToken.getControllerId() != null) { + final Action action = controllerManagement.getActionForDownloadByTargetAndSoftwareModule( + secruityToken.getControllerId(), localArtifact.getSoftwareModule()); + LOG.info("Found action for download authentication request action: {}, resource: {}", action, + secruityToken.getFileResource()); + } final Artifact artifact = convertDbArtifact(artifactManagement.loadLocalArtifactBinary(localArtifact)); if (artifact == null) { @@ -183,7 +188,9 @@ public class AmqpMessageHandlerService extends BaseAmqpService { } authentificationResponse.setArtifact(artifact); final String downloadId = UUID.randomUUID().toString(); - final DownloadArtifactCache downloadCache = new DownloadArtifactCache(DownloadType.BY_SHA1, sha1); + // SHA1 key is set, download by SHA1 + final DownloadArtifactCache downloadCache = new DownloadArtifactCache(DownloadType.BY_SHA1, + localArtifact.getSha1Hash()); cache.put(downloadId, downloadCache); authentificationResponse .setDownloadUrl(UriComponentsBuilder.fromUri(hostnameResolver.resolveHostname().toURI()) @@ -198,7 +205,7 @@ public class AmqpMessageHandlerService extends BaseAmqpService { authentificationResponse.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value()); authentificationResponse.setMessage("Building download URI failed"); } catch (final EntityNotFoundException e) { - final String errorMessage = "Artifact with sha1 " + sha1 + "not found "; + final String errorMessage = "Artifact for resource " + fileResource + "not found "; LOG.warn(errorMessage, e); authentificationResponse.setResponseCode(HttpStatus.NOT_FOUND.value()); authentificationResponse.setMessage(errorMessage); @@ -207,6 +214,23 @@ public class AmqpMessageHandlerService extends BaseAmqpService { return getMessageConverter().toMessage(authentificationResponse, messageProperties); } + private LocalArtifact findLocalArtifactByFileResource(final FileResource fileResource) { + LocalArtifact localArtifact = null; + if (fileResource.getSha1() != null) { + localArtifact = artifactManagement.findFirstLocalArtifactsBySHA1(fileResource.getSha1()); + } else if (fileResource.getFilename() != null) { + localArtifact = artifactManagement.findLocalArtifactByFilename(fileResource.getFilename()).stream() + .findFirst().orElse(null); + } else if (fileResource.getArtifactId() != null) { + final org.eclipse.hawkbit.repository.model.Artifact artifact = artifactManagement + .findArtifact(fileResource.getArtifactId()); + if (artifact instanceof LocalArtifact) { + localArtifact = (LocalArtifact) artifact; + } + } + return localArtifact; + } + private static Artifact convertDbArtifact(final DbArtifact dbArtifact) { final Artifact artifact = new Artifact(); artifact.setSize(dbArtifact.getSize()); diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java index 66527727a..d7ab805ed 100644 --- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java +++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java @@ -19,7 +19,8 @@ import static org.mockito.Mockito.when; import org.eclipse.hawkbit.dmf.amqp.api.MessageHeaderKey; import org.eclipse.hawkbit.dmf.amqp.api.MessageType; import org.eclipse.hawkbit.dmf.json.model.DownloadResponse; -import org.eclipse.hawkbit.dmf.json.model.TenantSecruityToken; +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken.FileResource; import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; @@ -105,7 +106,8 @@ public class AmqpControllerAuthenticationTest { @Test @Description("Tests authentication manager without principal") public void testAuthenticationeBadCredantialsWithoutPricipal() { - final TenantSecruityToken securityToken = new TenantSecruityToken(TENANT, CONTROLLLER_ID, "12345"); + final TenantSecurityToken securityToken = new TenantSecurityToken(TENANT, CONTROLLLER_ID, + FileResource.sha1("12345")); try { authenticationManager.doAuthenticate(securityToken); fail("BadCredentialsException was excepeted since principal was missing"); @@ -118,11 +120,12 @@ public class AmqpControllerAuthenticationTest { @Test @Description("Tests authentication manager without wrong credential") public void testAuthenticationBadCredantialsWithWrongCredential() { - final TenantSecruityToken securityToken = new TenantSecruityToken(TENANT, CONTROLLLER_ID, "12345"); + final TenantSecurityToken securityToken = new TenantSecurityToken(TENANT, CONTROLLLER_ID, + FileResource.sha1("12345")); when(tenantConfigurationManagement.getConfigurationValue( eq(TenantConfigurationKey.AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED), eq(Boolean.class))) .thenReturn(CONFIG_VALUE_TRUE); - securityToken.getHeaders().put(TenantSecruityToken.AUTHORIZATION_HEADER, "TargetToken 12" + CONTROLLLER_ID); + securityToken.getHeaders().put(TenantSecurityToken.AUTHORIZATION_HEADER, "TargetToken 12" + CONTROLLLER_ID); try { authenticationManager.doAuthenticate(securityToken); fail("BadCredentialsException was excepeted due to wrong credential"); @@ -135,11 +138,12 @@ public class AmqpControllerAuthenticationTest { @Test @Description("Tests authentication successfull") public void testSuccessfullAuthentication() { - final TenantSecruityToken securityToken = new TenantSecruityToken(TENANT, CONTROLLLER_ID, "12345"); + final TenantSecurityToken securityToken = new TenantSecurityToken(TENANT, CONTROLLLER_ID, + FileResource.sha1("12345")); when(tenantConfigurationManagement.getConfigurationValue( eq(TenantConfigurationKey.AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED), eq(Boolean.class))) .thenReturn(CONFIG_VALUE_TRUE); - securityToken.getHeaders().put(TenantSecruityToken.AUTHORIZATION_HEADER, "TargetToken " + CONTROLLLER_ID); + securityToken.getHeaders().put(TenantSecurityToken.AUTHORIZATION_HEADER, "TargetToken " + CONTROLLLER_ID); final Authentication authentication = authenticationManager.doAuthenticate(securityToken); assertThat(authentication).isNotNull(); } @@ -149,7 +153,8 @@ public class AmqpControllerAuthenticationTest { public void testAuthenticationMessageBadCredantialsWithoutPricipal() { final MessageProperties messageProperties = createMessageProperties(MessageType.AUTHENTIFICATION); - final TenantSecruityToken securityToken = new TenantSecruityToken(TENANT, CONTROLLLER_ID, "12345"); + final TenantSecurityToken securityToken = new TenantSecurityToken(TENANT, CONTROLLLER_ID, + FileResource.sha1("12345")); final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken, messageProperties); @@ -167,11 +172,12 @@ public class AmqpControllerAuthenticationTest { @Description("Tests authentication message without wrong credential") public void testAuthenticationMessageBadCredantialsWithWrongCredential() { final MessageProperties messageProperties = createMessageProperties(MessageType.AUTHENTIFICATION); - final TenantSecruityToken securityToken = new TenantSecruityToken(TENANT, CONTROLLLER_ID, "12345"); + final TenantSecurityToken securityToken = new TenantSecurityToken(TENANT, CONTROLLLER_ID, + FileResource.sha1("12345")); when(tenantConfigurationManagement.getConfigurationValue( eq(TenantConfigurationKey.AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED), eq(Boolean.class))) .thenReturn(CONFIG_VALUE_TRUE); - securityToken.getHeaders().put(TenantSecruityToken.AUTHORIZATION_HEADER, "TargetToken 12" + CONTROLLLER_ID); + securityToken.getHeaders().put(TenantSecurityToken.AUTHORIZATION_HEADER, "TargetToken 12" + CONTROLLLER_ID); final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken, messageProperties); @@ -189,11 +195,12 @@ public class AmqpControllerAuthenticationTest { @Description("Tests authentication message successfull") public void testSuccessfullMessageAuthentication() { final MessageProperties messageProperties = createMessageProperties(MessageType.AUTHENTIFICATION); - final TenantSecruityToken securityToken = new TenantSecruityToken(TENANT, CONTROLLLER_ID, "12345"); + final TenantSecurityToken securityToken = new TenantSecurityToken(TENANT, CONTROLLLER_ID, + FileResource.sha1("12345")); when(tenantConfigurationManagement.getConfigurationValue( eq(TenantConfigurationKey.AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED), eq(Boolean.class))) .thenReturn(CONFIG_VALUE_TRUE); - securityToken.getHeaders().put(TenantSecruityToken.AUTHORIZATION_HEADER, "TargetToken " + CONTROLLLER_ID); + securityToken.getHeaders().put(TenantSecurityToken.AUTHORIZATION_HEADER, "TargetToken " + CONTROLLLER_ID); final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken, messageProperties); 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 9d6ae3ba7..930ca02ad 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 @@ -34,7 +34,8 @@ import org.eclipse.hawkbit.dmf.amqp.api.MessageType; import org.eclipse.hawkbit.dmf.json.model.ActionStatus; import org.eclipse.hawkbit.dmf.json.model.ActionUpdateStatus; import org.eclipse.hawkbit.dmf.json.model.DownloadResponse; -import org.eclipse.hawkbit.dmf.json.model.TenantSecruityToken; +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken.FileResource; import org.eclipse.hawkbit.eventbus.event.TargetAssignDistributionSetEvent; import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.ControllerManagement; @@ -263,7 +264,7 @@ public class AmqpMessageHandlerServiceTest { @Description("Tests that an download request is denied for an artifact which does not exists") public void authenticationRequestDeniedForArtifactWhichDoesNotExists() { final MessageProperties messageProperties = createMessageProperties(MessageType.AUTHENTIFICATION); - final TenantSecruityToken securityToken = new TenantSecruityToken(TENANT, "123", "12345"); + final TenantSecurityToken securityToken = new TenantSecurityToken(TENANT, "123", FileResource.sha1("12345")); final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken, messageProperties); @@ -282,7 +283,7 @@ public class AmqpMessageHandlerServiceTest { @Description("Tests that an download request is denied for an artifact which is not assigned to the requested target") public void authenticationRequestDeniedForArtifactWhichIsNotAssignedToTarget() { final MessageProperties messageProperties = createMessageProperties(MessageType.AUTHENTIFICATION); - final TenantSecruityToken securityToken = new TenantSecruityToken(TENANT, "123", "12345"); + final TenantSecurityToken securityToken = new TenantSecurityToken(TENANT, "123", FileResource.sha1("12345")); final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken, messageProperties); @@ -306,7 +307,7 @@ public class AmqpMessageHandlerServiceTest { @Description("Tests that an download request is allowed for an artifact which exists and assigned to the requested target") public void authenticationRequestAllowedForArtifactWhichExistsAndAssignedToTarget() throws MalformedURLException { final MessageProperties messageProperties = createMessageProperties(MessageType.AUTHENTIFICATION); - final TenantSecruityToken securityToken = new TenantSecruityToken(TENANT, "123", "12345"); + final TenantSecurityToken securityToken = new TenantSecurityToken(TENANT, "123", FileResource.sha1("12345")); final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken, messageProperties); diff --git a/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecruityToken.java b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecruityToken.java deleted file mode 100644 index 351684f5e..000000000 --- a/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecruityToken.java +++ /dev/null @@ -1,94 +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.dmf.json.model; - -import java.util.Map; -import java.util.TreeMap; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * JSON representation to authenticate a tenant. - * - * - * - */ - -@JsonInclude(Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public class TenantSecruityToken { - - public static final String AUTHORIZATION_HEADER = "Authorization"; - public static final String COAP_AUTHORIZATION_HEADER = "Coap-Authorization"; - public static final String COAP_TOKEN_VALUE = "CoapToken"; - - @JsonProperty - private final String tenant; - @JsonProperty - private final String controllerId; - @JsonProperty(required = false) - private Map headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - @JsonProperty(required = false) - private final String sha1; - - /** - * Constructor. - * - * @param tenant - * the tenant for the security token - * @param controllerId - * the ID of the controller for the security token - * @param sha1 - * the sha1 of authentication - */ - @JsonCreator - public TenantSecruityToken(@JsonProperty("tenant") final String tenant, - @JsonProperty("controllerId") final String controllerId, @JsonProperty("sha1") final String sha1) { - this.tenant = tenant; - this.controllerId = controllerId; - this.sha1 = sha1; - } - - public String getTenant() { - return tenant; - } - - public String getControllerId() { - return controllerId; - } - - public Map getHeaders() { - return headers; - } - - public String getSha1() { - return sha1; - } - - /** - * Gets a header value. - * - * @param name - * of header - * @return the value - */ - public String getHeader(final String name) { - return headers.get(name); - } - - public void setHeaders(final Map headers) { - this.headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - this.headers.putAll(headers); - } - -} diff --git a/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecurityToken.java b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecurityToken.java new file mode 100644 index 000000000..9e07d3fc4 --- /dev/null +++ b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecurityToken.java @@ -0,0 +1,176 @@ +/** + * 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.dmf.json.model; + +import java.util.Map; +import java.util.TreeMap; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * JSON representation to authenticate a tenant. + */ + +@JsonInclude(Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class TenantSecurityToken { + + public static final String AUTHORIZATION_HEADER = "Authorization"; + public static final String COAP_AUTHORIZATION_HEADER = "Coap-Authorization"; + public static final String COAP_TOKEN_VALUE = "CoapToken"; + + @JsonProperty + private final String tenant; + @JsonProperty + private final String controllerId; + @JsonProperty(required = false) + private Map headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + + @JsonProperty(required = false) + private final FileResource fileResource; + + /** + * Constructor. + * + * @param tenant + * the tenant for the security token + * @param controllerId + * the ID of the controller for the security token + * @param fileResource + * the file to obtain + */ + @JsonCreator + public TenantSecurityToken(@JsonProperty("tenant") final String tenant, + @JsonProperty("controllerId") final String controllerId, + @JsonProperty("fileResource") final FileResource fileResource) { + this.tenant = tenant; + this.controllerId = controllerId; + this.fileResource = fileResource; + } + + public String getTenant() { + return tenant; + } + + public String getControllerId() { + return controllerId; + } + + public Map getHeaders() { + return headers; + } + + public FileResource getFileResource() { + return fileResource; + } + + /** + * Gets a header value. + * + * @param name + * of header + * @return the value + */ + public String getHeader(final String name) { + return headers.get(name); + } + + public void setHeaders(final Map headers) { + this.headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + this.headers.putAll(headers); + } + + /** + * File resource descriptor which is used to ask for the resource to + * download e.g. The lookup of the file can be different e.g. by SHA1 hash + * or by filename. + */ + @JsonInclude(Include.NON_NULL) + @JsonIgnoreProperties(ignoreUnknown = true) + public static class FileResource { + @JsonProperty(required = false) + private String sha1; + @JsonProperty(required = false) + private String filename; + @JsonProperty(required = false) + private Long artifactId; + + public String getSha1() { + return sha1; + } + + public void setSha1(final String sha1) { + this.sha1 = sha1; + } + + public String getFilename() { + return filename; + } + + public void setFilename(final String filename) { + this.filename = filename; + } + + public Long getArtifactId() { + return artifactId; + } + + public void setArtifactId(final Long artifactId) { + this.artifactId = artifactId; + } + + /** + * factory method to create a file resource for an SHA1 lookup. + * + * @param sha1 + * the SHA1 key of the file to obtain + * @return the {@link FileResource} with SHA1 key set + */ + public static FileResource sha1(final String sha1) { + final FileResource resource = new FileResource(); + resource.sha1 = sha1; + return resource; + } + + /** + * factory method to create a file resource for an filename lookup. + * + * @param filename + * the filename of the file to obtain + * @return the {@link FileResource} with filename set + */ + public static FileResource filename(final String filename) { + final FileResource resource = new FileResource(); + resource.filename = filename; + return resource; + } + + /** + * factory method to create a file resource for an artifactId lookup. + * + * @param artifactId + * the artifactId of the file to obtain + * @return the {@link FileResource} with artifactId set + */ + public static FileResource artifactId(final Long artifactId) { + final FileResource resource = new FileResource(); + resource.artifactId = artifactId; + return resource; + } + + @Override + public String toString() { + return "FileResource [sha1=" + sha1 + ", filename=" + filename + "]"; + } + } +} diff --git a/hawkbit-http-security/src/main/java/org/eclipse/hawkbit/security/AbstractHttpControllerAuthenticationFilter.java b/hawkbit-http-security/src/main/java/org/eclipse/hawkbit/security/AbstractHttpControllerAuthenticationFilter.java index adb2858b9..ace5bc834 100644 --- a/hawkbit-http-security/src/main/java/org/eclipse/hawkbit/security/AbstractHttpControllerAuthenticationFilter.java +++ b/hawkbit-http-security/src/main/java/org/eclipse/hawkbit/security/AbstractHttpControllerAuthenticationFilter.java @@ -17,7 +17,8 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; -import org.eclipse.hawkbit.dmf.json.model.TenantSecruityToken; +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken.FileResource; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; import org.eclipse.hawkbit.tenancy.TenantAware; import org.slf4j.Logger; @@ -96,7 +97,7 @@ public abstract class AbstractHttpControllerAuthenticationFilter extends Abstrac return; } - final TenantSecruityToken secruityToken = createTenantSecruityTokenVariables((HttpServletRequest) request); + final TenantSecurityToken secruityToken = createTenantSecruityTokenVariables((HttpServletRequest) request); if (secruityToken == null) { chain.doFilter(request, response); return; @@ -121,7 +122,7 @@ public abstract class AbstractHttpControllerAuthenticationFilter extends Abstrac * request does not match the pattern and no variables could be * extracted */ - protected TenantSecruityToken createTenantSecruityTokenVariables(final HttpServletRequest request) { + protected TenantSecurityToken createTenantSecruityTokenVariables(final HttpServletRequest request) { final String requestURI = request.getRequestURI(); if (pathExtractor.match(request.getContextPath() + CONTROLLER_REQUEST_ANT_PATTERN, requestURI)) { @@ -153,9 +154,9 @@ public abstract class AbstractHttpControllerAuthenticationFilter extends Abstrac } } - private TenantSecruityToken createTenantSecruityTokenVariables(final HttpServletRequest request, + private TenantSecurityToken createTenantSecruityTokenVariables(final HttpServletRequest request, final String tenant, final String controllerId) { - final TenantSecruityToken secruityToken = new TenantSecruityToken(tenant, controllerId, ""); + final TenantSecurityToken secruityToken = new TenantSecurityToken(tenant, controllerId, FileResource.sha1("")); final UnmodifiableIterator forEnumeration = Iterators.forEnumeration(request.getHeaderNames()); forEnumeration.forEachRemaining(header -> secruityToken.getHeaders().put(header, request.getHeader(header))); return secruityToken; @@ -163,7 +164,7 @@ public abstract class AbstractHttpControllerAuthenticationFilter extends Abstrac @Override protected Object getPreAuthenticatedPrincipal(final HttpServletRequest request) { - final TenantSecruityToken secruityToken = createTenantSecruityTokenVariables(request); + final TenantSecurityToken secruityToken = createTenantSecruityTokenVariables(request); if (secruityToken == null) { return null; } @@ -172,7 +173,7 @@ public abstract class AbstractHttpControllerAuthenticationFilter extends Abstrac @Override protected Object getPreAuthenticatedCredentials(final HttpServletRequest request) { - final TenantSecruityToken secruityToken = createTenantSecruityTokenVariables(request); + final TenantSecurityToken secruityToken = createTenantSecruityTokenVariables(request); if (secruityToken == null) { return null; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java index a5ee019dc..122d7b881 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java @@ -321,7 +321,8 @@ public class ArtifactManagement { } boolean artifactIsOnlyUsedByOneSoftwareModule = true; - for (LocalArtifact lArtifact : localArtifactRepository.findByGridFsFileName(existing.getGridFsFileName())) { + for (final LocalArtifact lArtifact : localArtifactRepository + .findByGridFsFileName(existing.getGridFsFileName())) { if (!lArtifact.getSoftwareModule().isDeleted() && lArtifact.getSoftwareModule().getId() != existing.getSoftwareModule().getId()) { artifactIsOnlyUsedByOneSoftwareModule = false; diff --git a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/AbstractControllerAuthenticationFilter.java b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/AbstractControllerAuthenticationFilter.java index d22c432cf..9a1cd2aea 100644 --- a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/AbstractControllerAuthenticationFilter.java +++ b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/AbstractControllerAuthenticationFilter.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.security; -import org.eclipse.hawkbit.dmf.json.model.TenantSecruityToken; +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; @@ -42,15 +42,15 @@ public abstract class AbstractControllerAuthenticationFilter implements PreAuthe protected abstract TenantConfigurationKey getTenantConfigurationKey(); @Override - public boolean isEnable(final TenantSecruityToken secruityToken) { + public boolean isEnable(final TenantSecurityToken secruityToken) { return tenantAware.runAsTenant(secruityToken.getTenant(), configurationKeyTenantRunner); } @Override - public abstract HeaderAuthentication getPreAuthenticatedPrincipal(TenantSecruityToken secruityToken); + public abstract HeaderAuthentication getPreAuthenticatedPrincipal(TenantSecurityToken secruityToken); @Override - public abstract HeaderAuthentication getPreAuthenticatedCredentials(TenantSecruityToken secruityToken); + public abstract HeaderAuthentication getPreAuthenticatedCredentials(TenantSecurityToken secruityToken); private final class SecurityConfigurationKeyTenantRunner implements TenantAware.TenantRunner { @Override diff --git a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/CoapAnonymousPreAuthenticatedFilter.java b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/CoapAnonymousPreAuthenticatedFilter.java index d9d8b9fa7..36a444c43 100644 --- a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/CoapAnonymousPreAuthenticatedFilter.java +++ b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/CoapAnonymousPreAuthenticatedFilter.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.security; -import org.eclipse.hawkbit.dmf.json.model.TenantSecruityToken; +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; /** * A Filter for device which download via coap. @@ -19,19 +19,19 @@ import org.eclipse.hawkbit.dmf.json.model.TenantSecruityToken; public class CoapAnonymousPreAuthenticatedFilter implements PreAuthenficationFilter { @Override - public HeaderAuthentication getPreAuthenticatedPrincipal(final TenantSecruityToken secruityToken) { - return new HeaderAuthentication(secruityToken.getControllerId(), TenantSecruityToken.COAP_TOKEN_VALUE); + public HeaderAuthentication getPreAuthenticatedPrincipal(final TenantSecurityToken secruityToken) { + return new HeaderAuthentication(secruityToken.getControllerId(), TenantSecurityToken.COAP_TOKEN_VALUE); } @Override - public HeaderAuthentication getPreAuthenticatedCredentials(final TenantSecruityToken secruityToken) { - return new HeaderAuthentication(secruityToken.getControllerId(), TenantSecruityToken.COAP_TOKEN_VALUE); + public HeaderAuthentication getPreAuthenticatedCredentials(final TenantSecurityToken secruityToken) { + return new HeaderAuthentication(secruityToken.getControllerId(), TenantSecurityToken.COAP_TOKEN_VALUE); } @Override - public boolean isEnable(final TenantSecruityToken secruityToken) { - final String authHeader = secruityToken.getHeader(TenantSecruityToken.COAP_AUTHORIZATION_HEADER); - return TenantSecruityToken.COAP_TOKEN_VALUE.equals(authHeader); + public boolean isEnable(final TenantSecurityToken secruityToken) { + final String authHeader = secruityToken.getHeader(TenantSecurityToken.COAP_AUTHORIZATION_HEADER); + return TenantSecurityToken.COAP_TOKEN_VALUE.equals(authHeader); } } diff --git a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticateSecurityTokenFilter.java b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticateSecurityTokenFilter.java index c30f60711..8ff1e9ebc 100644 --- a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticateSecurityTokenFilter.java +++ b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticateSecurityTokenFilter.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.security; -import org.eclipse.hawkbit.dmf.json.model.TenantSecruityToken; +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; import org.eclipse.hawkbit.im.authentication.SpPermission; import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails; import org.eclipse.hawkbit.repository.ControllerManagement; @@ -67,8 +67,8 @@ public class ControllerPreAuthenticateSecurityTokenFilter extends AbstractContro } @Override - public HeaderAuthentication getPreAuthenticatedPrincipal(final TenantSecruityToken secruityToken) { - final String authHeader = secruityToken.getHeader(TenantSecruityToken.AUTHORIZATION_HEADER); + public HeaderAuthentication getPreAuthenticatedPrincipal(final TenantSecurityToken secruityToken) { + final String authHeader = secruityToken.getHeader(TenantSecurityToken.AUTHORIZATION_HEADER); if ((authHeader != null) && authHeader.startsWith(TARGET_SECURITY_TOKEN_AUTH_SCHEME)) { LOGGER.debug("found authorization header with scheme {} using target security token for authentication", TARGET_SECURITY_TOKEN_AUTH_SCHEME); @@ -81,7 +81,7 @@ public class ControllerPreAuthenticateSecurityTokenFilter extends AbstractContro } @Override - public HeaderAuthentication getPreAuthenticatedCredentials(final TenantSecruityToken secruityToken) { + public HeaderAuthentication getPreAuthenticatedCredentials(final TenantSecurityToken secruityToken) { final String securityToken = tenantAware.runAsTenant(secruityToken.getTenant(), new GetSecurityTokenTenantRunner(secruityToken.getTenant(), secruityToken.getControllerId())); return new HeaderAuthentication(secruityToken.getControllerId(), securityToken); diff --git a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedGatewaySecurityTokenFilter.java b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedGatewaySecurityTokenFilter.java index 765589df4..7d1bd7b0f 100644 --- a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedGatewaySecurityTokenFilter.java +++ b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedGatewaySecurityTokenFilter.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.security; -import org.eclipse.hawkbit.dmf.json.model.TenantSecruityToken; +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; @@ -56,8 +56,8 @@ public class ControllerPreAuthenticatedGatewaySecurityTokenFilter extends Abstra } @Override - public HeaderAuthentication getPreAuthenticatedPrincipal(final TenantSecruityToken secruityToken) { - final String authHeader = secruityToken.getHeader(TenantSecruityToken.AUTHORIZATION_HEADER); + public HeaderAuthentication getPreAuthenticatedPrincipal(final TenantSecurityToken secruityToken) { + final String authHeader = secruityToken.getHeader(TenantSecurityToken.AUTHORIZATION_HEADER); if ((authHeader != null) && authHeader.startsWith(GATEWAY_SECURITY_TOKEN_AUTH_SCHEME)) { LOGGER.debug("found authorization header with scheme {} using target security token for authentication", GATEWAY_SECURITY_TOKEN_AUTH_SCHEME); @@ -71,7 +71,7 @@ public class ControllerPreAuthenticatedGatewaySecurityTokenFilter extends Abstra } @Override - public HeaderAuthentication getPreAuthenticatedCredentials(final TenantSecruityToken secruityToken) { + public HeaderAuthentication getPreAuthenticatedCredentials(final TenantSecurityToken secruityToken) { final String gatewayToken = tenantAware.runAsTenant(secruityToken.getTenant(), gatewaySecurityTokenKeyConfigRunner); return new HeaderAuthentication(secruityToken.getControllerId(), gatewayToken); diff --git a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedSecurityHeaderFilter.java b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedSecurityHeaderFilter.java index ef8b5fbf7..6836b8a31 100644 --- a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedSecurityHeaderFilter.java +++ b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedSecurityHeaderFilter.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.security; -import org.eclipse.hawkbit.dmf.json.model.TenantSecruityToken; +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; @@ -18,7 +18,7 @@ import org.slf4j.LoggerFactory; /** * An pre-authenticated processing filter which extracts the principal from a * request URI and the credential from a request header in a the - * {@link TenantSecruityToken}. + * {@link TenantSecurityToken}. * * * @@ -75,7 +75,7 @@ public class ControllerPreAuthenticatedSecurityHeaderFilter extends AbstractCont } @Override - public HeaderAuthentication getPreAuthenticatedPrincipal(final TenantSecruityToken secruityToken) { + public HeaderAuthentication getPreAuthenticatedPrincipal(final TenantSecurityToken secruityToken) { // retrieve the common name header and the authority name header from // the http request and // combine them together @@ -97,7 +97,7 @@ public class ControllerPreAuthenticatedSecurityHeaderFilter extends AbstractCont } @Override - public HeaderAuthentication getPreAuthenticatedCredentials(final TenantSecruityToken secruityToken) { + public HeaderAuthentication getPreAuthenticatedCredentials(final TenantSecurityToken secruityToken) { final String authorityNameConfigurationValue = tenantAware.runAsTenant(secruityToken.getTenant(), sslIssuerNameConfigTenantRunner); String controllerId = secruityToken.getControllerId(); @@ -117,7 +117,7 @@ public class ControllerPreAuthenticatedSecurityHeaderFilter extends AbstractCont * It's ok if we find the the hash in any the trusted CA chain to accept * this request for this tenant. */ - private String getIssuerHashHeader(final TenantSecruityToken secruityToken, final String knownIssuerHash) { + private String getIssuerHashHeader(final TenantSecurityToken secruityToken, final String knownIssuerHash) { // iterate over the headers until we get a null header. int iHeader = 1; String foundHash; diff --git a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/PreAuthenficationFilter.java b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/PreAuthenficationFilter.java index 8aa957005..8981fa9af 100644 --- a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/PreAuthenficationFilter.java +++ b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/PreAuthenficationFilter.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.security; -import org.eclipse.hawkbit.dmf.json.model.TenantSecruityToken; +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; /** * Interface for Pre Authenfication. @@ -25,7 +25,7 @@ public interface PreAuthenficationFilter { * the secruity info * @return is enabled diabled */ - boolean isEnable(TenantSecruityToken secruityToken); + boolean isEnable(TenantSecurityToken secruityToken); /** * Extract the principal information from the current secruityToken. @@ -34,7 +34,7 @@ public interface PreAuthenficationFilter { * the secruityToken * @return the extracted tenant and controller id */ - HeaderAuthentication getPreAuthenticatedPrincipal(TenantSecruityToken secruityToken); + HeaderAuthentication getPreAuthenticatedPrincipal(TenantSecurityToken secruityToken); /** * Extract the principal credentials from the current secruityToken. @@ -43,6 +43,6 @@ public interface PreAuthenficationFilter { * the secruityToken * @return the extracted tenant and controller id */ - HeaderAuthentication getPreAuthenticatedCredentials(TenantSecruityToken secruityToken); + HeaderAuthentication getPreAuthenticatedCredentials(TenantSecurityToken secruityToken); } From 74782527fedf14c727eaceda743dc1cf353100de Mon Sep 17 00:00:00 2001 From: Jonathan Philip Knoblauch Date: Wed, 23 Mar 2016 12:14:44 +0100 Subject: [PATCH 03/31] Added javadoc and refactored existing one. Signed-off-by: Jonathan Philip Knoblauch --- .../AuthenticationConfigurationView.java | 3 -- .../BaseConfigurationView.java | 4 +-- .../ConfigurationGroup.java | 5 ++- .../ConfigurationItem.java | 2 +- .../DefaultDistributionSetTypeLayout.java | 3 -- .../DownloadAnonymousConfigurationView.java | 11 ++----- .../PollingConfigurationView.java | 2 -- .../TenantConfigurationDashboardView.java | 12 +------ ...antConfigurationDashboardViewMenuItem.java | 3 -- ...ficateAuthenticationConfigurationItem.java | 31 ++----------------- ...yTokenAuthenticationConfigurationItem.java | 15 ++------- ...yTokenAuthenticationConfigurationItem.java | 22 ++----------- 12 files changed, 18 insertions(+), 95 deletions(-) diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/AuthenticationConfigurationView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/AuthenticationConfigurationView.java index 94e852813..d00223f5a 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/AuthenticationConfigurationView.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/AuthenticationConfigurationView.java @@ -30,9 +30,6 @@ import com.vaadin.ui.VerticalLayout; /** * View to configure the authentication mode. - * - * - * */ @SpringComponent @ViewScope diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/BaseConfigurationView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/BaseConfigurationView.java index 559eeae02..a68b095b4 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/BaseConfigurationView.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/BaseConfigurationView.java @@ -14,8 +14,8 @@ import java.util.List; import com.vaadin.ui.CustomComponent; /** - * base class for all configuration views. This class implements the logic for - * the handling of the + * Base class for all configuration views. This class implements the logic for + * the handling of the configurations in a consistent way. * */ public abstract class BaseConfigurationView extends CustomComponent implements ConfigurationGroup { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/ConfigurationGroup.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/ConfigurationGroup.java index 90a38dd56..3ac3610f9 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/ConfigurationGroup.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/ConfigurationGroup.java @@ -11,9 +11,8 @@ package org.eclipse.hawkbit.ui.tenantconfiguration; import com.vaadin.ui.Component; /** - * - * - * + * Interface that all system configurations have to implement to save and undo + * their customized changes. */ public interface ConfigurationGroup extends Component, ConfigurationItem { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/ConfigurationItem.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/ConfigurationItem.java index 142de0abb..856b2090d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/ConfigurationItem.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/ConfigurationItem.java @@ -11,7 +11,7 @@ package org.eclipse.hawkbit.ui.tenantconfiguration; import java.io.Serializable; /** - * represents an configurationItem, which can be modified by the user + * Represents an configurationItem, which can be modified by the user */ public interface ConfigurationItem { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DefaultDistributionSetTypeLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DefaultDistributionSetTypeLayout.java index ec0e643de..0162f6ed8 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DefaultDistributionSetTypeLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DefaultDistributionSetTypeLayout.java @@ -33,9 +33,6 @@ import com.vaadin.ui.VerticalLayout; /** * Default DistributionSet Panel. - * - * - * */ @SpringComponent @ViewScope diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java index 7366a251f..505c0963d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java @@ -28,10 +28,8 @@ import com.vaadin.ui.Panel; import com.vaadin.ui.VerticalLayout; /** - * @author Jonathan Knoblauch - * + * View to enable anonymous download. */ - @SpringComponent @ViewScope public class DownloadAnonymousConfigurationView extends BaseConfigurationView @@ -42,7 +40,7 @@ public class DownloadAnonymousConfigurationView extends BaseConfigurationView private static final long serialVersionUID = 1L; @Autowired - private I18N i18n; // TODO + private I18N i18n; @Autowired private transient TenantConfigurationManagement tenantConfigurationManagement; @@ -52,7 +50,7 @@ public class DownloadAnonymousConfigurationView extends BaseConfigurationView private CheckBox downloadAnonymousCheckBox; /** - * Initialize Default Distribution Set layout. + * Initialize Default Download Anonymous layout. */ @PostConstruct public void init() { @@ -81,7 +79,6 @@ public class DownloadAnonymousConfigurationView extends BaseConfigurationView downloadAnonymousCheckBox = SPUIComponentProvider.getCheckBox("", DIST_CHECKBOX_STYLE, null, false, ""); downloadAnonymousCheckBox.setValue(anonymousDownloadEnabled); - downloadAnonymousCheckBox.setId("TODO"); downloadAnonymousCheckBox.addValueChangeListener(event -> configurationHasChanged()); gridLayout.addComponent(downloadAnonymousCheckBox); @@ -94,7 +91,6 @@ public class DownloadAnonymousConfigurationView extends BaseConfigurationView rootPanel.setContent(vLayout); setCompositionRoot(rootPanel); - } @Override @@ -107,7 +103,6 @@ public class DownloadAnonymousConfigurationView extends BaseConfigurationView public void save() { tenantConfigurationManagement.addOrUpdateConfiguration(TenantConfigurationKey.ANONYMOUS_DOWNLOAD_MODE_ENABLED, downloadAnonymousCheckBox.getValue()); - // TODO notification Download server } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/PollingConfigurationView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/PollingConfigurationView.java index f751481be..2389a2efa 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/PollingConfigurationView.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/PollingConfigurationView.java @@ -29,8 +29,6 @@ import com.vaadin.ui.VerticalLayout; /** * View to configure the polling interval and the overdue time. - * - * */ @SpringComponent @ViewScope diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/TenantConfigurationDashboardView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/TenantConfigurationDashboardView.java index 0349ba867..cada6d167 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/TenantConfigurationDashboardView.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/TenantConfigurationDashboardView.java @@ -38,9 +38,6 @@ import com.vaadin.ui.VerticalLayout; /** * Main UI for the system configuration view. - * - * - * */ @SpringView(name = TenantConfigurationDashboardView.VIEW_NAME, ui = HawkbitUI.class) @ViewScope @@ -76,7 +73,7 @@ public class TenantConfigurationDashboardView extends CustomComponent implements private final List configurationViews = new ArrayList<>(); /** - * init method adds all Configuration Views to the list of Views. + * Init method adds all Configuration Views to the list of Views. */ @PostConstruct public void init() { @@ -158,13 +155,6 @@ public class TenantConfigurationDashboardView extends CustomComponent implements undoConfigurationBtn.setEnabled(false); } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.tenantconfiguration.ConfigurationGroup. - * ConfigurationGroupChangeListener #configurationChanged() - */ @Override public void configurationHasChanged() { saveConfigurationBtn.setEnabled(true); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/TenantConfigurationDashboardViewMenuItem.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/TenantConfigurationDashboardViewMenuItem.java index 1eea3014d..42f96f2c6 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/TenantConfigurationDashboardViewMenuItem.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/TenantConfigurationDashboardViewMenuItem.java @@ -21,9 +21,6 @@ import com.vaadin.server.Resource; /** * Menu item for system configuration view. - * - * - * */ @Component @Order(700) diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/CertificateAuthenticationConfigurationItem.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/CertificateAuthenticationConfigurationItem.java index cf2744718..b17d9596f 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/CertificateAuthenticationConfigurationItem.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/CertificateAuthenticationConfigurationItem.java @@ -26,16 +26,13 @@ import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.ValoTheme; /** - * - * + * This class represents the UI item for the certificate authenticated by an + * reverse proxy in the authentication configuration view. */ @SpringComponent @ViewScope public class CertificateAuthenticationConfigurationItem extends AbstractAuthenticationTenantConfigurationItem { - /** - * - */ private static final long serialVersionUID = 1L; @Autowired @@ -59,7 +56,7 @@ public class CertificateAuthenticationConfigurationItem extends AbstractAuthenti } /** - * init mehotd called by spring. + * Init mehotd called by spring. */ @PostConstruct public void init() { @@ -94,12 +91,6 @@ public class CertificateAuthenticationConfigurationItem extends AbstractAuthenti } } - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.ui.tenantconfiguration. - * TenantConfigurationItem# configEnable() - */ @Override public void configEnable() { if (!configurationEnabled) { @@ -110,12 +101,6 @@ public class CertificateAuthenticationConfigurationItem extends AbstractAuthenti setDetailVisible(true); } - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.ui.tenantconfiguration. - * TenantConfigurationItem# configDisable() - */ @Override public void configDisable() { if (configurationEnabled) { @@ -125,11 +110,6 @@ public class CertificateAuthenticationConfigurationItem extends AbstractAuthenti setDetailVisible(false); } - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.tenantconfiguration.TenantConfigurationItem#save() - */ @Override public void save() { if (configurationEnabledChange) { @@ -142,11 +122,6 @@ public class CertificateAuthenticationConfigurationItem extends AbstractAuthenti } } - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.tenantconfiguration.TenantConfigurationItem#undo() - */ @Override public void undo() { configurationEnabledChange = false; 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 fa1ca9271..757460809 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 @@ -30,16 +30,13 @@ import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.ValoTheme; /** - * - * + * This class represents the UI item for the gateway security token section in + * the authentication configuration view. */ @SpringComponent @ViewScope public class GatewaySecurityTokenAuthenticationConfigurationItem extends AbstractAuthenticationTenantConfigurationItem { - /** - * - */ private static final long serialVersionUID = 1L; @Autowired @@ -70,7 +67,7 @@ public class GatewaySecurityTokenAuthenticationConfigurationItem extends Abstrac } /** - * init mehotd called by spring. + * Init mehotd called by spring. */ @PostConstruct public void init() { @@ -135,12 +132,6 @@ public class GatewaySecurityTokenAuthenticationConfigurationItem extends Abstrac notifyConfigurationChanged(); } - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.ui.tenantconfiguration. - * TenantConfigurationItem# configEnable() - */ @Override public void configEnable() { if (!configurationEnabled) { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/TargetSecurityTokenAuthenticationConfigurationItem.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/TargetSecurityTokenAuthenticationConfigurationItem.java index 42e50da2c..641982d73 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/TargetSecurityTokenAuthenticationConfigurationItem.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/TargetSecurityTokenAuthenticationConfigurationItem.java @@ -19,17 +19,13 @@ import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; /** - * - * - * + * This class represents the UI item for the target security token section in + * the authentication configuration view. */ @SpringComponent @ViewScope public class TargetSecurityTokenAuthenticationConfigurationItem extends AbstractAuthenticationTenantConfigurationItem { - /** - * - */ private static final long serialVersionUID = 1L; @Autowired @@ -49,7 +45,7 @@ public class TargetSecurityTokenAuthenticationConfigurationItem extends Abstract } /** - * init mehotd called by spring. + * Init mehotd called by spring. */ @PostConstruct public void init() { @@ -57,12 +53,6 @@ public class TargetSecurityTokenAuthenticationConfigurationItem extends Abstract configurationEnabled = isConfigEnabled(); } - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.ui.tenantconfiguration. - * TenantConfigurationItem# configEnable() - */ @Override public void configEnable() { if (!configurationEnabled) { @@ -71,12 +61,6 @@ public class TargetSecurityTokenAuthenticationConfigurationItem extends Abstract configurationEnabled = true; } - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.ui.tenantconfiguration. - * TenantConfigurationItem# configDisable() - */ @Override public void configDisable() { if (configurationEnabled) { From 3ff352584e104d1e28123b8a17f957b0af6ca557 Mon Sep 17 00:00:00 2001 From: Jonathan Philip Knoblauch Date: Wed, 23 Mar 2016 14:28:24 +0100 Subject: [PATCH 04/31] Small fix since wrong config value was being accessed. Signed-off-by: Jonathan Philip Knoblauch --- .../DownloadAnonymousConfigurationView.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java index 505c0963d..fa441476d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java @@ -107,10 +107,10 @@ public class DownloadAnonymousConfigurationView extends BaseConfigurationView @Override public void undo() { - anonymousDownloadEnabled = tenantConfigurationManagement - .getGlobalConfigurationValue(TenantConfigurationKey.ANONYMOUS_DOWNLOAD_MODE_ENABLED, Boolean.class); + final TenantConfigurationValue value = tenantConfigurationManagement + .getConfigurationValue(TenantConfigurationKey.ANONYMOUS_DOWNLOAD_MODE_ENABLED, Boolean.class); + anonymousDownloadEnabled = value.getValue(); downloadAnonymousCheckBox.setValue(anonymousDownloadEnabled); - } } From 1cb7519ace523844a72854944f305cb5c45eaf5a Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Wed, 23 Mar 2016 16:17:53 +0100 Subject: [PATCH 05/31] add security and filters for anonymous download via http and amqp requests Signed-off-by: Michael Hirsch --- .../SecurityManagedConfiguration.java | 20 ++++-- .../amqp/AmqpControllerAuthentfication.java | 7 ++ .../amqp/AmqpMessageHandlerService.java | 16 ++--- .../AmqpControllerAuthenticationTest.java | 7 ++ .../dmf/json/model/TenantSecurityToken.java | 62 ++++++++++++++--- ...actHttpControllerAuthenticationFilter.java | 26 ++++--- ...reAuthenticateAnonymousDownloadFilter.java | 47 +++++++++++++ .../repository/ArtifactManagement.java | 2 +- .../im/authentication/SpPermission.java | 18 ++++- ...llerPreAuthenticatedAnonymousDownload.java | 69 +++++++++++++++++++ ...rollerPreAuthenticatedAnonymousFilter.java | 47 +++++++++++++ ...okenSourceTrustAuthenticationProvider.java | 1 + .../security/PreAuthenficationFilter.java | 17 +++++ 13 files changed, 304 insertions(+), 35 deletions(-) create mode 100644 hawkbit-http-security/src/main/java/org/eclipse/hawkbit/security/HttpControllerPreAuthenticateAnonymousDownloadFilter.java create mode 100644 hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousDownload.java create mode 100644 hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousFilter.java 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 24e9667c2..9638377eb 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 @@ -10,7 +10,6 @@ package org.eclipse.hawkbit.autoconfigure.security; import java.io.IOException; import java.net.URI; -import java.util.Collections; import javax.annotation.PostConstruct; import javax.servlet.Filter; @@ -35,6 +34,7 @@ import org.eclipse.hawkbit.security.ControllerTenantAwareAuthenticationDetailsSo import org.eclipse.hawkbit.security.DdiSecurityProperties; import org.eclipse.hawkbit.security.DosFilter; import org.eclipse.hawkbit.security.HawkbitSecurityProperties; +import org.eclipse.hawkbit.security.HttpControllerPreAuthenticateAnonymousDownloadFilter; import org.eclipse.hawkbit.security.HttpControllerPreAuthenticateSecurityTokenFilter; import org.eclipse.hawkbit.security.HttpControllerPreAuthenticatedGatewaySecurityTokenFilter; import org.eclipse.hawkbit.security.HttpControllerPreAuthenticatedSecurityHeaderFilter; @@ -83,6 +83,8 @@ import org.vaadin.spring.security.web.VaadinRedirectStrategy; import org.vaadin.spring.security.web.authentication.VaadinAuthenticationSuccessHandler; import org.vaadin.spring.security.web.authentication.VaadinUrlAuthenticationSuccessHandler; +import com.google.common.collect.Lists; + /** * All configurations related to SP authentication and authorization layer. * @@ -147,6 +149,12 @@ public class SecurityManagedConfiguration { gatewaySecurityTokenFilter.setCheckForPrincipalChanges(true); gatewaySecurityTokenFilter.setAuthenticationDetailsSource(authenticationDetailsSource); + final HttpControllerPreAuthenticateAnonymousDownloadFilter controllerAnonymousDownloadFilter = new HttpControllerPreAuthenticateAnonymousDownloadFilter( + tenantConfigurationManagement, tenantAware, systemSecurityContext); + controllerAnonymousDownloadFilter.setAuthenticationManager(authenticationManager()); + controllerAnonymousDownloadFilter.setCheckForPrincipalChanges(true); + controllerAnonymousDownloadFilter.setAuthenticationDetailsSource(authenticationDetailsSource); + HttpSecurity httpSec = http.csrf().disable().headers() .addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsMode.DENY)).contentTypeOptions() .xssProtection().httpStrictTransportSecurity().and(); @@ -159,15 +167,17 @@ public class SecurityManagedConfiguration { LOG.info( "******************\n** Anonymous controller security enabled, should only use for developing purposes **\n******************"); final AnonymousAuthenticationFilter anoymousFilter = new AnonymousAuthenticationFilter( - "controllerAnonymousFilter", "anonymous", Collections.singletonList( - new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS))); + "controllerAnonymousFilter", "anonymous", + Lists.newArrayList(new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS), + new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_DOWNLOAD_ROLE))); anoymousFilter.setAuthenticationDetailsSource(authenticationDetailsSource); httpSec.requestMatchers().antMatchers("/*/controller/v1/**", "/*/controller/artifacts/v1/**").and() .securityContext().disable().anonymous().authenticationFilter(anoymousFilter); } else { httpSec.addFilter(securityHeaderFilter).addFilter(securityTokenFilter) - .addFilter(gatewaySecurityTokenFilter).antMatcher("/*/controller/**").anonymous().disable() - .authorizeRequests().anyRequest().authenticated().and().exceptionHandling() + .addFilter(gatewaySecurityTokenFilter).addFilter(controllerAnonymousDownloadFilter) + .antMatcher("/*/controller/**").anonymous().disable().authorizeRequests().anyRequest() + .authenticated().and().exceptionHandling() .authenticationEntryPoint((request, response, authException) -> response .setStatus(HttpStatus.UNAUTHORIZED.value())) .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 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 3fa7979b9..9d120c17b 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 @@ -19,6 +19,8 @@ import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; import org.eclipse.hawkbit.security.CoapAnonymousPreAuthenticatedFilter; import org.eclipse.hawkbit.security.ControllerPreAuthenticateSecurityTokenFilter; +import org.eclipse.hawkbit.security.ControllerPreAuthenticatedAnonymousDownload; +import org.eclipse.hawkbit.security.ControllerPreAuthenticatedAnonymousFilter; import org.eclipse.hawkbit.security.ControllerPreAuthenticatedGatewaySecurityTokenFilter; import org.eclipse.hawkbit.security.ControllerPreAuthenticatedSecurityHeaderFilter; import org.eclipse.hawkbit.security.DdiSecurityProperties; @@ -90,6 +92,11 @@ public class AmqpControllerAuthentfication { tenantConfigurationManagement, controllerManagement, tenantAware, systemSecurityContext); filterChain.add(securityTokenFilter); + final ControllerPreAuthenticatedAnonymousDownload anonymousDownloadFilter = new ControllerPreAuthenticatedAnonymousDownload( + tenantConfigurationManagement, tenantAware, systemSecurityContext); + filterChain.add(anonymousDownloadFilter); + + filterChain.add(new ControllerPreAuthenticatedAnonymousFilter(ddiSecruityProperties)); filterChain.add(new CoapAnonymousPreAuthenticatedFilter()); } 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 71b8f8db8..c5fff29ad 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 @@ -27,9 +27,9 @@ import org.eclipse.hawkbit.dmf.amqp.api.MessageType; import org.eclipse.hawkbit.dmf.json.model.ActionUpdateStatus; import org.eclipse.hawkbit.dmf.json.model.Artifact; import org.eclipse.hawkbit.dmf.json.model.ArtifactHash; +import org.eclipse.hawkbit.dmf.json.model.DownloadResponse; import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken.FileResource; -import org.eclipse.hawkbit.dmf.json.model.DownloadResponse; import org.eclipse.hawkbit.eventbus.event.TargetAssignDistributionSetEvent; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails; @@ -158,8 +158,7 @@ public class AmqpMessageHandlerService extends BaseAmqpService { private Message handleAuthentifiactionMessage(final Message message) { final DownloadResponse authentificationResponse = new DownloadResponse(); final MessageProperties messageProperties = message.getMessageProperties(); - final TenantSecurityToken secruityToken = convertMessage(message, - TenantSecurityToken.class); + final TenantSecurityToken secruityToken = convertMessage(message, TenantSecurityToken.class); final FileResource fileResource = secruityToken.getFileResource(); try { SecurityContextHolder.getContext().setAuthentication(authenticationManager.doAuthenticate(secruityToken)); @@ -221,12 +220,11 @@ public class AmqpMessageHandlerService extends BaseAmqpService { } else if (fileResource.getFilename() != null) { localArtifact = artifactManagement.findLocalArtifactByFilename(fileResource.getFilename()).stream() .findFirst().orElse(null); - } else if (fileResource.getArtifactId() != null) { - final org.eclipse.hawkbit.repository.model.Artifact artifact = artifactManagement - .findArtifact(fileResource.getArtifactId()); - if (artifact instanceof LocalArtifact) { - localArtifact = (LocalArtifact) artifact; - } + } else if (fileResource.getSoftwareModuleFilenameResource() != null) { + localArtifact = artifactManagement + .findByFilenameAndSoftwareModule(fileResource.getSoftwareModuleFilenameResource().getFilename(), + fileResource.getSoftwareModuleFilenameResource().getSoftwareModuleId()) + .stream().findFirst().orElse(null); } return localArtifact; } diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java index d7ab805ed..881260579 100644 --- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java +++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java @@ -26,6 +26,7 @@ import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; import org.eclipse.hawkbit.repository.model.TenantConfigurationValue; import org.eclipse.hawkbit.security.DdiSecurityProperties; +import org.eclipse.hawkbit.security.DdiSecurityProperties.Authentication.Anonymous; import org.eclipse.hawkbit.security.DdiSecurityProperties.Rp; import org.eclipse.hawkbit.security.SecurityContextTenantAware; import org.eclipse.hawkbit.security.SystemSecurityContext; @@ -80,8 +81,14 @@ public class AmqpControllerAuthenticationTest { final DdiSecurityProperties secruityProperties = mock(DdiSecurityProperties.class); final Rp rp = mock(Rp.class); + final org.eclipse.hawkbit.security.DdiSecurityProperties.Authentication ddiAuthentication = mock( + org.eclipse.hawkbit.security.DdiSecurityProperties.Authentication.class); + final Anonymous anonymous = mock(Anonymous.class); when(secruityProperties.getRp()).thenReturn(rp); when(rp.getSslIssuerHashHeader()).thenReturn("X-Ssl-Issuer-Hash-%d"); + when(secruityProperties.getAuthentication()).thenReturn(ddiAuthentication); + when(ddiAuthentication.getAnonymous()).thenReturn(anonymous); + when(anonymous.isEnabled()).thenReturn(false); authenticationManager.setSecruityProperties(secruityProperties); tenantConfigurationManagement = mock(TenantConfigurationManagement.class); diff --git a/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecurityToken.java b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecurityToken.java index 9e07d3fc4..154ad5158 100644 --- a/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecurityToken.java +++ b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecurityToken.java @@ -103,7 +103,7 @@ public class TenantSecurityToken { @JsonProperty(required = false) private String filename; @JsonProperty(required = false) - private Long artifactId; + private SoftwareModuleFilenameResource softwareModuleFilenameResource; public String getSha1() { return sha1; @@ -121,12 +121,13 @@ public class TenantSecurityToken { this.filename = filename; } - public Long getArtifactId() { - return artifactId; + public SoftwareModuleFilenameResource getSoftwareModuleFilenameResource() { + return softwareModuleFilenameResource; } - public void setArtifactId(final Long artifactId) { - this.artifactId = artifactId; + public void setSoftwareModuleFilenameResource( + final SoftwareModuleFilenameResource softwareModuleFilenameResource) { + this.softwareModuleFilenameResource = softwareModuleFilenameResource; } /** @@ -156,15 +157,19 @@ public class TenantSecurityToken { } /** - * factory method to create a file resource for an artifactId lookup. + * factory method to create a file resource for an softwaremodule + + * filename lookup, because an filename is not globally unique but + * within a softwaremodule. * - * @param artifactId - * the artifactId of the file to obtain + * @param softwareModuleId + * the ID of the software module which contains the artifact + * @param filename + * the name of file to obtain within the software module * @return the {@link FileResource} with artifactId set */ - public static FileResource artifactId(final Long artifactId) { + public static FileResource softwareModuleFilename(final Long softwareModuleId, final String filename) { final FileResource resource = new FileResource(); - resource.artifactId = artifactId; + resource.softwareModuleFilenameResource = new SoftwareModuleFilenameResource(softwareModuleId, filename); return resource; } @@ -172,5 +177,42 @@ public class TenantSecurityToken { public String toString() { return "FileResource [sha1=" + sha1 + ", filename=" + filename + "]"; } + + /** + * Inner class which holds the pointer to an artifact based on the + * softwaremoduleId and the filename. + */ + @JsonInclude(Include.NON_NULL) + @JsonIgnoreProperties(ignoreUnknown = true) + public static class SoftwareModuleFilenameResource { + @JsonProperty(required = false) + private final Long softwareModuleId; + @JsonProperty(required = false) + private final String filename; + + /** + * Constructor. + * + * @param softwareModuleId + * the ID of the softwaremodule + * @param filename + * the name of the file of the artifact within the + * softwaremodule + */ + @JsonCreator + public SoftwareModuleFilenameResource(@JsonProperty("softwareModuleId") final Long softwareModuleId, + @JsonProperty("filename") final String filename) { + this.softwareModuleId = softwareModuleId; + this.filename = filename; + } + + public Long getSoftwareModuleId() { + return softwareModuleId; + } + + public String getFilename() { + return filename; + } + } } } diff --git a/hawkbit-http-security/src/main/java/org/eclipse/hawkbit/security/AbstractHttpControllerAuthenticationFilter.java b/hawkbit-http-security/src/main/java/org/eclipse/hawkbit/security/AbstractHttpControllerAuthenticationFilter.java index ace5bc834..0e67489ea 100644 --- a/hawkbit-http-security/src/main/java/org/eclipse/hawkbit/security/AbstractHttpControllerAuthenticationFilter.java +++ b/hawkbit-http-security/src/main/java/org/eclipse/hawkbit/security/AbstractHttpControllerAuthenticationFilter.java @@ -9,6 +9,8 @@ package org.eclipse.hawkbit.security; import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; import java.util.Map; import javax.servlet.FilterChain; @@ -16,6 +18,7 @@ import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken.FileResource; @@ -23,8 +26,11 @@ import org.eclipse.hawkbit.repository.TenantConfigurationManagement; import org.eclipse.hawkbit.tenancy.TenantAware; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; +import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import org.springframework.util.AntPathMatcher; import com.google.common.collect.Iterators; @@ -80,14 +86,6 @@ public abstract class AbstractHttpControllerAuthenticationFilter extends Abstrac pathExtractor = new AntPathMatcher(); } - /* - * (non-Javadoc) - * - * @see org.springframework.security.web.authentication.preauth. - * AbstractPreAuthenticatedProcessingFilter - * #doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, - * javax.servlet.FilterChain) - */ @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { @@ -113,6 +111,18 @@ public abstract class AbstractHttpControllerAuthenticationFilter extends Abstrac protected abstract PreAuthenficationFilter createControllerAuthenticationFilter(); + @Override + protected void successfulAuthentication(final HttpServletRequest request, final HttpServletResponse response, + final Authentication authResult) { + final Collection authorities = new ArrayList<>(); + authorities.addAll(authResult.getAuthorities()); + authorities.addAll(abstractControllerAuthenticationFilter.getSuccessfulAuthenticationAuthorities()); + final PreAuthenticatedAuthenticationToken authTokenWithGrantedAuthorities = new PreAuthenticatedAuthenticationToken( + authResult.getPrincipal(), authResult.getCredentials(), authorities); + authTokenWithGrantedAuthorities.setDetails(authResult.getDetails()); + super.successfulAuthentication(request, response, authTokenWithGrantedAuthorities); + } + /** * Extracts tenant and controllerId from the request URI as path variables. * diff --git a/hawkbit-http-security/src/main/java/org/eclipse/hawkbit/security/HttpControllerPreAuthenticateAnonymousDownloadFilter.java b/hawkbit-http-security/src/main/java/org/eclipse/hawkbit/security/HttpControllerPreAuthenticateAnonymousDownloadFilter.java new file mode 100644 index 000000000..40fd1e555 --- /dev/null +++ b/hawkbit-http-security/src/main/java/org/eclipse/hawkbit/security/HttpControllerPreAuthenticateAnonymousDownloadFilter.java @@ -0,0 +1,47 @@ +/** + * 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.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; +import org.eclipse.hawkbit.repository.TenantConfigurationManagement; +import org.eclipse.hawkbit.tenancy.TenantAware; + +/** + * An pre-authenticated processing filter which add the + * {@link SpringEvalExpressions#CONTROLLER_DOWNLOAD_ROLE_ANONYMOUS} to the + * security context in case the anonymous download is allowed through + * configuration. + */ +public class HttpControllerPreAuthenticateAnonymousDownloadFilter extends AbstractHttpControllerAuthenticationFilter { + + /** + * Constructor. + * + * @param tenantConfigurationManagement + * the system management service to retrieve configuration + * properties + * @param tenantAware + * the tenant aware service to get configuration for the specific + * tenant + * @param systemSecurityContext + * the system security context + */ + public HttpControllerPreAuthenticateAnonymousDownloadFilter( + final TenantConfigurationManagement tenantConfigurationManagement, final TenantAware tenantAware, + final SystemSecurityContext systemSecurityContext) { + super(tenantConfigurationManagement, tenantAware, systemSecurityContext); + } + + @Override + protected PreAuthenficationFilter createControllerAuthenticationFilter() { + return new ControllerPreAuthenticatedAnonymousDownload(tenantConfigurationManagement, tenantAware, + systemSecurityContext); + } + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java index 122d7b881..145287fbf 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java @@ -404,7 +404,7 @@ public class ArtifactManagement { * if file could not be found in store */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DOWNLOAD_ARTIFACT + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_CONTROLLER) + + SpringEvalExpressions.HAS_CONTROLLER_DOWNLOAD) public DbArtifact loadLocalArtifactBinary(@NotNull final LocalArtifact artifact) { final DbArtifact result = artifactRepository.getArtifactBySha1(artifact.getGridFsFileName()); if (result == null) { diff --git a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/im/authentication/SpPermission.java b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/im/authentication/SpPermission.java index 5d4ab9283..2e222d879 100644 --- a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/im/authentication/SpPermission.java +++ b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/im/authentication/SpPermission.java @@ -182,6 +182,12 @@ public final class SpPermission { */ public static final String CONTROLLER_ROLE_ANONYMOUS = "ROLE_CONTROLLER_ANONYMOUS"; + /** + * The role which contains in the spring security context in case an + * controller is authenticated to download artifacts. + */ + public static final String CONTROLLER_DOWNLOAD_ROLE = "ROLE_CONTROLLER_DOWNLOAD"; + /** * The role which contains the spring security context in case the * system is executing code which is necessary to be privileged. @@ -275,8 +281,16 @@ public final class SpPermission { * context contains the anoynmous role or the controller specific role * {@link SpPermission#CONTROLLER_ROLE}. */ - public static final String IS_CONTROLLER = "hasAnyRole('" + CONTROLLER_ROLE_ANONYMOUS + "', '" - + CONTROLLER_ROLE + "')"; + public static final String IS_CONTROLLER = "hasAnyRole('" + CONTROLLER_ROLE_ANONYMOUS + "', '" + CONTROLLER_ROLE + + "')"; + + /** + * Spring security eval hasAuthority expression to check if the spring + * context contains the role to allow controllers to download specific + * role {@link SpPermission#CONTROLLER_DOWNLOAD_ROLE}. + */ + public static final String HAS_CONTROLLER_DOWNLOAD = HAS_AUTH_PREFIX + CONTROLLER_DOWNLOAD_ROLE + + HAS_AUTH_SUFFIX; /** * Spring security eval hasAnyRole expression to check if the spring diff --git a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousDownload.java b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousDownload.java new file mode 100644 index 000000000..b4457bfcf --- /dev/null +++ b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousDownload.java @@ -0,0 +1,69 @@ +/** + * 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.Collection; + +import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; +import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; +import org.eclipse.hawkbit.repository.TenantConfigurationManagement; +import org.eclipse.hawkbit.tenancy.TenantAware; +import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; + +import com.google.common.collect.Lists; + +/** + * An pre-authenticated processing filter which add the + * {@link SpringEvalExpressions#CONTROLLER_DOWNLOAD_ROLE_ANONYMOUS} to the + * security context in case the anonymous download is allowed through + * configuration. + */ +public class ControllerPreAuthenticatedAnonymousDownload extends AbstractControllerAuthenticationFilter { + + /** + * Constructor. + * + * @param tenantConfigurationManagement + * the tenant management service to retrieve configuration + * properties + * @param tenantAware + * the tenant aware service to get configuration for the specific + * tenant + * @param systemSecurityContext + * the system security context to get access to tenant + * configuration + */ + public ControllerPreAuthenticatedAnonymousDownload( + final TenantConfigurationManagement tenantConfigurationManagement, final TenantAware tenantAware, + final SystemSecurityContext systemSecurityContext) { + super(tenantConfigurationManagement, tenantAware, systemSecurityContext); + } + + @Override + public HeaderAuthentication getPreAuthenticatedPrincipal(final TenantSecurityToken secruityToken) { + return new HeaderAuthentication(secruityToken.getControllerId(), secruityToken.getControllerId()); + } + + @Override + public HeaderAuthentication getPreAuthenticatedCredentials(final TenantSecurityToken secruityToken) { + return new HeaderAuthentication(secruityToken.getControllerId(), secruityToken.getControllerId()); + } + + @Override + protected TenantConfigurationKey getTenantConfigurationKey() { + return TenantConfigurationKey.ANONYMOUS_DOWNLOAD_MODE_ENABLED; + } + + @Override + public Collection getSuccessfulAuthenticationAuthorities() { + return Lists.newArrayList(new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_DOWNLOAD_ROLE)); + } +} diff --git a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousFilter.java b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousFilter.java new file mode 100644 index 000000000..cf55c47fb --- /dev/null +++ b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousFilter.java @@ -0,0 +1,47 @@ +/** + * 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.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; + +/** + * An anonymous controller filter which is only enabled in case of anonymous + * access is granted. This should only be for development purposes. + * + * @see DdiSecurityProperties + */ +public class ControllerPreAuthenticatedAnonymousFilter implements PreAuthenficationFilter { + + private final DdiSecurityProperties ddiSecurityConfiguration; + + /** + * @param ddiSecurityConfiguration + * the security configuration which holds the configuration if + * anonymous is enabled or not + */ + public ControllerPreAuthenticatedAnonymousFilter(final DdiSecurityProperties ddiSecurityConfiguration) { + this.ddiSecurityConfiguration = ddiSecurityConfiguration; + } + + @Override + public HeaderAuthentication getPreAuthenticatedPrincipal(final TenantSecurityToken secruityToken) { + return new HeaderAuthentication(secruityToken.getControllerId(), secruityToken.getControllerId()); + } + + @Override + public HeaderAuthentication getPreAuthenticatedCredentials(final TenantSecurityToken secruityToken) { + return new HeaderAuthentication(secruityToken.getControllerId(), secruityToken.getControllerId()); + } + + @Override + public boolean isEnable(final TenantSecurityToken secruityToken) { + return ddiSecurityConfiguration.getAuthentication().getAnonymous().isEnabled(); + } + +} diff --git a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProvider.java b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProvider.java index ca38404f7..b81b76e5c 100644 --- a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProvider.java +++ b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProvider.java @@ -109,6 +109,7 @@ public class PreAuthTokenSourceTrustAuthenticationProvider implements Authentica if (successAuthentication) { final Collection controllerAuthorities = new ArrayList<>(); controllerAuthorities.add(new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_ROLE)); + controllerAuthorities.add(new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_DOWNLOAD_ROLE)); final PreAuthenticatedAuthenticationToken successToken = new PreAuthenticatedAuthenticationToken(principal, credentials, controllerAuthorities); successToken.setDetails(tokenDetails); diff --git a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/PreAuthenficationFilter.java b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/PreAuthenficationFilter.java index 8981fa9af..5e4aacfa9 100644 --- a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/PreAuthenficationFilter.java +++ b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/PreAuthenficationFilter.java @@ -8,7 +8,12 @@ */ package org.eclipse.hawkbit.security; +import java.util.Collection; +import java.util.Collections; + import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; /** * Interface for Pre Authenfication. @@ -45,4 +50,16 @@ public interface PreAuthenficationFilter { */ HeaderAuthentication getPreAuthenticatedCredentials(TenantSecurityToken secruityToken); + /** + * Allows to add additional authorities to the successful authenticated + * token. + * + * @return the authorities granted to the principal, or an empty collection + * if the token has not been authenticated. Never null. + * @see Authentication#getAuthorities() + */ + default Collection getSuccessfulAuthenticationAuthorities() { + return Collections.emptyList(); + }; + } From 771516988946924c2a0b6746cc6355b8440b8fc3 Mon Sep 17 00:00:00 2001 From: Jonathan Philip Knoblauch Date: Thu, 24 Mar 2016 11:02:28 +0100 Subject: [PATCH 06/31] Added id for checkbox component for selenium tests Signed-off-by: Jonathan Philip Knoblauch --- .../DownloadAnonymousConfigurationView.java | 3 +++ .../hawkbit/ui/utils/SPUIComponetIdProvider.java | 11 ++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java index fa441476d..e008e03f2 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DownloadAnonymousConfigurationView.java @@ -15,6 +15,7 @@ import org.eclipse.hawkbit.repository.model.TenantConfigurationValue; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.utils.I18N; +import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.springframework.beans.factory.annotation.Autowired; @@ -80,6 +81,8 @@ public class DownloadAnonymousConfigurationView extends BaseConfigurationView downloadAnonymousCheckBox = SPUIComponentProvider.getCheckBox("", DIST_CHECKBOX_STYLE, null, false, ""); downloadAnonymousCheckBox.setValue(anonymousDownloadEnabled); downloadAnonymousCheckBox.addValueChangeListener(event -> configurationHasChanged()); + downloadAnonymousCheckBox.setId(SPUIComponetIdProvider.SYSTEM_CONFIGURATION_ANONYMOUS_DOWNLOAD_CHECKBOX); + gridLayout.addComponent(downloadAnonymousCheckBox); final Label configurationLabel = SPUIComponentProvider.getLabel(i18n.get("enonymous.download.label"), diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIComponetIdProvider.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIComponetIdProvider.java index 163be34c4..48e501e1d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIComponetIdProvider.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIComponetIdProvider.java @@ -501,6 +501,11 @@ public final class SPUIComponetIdProvider { */ public static final String SYSTEM_CONFIGURATION_CANCEL = "system.configuration.cancel"; + /** + * Id of the anonymous download checkbox. + */ + public static final String SYSTEM_CONFIGURATION_ANONYMOUS_DOWNLOAD_CHECKBOX = "system.configuration.anonymous.download.checkbox"; + /** * Id of maximize/minimize icon of table - Software module table. */ @@ -827,7 +832,7 @@ public final class SPUIComponetIdProvider { * Rollout status label id. */ public static final String ROLLOUT_STATUS_LABEL_ID = "rollout.status.id"; - + /** * Rollout group status label id. */ @@ -867,12 +872,12 @@ public final class SPUIComponetIdProvider { * Rollout group targets count message label. */ public static final String ROLLOUT_GROUP_TARGET_LABEL = "rollout.group.target.label"; - + /** * Action confirmation popup id. */ public static final String CONFIRMATION_POPUP_ID = "action.confirmation.popup.id"; - + /** * Validation status icon . */ From e033e8718ceba8bbb35b676fa0935c011b0db425 Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Tue, 29 Mar 2016 11:12:42 +0200 Subject: [PATCH 07/31] unit tests for ControllerPreAuthenticatedAnonymousDownloadTest Signed-off-by: Michael Hirsch --- hawkbit-security-integration/pom.xml | 42 +++++++++---- ...PreAuthenticatedAnonymousDownloadTest.java | 61 +++++++++++++++++++ 2 files changed, 91 insertions(+), 12 deletions(-) create mode 100644 hawkbit-security-integration/src/test/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousDownloadTest.java diff --git a/hawkbit-security-integration/pom.xml b/hawkbit-security-integration/pom.xml index 9d89c1806..591552997 100644 --- a/hawkbit-security-integration/pom.xml +++ b/hawkbit-security-integration/pom.xml @@ -1,13 +1,6 @@ - + 4.0.0 @@ -35,7 +28,32 @@ org.springframework.security spring-security-web + + + + junit + junit + test + + + org.easytesting + fest-assert-core + test + + + org.easytesting + fest-assert + test + + + org.mockito + mockito-core + test + + + ru.yandex.qatools.allure + allure-junit-adaptor + test + - - diff --git a/hawkbit-security-integration/src/test/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousDownloadTest.java b/hawkbit-security-integration/src/test/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousDownloadTest.java new file mode 100644 index 000000000..b8195d023 --- /dev/null +++ b/hawkbit-security-integration/src/test/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousDownloadTest.java @@ -0,0 +1,61 @@ +/** + * 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 static org.fest.assertions.Assertions.assertThat; + +import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; +import org.eclipse.hawkbit.repository.TenantConfigurationManagement; +import org.eclipse.hawkbit.tenancy.TenantAware; +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.security.core.authority.SimpleGrantedAuthority; + +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +/** + * @author Michael Hirsch + * + */ +@Features("Unit Tests - Security") +@Stories("Exclude path aware shallow ETag filter") +@RunWith(MockitoJUnitRunner.class) +public class ControllerPreAuthenticatedAnonymousDownloadTest { + + private ControllerPreAuthenticatedAnonymousDownload underTest; + + @Mock + private TenantConfigurationManagement tenantConfigurationManagementMock; + + @Mock + private TenantAware tenantAwareMock; + + @Before + public void before() { + underTest = new ControllerPreAuthenticatedAnonymousDownload(tenantConfigurationManagementMock, tenantAwareMock, + new SystemSecurityContext(tenantAwareMock)); + } + + @Test + public void useCorrectTenantConfiguationKey() { + assertThat(underTest.getTenantConfigurationKey()).as("Should be using the correct tenant configuration key") + .isEqualTo(underTest.getTenantConfigurationKey()); + } + + @Test + public void successfulAuthenticationAdditionalAuthoritiesForDownload() { + assertThat(underTest.getSuccessfulAuthenticationAuthorities()) + .as("Additional authorities should be containing the download anonymous role") + .contains(new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_DOWNLOAD_ROLE)); + } +} From 4a52936a3c4f2b06ce168925913a3b2a72f5cb50 Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Tue, 29 Mar 2016 15:03:58 +0200 Subject: [PATCH 08/31] allow to set the filename and software module id Signed-off-by: Michael Hirsch --- .../hawkbit/dmf/json/model/TenantSecurityToken.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecurityToken.java b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecurityToken.java index 154ad5158..ccc3a5b42 100644 --- a/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecurityToken.java +++ b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecurityToken.java @@ -186,9 +186,9 @@ public class TenantSecurityToken { @JsonIgnoreProperties(ignoreUnknown = true) public static class SoftwareModuleFilenameResource { @JsonProperty(required = false) - private final Long softwareModuleId; + private Long softwareModuleId; @JsonProperty(required = false) - private final String filename; + private String filename; /** * Constructor. @@ -213,6 +213,14 @@ public class TenantSecurityToken { public String getFilename() { return filename; } + + public void setSoftwareModuleId(final Long softwareModuleId) { + this.softwareModuleId = softwareModuleId; + } + + public void setFilename(final String filename) { + this.filename = filename; + } } } } From b03fa5eec8fe8f5ee48fdc325b80ad9c14a396b9 Mon Sep 17 00:00:00 2001 From: Jonathan Philip Knoblauch Date: Thu, 31 Mar 2016 13:04:21 +0200 Subject: [PATCH 09/31] Verify all download URLs generated by SP-server (e.g. DDI and DMF API) - the get artifact request for the DDI API know contains https links - additional there where http links added - section for creating download urls based on patters was moved to hawkbit-core - tests where adapted and extended Signed-off-by: Jonathan Philip Knoblauch --- .../hawkbit/api}/ArtifactUrlHandler.java | 11 +- .../api}/ArtifactUrlHandlerProperties.java | 112 +----------------- .../api}/PropertyBasedArtifactUrlHandler.java | 28 ++--- .../org/eclipse/hawkbit/api/UrlProtocol.java | 11 ++ hawkbit-dmf-amqp/pom.xml | 5 + .../amqp/AmqpMessageDispatcherService.java | 13 +- .../AmqpMessageDispatcherServiceTest.java | 6 +- .../PropertyBasedArtifactUrlHandlerTest.java | 23 +++- hawkbit-rest-resource/pom.xml | 5 + .../controller/DataConversionHelper.java | 36 +++--- .../hawkbit/controller/RootController.java | 10 +- .../controller/DeploymentBaseTest.java | 74 ++++++++++-- 12 files changed, 167 insertions(+), 167 deletions(-) rename {hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/util => hawkbit-core/src/main/java/org/eclipse/hawkbit/api}/ArtifactUrlHandler.java (73%) rename {hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/util => hawkbit-core/src/main/java/org/eclipse/hawkbit/api}/ArtifactUrlHandlerProperties.java (75%) rename {hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/util => hawkbit-core/src/main/java/org/eclipse/hawkbit/api}/PropertyBasedArtifactUrlHandler.java (79%) create mode 100644 hawkbit-core/src/main/java/org/eclipse/hawkbit/api/UrlProtocol.java diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/util/ArtifactUrlHandler.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/ArtifactUrlHandler.java similarity index 73% rename from hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/util/ArtifactUrlHandler.java rename to hawkbit-core/src/main/java/org/eclipse/hawkbit/api/ArtifactUrlHandler.java index f477da03a..a80551f9e 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/util/ArtifactUrlHandler.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/ArtifactUrlHandler.java @@ -6,10 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.util; - -import org.eclipse.hawkbit.dmf.json.model.Artifact; -import org.eclipse.hawkbit.repository.model.LocalArtifact; +package org.eclipse.hawkbit.api; /** * Interface declaration of the {@link ArtifactUrlHandler} which generates the @@ -23,13 +20,13 @@ public interface ArtifactUrlHandler { * Returns a generated URL for a given artifact for a specific protocol. * * @param controllerId - * the authentifacted controller id + * the authenticated controller id * @param localArtifact * the artifact to retrieve a URL to * @param protocol * the protocol the URL should be generated * @return an URL for the given artifact in a given protocol */ - String getUrl(String controllerId, LocalArtifact localArtifact, final Artifact.UrlProtocol protocol); - + String getUrl(String controllerId, final Long softwareModuleId, final String filename, final String sha1Hash, + final UrlProtocol protocol); } diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/util/ArtifactUrlHandlerProperties.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/ArtifactUrlHandlerProperties.java similarity index 75% rename from hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/util/ArtifactUrlHandlerProperties.java rename to hawkbit-core/src/main/java/org/eclipse/hawkbit/api/ArtifactUrlHandlerProperties.java index 91c385fae..33fe8651e 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/util/ArtifactUrlHandlerProperties.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/ArtifactUrlHandlerProperties.java @@ -6,13 +6,13 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.util; +package org.eclipse.hawkbit.api; import org.springframework.boot.context.properties.ConfigurationProperties; /** - * - * + * Artifact handler properties class for holding all supported protocols with + * host, ip, port and download pattern. */ @ConfigurationProperties("hawkbit.artifact.url") public class ArtifactUrlHandlerProperties { @@ -23,23 +23,14 @@ public class ArtifactUrlHandlerProperties { private final Https https = new Https(); private final Coap coap = new Coap(); - /** - * @return the http - */ public Http getHttp() { return http; } - /** - * @return the https - */ public Https getHttps() { return https; } - /** - * @return the coap - */ public Coap getCoap() { return coap; } @@ -66,9 +57,6 @@ public class ArtifactUrlHandlerProperties { /** * Interface for declaring common properties through all supported protocols * pattern. - * - * - * */ public interface ProtocolProperties { /** @@ -94,9 +82,6 @@ public class ArtifactUrlHandlerProperties { /** * Object to hold the properties for the HTTP protocol. - * - * - * */ public static class Http implements ProtocolProperties { private String hostname = LOCALHOST; @@ -108,66 +93,38 @@ public class ArtifactUrlHandlerProperties { */ private String pattern = "{protocol}://{hostname}:{port}/{tenant}/controller/v1/{targetId}/softwaremodules/{softwareModuleId}/artifacts/{artifactFileName}"; - /** - * @return the hostname - */ @Override public String getHostname() { return hostname; } - /** - * @param hostname - * the hostname to set - */ public void setHostname(final String hostname) { this.hostname = hostname; } - /** - * @return the ip - */ @Override public String getIp() { return ip; } - /** - * @param ip - * the ip to set - */ public void setIp(final String ip) { this.ip = ip; } - /** - * @return the urlPattern - */ @Override public String getPattern() { return pattern; } - /** - * @param urlPattern - * the urlPattern to set - */ public void setPattern(final String urlPattern) { this.pattern = urlPattern; } - /** - * @return the port - */ @Override public String getPort() { return port; } - /** - * @param port - * the port to set - */ public void setPort(final String port) { this.port = port; } @@ -175,9 +132,6 @@ public class ArtifactUrlHandlerProperties { /** * Object to hold the properties for the HTTP protocol. - * - * - * */ public static class Https implements ProtocolProperties { private String hostname = LOCALHOST; @@ -189,66 +143,38 @@ public class ArtifactUrlHandlerProperties { */ private String pattern = "{protocol}://{hostname}:{port}/{tenant}/controller/v1/{targetId}/softwaremodules/{softwareModuleId}/artifacts/{artifactFileName}"; - /** - * @return the hostname - */ @Override public String getHostname() { return hostname; } - /** - * @param hostname - * the hostname to set - */ public void setHostname(final String hostname) { this.hostname = hostname; } - /** - * @return the ip - */ @Override public String getIp() { return ip; } - /** - * @param ip - * the ip to set - */ public void setIp(final String ip) { this.ip = ip; } - /** - * @return the urlPattern - */ @Override public String getPattern() { return pattern; } - /** - * @param urlPattern - * the urlPattern to set - */ public void setPattern(final String urlPattern) { this.pattern = urlPattern; } - /** - * @return the port - */ @Override public String getPort() { return port; } - /** - * @param port - * the port to set - */ public void setPort(final String port) { this.port = port; } @@ -256,9 +182,6 @@ public class ArtifactUrlHandlerProperties { /** * Object to hold the properties for the HTTP protocol. - * - * - * */ public static class Coap implements ProtocolProperties { private String hostname = LOCALHOST; @@ -270,68 +193,41 @@ public class ArtifactUrlHandlerProperties { */ private String pattern = "{protocol}://{ip}:{port}/fw/{tenant}/{targetId}/sha1/{artifactSHA1}"; - /** - * @return the hostname - */ @Override public String getHostname() { return hostname; } - /** - * @param hostname - * the hostname to set - */ public void setHostname(final String hostname) { this.hostname = hostname; } - /** - * @return the ip - */ @Override public String getIp() { return ip; } - /** - * @param ip - * the ip to set - */ public void setIp(final String ip) { this.ip = ip; } - /** - * @return the urlPattern - */ @Override public String getPattern() { return pattern; } - /** - * @param urlPattern - * the urlPattern to set - */ public void setPattern(final String urlPattern) { this.pattern = urlPattern; } - /** - * @return the port - */ @Override public String getPort() { return port; } - /** - * @param port - * the port to set - */ public void setPort(final String port) { this.port = port; } } + } diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/util/PropertyBasedArtifactUrlHandler.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/PropertyBasedArtifactUrlHandler.java similarity index 79% rename from hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/util/PropertyBasedArtifactUrlHandler.java rename to hawkbit-core/src/main/java/org/eclipse/hawkbit/api/PropertyBasedArtifactUrlHandler.java index 8d4cfbc28..174086613 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/util/PropertyBasedArtifactUrlHandler.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/PropertyBasedArtifactUrlHandler.java @@ -6,17 +6,15 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.util; +package org.eclipse.hawkbit.api; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import org.eclipse.hawkbit.dmf.json.model.Artifact; -import org.eclipse.hawkbit.repository.model.LocalArtifact; +import org.eclipse.hawkbit.api.ArtifactUrlHandlerProperties.ProtocolProperties; import org.eclipse.hawkbit.tenancy.TenantAware; -import org.eclipse.hawkbit.util.ArtifactUrlHandlerProperties.ProtocolProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.stereotype.Component; @@ -24,8 +22,8 @@ import org.springframework.stereotype.Component; import com.google.common.base.Strings; /** - * - * + * Implementation for ArtifactUrlHandler for creating urls to download resource + * based on pattern. */ @Component @EnableConfigurationProperties(ArtifactUrlHandlerProperties.class) @@ -48,7 +46,9 @@ public class PropertyBasedArtifactUrlHandler implements ArtifactUrlHandler { private TenantAware tenantAware; @Override - public String getUrl(final String targetId, final LocalArtifact artifact, final Artifact.UrlProtocol protocol) { + public String getUrl(final String targetId, final Long softwareModuleId, final String filename, + final String sha1Hash, final UrlProtocol protocol) { + final String protocolString = protocol.name().toLowerCase(); final ProtocolProperties properties = urlHandlerProperties.getProperties(protocolString); if (properties == null || properties.getPattern() == null) { @@ -56,8 +56,8 @@ public class PropertyBasedArtifactUrlHandler implements ArtifactUrlHandler { } String urlPattern = properties.getPattern(); - final Set> entrySet = getReplaceMap(targetId, artifact, protocolString, properties) - .entrySet(); + final Set> entrySet = getReplaceMap(targetId, softwareModuleId, filename, sha1Hash, + protocolString, properties).entrySet(); for (final Entry entry : entrySet) { if (entry.getKey().equals(PORT_PLACEHOLDER)) { urlPattern = urlPattern.replace(":{" + entry.getKey() + "}", @@ -69,18 +69,18 @@ public class PropertyBasedArtifactUrlHandler implements ArtifactUrlHandler { return urlPattern; } - private Map getReplaceMap(final String targetId, final LocalArtifact artifact, - final String protocol, final ProtocolProperties properties) { + private Map getReplaceMap(final String targetId, final Long softwareModuleId, final String filename, + final String sha1Hash, final String protocol, final ProtocolProperties properties) { final Map replaceMap = new HashMap<>(); replaceMap.put(IP_PLACEHOLDER, properties.getIp()); replaceMap.put(HOSTNAME_PLACEHOLDER, properties.getHostname()); - replaceMap.put(ARTIFACT_FILENAME_PLACEHOLDER, artifact.getFilename()); - replaceMap.put(ARTIFACT_SHA1_PLACEHOLDER, artifact.getSha1Hash()); + replaceMap.put(ARTIFACT_FILENAME_PLACEHOLDER, filename); + replaceMap.put(ARTIFACT_SHA1_PLACEHOLDER, sha1Hash); replaceMap.put(PROTOCOL_PLACEHOLDER, protocol); replaceMap.put(PORT_PLACEHOLDER, properties.getPort()); replaceMap.put(TENANT_PLACEHOLDER, tenantAware.getCurrentTenant()); replaceMap.put(TARGET_ID_PLACEHOLDER, targetId); - replaceMap.put(SOFTWARE_MODULE_ID_PLACDEHOLDER, String.valueOf(artifact.getSoftwareModule().getId())); + replaceMap.put(SOFTWARE_MODULE_ID_PLACDEHOLDER, String.valueOf(softwareModuleId)); return replaceMap; } diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/UrlProtocol.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/UrlProtocol.java new file mode 100644 index 000000000..4dd84b7da --- /dev/null +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/UrlProtocol.java @@ -0,0 +1,11 @@ +/** + * Copyright (c) 2011-2016 Bosch Software Innovations GmbH, Germany. All rights reserved. + */ +package org.eclipse.hawkbit.api; + +/** + * Represented the supported protocols for artifact url's. + */ +public enum UrlProtocol { + COAP, HTTP, HTTPS +} diff --git a/hawkbit-dmf-amqp/pom.xml b/hawkbit-dmf-amqp/pom.xml index 2fded8559..127103b91 100644 --- a/hawkbit-dmf-amqp/pom.xml +++ b/hawkbit-dmf-amqp/pom.xml @@ -25,6 +25,11 @@ org.eclipse.hawkbit hawkbit-repository ${project.version} + + + org.eclipse.hawkbit + hawkbit-core + ${project.version} org.eclipse.hawkbit 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 b9e6fe9da..19e0cbadf 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 @@ -14,6 +14,8 @@ import java.util.Collections; import java.util.List; import java.util.stream.Collectors; +import org.eclipse.hawkbit.api.ArtifactUrlHandler; +import org.eclipse.hawkbit.api.UrlProtocol; import org.eclipse.hawkbit.dmf.amqp.api.EventTopic; import org.eclipse.hawkbit.dmf.amqp.api.MessageHeaderKey; import org.eclipse.hawkbit.dmf.amqp.api.MessageType; @@ -25,7 +27,6 @@ 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.util.ArtifactUrlHandler; import org.eclipse.hawkbit.util.IpUtil; import org.springframework.amqp.core.Message; import org.springframework.amqp.core.MessageProperties; @@ -152,12 +153,16 @@ public class AmqpMessageDispatcherService extends BaseAmqpService { private Artifact convertArtifact(final String targetId, final LocalArtifact localArtifact) { final Artifact artifact = new Artifact(); + artifact.getUrls().put(Artifact.UrlProtocol.COAP, - artifactUrlHandler.getUrl(targetId, localArtifact, Artifact.UrlProtocol.COAP)); + artifactUrlHandler.getUrl(targetId, localArtifact.getSoftwareModule().getId(), + localArtifact.getFilename(), localArtifact.getSha1Hash(), UrlProtocol.COAP)); artifact.getUrls().put(Artifact.UrlProtocol.HTTP, - artifactUrlHandler.getUrl(targetId, localArtifact, Artifact.UrlProtocol.HTTP)); + artifactUrlHandler.getUrl(targetId, localArtifact.getSoftwareModule().getId(), + localArtifact.getFilename(), localArtifact.getSha1Hash(), UrlProtocol.HTTP)); artifact.getUrls().put(Artifact.UrlProtocol.HTTPS, - artifactUrlHandler.getUrl(targetId, localArtifact, Artifact.UrlProtocol.HTTPS)); + artifactUrlHandler.getUrl(targetId, localArtifact.getSoftwareModule().getId(), + localArtifact.getFilename(), localArtifact.getSha1Hash(), UrlProtocol.HTTPS)); artifact.setFilename(localArtifact.getFilename()); artifact.setHashes(new ArtifactHash(localArtifact.getSha1Hash(), null)); 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 46ddd35cc..f2c3d254c 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 @@ -13,6 +13,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; @@ -25,6 +26,7 @@ import java.util.List; import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB; import org.eclipse.hawkbit.TestDataUtil; +import org.eclipse.hawkbit.api.ArtifactUrlHandler; import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; import org.eclipse.hawkbit.dmf.amqp.api.EventTopic; import org.eclipse.hawkbit.dmf.amqp.api.MessageHeaderKey; @@ -36,7 +38,6 @@ import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.eclipse.hawkbit.repository.model.SoftwareModule; -import org.eclipse.hawkbit.util.ArtifactUrlHandler; import org.eclipse.hawkbit.util.IpUtil; import org.junit.Test; import org.mockito.ArgumentCaptor; @@ -77,7 +78,8 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit amqpMessageDispatcherService.setAmqpSenderService(senderService); final ArtifactUrlHandler artifactUrlHandlerMock = Mockito.mock(ArtifactUrlHandler.class); - when(artifactUrlHandlerMock.getUrl(anyString(), any(), anyObject())).thenReturn("http://mockurl"); + when(artifactUrlHandlerMock.getUrl(anyString(), anyLong(), anyString(), anyString(), anyObject())) + .thenReturn("http://mockurl"); amqpMessageDispatcherService.setArtifactUrlHandler(artifactUrlHandlerMock); 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 e7ba06d19..bfc560c38 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 @@ -15,7 +15,8 @@ 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.api.ArtifactUrlHandler; +import org.eclipse.hawkbit.api.UrlProtocol; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.eclipse.hawkbit.repository.model.SoftwareModule; @@ -30,8 +31,7 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; /** - * - * + * Tests for creating urls to download artifacts. */ @Features("Component Tests - Artifact URL Handler") @Stories("Test to generate the artifact download URL") @@ -45,6 +45,9 @@ public class PropertyBasedArtifactUrlHandlerTest extends AbstractIntegrationTest private TenantAware tenantAware; private LocalArtifact localArtifact; private final String controllerId = "Test"; + private String fileName; + private Long softwareModuleId; + private String sha1Hash; @Before public void setup() { @@ -53,12 +56,18 @@ public class PropertyBasedArtifactUrlHandlerTest extends AbstractIntegrationTest final SoftwareModule module = dsA.getModules().iterator().next(); localArtifact = (LocalArtifact) TestDataUtil.generateArtifacts(artifactManagement, module.getId()).stream() .findAny().get(); + softwareModuleId = localArtifact.getSoftwareModule().getId(); + fileName = localArtifact.getFilename(); + sha1Hash = localArtifact.getSha1Hash(); + } @Test @Description("Tests the generation of http download url.") public void testHttpUrl() { - final String url = urlHandlerProperties.getUrl(controllerId, localArtifact, Artifact.UrlProtocol.HTTP); + + final String url = urlHandlerProperties.getUrl(controllerId, softwareModuleId, fileName, sha1Hash, + UrlProtocol.HTTP); assertEquals("http is build incorrect", "http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/" + controllerId + "/softwaremodules/" + localArtifact.getSoftwareModule().getId() + "/artifacts/" @@ -69,7 +78,8 @@ public class PropertyBasedArtifactUrlHandlerTest extends AbstractIntegrationTest @Test @Description("Tests the generation of https download url.") public void testHttpsUrl() { - final String url = urlHandlerProperties.getUrl(controllerId, localArtifact, Artifact.UrlProtocol.HTTPS); + final String url = urlHandlerProperties.getUrl(controllerId, softwareModuleId, fileName, sha1Hash, + UrlProtocol.HTTPS); assertEquals("https is build incorrect", "https://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/" + controllerId + "/softwaremodules/" + localArtifact.getSoftwareModule().getId() + "/artifacts/" @@ -80,7 +90,8 @@ public class PropertyBasedArtifactUrlHandlerTest extends AbstractIntegrationTest @Test @Description("Tests the generation of coap download url.") public void testCoapUrl() { - final String url = urlHandlerProperties.getUrl(controllerId, localArtifact, Artifact.UrlProtocol.COAP); + final String url = urlHandlerProperties.getUrl(controllerId, softwareModuleId, fileName, sha1Hash, + UrlProtocol.COAP); assertEquals("coap is build incorrect", "coap://127.0.0.1:5683/fw/" + tenantAware.getCurrentTenant() + "/" + controllerId + "/sha1/" + localArtifact.getSha1Hash(), url); diff --git a/hawkbit-rest-resource/pom.xml b/hawkbit-rest-resource/pom.xml index 633a1f8cc..0be5d20f5 100644 --- a/hawkbit-rest-resource/pom.xml +++ b/hawkbit-rest-resource/pom.xml @@ -25,6 +25,11 @@ org.eclipse.hawkbit hawkbit-repository ${project.version} + + + org.eclipse.hawkbit + hawkbit-core + ${project.version} org.eclipse.hawkbit diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/DataConversionHelper.java b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/DataConversionHelper.java index ef4468815..03623abdd 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/DataConversionHelper.java +++ b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/DataConversionHelper.java @@ -18,6 +18,8 @@ import java.util.stream.Collectors; import javax.servlet.http.HttpServletResponse; +import org.eclipse.hawkbit.api.ArtifactUrlHandler; +import org.eclipse.hawkbit.api.UrlProtocol; import org.eclipse.hawkbit.controller.model.Artifact; import org.eclipse.hawkbit.controller.model.Chunk; import org.eclipse.hawkbit.controller.model.Config; @@ -29,27 +31,29 @@ import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.rest.resource.model.artifact.ArtifactHash; import org.eclipse.hawkbit.tenancy.TenantAware; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.hateoas.Link; import com.google.common.base.Charsets; /** * Utility class for the Controller API. - * - * - * - * */ public final class DataConversionHelper { + @Autowired + ArtifactUrlHandler artifactUrlHandler; + // utility class, private constructor. private DataConversionHelper() { } - static List createChunks(final String targetid, final Action uAction, final TenantAware tenantAware) { - return uAction.getDistributionSet() - .getModules().stream().map(module -> new Chunk(mapChunkLegacyKeys(module.getType().getKey()), - module.getVersion(), module.getName(), createArtifacts(targetid, module, tenantAware))) + static List createChunks(final String targetid, final Action uAction, final TenantAware tenantAware, + final ArtifactUrlHandler artifactUrlHandler) { + return uAction.getDistributionSet().getModules().stream() + .map(module -> new Chunk(mapChunkLegacyKeys(module.getType().getKey()), module.getVersion(), + module.getName(), createArtifacts(targetid, module, tenantAware, artifactUrlHandler))) .collect(Collectors.toList()); } @@ -77,18 +81,22 @@ public final class DataConversionHelper { * @return a list of artifacts or a empty list. Cannot be . */ public static List createArtifacts(final String targetid, - final org.eclipse.hawkbit.repository.model.SoftwareModule module, final TenantAware tenantAware) { + final org.eclipse.hawkbit.repository.model.SoftwareModule module, final TenantAware tenantAware, + final ArtifactUrlHandler artifactUrlHandler) { final List files = new ArrayList<>(); module.getLocalArtifacts().forEach(artifact -> { final Artifact file = new Artifact(); file.setHashes(new ArtifactHash(artifact.getSha1Hash(), artifact.getMd5Hash())); file.setFilename(artifact.getFilename()); file.setSize(artifact.getSize()); - - file.add(linkTo(methodOn(RootController.class, tenantAware.getCurrentTenant()).downloadArtifact(targetid, - artifact.getSoftwareModule().getId(), artifact.getFilename(), null, null)).withRel("download")); - file.add(linkTo(methodOn(RootController.class, tenantAware.getCurrentTenant()).downloadArtifactMd5(targetid, - artifact.getSoftwareModule().getId(), artifact.getFilename(), null, null)).withRel("md5sum")); + final String linkHttp = artifactUrlHandler.getUrl(targetid, artifact.getSoftwareModule().getId(), + artifact.getFilename(), artifact.getSha1Hash(), UrlProtocol.HTTP); + final String linkHttps = artifactUrlHandler.getUrl(targetid, artifact.getSoftwareModule().getId(), + artifact.getFilename(), artifact.getSha1Hash(), UrlProtocol.HTTPS); + file.add(new Link(linkHttps).withRel("download")); + file.add(new Link(linkHttps + ".MD5SUM").withRel("md5sum")); + file.add(new Link(linkHttp).withRel("download-http")); + file.add(new Link(linkHttp + ".MD5SUM").withRel("md5sum-http")); files.add(file); }); 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 ff1e26f8b..0a668338c 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 @@ -15,6 +15,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; +import org.eclipse.hawkbit.api.ArtifactUrlHandler; import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; import org.eclipse.hawkbit.cache.CacheWriteNotify; import org.eclipse.hawkbit.controller.model.ActionFeedback; @@ -94,6 +95,9 @@ public class RootController { @Autowired private HawkbitSecurityProperties securityProperties; + @Autowired + private ArtifactUrlHandler artifactUrlHandler; + /** * Returns all artifacts of a given software module and target. * @@ -118,7 +122,8 @@ public class RootController { } - return new ResponseEntity<>(DataConversionHelper.createArtifacts(targetid, softwareModule, tenantAware), + return new ResponseEntity<>( + DataConversionHelper.createArtifacts(targetid, softwareModule, tenantAware, artifactUrlHandler), HttpStatus.OK); } @@ -307,7 +312,8 @@ public class RootController { if (!action.isCancelingOrCanceled()) { - final List chunks = DataConversionHelper.createChunks(targetid, action, tenantAware); + final List chunks = DataConversionHelper.createChunks(targetid, action, tenantAware, + artifactUrlHandler); final HandlingType handlingType = action.isForce() ? HandlingType.FORCED : HandlingType.ATTEMPT; 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 2b2b7e597..75e0f906a 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 @@ -170,15 +170,27 @@ public class DeploymentBaseTest extends AbstractIntegrationTestWithMongoDB { jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].hashes.sha1", equalTo(artifact.getSha1Hash()))) .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.download.href", - equalTo("http://localhost/" + tenantAware.getCurrentTenant() + equalTo("https://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).getId() + "/artifacts/test1"))) .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.md5sum.href", + equalTo("https://localhost/" + tenantAware.getCurrentTenant() + + "/controller/v1/4712/softwaremodules/" + + findDistributionSetByAction.findFirstModuleByType(osType).getId() + + "/artifacts/test1.MD5SUM"))) + + .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.download-http.href", + equalTo("http://localhost/" + tenantAware.getCurrentTenant() + + "/controller/v1/4712/softwaremodules/" + + findDistributionSetByAction.findFirstModuleByType(osType).getId() + + "/artifacts/test1"))) + .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.md5sum-http.href", equalTo("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).getId() + "/artifacts/test1.MD5SUM"))) + .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].size", equalTo(5 * 1024))) .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].filename", equalTo("test1.signature"))) @@ -188,11 +200,21 @@ public class DeploymentBaseTest extends AbstractIntegrationTestWithMongoDB { jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].hashes.sha1", equalTo(artifactSignature.getSha1Hash()))) .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.download.href", - equalTo("http://localhost/" + tenantAware.getCurrentTenant() + equalTo("https://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).getId() + "/artifacts/test1.signature"))) .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.md5sum.href", + equalTo("https://localhost/" + tenantAware.getCurrentTenant() + + "/controller/v1/4712/softwaremodules/" + + findDistributionSetByAction.findFirstModuleByType(osType).getId() + + "/artifacts/test1.signature.MD5SUM"))) + .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.download-http.href", + equalTo("http://localhost/" + tenantAware.getCurrentTenant() + + "/controller/v1/4712/softwaremodules/" + + findDistributionSetByAction.findFirstModuleByType(osType).getId() + + "/artifacts/test1.signature"))) + .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.md5sum-http.href", equalTo("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).getId() @@ -293,12 +315,12 @@ public class DeploymentBaseTest extends AbstractIntegrationTestWithMongoDB { jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].hashes.sha1", equalTo(artifact.getSha1Hash()))) .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.download.href", - equalTo("http://localhost/" + tenantAware.getCurrentTenant() + equalTo("https://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).getId() + "/artifacts/test1"))) .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.md5sum.href", - equalTo("http://localhost/" + tenantAware.getCurrentTenant() + equalTo("https://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).getId() + "/artifacts/test1.MD5SUM"))) @@ -311,11 +333,21 @@ public class DeploymentBaseTest extends AbstractIntegrationTestWithMongoDB { jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].hashes.sha1", equalTo(artifactSignature.getSha1Hash()))) .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.download.href", - equalTo("http://localhost/" + tenantAware.getCurrentTenant() + equalTo("https://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).getId() + "/artifacts/test1.signature"))) .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.md5sum.href", + equalTo("https://localhost/" + tenantAware.getCurrentTenant() + + "/controller/v1/4712/softwaremodules/" + + findDistributionSetByAction.findFirstModuleByType(osType).getId() + + "/artifacts/test1.signature.MD5SUM"))) + .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.download-http.href", + equalTo("http://localhost/" + tenantAware.getCurrentTenant() + + "/controller/v1/4712/softwaremodules/" + + findDistributionSetByAction.findFirstModuleByType(osType).getId() + + "/artifacts/test1.signature"))) + .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.md5sum-http.href", equalTo("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).getId() @@ -409,15 +441,25 @@ public class DeploymentBaseTest extends AbstractIntegrationTestWithMongoDB { .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].filename", equalTo("test1"))) .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].hashes.md5", equalTo(artifact.getMd5Hash()))) - .andExpect( - jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].hashes.sha1", - equalTo(artifact.getSha1Hash()))) + .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].hashes.sha1", + equalTo(artifact.getSha1Hash()))) + .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.download.href", - equalTo("http://localhost/" + tenantAware.getCurrentTenant() + equalTo("https://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).getId() + "/artifacts/test1"))) .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.md5sum.href", + equalTo("https://localhost/" + tenantAware.getCurrentTenant() + + "/controller/v1/4712/softwaremodules/" + + findDistributionSetByAction.findFirstModuleByType(osType).getId() + + "/artifacts/test1.MD5SUM"))) + .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.download-http.href", + equalTo("http://localhost/" + tenantAware.getCurrentTenant() + + "/controller/v1/4712/softwaremodules/" + + findDistributionSetByAction.findFirstModuleByType(osType).getId() + + "/artifacts/test1"))) + .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.md5sum-http.href", equalTo("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).getId() @@ -431,15 +473,27 @@ public class DeploymentBaseTest extends AbstractIntegrationTestWithMongoDB { jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].hashes.sha1", equalTo(artifactSignature.getSha1Hash()))) .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.download.href", - equalTo("http://localhost/" + tenantAware.getCurrentTenant() + equalTo("https://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).getId() + "/artifacts/test1.signature"))) .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.md5sum.href", + equalTo("https://localhost/" + tenantAware.getCurrentTenant() + + "/controller/v1/4712/softwaremodules/" + + findDistributionSetByAction.findFirstModuleByType(osType).getId() + + "/artifacts/test1.signature.MD5SUM"))) + + .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.download-http.href", + equalTo("http://localhost/" + tenantAware.getCurrentTenant() + + "/controller/v1/4712/softwaremodules/" + + findDistributionSetByAction.findFirstModuleByType(osType).getId() + + "/artifacts/test1.signature"))) + .andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.md5sum-http.href", equalTo("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/" + findDistributionSetByAction.findFirstModuleByType(osType).getId() + "/artifacts/test1.signature.MD5SUM"))) + .andExpect(jsonPath("$deployment.chunks[?(@.part==bApp)][0].version", equalTo(ds.findFirstModuleByType(appType).getVersion()))) .andExpect(jsonPath("$deployment.chunks[?(@.part==bApp)][0].name", From 1d416327d69380ffd48fe8b25a969f1b0f9c9b1e Mon Sep 17 00:00:00 2001 From: Jonathan Philip Knoblauch Date: Thu, 31 Mar 2016 15:08:20 +0200 Subject: [PATCH 10/31] Sonar fix moving private methods to inner classes - Rule: "private" methods called only by inner classes should be moved to those classes Signed-off-by: Jonathan Philip Knoblauch --- .../ui/artifacts/upload/UploadLayout.java | 31 ++- .../common/tagdetails/AbstractTagToken.java | 34 +-- .../targettable/BulkUploadHandler.java | 213 ++++++++---------- .../ui/rollout/rollout/RolloutListGrid.java | 53 ++--- .../rolloutgroup/RolloutGroupListGrid.java | 24 +- .../RolloutGroupTargetsListGrid.java | 63 +++--- .../polling/DurationConfigField.java | 12 +- 7 files changed, 199 insertions(+), 231 deletions(-) diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadLayout.java index 41304ddc9..3fb735284 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadLayout.java @@ -215,13 +215,18 @@ public class UploadLayout extends VerticalLayout { hasDirectory = Boolean.TRUE; } } - } - private static boolean isDirectory(final Html5File file) { - if (Strings.isNullOrEmpty(file.getType()) && file.getFileSize() % 4096 == 0) { - return true; + private StreamVariable createStreamVariable(final Html5File file) { + return new UploadHandler(file.getFileName(), file.getFileSize(), UploadLayout.this, uploadInfoWindow, + spInfo.getMaxArtifactFileSize(), null, file.getType()); + } + + private boolean isDirectory(final Html5File file) { + if (Strings.isNullOrEmpty(file.getType()) && file.getFileSize() % 4096 == 0) { + return true; + } + return false; } - return false; } private void displayCompositeMessage() { @@ -282,11 +287,6 @@ public class UploadLayout extends VerticalLayout { discardBtn.addClickListener(event -> discardUploadData(event)); } - private StreamVariable createStreamVariable(final Html5File file) { - return new UploadHandler(file.getFileName(), file.getFileSize(), this, uploadInfoWindow, - spInfo.getMaxArtifactFileSize(), null, file.getType()); - } - boolean checkForDuplicate(final String filename) { final Boolean isDuplicate = checkIfFileIsDuplicate(filename); if (isDuplicate) { @@ -349,17 +349,17 @@ public class UploadLayout extends VerticalLayout { } } - Boolean validate(DragAndDropEvent event) { + Boolean validate(final DragAndDropEvent event) { // check if drop is valid.If valid ,check if software module is // selected. - if(!isFilesDropped(event)){ + if (!isFilesDropped(event)) { uiNotification.displayValidationError(i18n.get("message.action.not.allowed")); return false; } return checkIfSoftwareModuleIsSelected(); } - private boolean isFilesDropped(DragAndDropEvent event) { + private boolean isFilesDropped(final DragAndDropEvent event) { if (event.getTransferable() instanceof WrapperTransferable) { final Html5File[] files = ((WrapperTransferable) event.getTransferable()).getFiles(); // other components can also be wrapped in WrapperTransferable , so @@ -448,7 +448,7 @@ public class UploadLayout extends VerticalLayout { } private String getDuplicateFileValidationMessage() { - StringBuilder message = new StringBuilder(); + final StringBuilder message = new StringBuilder(); if (!duplicateFileNamesList.isEmpty()) { final String fileNames = StringUtils.collectionToCommaDelimitedString(duplicateFileNamesList); if (duplicateFileNamesList.size() == 1) { @@ -655,8 +655,7 @@ public class UploadLayout extends VerticalLayout { return uiNotification; } - - public void setHasDirectory(Boolean hasDirectory) { + public void setHasDirectory(final Boolean hasDirectory) { this.hasDirectory = hasDirectory; } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/AbstractTagToken.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/AbstractTagToken.java index a00b8ce70..5e5389c9f 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/AbstractTagToken.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/AbstractTagToken.java @@ -151,18 +151,25 @@ public abstract class AbstractTagToken implements Serializable { } } - } + private void updateTokenStyle(final Object tokenId, final Button button) { + final String color = getColor(tokenId); + button.setCaption("" + FontAwesome.CIRCLE.getHtml() + + "" + " " + getItemNameProperty(tokenId).getValue().toString().concat(" ×")); + button.setCaptionAsHtml(true); + } - private void updateTokenStyle(final Object tokenId, final Button button) { - final String color = getColor(tokenId); - button.setCaption("" + FontAwesome.CIRCLE.getHtml() + "" - + " " + getItemNameProperty(tokenId).getValue().toString().concat(" ×")); - button.setCaptionAsHtml(true); - } + private void onTokenSearch(final Object tokenId) { + assignTag(getItemNameProperty(tokenId).getValue().toString()); + removeTagAssignedFromCombo((Long) tokenId); + } + + private void tokenClick(final Object tokenId) { + final Item item = tokenField.getContainerDataSource().addItem(tokenId); + item.getItemProperty("name").setValue(tagDetails.get(tokenId).getName()); + item.getItemProperty(COLOR_PROPERTY).setValue(tagDetails.get(tokenId).getColor()); + unassignTag(tagDetails.get(tokenId).getName()); + } - private void onTokenSearch(final Object tokenId) { - assignTag(getItemNameProperty(tokenId).getValue().toString()); - removeTagAssignedFromCombo((Long) tokenId); } private Property getItemNameProperty(final Object tokenId) { @@ -184,13 +191,6 @@ public abstract class AbstractTagToken implements Serializable { return (String) item.getItemProperty("name").getValue(); } - private void tokenClick(final Object tokenId) { - final Item item = tokenField.getContainerDataSource().addItem(tokenId); - item.getItemProperty("name").setValue(tagDetails.get(tokenId).getName()); - item.getItemProperty(COLOR_PROPERTY).setValue(tagDetails.get(tokenId).getColor()); - unassignTag(tagDetails.get(tokenId).getName()); - } - protected void removePreviouslyAddedTokens() { tokensAdded.keySet().forEach(previouslyAddedToken -> tokenField.removeToken(previouslyAddedToken)); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java index 0716e6bd6..1a388c324 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java @@ -63,14 +63,10 @@ import com.vaadin.ui.Upload.SucceededListener; /** * Bulk target upload handler. - * */ public class BulkUploadHandler extends CustomComponent implements SucceededListener, FailedListener, Receiver, StartedListener { - /** - * - */ private static final long serialVersionUID = -1273494705754674501L; private static final Logger LOG = LoggerFactory.getLogger(BulkUploadHandler.class); @@ -149,12 +145,6 @@ public class BulkUploadHandler extends CustomComponent setCompositionRoot(horizontalLayout); } - /* - * (non-Javadoc) - * - * @see com.vaadin.ui.Upload.Receiver#receiveUpload(java.lang.String, - * java.lang.String) - */ @Override public OutputStream receiveUpload(final String filename, final String mimeType) { try { @@ -170,25 +160,11 @@ public class BulkUploadHandler extends CustomComponent return new NullOutputStream(); } - /* - * (non-Javadoc) - * - * @see - * com.vaadin.ui.Upload.FailedListener#uploadFailed(com.vaadin.ui.Upload. - * FailedEvent) - */ @Override public void uploadFailed(final FailedEvent event) { LOG.info("Upload failed for file :{} due to {}", event.getFilename(), event.getReason()); } - /* - * (non-Javadoc) - * - * @see - * com.vaadin.ui.Upload.SucceededListener#uploadSucceeded(com.vaadin.ui. - * Upload.SucceededEvent) - */ @Override public void uploadSucceeded(final SucceededEvent event) { executor.execute(new UploadAsync(event)); @@ -252,6 +228,61 @@ public class BulkUploadHandler extends CustomComponent } } + private double getTotalNumberOfLines() { + + double totalFileSize = 0; + try (InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(tempFile), + Charset.defaultCharset())) { + try (BufferedReader readerForSize = new BufferedReader(inputStreamReader)) { + totalFileSize = readerForSize.lines().count(); + } + } catch (final FileNotFoundException e) { + LOG.error("Error reading file {}", tempFile.getName(), e); + } catch (final IOException e) { + LOG.error("Error while closing reader of file {}", tempFile.getName(), e); + } + + return totalFileSize; + } + + private void resetCounts() { + successfullTargetCount = 0; + failedTargetCount = 0; + } + + private void deleteFile() { + if (tempFile.exists()) { + final boolean isDeleted = tempFile.delete(); + if (!isDeleted) { + LOG.info("File {} was not deleted !", tempFile.getName()); + } + } + tempFile = null; + } + + private void readEachLine(final String line, final double innerCounter, final double totalFileSize) { + final String csvDelimiter = ","; + final String[] targets = line.split(csvDelimiter); + if (targets.length == 2) { + final String controllerId = targets[0]; + final String targetName = targets[1]; + addNewTarget(controllerId, targetName); + } else { + failedTargetCount++; + } + final float current = managementUIState.getTargetTableFilters().getBulkUpload() + .getProgressBarCurrentValue(); + final float next = (float) (innerCounter / totalFileSize); + if (Math.abs(next - 0.1) < 0.00001 || current - next >= 0 || next - current >= 0.05 + || Math.abs(next - 1) < 0.00001) { + managementUIState.getTargetTableFilters().getBulkUpload().setProgressBarCurrentValue(next); + managementUIState.getTargetTableFilters().getBulkUpload() + .setSucessfulUploadCount(successfullTargetCount); + managementUIState.getTargetTableFilters().getBulkUpload().setFailedUploadCount(failedTargetCount); + eventBus.publish(this, new TargetTableEvent(TargetComponentEvent.BULK_TARGET_CREATED)); + } + } + private void doAssignments() { final StringBuilder errorMessage = new StringBuilder(); String dsAssignmentFailedMsg = null; @@ -267,6 +298,43 @@ public class BulkUploadHandler extends CustomComponent displayValidationMessage(errorMessage, dsAssignmentFailedMsg, tagAssignmentFailedMsg); } + private String saveAllAssignments() { + final ActionType actionType = ActionType.FORCED; + final long forcedTimeStamp = new Date().getTime(); + final TargetBulkUpload targetBulkUpload = managementUIState.getTargetTableFilters().getBulkUpload(); + final List targetsList = targetBulkUpload.getTargetsCreated(); + final DistributionSetIdName dsSelected = (DistributionSetIdName) comboBox.getValue(); + if (distributionSetManagement.findDistributionSetById(dsSelected.getId()) == null) { + return i18n.get("message.bulk.upload.assignment.failed"); + } else { + deploymentManagement.assignDistributionSet(targetBulkUpload.getDsNameAndVersion().getId(), actionType, + forcedTimeStamp, targetsList.toArray(new String[targetsList.size()])); + return null; + } + } + + private String tagAssignment() { + final Map tokensSelected = targetBulkTokenTags.getTokensAdded(); + final List deletedTags = new ArrayList<>(); + for (final TagData tagData : tokensSelected.values()) { + if (tagManagement.findTargetTagById(tagData.getId()) == null) { + deletedTags.add(tagData.getName()); + } else { + targetManagement.toggleTagAssignment( + managementUIState.getTargetTableFilters().getBulkUpload().getTargetsCreated(), + tagData.getName()); + } + } + if (!deletedTags.isEmpty()) { + if (deletedTags.size() == 1) { + return i18n.get("message.bulk.upload.tag.assignment.failed", deletedTags.get(0)); + } else { + return i18n.get("message.bulk.upload.tag.assignments.failed"); + } + } + return null; + } + private boolean ifTagsSelected() { return targetBulkTokenTags.getTokenField().getValue() != null; } @@ -307,59 +375,6 @@ public class BulkUploadHandler extends CustomComponent } } - private double getTotalNumberOfLines() { - - double totalFileSize = 0; - try (InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(tempFile), - Charset.defaultCharset())) { - try (BufferedReader readerForSize = new BufferedReader(inputStreamReader)) { - totalFileSize = readerForSize.lines().count(); - } - } catch (final FileNotFoundException e) { - LOG.error("Error reading file {}", tempFile.getName(), e); - } catch (final IOException e) { - LOG.error("Error while closing reader of file {}", tempFile.getName(), e); - } - - return totalFileSize; - } - - private void resetCounts() { - successfullTargetCount = 0; - failedTargetCount = 0; - } - - private void deleteFile() { - if (tempFile.exists()) { - final boolean isDeleted = tempFile.delete(); - if (!isDeleted) { - LOG.info("File {} was not deleted !", tempFile.getName()); - } - } - tempFile = null; - } - - private void readEachLine(final String line, final double innerCounter, final double totalFileSize) { - final String csvDelimiter = ","; - final String[] targets = line.split(csvDelimiter); - if (targets.length == 2) { - final String controllerId = targets[0]; - final String targetName = targets[1]; - addNewTarget(controllerId, targetName); - } else { - failedTargetCount++; - } - final float current = managementUIState.getTargetTableFilters().getBulkUpload().getProgressBarCurrentValue(); - final float next = (float) (innerCounter / totalFileSize); - if (Math.abs(next - 0.1) < 0.00001 || current - next >= 0 || next - current >= 0.05 - || Math.abs(next - 1) < 0.00001) { - managementUIState.getTargetTableFilters().getBulkUpload().setProgressBarCurrentValue(next); - managementUIState.getTargetTableFilters().getBulkUpload().setSucessfulUploadCount(successfullTargetCount); - managementUIState.getTargetTableFilters().getBulkUpload().setFailedUploadCount(failedTargetCount); - eventBus.publish(this, new TargetTableEvent(TargetComponentEvent.BULK_TARGET_CREATED)); - } - } - private void addNewTarget(final String controllerId, final String name) { final String newControllerId = HawkbitCommonUtil.trimAndNullIfEmpty(controllerId); if (mandatoryCheck(newControllerId) && duplicateCheck(newControllerId)) { @@ -405,43 +420,6 @@ public class BulkUploadHandler extends CustomComponent } } - private String saveAllAssignments() { - final ActionType actionType = ActionType.FORCED; - final long forcedTimeStamp = new Date().getTime(); - final TargetBulkUpload targetBulkUpload = managementUIState.getTargetTableFilters().getBulkUpload(); - final List targetsList = targetBulkUpload.getTargetsCreated(); - final DistributionSetIdName dsSelected = (DistributionSetIdName) comboBox.getValue(); - if (distributionSetManagement.findDistributionSetById(dsSelected.getId()) == null) { - return i18n.get("message.bulk.upload.assignment.failed"); - } else { - deploymentManagement.assignDistributionSet(targetBulkUpload.getDsNameAndVersion().getId(), actionType, - forcedTimeStamp, targetsList.toArray(new String[targetsList.size()])); - return null; - } - } - - private String tagAssignment() { - final Map tokensSelected = targetBulkTokenTags.getTokensAdded(); - final List deletedTags = new ArrayList<>(); - for (final TagData tagData : tokensSelected.values()) { - if (tagManagement.findTargetTagById(tagData.getId()) == null) { - deletedTags.add(tagData.getName()); - } else { - targetManagement.toggleTagAssignment( - managementUIState.getTargetTableFilters().getBulkUpload().getTargetsCreated(), - tagData.getName()); - } - } - if (!deletedTags.isEmpty()) { - if (deletedTags.size() == 1) { - return i18n.get("message.bulk.upload.tag.assignment.failed", deletedTags.get(0)); - } else { - return i18n.get("message.bulk.upload.tag.assignments.failed"); - } - } - return null; - } - private static class NullOutputStream extends OutputStream { /** * null output stream. @@ -462,13 +440,6 @@ public class BulkUploadHandler extends CustomComponent return upload; } - /* - * (non-Javadoc) - * - * @see - * com.vaadin.ui.Upload.StartedListener#uploadStarted(com.vaadin.ui.Upload - * .StartedEvent) - */ @Override public void uploadStarted(final StartedEvent event) { if (!event.getFilename().endsWith(".csv")) { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java index 9151f3932..d60d72527 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java @@ -245,7 +245,7 @@ public class RolloutListGrid extends AbstractGrid { @Override protected void setColumnProperties() { - List columnList = new ArrayList<>(); + final List columnList = new ArrayList<>(); columnList.add(SPUILabelDefinitions.VAR_NAME); columnList.add(SPUILabelDefinitions.VAR_DIST_NAME_VERSION); columnList.add(SPUILabelDefinitions.VAR_STATUS); @@ -265,13 +265,13 @@ public class RolloutListGrid extends AbstractGrid { @Override protected void setHiddenColumns() { - List columnsToBeHidden = new ArrayList<>(); + final List columnsToBeHidden = new ArrayList<>(); columnsToBeHidden.add(SPUILabelDefinitions.VAR_CREATED_DATE); columnsToBeHidden.add(SPUILabelDefinitions.VAR_CREATED_USER); columnsToBeHidden.add(SPUILabelDefinitions.VAR_MODIFIED_DATE); columnsToBeHidden.add(SPUILabelDefinitions.VAR_MODIFIED_BY); columnsToBeHidden.add(SPUILabelDefinitions.VAR_DESC); - for (Object propertyId : columnsToBeHidden) { + for (final Object propertyId : columnsToBeHidden) { getColumn(propertyId).setHidden(true); } @@ -318,7 +318,7 @@ public class RolloutListGrid extends AbstractGrid { @Override public String getStyle(final CellReference cellReference) { - String[] coulmnNames = { SPUILabelDefinitions.VAR_STATUS, SPUILabelDefinitions.ACTION }; + final String[] coulmnNames = { SPUILabelDefinitions.VAR_STATUS, SPUILabelDefinitions.ACTION }; if (Arrays.asList(coulmnNames).contains(cellReference.getPropertyId())) { return "centeralign"; } @@ -327,18 +327,18 @@ public class RolloutListGrid extends AbstractGrid { }); } - private void onClickOfRolloutName(RendererClickEvent event) { + private void onClickOfRolloutName(final RendererClickEvent event) { rolloutUIState.setRolloutId((long) event.getItemId()); final String rolloutName = (String) getContainerDataSource().getItem(event.getItemId()) .getItemProperty(SPUILabelDefinitions.VAR_NAME).getValue(); rolloutUIState.setRolloutName(rolloutName); - String ds = (String) getContainerDataSource().getItem(event.getItemId()) + final String ds = (String) getContainerDataSource().getItem(event.getItemId()) .getItemProperty(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).getValue(); rolloutUIState.setRolloutDistributionSet(ds); eventBus.publish(this, RolloutEvent.SHOW_ROLLOUT_GROUPS); } - private void onClickOfActionBtn(RendererClickEvent event) { + private void onClickOfActionBtn(final RendererClickEvent event) { final ContextMenu contextMenu = createContextMenu((Long) event.getItemId()); contextMenu.setAsContextMenuOf((AbstractClientConnector) event.getComponent()); contextMenu.open(event.getClientX(), event.getClientY()); @@ -377,7 +377,6 @@ public class RolloutListGrid extends AbstractGrid { return context; } - private void getUpdateMenuItem(final ContextMenu context, final Long rolloutId) { // Add 'Update' option only if user has update permission if (!permissionChecker.hasRolloutUpdatePermission()) { @@ -387,17 +386,6 @@ public class RolloutListGrid extends AbstractGrid { cancelItem.setData(new ContextMenuData(rolloutId, ACTION.UPDATE)); } - private String convertRolloutStatusToString(final RolloutStatus value) { - StatusFontIcon statusFontIcon = statusIconMap.get(value); - if (statusFontIcon == null) { - return null; - } - String codePoint = statusFontIcon.getFontIcon() != null - ? Integer.toString(statusFontIcon.getFontIcon().getCodepoint()) : null; - return HawkbitCommonUtil.getStatusLabelDetailsInString(codePoint, statusFontIcon.getStyle(), - SPUIComponetIdProvider.ROLLOUT_STATUS_LABEL_ID); - } - private void menuItemClicked(final ContextMenuItemClickEvent event) { final ContextMenuItem item = (ContextMenuItem) event.getSource(); final ContextMenuData contextMenuData = (ContextMenuData) item.getData(); @@ -441,12 +429,12 @@ public class RolloutListGrid extends AbstractGrid { private static final long serialVersionUID = 2544026030795375748L; private final FontAwesome fontIcon; - public FontIconGenerator(FontAwesome icon) { + public FontIconGenerator(final FontAwesome icon) { this.fontIcon = icon; } @Override - public String getValue(Item item, Object itemId, Object propertyId) { + public String getValue(final Item item, final Object itemId, final Object propertyId) { return fontIcon.getHtml(); } @@ -456,7 +444,7 @@ public class RolloutListGrid extends AbstractGrid { } } - private String getDescription(CellReference cell) { + private String getDescription(final CellReference cell) { if (SPUILabelDefinitions.VAR_STATUS.equals(cell.getPropertyId())) { return cell.getProperty().getValue().toString().toLowerCase(); } else if (SPUILabelDefinitions.ACTION.equals(cell.getPropertyId())) { @@ -558,6 +546,17 @@ public class RolloutListGrid extends AbstractGrid { public Class getPresentationType() { return String.class; } + + private String convertRolloutStatusToString(final RolloutStatus value) { + final StatusFontIcon statusFontIcon = statusIconMap.get(value); + if (statusFontIcon == null) { + return null; + } + final String codePoint = statusFontIcon.getFontIcon() != null + ? Integer.toString(statusFontIcon.getFontIcon().getCodepoint()) : null; + return HawkbitCommonUtil.getStatusLabelDetailsInString(codePoint, statusFontIcon.getStyle(), + SPUIComponetIdProvider.ROLLOUT_STATUS_LABEL_ID); + } } /** @@ -570,14 +569,16 @@ public class RolloutListGrid extends AbstractGrid { private static final long serialVersionUID = -5794528427855153924L; @Override - public TotalTargetCountStatus convertToModel(String value, Class targetType, - Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException { + public TotalTargetCountStatus convertToModel(final String value, + final Class targetType, final Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { return null; } @Override - public String convertToPresentation(TotalTargetCountStatus value, Class targetType, - Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException { + public String convertToPresentation(final TotalTargetCountStatus value, + final Class targetType, final Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { return DistributionBarHelper.getDistributionBarAsHTMLString(value.getStatusTotalCountMap()); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java index 44d945efd..bb4adfe4a 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java @@ -273,17 +273,7 @@ public class RolloutGroupListGrid extends AbstractGrid { eventBus.publish(this, RolloutEvent.SHOW_ROLLOUT_GROUP_TARGETS); } - private String convertRolloutGroupStatusToString(final RolloutGroupStatus value) { - StatusFontIcon statusFontIcon = statusIconMap.get(value); - if (statusFontIcon == null) { - return null; - } - String codePoint = statusFontIcon.getFontIcon() != null - ? Integer.toString(statusFontIcon.getFontIcon().getCodepoint()) : null; - return HawkbitCommonUtil.getStatusLabelDetailsInString(codePoint, statusFontIcon.getStyle(), - SPUIComponetIdProvider.ROLLOUT_GROUP_STATUS_LABEL_ID); - - } + private void createRolloutGroupStatusToFontMap() { statusIconMap.put(RolloutGroupStatus.FINISHED, @@ -391,6 +381,18 @@ public class RolloutGroupListGrid extends AbstractGrid { public Class getPresentationType() { return String.class; } + + private String convertRolloutGroupStatusToString(final RolloutGroupStatus value) { + StatusFontIcon statusFontIcon = statusIconMap.get(value); + if (statusFontIcon == null) { + return null; + } + String codePoint = statusFontIcon.getFontIcon() != null + ? Integer.toString(statusFontIcon.getFontIcon().getCodepoint()) : null; + return HawkbitCommonUtil.getStatusLabelDetailsInString(codePoint, statusFontIcon.getStyle(), + SPUIComponetIdProvider.ROLLOUT_GROUP_STATUS_LABEL_ID); + + } } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsListGrid.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsListGrid.java index e55b30111..0099dfc95 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsListGrid.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsListGrid.java @@ -158,7 +158,7 @@ public class RolloutGroupTargetsListGrid extends AbstractGrid { @Override protected void setColumnProperties() { - List columnList = new ArrayList<>(); + final List columnList = new ArrayList<>(); columnList.add(SPUILabelDefinitions.VAR_NAME); columnList.add(SPUILabelDefinitions.VAR_CREATED_DATE); columnList.add(SPUILabelDefinitions.VAR_CREATED_BY); @@ -218,11 +218,9 @@ public class RolloutGroupTargetsListGrid extends AbstractGrid { public String convertToPresentation(final Status status, final Class targetType, final Locale locale) { if (status == null) { - // Actions are not created for targets when - // rollout's status - // is READY and when duplicate assignment is done. - // In these cases display a appropriate status with - // description + // Actions are not created for targets when rollout's status is + // READY and when duplicate assignment is done. In these cases + // display a appropriate status with description return getStatus(); } return processActionStatus(status); @@ -238,16 +236,31 @@ public class RolloutGroupTargetsListGrid extends AbstractGrid { return String.class; } - } - - private String processActionStatus(final Status status) { - StatusFontIcon statusFontIcon = statusIconMap.get(status); - if (statusFontIcon == null) { - return null; + private String processActionStatus(final Status status) { + final StatusFontIcon statusFontIcon = statusIconMap.get(status); + if (statusFontIcon == null) { + return null; + } + final String codePoint = statusFontIcon.getFontIcon() != null + ? Integer.toString(statusFontIcon.getFontIcon().getCodepoint()) : null; + return HawkbitCommonUtil.getStatusLabelDetailsInString(codePoint, statusFontIcon.getStyle(), null); } - String codePoint = statusFontIcon.getFontIcon() != null - ? Integer.toString(statusFontIcon.getFontIcon().getCodepoint()) : null; - return HawkbitCommonUtil.getStatusLabelDetailsInString(codePoint, statusFontIcon.getStyle(), null); + + private String getStatus() { + final RolloutGroup rolloutGroup = rolloutUIState.getRolloutGroup().isPresent() + ? rolloutUIState.getRolloutGroup().get() : null; + if (rolloutGroup != null && rolloutGroup.getStatus() == RolloutGroupStatus.READY) { + return HawkbitCommonUtil.getStatusLabelDetailsInString( + Integer.toString(FontAwesome.DOT_CIRCLE_O.getCodepoint()), "statusIconLightBlue", null); + } else if (rolloutGroup != null && rolloutGroup.getStatus() == RolloutGroupStatus.FINISHED) { + return HawkbitCommonUtil.getStatusLabelDetailsInString( + Integer.toString(FontAwesome.MINUS_CIRCLE.getCodepoint()), "statusIconBlue", null); + } else { + return HawkbitCommonUtil.getStatusLabelDetailsInString( + Integer.toString(FontAwesome.QUESTION_CIRCLE.getCodepoint()), "statusIconBlue", null); + } + } + } private void createRolloutStatusToFontMap() { @@ -271,22 +284,7 @@ public class RolloutGroupTargetsListGrid extends AbstractGrid { new StatusFontIcon(FontAwesome.EXCLAMATION_CIRCLE, SPUIStyleDefinitions.STATUS_ICON_RED)); } - private String getStatus() { - final RolloutGroup rolloutGroup = rolloutUIState.getRolloutGroup().isPresent() - ? rolloutUIState.getRolloutGroup().get() : null; - if (rolloutGroup != null && rolloutGroup.getStatus() == RolloutGroupStatus.READY) { - return HawkbitCommonUtil.getStatusLabelDetailsInString( - Integer.toString(FontAwesome.DOT_CIRCLE_O.getCodepoint()), "statusIconLightBlue", null); - } else if (rolloutGroup != null && rolloutGroup.getStatus() == RolloutGroupStatus.FINISHED) { - return HawkbitCommonUtil.getStatusLabelDetailsInString( - Integer.toString(FontAwesome.MINUS_CIRCLE.getCodepoint()), "statusIconBlue", null); - } else { - return HawkbitCommonUtil.getStatusLabelDetailsInString( - Integer.toString(FontAwesome.QUESTION_CIRCLE.getCodepoint()), "statusIconBlue", null); - } - } - - private String getDescription(CellReference cell) { + private String getDescription(final CellReference cell) { if (!SPUILabelDefinitions.VAR_STATUS.equals(cell.getPropertyId())) { return null; } @@ -296,7 +294,6 @@ public class RolloutGroupTargetsListGrid extends AbstractGrid { } return cell.getProperty().getValue().toString().toLowerCase(); } - private String getDescriptionWhenNoAction() { final RolloutGroup rolloutGroup = rolloutUIState.getRolloutGroup().isPresent() @@ -304,7 +301,7 @@ public class RolloutGroupTargetsListGrid extends AbstractGrid { if (rolloutGroup != null && rolloutGroup.getStatus() == RolloutGroupStatus.READY) { return RolloutGroupStatus.READY.toString().toLowerCase(); } else if (rolloutGroup != null && rolloutGroup.getStatus() == RolloutGroupStatus.FINISHED) { - String ds = rolloutUIState.getRolloutDistributionSet().isPresent() + final String ds = rolloutUIState.getRolloutDistributionSet().isPresent() ? rolloutUIState.getRolloutDistributionSet().get() : ""; return i18n.get("message.dist.already.assigned", new Object[] { ds }); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/polling/DurationConfigField.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/polling/DurationConfigField.java index 8cefc15fa..e1569db02 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/polling/DurationConfigField.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/polling/DurationConfigField.java @@ -14,8 +14,6 @@ import java.util.List; import org.eclipse.hawkbit.ui.tenantconfiguration.ConfigurationItem; -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.ui.Alignment; import com.vaadin.ui.CheckBox; import com.vaadin.ui.GridLayout; @@ -50,8 +48,8 @@ public class DurationConfigField extends GridLayout implements ConfigurationItem this.addComponent(durationField, 1, 0); this.setComponentAlignment(durationField, Alignment.MIDDLE_LEFT); - checkBox.addValueChangeListener(event->checkBoxChange()); - durationField.addValueChangeListener(event->notifyConfigurationChanged()); + checkBox.addValueChangeListener(event -> checkBoxChange()); + durationField.addValueChangeListener(event -> notifyConfigurationChanged()); } private void checkBoxChange() { @@ -72,16 +70,16 @@ public class DurationConfigField extends GridLayout implements ConfigurationItem * @param globalDuration * duration value which is stored in the global configuration */ - private void init(final Duration globalDuration, final Duration tenantDuration) { + protected void init(final Duration globalDuration, final Duration tenantDuration) { this.globalDuration = globalDuration; this.setValue(tenantDuration); } - private void setCheckBoxTooltip(final String label) { + protected void setCheckBoxTooltip(final String label) { checkBox.setDescription(label); } - private void setAllowedRange(final Duration minimumDuration, final Duration maximumDuration) { + protected void setAllowedRange(final Duration minimumDuration, final Duration maximumDuration) { durationField.setMinimumDuration(minimumDuration); durationField.setMaximumDuration(maximumDuration); } From bd974ef6ab69d088f531bb380862551fb6e598b1 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Sat, 2 Apr 2016 13:29:40 +0200 Subject: [PATCH 11/31] Prepared cloud deployment of hawkbit sandbox --- .../hawkbit-device-simulator/cf/manifest.yml | 21 ++++++++++++++++ examples/hawkbit-device-simulator/pom.xml | 10 ++++++++ .../simulator/DeviceSimulatorUpdater.java | 12 ++++++++- .../simulator/amqp/AmqpConfiguration.java | 5 ++-- .../simulator/amqp/SpReceiverService.java | 18 ++----------- .../src/main/resources/application.properties | 6 +---- examples/hawkbit-example-app/README.md | 25 +++++++++++++++---- .../cf/manifest-simple.yml | 19 ++++++++++++++ examples/hawkbit-example-app/cf/manifest.yml | 21 ++++++++++++++++ examples/hawkbit-example-app/pom.xml | 11 ++++++++ .../application-cloudsandbox.properties | 11 ++++++++ 11 files changed, 130 insertions(+), 29 deletions(-) create mode 100644 examples/hawkbit-device-simulator/cf/manifest.yml create mode 100644 examples/hawkbit-example-app/cf/manifest-simple.yml create mode 100644 examples/hawkbit-example-app/cf/manifest.yml create mode 100644 examples/hawkbit-example-app/src/main/resources/application-cloudsandbox.properties diff --git a/examples/hawkbit-device-simulator/cf/manifest.yml b/examples/hawkbit-device-simulator/cf/manifest.yml new file mode 100644 index 000000000..8a65690fe --- /dev/null +++ b/examples/hawkbit-device-simulator/cf/manifest.yml @@ -0,0 +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 +# +--- +applications: +- name: hawkbit-simulator + memory: 512M + instances: 1 + buildpack: https://github.com/cloudfoundry/java-buildpack + path: hawkbit-example-app-0.2.0-SNAPSHOT.jar + services: + - dmf-rabbit + env: + SPRING_PROFILES_ACTIVE: cloudsandbox,amqp + CF_STAGING_TIMEOUT: 15 + CF_STARTUP_TIMEOUT: 15 diff --git a/examples/hawkbit-device-simulator/pom.xml b/examples/hawkbit-device-simulator/pom.xml index a2575e9db..5ee781e34 100644 --- a/examples/hawkbit-device-simulator/pom.xml +++ b/examples/hawkbit-device-simulator/pom.xml @@ -42,6 +42,16 @@ + + + cf + true + ${project.build.directory} + + manifest.yml + + + diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulatorUpdater.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulatorUpdater.java index b8b5011aa..afc3a2569 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulatorUpdater.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulatorUpdater.java @@ -14,6 +14,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import org.eclipse.hawkbit.simulator.AbstractSimulatedDevice.Protocol; import org.eclipse.hawkbit.simulator.amqp.SpSenderService; import org.eclipse.hawkbit.simulator.event.InitUpdate; import org.eclipse.hawkbit.simulator.event.ProgressUpdate; @@ -34,6 +35,9 @@ public class DeviceSimulatorUpdater { @Autowired private SpSenderService spSenderService; + @Autowired + private SimulatedDeviceFactory deviceFactory; + @Autowired private EventBus eventbus; @@ -58,7 +62,13 @@ public class DeviceSimulatorUpdater { */ public void startUpdate(final String tenant, final String id, final long actionId, final String swVersion, final UpdaterCallback callback) { - final AbstractSimulatedDevice device = repository.get(tenant, id); + AbstractSimulatedDevice device = repository.get(tenant, id); + + // plug and play - non existing device will be auto created + if (device == null) { + device = repository.add(deviceFactory.createSimulatedDevice(id, tenant, Protocol.DMF_AMQP, -1, null, null)); + } + device.setProgress(0.0); device.setSwversion(swVersion); eventbus.post(new InitUpdate(device)); diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/AmqpConfiguration.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/AmqpConfiguration.java index 492bb3857..bf5d723a8 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/AmqpConfiguration.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/AmqpConfiguration.java @@ -59,7 +59,8 @@ public class AmqpConfiguration { } /** - * Create the receiver queue from sp. Receive messages from sp. + * Creates the receiver queue from update server for receiving message from + * update server. * * @return the queue */ @@ -70,7 +71,7 @@ public class AmqpConfiguration { } /** - * Create the recevier exchange. Sp send messages to this exchange. + * Creates the receiver exchange for sending messages to update server. * * @return the exchange */ diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/SpReceiverService.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/SpReceiverService.java index 1c314d56f..9f7e4d9ca 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/SpReceiverService.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/SpReceiverService.java @@ -26,9 +26,7 @@ import org.springframework.messaging.handler.annotation.Header; import org.springframework.stereotype.Component; /** - * Handle all incoming Messages from SP. - * - * + * Handle all incoming Messages from hawkBit update server. * */ @Component @@ -44,17 +42,6 @@ public class SpReceiverService extends ReceiverService { /** * Constructor. - * - * @param rabbitTemplate - * the rabbit template - * @param amqpProperties - * the amqp properties - * @param lwm2mSenderService - * the lwm2mSenderService - * @param spSenderService - * the spSenderService - * @param deviceUpdater - * the updater service to simulate update process */ @Autowired public SpReceiverService(final RabbitTemplate rabbitTemplate, final AmqpProperties amqpProperties, @@ -62,12 +49,11 @@ public class SpReceiverService extends ReceiverService { super(rabbitTemplate, amqpProperties); this.spSenderService = spSenderService; this.deviceUpdater = deviceUpdater; - } /** * Handle the incoming Message from Queue with the property - * (com.bosch.sp.lwm2m.connector.amqp.receiverConnectorQueueFromSp). + * (hawkbit.device.simulator.amqp.receiverConnectorQueueFromSp). * * @param message * the incoming message diff --git a/examples/hawkbit-device-simulator/src/main/resources/application.properties b/examples/hawkbit-device-simulator/src/main/resources/application.properties index 56d0190a7..cdc72ba28 100644 --- a/examples/hawkbit-device-simulator/src/main/resources/application.properties +++ b/examples/hawkbit-device-simulator/src/main/resources/application.properties @@ -7,11 +7,7 @@ # http://www.eclipse.org/legal/epl-v10.html # - -######################################################################################### -# PUBLIC configuration, i.e. can be changed by users at runtime (defaults provided here) -######################################################################################### -## Configuration for RabbitMQ communication +## Configuration for DMF communication hawkbit.device.simulator.amqp.receiverConnectorQueueFromSp=simulator_receiver hawkbit.device.simulator.amqp.deadLetterQueue=simulator_deadletter hawkbit.device.simulator.amqp.deadLetterExchange=simulator.deadletter diff --git a/examples/hawkbit-example-app/README.md b/examples/hawkbit-example-app/README.md index eaf30f306..4efbdb8ed 100644 --- a/examples/hawkbit-example-app/README.md +++ b/examples/hawkbit-example-app/README.md @@ -1,7 +1,15 @@ # hawkBit Example Application -The hawkBit example application is a standalone spring-boot application with an embedded servlet container to start the hawkBit. +The hawkBit example application is a standalone spring-boot application with an embedded servlet container to host the hawkBit Update Server. -## Run +We have have described several options for you to get access to the example. + +## Try out the example application in our hawkBit sandbox on Bluemix +- try out Management UI https://hawkbit.eu-gb.mybluemix.net/UI +- try out Management API https://hawkbit.eu-gb.mybluemix.net/rest/v1/targets (don't forget basic auth header) +- try out DDI API https://hawkbit.eu-gb.mybluemix.net/DEFAULT/controller/v1/MYTESTDEVICE + +## On your own workstation +### Run ``` java -jar examples/hawkbit-example-app/target/hawkbit-example-app-*-SNAPSHOT.jar ``` @@ -10,6 +18,13 @@ Or: run org eclipse.hawkbit.app.Start ``` -## Usage -The UI can be accessed via _http://localhost:8080/UI_. -The REST API can be accessed via _http://localhost:8080/rest/v1_. +### Usage +The Management UI can be accessed via http://localhost:8080/UI +The Management API can be accessed via http://localhost:8080/rest/v1 + +## Deploy example app to Cloud Foundry + +- Go to ```cf``` subfolder. +- Select one of the two manifests + - **manifest-simple.yml** for a standalone hawkBit installation with embedded H2. + - **manifest.yml** for a standalone hawkBit installation with embedded H2 and RabbitMQ service binding for DMF integration (note: this manifest is used for the sandbox above). diff --git a/examples/hawkbit-example-app/cf/manifest-simple.yml b/examples/hawkbit-example-app/cf/manifest-simple.yml new file mode 100644 index 000000000..4d4a798ef --- /dev/null +++ b/examples/hawkbit-example-app/cf/manifest-simple.yml @@ -0,0 +1,19 @@ +# +# 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 +# +--- +applications: +- name: hawkbit-simple + memory: 1024M + instances: 1 + buildpack: https://github.com/cloudfoundry/java-buildpack + path: ${project.build.finalName}.jar + env: + SPRING_PROFILES_ACTIVE: cloudsandbox + CF_STAGING_TIMEOUT: 15 + CF_STARTUP_TIMEOUT: 15 diff --git a/examples/hawkbit-example-app/cf/manifest.yml b/examples/hawkbit-example-app/cf/manifest.yml new file mode 100644 index 000000000..278f43681 --- /dev/null +++ b/examples/hawkbit-example-app/cf/manifest.yml @@ -0,0 +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 +# +--- +applications: +- name: hawkbit + memory: 1024M + instances: 1 + buildpack: https://github.com/cloudfoundry/java-buildpack + path: ${project.build.finalName}.jar + services: + - dmf-rabbit + env: + SPRING_PROFILES_ACTIVE: cloudsandbox,amqp + CF_STAGING_TIMEOUT: 15 + CF_STARTUP_TIMEOUT: 15 diff --git a/examples/hawkbit-example-app/pom.xml b/examples/hawkbit-example-app/pom.xml index 33624ffd7..e9f57ad54 100644 --- a/examples/hawkbit-example-app/pom.xml +++ b/examples/hawkbit-example-app/pom.xml @@ -39,6 +39,17 @@ + + + cf + true + ${project.build.directory} + + manifest.yml + manifest-simple.yml + + + diff --git a/examples/hawkbit-example-app/src/main/resources/application-cloudsandbox.properties b/examples/hawkbit-example-app/src/main/resources/application-cloudsandbox.properties new file mode 100644 index 000000000..d54e1d6a2 --- /dev/null +++ b/examples/hawkbit-example-app/src/main/resources/application-cloudsandbox.properties @@ -0,0 +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 +# + +spring.profiles.active= +vaadin.servlet.productionMode=true From 6d143273f76d903334b0e358952ef7a1a392b38c Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Sat, 2 Apr 2016 21:00:34 +0200 Subject: [PATCH 12/31] Added simulator autostart and cf deployment. --- examples/hawkbit-device-simulator/README.md | 15 +- .../hawkbit-device-simulator/cf/manifest.yml | 6 +- .../simulator/SimulationController.java | 4 +- .../simulator/SimulationProperties.java | 136 ++++++++++++++++++ .../hawkbit/simulator/SimulatorStartup.java | 51 +++++++ .../simulator/amqp/AmqpProperties.java | 9 +- .../simulator/amqp/SpReceiverService.java | 1 - .../src/main/resources/application.properties | 5 +- examples/hawkbit-example-app/README.md | 3 +- .../application-cloudsandbox.properties | 1 - 10 files changed, 212 insertions(+), 19 deletions(-) create mode 100644 examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulationProperties.java create mode 100644 examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatorStartup.java diff --git a/examples/hawkbit-device-simulator/README.md b/examples/hawkbit-device-simulator/README.md index 869f80511..1ba29bb7e 100644 --- a/examples/hawkbit-device-simulator/README.md +++ b/examples/hawkbit-device-simulator/README.md @@ -2,7 +2,7 @@ The device simulator handles software update commands from the update server. -## Run +## Run on your own workstation ``` java -jar examples/hawkbit-device-simulator/target/hawkbit-device-simulator-*-SNAPSHOT.jar ``` @@ -11,6 +11,11 @@ Or: run org.eclipse.hawkbit.simulator.DeviceSimulator ``` +## Deploy to cloud foundry environment + +- Go to ```target``` subfolder. +- Run ```cf push``` + ## Notes The simulator has user authentication enabled in **cloud profile**. Default credentials: @@ -30,9 +35,9 @@ http://localhost:8083 ``` ![](src/main/images/generateScreenshot.png) - + ![](src/main/images/updateProcessScreenshot.png) - + ![](src/main/images/updateResultOverviewScreenshot.png) @@ -54,12 +59,12 @@ Example: for 20 simulated devices (default) http://localhost:8083/start ``` -Example: for 10 simulated devices that start with the name prefix "activeSim": +Example: for 10 simulated devices that start with the name prefix "activeSim": ``` http://localhost:8083/start?amount=10&name=activeSim ``` -Example: for 5 simulated devices that start with the name prefix "ddi" using the Direct Device Integration API (http): +Example: for 5 simulated devices that start with the name prefix "ddi" using the Direct Device Integration API (http): ``` http://localhost:8083/start?amount=5&name=ddi?api=ddi ``` diff --git a/examples/hawkbit-device-simulator/cf/manifest.yml b/examples/hawkbit-device-simulator/cf/manifest.yml index 8a65690fe..df69f92e3 100644 --- a/examples/hawkbit-device-simulator/cf/manifest.yml +++ b/examples/hawkbit-device-simulator/cf/manifest.yml @@ -9,13 +9,13 @@ --- applications: - name: hawkbit-simulator - memory: 512M + memory: 1024M instances: 1 buildpack: https://github.com/cloudfoundry/java-buildpack - path: hawkbit-example-app-0.2.0-SNAPSHOT.jar + path: ${project.build.finalName}.jar services: - dmf-rabbit env: - SPRING_PROFILES_ACTIVE: cloudsandbox,amqp + SPRING_PROFILES_ACTIVE: cloud,amqp CF_STAGING_TIMEOUT: 15 CF_STARTUP_TIMEOUT: 15 diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulationController.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulationController.java index c1f358d89..426860d8b 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulationController.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulationController.java @@ -55,7 +55,7 @@ public class SimulationController { * number of delay in milliseconds to delay polling of DDI * devices * @param gatewayToken - * the hawkbit-update-server gatwaytoken in case authentication + * the hawkbit-update-server gatewaytoken in case authentication * is enforced in hawkbit * @return a response string that devices has been created * @throws MalformedURLException @@ -68,7 +68,7 @@ public class SimulationController { @RequestParam(value = "endpoint", defaultValue = "http://localhost:8080") final String endpoint, @RequestParam(value = "polldelay", defaultValue = "30") final int pollDelay, @RequestParam(value = "gatewaytoken", defaultValue = "") final String gatewayToken) - throws MalformedURLException { + throws MalformedURLException { final Protocol protocol; switch (api.toLowerCase()) { diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulationProperties.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulationProperties.java new file mode 100644 index 000000000..354263934 --- /dev/null +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulationProperties.java @@ -0,0 +1,136 @@ +/** + * 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.simulator; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.hawkbit.simulator.AbstractSimulatedDevice.Protocol; +import org.hibernate.validator.constraints.NotEmpty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * General simulator service properties. + * + */ +@Component +@ConfigurationProperties("hawkbit.device.simulator") +public class SimulationProperties { + + /** + * List of tenants where the simulator should auto start simulations after + * startup. + */ + private final List autostarts = new ArrayList<>(); + + public List getAutostarts() { + return this.autostarts; + } + + /** + * Auto start configuration for simulation setups that the simulator begins + * after startup. + * + */ + public static class Autostart { + /** + * Name prefix of simulated devices, followed by counter, e.g. + * simulated0, simulated1, simulated2.... + */ + private String name = "simulated"; + + /** + * Amount of simulated devices. + */ + private int amount = 20; + + /** + * Tenant name for the simulation. + */ + @NotEmpty + private String tenant; + + /** + * API for simulation. + */ + private Protocol api = Protocol.DMF_AMQP; + + /** + * Endpoint in case of DDI API based simulation. + */ + private String endpoint = "http://localhost:8080"; + + /** + * Poll time in case of DDI API based simulation. + */ + private int pollDelay = 30; + + /** + * Optional gateway token for DDI API based simulation. + */ + private String gatewayToken = ""; + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public int getAmount() { + return amount; + } + + public void setAmount(final int amount) { + this.amount = amount; + } + + public String getTenant() { + return tenant; + } + + public void setTenant(final String tenant) { + this.tenant = tenant; + } + + public Protocol getApi() { + return api; + } + + public void setApi(final Protocol api) { + this.api = api; + } + + public String getEndpoint() { + return endpoint; + } + + public void setEndpoint(final String endpoint) { + this.endpoint = endpoint; + } + + public int getPollDelay() { + return pollDelay; + } + + public void setPollDelay(final int pollDelay) { + this.pollDelay = pollDelay; + } + + public String getGatewayToken() { + return gatewayToken; + } + + public void setGatewayToken(final String gatewayToken) { + this.gatewayToken = gatewayToken; + } + } +} diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatorStartup.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatorStartup.java new file mode 100644 index 000000000..c0e22a994 --- /dev/null +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatorStartup.java @@ -0,0 +1,51 @@ +package org.eclipse.hawkbit.simulator; + +import java.net.URL; + +import org.eclipse.hawkbit.simulator.amqp.SpSenderService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.stereotype.Component; + +/** + * Execution of operations after startup. Set up of simulations. + * + */ +@Component +public class SimulatorStartup implements ApplicationListener { + private static final Logger LOGGER = LoggerFactory.getLogger(SimulatorStartup.class); + + @Autowired + private SimulationProperties simulationProperties; + + @Autowired + private SpSenderService spSenderService; + + @Autowired + private DeviceSimulatorRepository repository; + + @Autowired + private SimulatedDeviceFactory deviceFactory; + + @Override + public void onApplicationEvent(final ContextRefreshedEvent event) { + simulationProperties.getAutostarts().forEach(autostart -> { + for (int i = 0; i < autostart.getAmount(); i++) { + final String deviceId = autostart.getName() + i; + try { + repository.add(deviceFactory.createSimulatedDevice(deviceId, autostart.getTenant(), + autostart.getApi(), autostart.getPollDelay(), new URL(autostart.getEndpoint()), + autostart.getGatewayToken())); + } catch (final Exception e) { + LOGGER.error("Creation of simulated device at startup failed.", e); + } + + spSenderService.createOrUpdateThing(autostart.getTenant(), deviceId); + } + }); + } + +} 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 f9e6ab23d..f58355980 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 @@ -19,26 +19,25 @@ import org.springframework.stereotype.Component; @Component @ConfigurationProperties("hawkbit.device.simulator.amqp") public class AmqpProperties { - /** * Queue for receiving DMF messages from update server. */ - private String receiverConnectorQueueFromSp; + private String receiverConnectorQueueFromSp = "simulator_receiver"; /** * Exchange for sending DMF messages to update server. */ - private String senderForSpExchange; + private String senderForSpExchange = "simulator.replyTo"; /** * Simulator dead letter queue. */ - private String deadLetterQueue; + private String deadLetterQueue = "simulator_deadletter"; /** * Simulator dead letter exchange. */ - private String deadLetterExchange; + private String deadLetterExchange = "simulator.deadletter"; public String getReceiverConnectorQueueFromSp() { return receiverConnectorQueueFromSp; diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/SpReceiverService.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/SpReceiverService.java index 9f7e4d9ca..f22839422 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/SpReceiverService.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/SpReceiverService.java @@ -31,7 +31,6 @@ import org.springframework.stereotype.Component; */ @Component public class SpReceiverService extends ReceiverService { - private static final Logger LOGGER = LoggerFactory.getLogger(ReceiverService.class); public static final String SOFTWARE_MODULE_FIRMWARE = "firmware"; diff --git a/examples/hawkbit-device-simulator/src/main/resources/application.properties b/examples/hawkbit-device-simulator/src/main/resources/application.properties index cdc72ba28..fbe7261be 100644 --- a/examples/hawkbit-device-simulator/src/main/resources/application.properties +++ b/examples/hawkbit-device-simulator/src/main/resources/application.properties @@ -13,8 +13,11 @@ hawkbit.device.simulator.amqp.deadLetterQueue=simulator_deadletter hawkbit.device.simulator.amqp.deadLetterExchange=simulator.deadletter hawkbit.device.simulator.amqp.senderForSpExchange=simulator.replyTo +## Configuration for simulations +hawkbit.device.simulator.autostarts.[0].tenant=DEFAULT -## Configuration for RabbitMQ integration + +## Configuration for local RabbitMQ integration spring.rabbitmq.username=guest spring.rabbitmq.password=guest spring.rabbitmq.virtualHost=/ diff --git a/examples/hawkbit-example-app/README.md b/examples/hawkbit-example-app/README.md index 4efbdb8ed..ecbec93c3 100644 --- a/examples/hawkbit-example-app/README.md +++ b/examples/hawkbit-example-app/README.md @@ -24,7 +24,8 @@ The Management API can be accessed via http://localhost:8080/rest/v1 ## Deploy example app to Cloud Foundry -- Go to ```cf``` subfolder. +- Go to ```target``` subfolder. - Select one of the two manifests - **manifest-simple.yml** for a standalone hawkBit installation with embedded H2. - **manifest.yml** for a standalone hawkBit installation with embedded H2 and RabbitMQ service binding for DMF integration (note: this manifest is used for the sandbox above). +- Run ```cf push``` against you cloud foundry environment. diff --git a/examples/hawkbit-example-app/src/main/resources/application-cloudsandbox.properties b/examples/hawkbit-example-app/src/main/resources/application-cloudsandbox.properties index d54e1d6a2..ecf71da41 100644 --- a/examples/hawkbit-example-app/src/main/resources/application-cloudsandbox.properties +++ b/examples/hawkbit-example-app/src/main/resources/application-cloudsandbox.properties @@ -7,5 +7,4 @@ # http://www.eclipse.org/legal/epl-v10.html # -spring.profiles.active= vaadin.servlet.productionMode=true From 171dc461071f37ffb9414e2ce69d9d73416f7f9a Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Sat, 2 Apr 2016 21:14:41 +0200 Subject: [PATCH 13/31] Fixed problem that client works only with localhost. --- .../mgmt/client/resource/DistributionSetResourceClient.java | 2 +- .../client/resource/DistributionSetTagResourceClient.java | 2 +- .../client/resource/DistributionSetTypeResourceClient.java | 2 +- .../hawkbit/mgmt/client/resource/RolloutResourceClient.java | 2 +- .../mgmt/client/resource/SoftwareModuleResourceClient.java | 2 +- .../client/resource/SoftwareModuleTypeResourceClient.java | 2 +- .../hawkbit/mgmt/client/resource/TargetResourceClient.java | 2 +- .../hawkbit/mgmt/client/resource/TargetTagResourceClient.java | 2 +- .../mgmt/client/resource/builder/DistributionSetBuilder.java | 4 ---- .../client/resource/builder/DistributionSetTypeBuilder.java | 2 -- .../hawkbit/mgmt/client/resource/builder/RolloutBuilder.java | 2 -- .../resource/builder/SoftwareModuleAssigmentBuilder.java | 2 -- .../mgmt/client/resource/builder/SoftwareModuleBuilder.java | 2 -- .../client/resource/builder/SoftwareModuleTypeBuilder.java | 2 -- .../hawkbit/mgmt/client/resource/builder/TagBuilder.java | 2 -- .../hawkbit/mgmt/client/resource/builder/TargetBuilder.java | 2 -- .../mgmt/client/scenarios/CreateStartedRolloutExample.java | 2 +- .../mgmt/client/scenarios/GettingStartedDefaultScenario.java | 4 ++-- 18 files changed, 11 insertions(+), 29 deletions(-) diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetResourceClient.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetResourceClient.java index 00a9b3fba..5ac11e012 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetResourceClient.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetResourceClient.java @@ -14,7 +14,7 @@ import org.springframework.cloud.netflix.feign.FeignClient; /** * Client binding for the DistributionSet resource of the management API. */ -@FeignClient(url = "${hawkbit.endpoint.url:localhost:8080}/rest/v1/distributionsets") +@FeignClient(url = "${hawkbit.url:localhost:8080}/rest/v1/distributionsets") public interface DistributionSetResourceClient extends DistributionSetRestApi { } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetTagResourceClient.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetTagResourceClient.java index ea9f5d28a..5fbdaf857 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetTagResourceClient.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetTagResourceClient.java @@ -14,7 +14,7 @@ import org.springframework.cloud.netflix.feign.FeignClient; /** * Client binding for the DistributionSetTag resource of the management API. */ -@FeignClient(url = "${hawkbit.endpoint.url:localhost:8080}/rest/v1/distributionsettags") +@FeignClient(url = "${hawkbit.url:localhost:8080}/rest/v1/distributionsettags") public interface DistributionSetTagResourceClient extends DistributionSetTagRestApi { } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetTypeResourceClient.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetTypeResourceClient.java index 08d40dfa5..300f8ddcb 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetTypeResourceClient.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetTypeResourceClient.java @@ -15,7 +15,7 @@ import org.springframework.cloud.netflix.feign.FeignClient; * Client binding for the DistributionSetType resource of the management API. * */ -@FeignClient(url = "${hawkbit.endpoint.url:localhost:8080}/rest/v1/distributionsettypes") +@FeignClient(url = "${hawkbit.url:localhost:8080}/rest/v1/distributionsettypes") public interface DistributionSetTypeResourceClient extends DistributionSetTypeRestApi { } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/RolloutResourceClient.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/RolloutResourceClient.java index 78b7413e7..aed3af7a2 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/RolloutResourceClient.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/RolloutResourceClient.java @@ -14,7 +14,7 @@ import org.springframework.cloud.netflix.feign.FeignClient; /** * Client binding for the Rollout resource of the management API. */ -@FeignClient(url = "${hawkbit.endpoint.url:localhost:8080}/rest/v1/rollouts") +@FeignClient(url = "${hawkbit.url:localhost:8080}/rest/v1/rollouts") public interface RolloutResourceClient extends RolloutRestApi { } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/SoftwareModuleResourceClient.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/SoftwareModuleResourceClient.java index 88e664d78..8610643ef 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/SoftwareModuleResourceClient.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/SoftwareModuleResourceClient.java @@ -14,7 +14,7 @@ import org.springframework.cloud.netflix.feign.FeignClient; /** * Client binding for the SoftwareModule resource of the management API. */ -@FeignClient(url = "${hawkbit.endpoint.url:localhost:8080}/rest/v1/softwaremodules") +@FeignClient(url = "${hawkbit.url:localhost:8080}/rest/v1/softwaremodules") public interface SoftwareModuleResourceClient extends SoftwareModuleRestAPI { } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/SoftwareModuleTypeResourceClient.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/SoftwareModuleTypeResourceClient.java index 4896cb8d8..46410dd6c 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/SoftwareModuleTypeResourceClient.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/SoftwareModuleTypeResourceClient.java @@ -14,7 +14,7 @@ import org.springframework.cloud.netflix.feign.FeignClient; /** * Client binding for the oftwareModuleType resource of the management API. */ -@FeignClient(url = "${hawkbit.endpoint.url:localhost:8080}/rest/v1/softwaremoduletypes") +@FeignClient(url = "${hawkbit.url:localhost:8080}/rest/v1/softwaremoduletypes") public interface SoftwareModuleTypeResourceClient extends SoftwareModuleTypeRestApi { } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/TargetResourceClient.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/TargetResourceClient.java index a82aa5443..79385fea4 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/TargetResourceClient.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/TargetResourceClient.java @@ -14,7 +14,7 @@ import org.springframework.cloud.netflix.feign.FeignClient; /** * Client binding for the Target resource of the management API. */ -@FeignClient(url = "${hawkbit.endpoint.url:localhost:8080}/rest/v1/targets") +@FeignClient(url = "${hawkbit.url:localhost:8080}/rest/v1/targets") public interface TargetResourceClient extends TargetRestApi { } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/TargetTagResourceClient.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/TargetTagResourceClient.java index fee30c686..930931a87 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/TargetTagResourceClient.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/TargetTagResourceClient.java @@ -14,7 +14,7 @@ import org.springframework.cloud.netflix.feign.FeignClient; /** * Client binding for the TargetTag resource of the management API. */ -@FeignClient(url = "${hawkbit.endpoint.url:localhost:8080}/rest/v1/targettags") +@FeignClient(url = "${hawkbit.url:localhost:8080}/rest/v1/targettags") public interface TargetTagResourceClient extends TargetTagRestApi { } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetBuilder.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetBuilder.java index c821b106c..358cff0db 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetBuilder.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetBuilder.java @@ -16,11 +16,7 @@ import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetRe import com.google.common.collect.Lists; /** - * * Builder pattern for building {@link DistributionSetRequestBodyPost}. - * - * @author Jonathan Knoblauch - * */ public class DistributionSetBuilder { diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetTypeBuilder.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetTypeBuilder.java index e1da1f048..752834c7d 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetTypeBuilder.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetTypeBuilder.java @@ -19,8 +19,6 @@ import com.google.common.collect.Lists; /** * * Builder pattern for building {@link DistributionSetTypeRequestBodyPost}. - * - * @author Jonathan Knoblauch * */ public class DistributionSetTypeBuilder { diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/RolloutBuilder.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/RolloutBuilder.java index bea0fd9a4..2e01e0ba2 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/RolloutBuilder.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/RolloutBuilder.java @@ -15,8 +15,6 @@ import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutRestRequestBody; /** * * Builder pattern for building {@link RolloutRestRequestBody}. - * - * @author Jonathan Knoblauch * */ public class RolloutBuilder { 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 b209dbe8b..8d69db619 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 @@ -16,8 +16,6 @@ import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleAssi /** * * Builder pattern for building {@link SoftwareModuleAssigmentRest}. - * - * @author Jonathan Knoblauch * */ public class SoftwareModuleAssigmentBuilder { diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleBuilder.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleBuilder.java index 30b85d901..4bbfd92b4 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleBuilder.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleBuilder.java @@ -19,8 +19,6 @@ import com.google.common.collect.Lists; /** * * Builder pattern for building {@link SoftwareModuleRequestBodyPost}. - * - * @author Jonathan Knoblauch * */ public class SoftwareModuleBuilder { diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleTypeBuilder.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleTypeBuilder.java index ce128d592..a6472f0a0 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleTypeBuilder.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleTypeBuilder.java @@ -19,8 +19,6 @@ import com.google.common.collect.Lists; /** * * Builder pattern for building {@link SoftwareModuleRequestBodyPost}. - * - * @author Jonathan Knoblauch * */ public class SoftwareModuleTypeBuilder { diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TagBuilder.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TagBuilder.java index f3888de54..6f2eb3248 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TagBuilder.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TagBuilder.java @@ -17,8 +17,6 @@ import com.google.common.collect.Lists; /** * Builder pattern for building {@link TagRequestBodyPut}. - * - * @author Jonathan Knoblauch * */ public class TagBuilder { diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TargetBuilder.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TargetBuilder.java index 5123903d9..e496407e1 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TargetBuilder.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TargetBuilder.java @@ -19,8 +19,6 @@ import com.google.common.collect.Lists; /** * * Builder pattern for building {@link TargetRequestBody}. - * - * @author Jonathan Knoblauch * */ public class TargetBuilder { diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/CreateStartedRolloutExample.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/CreateStartedRolloutExample.java index e92f81326..cd74c0474 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/CreateStartedRolloutExample.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/CreateStartedRolloutExample.java @@ -41,7 +41,7 @@ public class CreateStartedRolloutExample { private static final String SM_MODULE_TYPE = "firmware"; /* known distribution set type name and key */ - private static final String DS_MODULE_TYPE = "firmware"; + private static final String DS_MODULE_TYPE = SM_MODULE_TYPE; @Autowired private DistributionSetResourceClient distributionSetResource; diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/GettingStartedDefaultScenario.java b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/GettingStartedDefaultScenario.java index d17048dea..5873403f0 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/GettingStartedDefaultScenario.java +++ b/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/GettingStartedDefaultScenario.java @@ -41,13 +41,13 @@ public class GettingStartedDefaultScenario { private static final String SM_MODULE_TYPE = "gettingstarted"; /* known distribution set type name and key */ - private static final String DS_MODULE_TYPE = "gettingstarted"; + private static final String DS_MODULE_TYPE = SM_MODULE_TYPE; /* known distribution name of this getting started example */ private static final String SM_EXAMPLE_NAME = "gettingstarted-example"; /* known distribution name of this getting started example */ - private static final String DS_EXAMPLE_NAME = "gettingstarted-example"; + private static final String DS_EXAMPLE_NAME = SM_EXAMPLE_NAME; @Autowired private DistributionSetResourceClient distributionSetResource; From 4b95ebc75d92899a2500258855702ac4c01314d5 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Sat, 2 Apr 2016 21:36:06 +0200 Subject: [PATCH 14/31] Skript for sandbox setup --- deployHawkBitSandbox.sh | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 deployHawkBitSandbox.sh diff --git a/deployHawkBitSandbox.sh b/deployHawkBitSandbox.sh new file mode 100644 index 000000000..ac2498e2b --- /dev/null +++ b/deployHawkBitSandbox.sh @@ -0,0 +1,20 @@ +# +# 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 +# + +# This script allows the deployment of the complete hawkBit sandbox including +# data example to a cloud foundry enviroment. Expects existing CF CLI +# installation and login to be existing already. + +cd examples/hawkbit-example-app/target/ +cf push +cd ../.. +java -jar hawkbit-mgmt-api-client/target/hawkbit-mgmt-api-client-0.2.0-SNAPSHOT.jar -Dhawkbit.url=hawkbit.eu-gb.mybluemix.net +cd hawkbit-device-simulator/target/ +cf push +cd ../../.. From 36e8949febdd8e538be5de1dcba85052c04bc2cc Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Sat, 2 Apr 2016 22:13:21 +0200 Subject: [PATCH 15/31] Fixed final bugs. Sandbox works now. --- deployHawkBitSandbox.sh | 2 +- examples/hawkbit-device-simulator/pom.xml | 3 +++ examples/hawkbit-example-app/pom.xml | 3 +++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/deployHawkBitSandbox.sh b/deployHawkBitSandbox.sh index ac2498e2b..d774f4205 100644 --- a/deployHawkBitSandbox.sh +++ b/deployHawkBitSandbox.sh @@ -14,7 +14,7 @@ cd examples/hawkbit-example-app/target/ cf push cd ../.. -java -jar hawkbit-mgmt-api-client/target/hawkbit-mgmt-api-client-0.2.0-SNAPSHOT.jar -Dhawkbit.url=hawkbit.eu-gb.mybluemix.net +java -jar hawkbit-mgmt-api-client/target/hawkbit-mgmt-api-client-0.2.0-SNAPSHOT.jar --hawkbit.url=hawkbit.eu-gb.mybluemix.net cd hawkbit-device-simulator/target/ cf push cd ../../.. diff --git a/examples/hawkbit-device-simulator/pom.xml b/examples/hawkbit-device-simulator/pom.xml index 5ee781e34..a23051124 100644 --- a/examples/hawkbit-device-simulator/pom.xml +++ b/examples/hawkbit-device-simulator/pom.xml @@ -43,6 +43,9 @@ + + src/main/resources + cf true diff --git a/examples/hawkbit-example-app/pom.xml b/examples/hawkbit-example-app/pom.xml index e9f57ad54..a5c0f864d 100644 --- a/examples/hawkbit-example-app/pom.xml +++ b/examples/hawkbit-example-app/pom.xml @@ -40,6 +40,9 @@ + + src/main/resources + cf true From 19e628aac9e21d8b534bbe855af61b5f46ae9c7f Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Sat, 2 Apr 2016 22:18:04 +0200 Subject: [PATCH 16/31] Added sandbox chapter --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index fb649633b..461e12e81 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,11 @@ see [hawkBit Wiki](https://github.com/eclipse/hawkbit/wiki) * Having issues with hawkBit? Open a [GitHub issue](https://github.com/eclipse/hawkbit/issues). * You can also check out our [Project Homepage](https://projects.eclipse.org/projects/iot.hawkbit) for further contact options. +# hawkBit sandbox + +We offer a sandbox installation that is free for everyone to try out hawkBit. However, keep in mind that the sandbox database will be reset from time to time. It is also not possible to upload any artifacts into the sandbox. But you can use it to try out the Management UI, Management API and DDI API. + +https://hawkbit.eu-gb.mybluemix.net/UI/ # Compile, Run and Getting Started From f4bd947cbd521856f5a92c8836755a8066b60bd0 Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Mon, 4 Apr 2016 08:03:42 +0200 Subject: [PATCH 17/31] remove unused parameter Signed-off-by: Michael Hirsch --- .../hawkbit/controller/DataConversionHelper.java | 12 +++++------- .../eclipse/hawkbit/controller/RootController.java | 10 ++++------ 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/DataConversionHelper.java b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/DataConversionHelper.java index 03623abdd..e035c47ee 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/DataConversionHelper.java +++ b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/DataConversionHelper.java @@ -49,11 +49,11 @@ public final class DataConversionHelper { } - static List createChunks(final String targetid, final Action uAction, final TenantAware tenantAware, + static List createChunks(final String targetid, final Action uAction, final ArtifactUrlHandler artifactUrlHandler) { return uAction.getDistributionSet().getModules().stream() .map(module -> new Chunk(mapChunkLegacyKeys(module.getType().getKey()), module.getVersion(), - module.getName(), createArtifacts(targetid, module, tenantAware, artifactUrlHandler))) + module.getName(), createArtifacts(targetid, module, artifactUrlHandler))) .collect(Collectors.toList()); } @@ -76,12 +76,10 @@ public final class DataConversionHelper { * of the target * @param module * the software module - * @param tenantAware - * of the tenant * @return a list of artifacts or a empty list. Cannot be . */ public static List createArtifacts(final String targetid, - final org.eclipse.hawkbit.repository.model.SoftwareModule module, final TenantAware tenantAware, + final org.eclipse.hawkbit.repository.model.SoftwareModule module, final ArtifactUrlHandler artifactUrlHandler) { final List files = new ArrayList<>(); module.getLocalArtifacts().forEach(artifact -> { @@ -94,9 +92,9 @@ public final class DataConversionHelper { final String linkHttps = artifactUrlHandler.getUrl(targetid, artifact.getSoftwareModule().getId(), artifact.getFilename(), artifact.getSha1Hash(), UrlProtocol.HTTPS); file.add(new Link(linkHttps).withRel("download")); - file.add(new Link(linkHttps + ".MD5SUM").withRel("md5sum")); + file.add(new Link(linkHttps + ControllerConstants.ARTIFACT_MD5_DWNL_SUFFIX).withRel("md5sum")); file.add(new Link(linkHttp).withRel("download-http")); - file.add(new Link(linkHttp + ".MD5SUM").withRel("md5sum-http")); + file.add(new Link(linkHttp + ControllerConstants.ARTIFACT_MD5_DWNL_SUFFIX).withRel("md5sum-http")); files.add(file); }); 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 0a668338c..358448dfd 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 @@ -90,10 +90,10 @@ public class RootController { private CacheWriteNotify cacheWriteNotify; @Autowired - private TenantAware tenantAware; + private HawkbitSecurityProperties securityProperties; @Autowired - private HawkbitSecurityProperties securityProperties; + private TenantAware tenantAware; @Autowired private ArtifactUrlHandler artifactUrlHandler; @@ -122,8 +122,7 @@ public class RootController { } - return new ResponseEntity<>( - DataConversionHelper.createArtifacts(targetid, softwareModule, tenantAware, artifactUrlHandler), + return new ResponseEntity<>(DataConversionHelper.createArtifacts(targetid, softwareModule, artifactUrlHandler), HttpStatus.OK); } @@ -312,8 +311,7 @@ public class RootController { if (!action.isCancelingOrCanceled()) { - final List chunks = DataConversionHelper.createChunks(targetid, action, tenantAware, - artifactUrlHandler); + final List chunks = DataConversionHelper.createChunks(targetid, action, artifactUrlHandler); final HandlingType handlingType = action.isForce() ? HandlingType.FORCED : HandlingType.ATTEMPT; From 5c661cd6a49b608cf43415b5401904dffdfa1695 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Mon, 4 Apr 2016 08:58:58 +0200 Subject: [PATCH 18/31] Added license header --- examples/hawkbit-device-simulator/cf/manifest.yml | 1 + .../org/eclipse/hawkbit/simulator/SimulatorStartup.java | 8 ++++++++ examples/hawkbit-example-app/cf/manifest-simple.yml | 1 + examples/hawkbit-example-app/cf/manifest.yml | 1 + 4 files changed, 11 insertions(+) diff --git a/examples/hawkbit-device-simulator/cf/manifest.yml b/examples/hawkbit-device-simulator/cf/manifest.yml index df69f92e3..51a43ace6 100644 --- a/examples/hawkbit-device-simulator/cf/manifest.yml +++ b/examples/hawkbit-device-simulator/cf/manifest.yml @@ -6,6 +6,7 @@ # which accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # + --- applications: - name: hawkbit-simulator diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatorStartup.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatorStartup.java index c0e22a994..faff1cc6c 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatorStartup.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatorStartup.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.simulator; import java.net.URL; diff --git a/examples/hawkbit-example-app/cf/manifest-simple.yml b/examples/hawkbit-example-app/cf/manifest-simple.yml index 4d4a798ef..c87a533f4 100644 --- a/examples/hawkbit-example-app/cf/manifest-simple.yml +++ b/examples/hawkbit-example-app/cf/manifest-simple.yml @@ -6,6 +6,7 @@ # which accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # + --- applications: - name: hawkbit-simple diff --git a/examples/hawkbit-example-app/cf/manifest.yml b/examples/hawkbit-example-app/cf/manifest.yml index 278f43681..2145f467d 100644 --- a/examples/hawkbit-example-app/cf/manifest.yml +++ b/examples/hawkbit-example-app/cf/manifest.yml @@ -6,6 +6,7 @@ # which accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # + --- applications: - name: hawkbit From fd3d854bf8f18ab72df903cd96f920b0ca86e4ef Mon Sep 17 00:00:00 2001 From: Jonathan Philip Knoblauch Date: Mon, 4 Apr 2016 10:31:05 +0200 Subject: [PATCH 19/31] Reseted changes because a bigger refactoring is necessary Signed-off-by: Jonathan Philip Knoblauch --- .../ui/tenantconfiguration/polling/DurationConfigField.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/polling/DurationConfigField.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/polling/DurationConfigField.java index e1569db02..15f51877d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/polling/DurationConfigField.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/polling/DurationConfigField.java @@ -70,16 +70,16 @@ public class DurationConfigField extends GridLayout implements ConfigurationItem * @param globalDuration * duration value which is stored in the global configuration */ - protected void init(final Duration globalDuration, final Duration tenantDuration) { + private void init(final Duration globalDuration, final Duration tenantDuration) { this.globalDuration = globalDuration; this.setValue(tenantDuration); } - protected void setCheckBoxTooltip(final String label) { + private void setCheckBoxTooltip(final String label) { checkBox.setDescription(label); } - protected void setAllowedRange(final Duration minimumDuration, final Duration maximumDuration) { + private void setAllowedRange(final Duration minimumDuration, final Duration maximumDuration) { durationField.setMinimumDuration(minimumDuration); durationField.setMaximumDuration(maximumDuration); } From 84f543382c0e8a3cd15a43b71ac856d96bb1d052 Mon Sep 17 00:00:00 2001 From: Jonathan Philip Knoblauch Date: Mon, 4 Apr 2016 10:48:14 +0200 Subject: [PATCH 20/31] Updated javadoc for the getURl method Signed-off-by: Jonathan Philip Knoblauch --- .../org/eclipse/hawkbit/api/ArtifactUrlHandler.java | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/ArtifactUrlHandler.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/ArtifactUrlHandler.java index a80551f9e..522444961 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/ArtifactUrlHandler.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/ArtifactUrlHandler.java @@ -17,15 +17,20 @@ package org.eclipse.hawkbit.api; public interface ArtifactUrlHandler { /** - * Returns a generated URL for a given artifact for a specific protocol. + * Returns a generated download URL for a given artifact parameters for a + * specific protocol. * * @param controllerId * the authenticated controller id - * @param localArtifact - * the artifact to retrieve a URL to + * @param softwareModuleId + * the softwareModuleId belonging to the artifact + * @param filename + * the filename of the artifact + * @param sha1Hash + * the sha1Hash of the artifact * @param protocol * the protocol the URL should be generated - * @return an URL for the given artifact in a given protocol + * @return an URL for the given artifact parameters in a given protocol */ String getUrl(String controllerId, final Long softwareModuleId, final String filename, final String sha1Hash, final UrlProtocol protocol); From a98f91f05e5f067000545ddc414e9a7d9d97e8aa Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Mon, 4 Apr 2016 12:54:30 +0200 Subject: [PATCH 21/31] Fixed typos --- examples/hawkbit-mgmt-api-client/README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/examples/hawkbit-mgmt-api-client/README.md b/examples/hawkbit-mgmt-api-client/README.md index eff301e20..ac8e7a4cd 100644 --- a/examples/hawkbit-mgmt-api-client/README.md +++ b/examples/hawkbit-mgmt-api-client/README.md @@ -1,4 +1,4 @@ -# HawkBit management API example +# hawkBit Management API example client Example client that shows how to efficiently use the hawkBit management API. @@ -36,4 +36,3 @@ In rollout mode: * assigning software modules to distribution sets * creating a rollout * starting a rollout - From 87661624ba0f57edf3f3e513624b3a59a7eb78d0 Mon Sep 17 00:00:00 2001 From: Jonathan Philip Knoblauch Date: Mon, 4 Apr 2016 18:02:43 +0200 Subject: [PATCH 22/31] Refactoring after review - added new method to HawkbitCommenUtil to reduce duplicated code - added early return Signed-off-by: Jonathan Philip Knoblauch --- .../targettable/BulkUploadHandler.java | 14 ++++---- .../ui/rollout/rollout/RolloutListGrid.java | 6 +--- .../rolloutgroup/RolloutGroupListGrid.java | 36 +++++++++---------- .../RolloutGroupTargetsListGrid.java | 6 +--- .../hawkbit/ui/utils/HawkbitCommonUtil.java | 26 +++++++++++--- 5 files changed, 46 insertions(+), 42 deletions(-) diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java index 1a388c324..d52537a92 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java @@ -325,14 +325,14 @@ public class BulkUploadHandler extends CustomComponent tagData.getName()); } } - if (!deletedTags.isEmpty()) { - if (deletedTags.size() == 1) { - return i18n.get("message.bulk.upload.tag.assignment.failed", deletedTags.get(0)); - } else { - return i18n.get("message.bulk.upload.tag.assignments.failed"); - } + if (deletedTags.isEmpty()) { + return null; + } + if (deletedTags.size() == 1) { + return i18n.get("message.bulk.upload.tag.assignment.failed", deletedTags.get(0)); + } else { + return i18n.get("message.bulk.upload.tag.assignments.failed"); } - return null; } private boolean ifTagsSelected() { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java index d60d72527..f17a93b56 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java @@ -549,11 +549,7 @@ public class RolloutListGrid extends AbstractGrid { private String convertRolloutStatusToString(final RolloutStatus value) { final StatusFontIcon statusFontIcon = statusIconMap.get(value); - if (statusFontIcon == null) { - return null; - } - final String codePoint = statusFontIcon.getFontIcon() != null - ? Integer.toString(statusFontIcon.getFontIcon().getCodepoint()) : null; + final String codePoint = HawkbitCommonUtil.getCodePoint(statusFontIcon); return HawkbitCommonUtil.getStatusLabelDetailsInString(codePoint, statusFontIcon.getStyle(), SPUIComponetIdProvider.ROLLOUT_STATUS_LABEL_ID); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java index bb4adfe4a..a87bcc525 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java @@ -218,7 +218,7 @@ public class RolloutGroupListGrid extends AbstractGrid { @Override protected void setColumnProperties() { - List columnList = new ArrayList<>(); + final List columnList = new ArrayList<>(); columnList.add(SPUILabelDefinitions.VAR_NAME); columnList.add(SPUILabelDefinitions.VAR_STATUS); columnList.add(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS); @@ -240,7 +240,7 @@ public class RolloutGroupListGrid extends AbstractGrid { createRolloutGroupStatusToFontMap(); getColumn(SPUILabelDefinitions.VAR_STATUS).setRenderer(new HtmlLabelRenderer(), new RolloutGroupStatusConverter()); - + getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS).setRenderer(new HtmlRenderer(), new TotalTargetCountStatusConverter()); if (permissionChecker.hasRolloutTargetsReadPermission()) { @@ -251,13 +251,13 @@ public class RolloutGroupListGrid extends AbstractGrid { @Override protected void setHiddenColumns() { - List columnsToBeHidden = new ArrayList<>(); + final List columnsToBeHidden = new ArrayList<>(); columnsToBeHidden.add(SPUILabelDefinitions.VAR_CREATED_DATE); columnsToBeHidden.add(SPUILabelDefinitions.VAR_CREATED_USER); columnsToBeHidden.add(SPUILabelDefinitions.VAR_MODIFIED_DATE); columnsToBeHidden.add(SPUILabelDefinitions.VAR_MODIFIED_BY); columnsToBeHidden.add(SPUILabelDefinitions.VAR_DESC); - for (Object propertyId : columnsToBeHidden) { + for (final Object propertyId : columnsToBeHidden) { getColumn(propertyId).setHidden(true); } } @@ -267,14 +267,12 @@ public class RolloutGroupListGrid extends AbstractGrid { return cell -> getDescription(cell); } - private void onClickOfRolloutGroupName(RendererClickEvent event) { + private void onClickOfRolloutGroupName(final RendererClickEvent event) { rolloutUIState .setRolloutGroup(rolloutGroupManagement.findRolloutGroupWithDetailedStatus((Long) event.getItemId())); eventBus.publish(this, RolloutEvent.SHOW_ROLLOUT_GROUP_TARGETS); } - - private void createRolloutGroupStatusToFontMap() { statusIconMap.put(RolloutGroupStatus.FINISHED, new StatusFontIcon(FontAwesome.CHECK_CIRCLE, SPUIStyleDefinitions.STATUS_ICON_GREEN)); @@ -288,7 +286,7 @@ public class RolloutGroupListGrid extends AbstractGrid { new StatusFontIcon(FontAwesome.EXCLAMATION_CIRCLE, SPUIStyleDefinitions.STATUS_ICON_RED)); } - private String getDescription(CellReference cell) { + private String getDescription(final CellReference cell) { if (SPUILabelDefinitions.VAR_STATUS.equals(cell.getPropertyId())) { return cell.getProperty().getValue().toString().toLowerCase(); } else if (SPUILabelDefinitions.ACTION.equals(cell.getPropertyId())) { @@ -308,7 +306,7 @@ public class RolloutGroupListGrid extends AbstractGrid { @Override public String getStyle(final CellReference cellReference) { - String[] coulmnNames = { SPUILabelDefinitions.VAR_STATUS, + final String[] coulmnNames = { SPUILabelDefinitions.VAR_STATUS, SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS }; if (Arrays.asList(coulmnNames).contains(cellReference.getPropertyId())) { return "centeralign"; @@ -329,14 +327,16 @@ public class RolloutGroupListGrid extends AbstractGrid { private static final long serialVersionUID = -9205943894818450807L; @Override - public TotalTargetCountStatus convertToModel(String value, Class targetType, - Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException { + public TotalTargetCountStatus convertToModel(final String value, + final Class targetType, final Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { return null; } @Override - public String convertToPresentation(TotalTargetCountStatus value, Class targetType, - Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException { + public String convertToPresentation(final TotalTargetCountStatus value, + final Class targetType, final Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { return DistributionBarHelper.getDistributionBarAsHTMLString(value.getStatusTotalCountMap()); } @@ -381,14 +381,10 @@ public class RolloutGroupListGrid extends AbstractGrid { public Class getPresentationType() { return String.class; } - + private String convertRolloutGroupStatusToString(final RolloutGroupStatus value) { - StatusFontIcon statusFontIcon = statusIconMap.get(value); - if (statusFontIcon == null) { - return null; - } - String codePoint = statusFontIcon.getFontIcon() != null - ? Integer.toString(statusFontIcon.getFontIcon().getCodepoint()) : null; + final StatusFontIcon statusFontIcon = statusIconMap.get(value); + final String codePoint = HawkbitCommonUtil.getCodePoint(statusFontIcon); return HawkbitCommonUtil.getStatusLabelDetailsInString(codePoint, statusFontIcon.getStyle(), SPUIComponetIdProvider.ROLLOUT_GROUP_STATUS_LABEL_ID); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsListGrid.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsListGrid.java index 0099dfc95..0a1446169 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsListGrid.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsListGrid.java @@ -238,11 +238,7 @@ public class RolloutGroupTargetsListGrid extends AbstractGrid { private String processActionStatus(final Status status) { final StatusFontIcon statusFontIcon = statusIconMap.get(status); - if (statusFontIcon == null) { - return null; - } - final String codePoint = statusFontIcon.getFontIcon() != null - ? Integer.toString(statusFontIcon.getFontIcon().getCodepoint()) : null; + final String codePoint = HawkbitCommonUtil.getCodePoint(statusFontIcon); return HawkbitCommonUtil.getStatusLabelDetailsInString(codePoint, statusFontIcon.getStyle(), null); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java index e697e220e..a8c66a2a8 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java @@ -37,6 +37,7 @@ import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus; import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus.Status; import org.eclipse.hawkbit.ui.management.dstable.DistributionTable; import org.eclipse.hawkbit.ui.management.targettable.TargetTable; +import org.eclipse.hawkbit.ui.rollout.StatusFontIcon; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.userdetails.UserDetails; @@ -1359,12 +1360,12 @@ public final class HawkbitCommonUtil { * details of status and count * @return String */ - public static String getFormattedString(Map details) { - StringBuilder val = new StringBuilder(); + public static String getFormattedString(final Map details) { + final StringBuilder val = new StringBuilder(); if (details == null || details.isEmpty()) { return null; } - for (Entry entry : details.entrySet()) { + for (final Entry entry : details.entrySet()) { val.append(entry.getKey()).append(":").append(entry.getValue()).append(","); } return val.substring(0, val.length() - 1); @@ -1382,8 +1383,8 @@ public final class HawkbitCommonUtil { * label id * @return */ - public static String getStatusLabelDetailsInString(String value, String style, String id) { - StringBuilder val = new StringBuilder(); + public static String getStatusLabelDetailsInString(final String value, final String style, final String id) { + final StringBuilder val = new StringBuilder(); if (!Strings.isNullOrEmpty(value)) { val.append("value:").append(value).append(","); } @@ -1394,4 +1395,19 @@ public final class HawkbitCommonUtil { return val.toString(); } + /** + * Receive the code point of a given StatusFontIcon. + * + * @param statusFontIcon + * the status font icon + * @return the code point of the StatusFontIcon + */ + public static String getCodePoint(final StatusFontIcon statusFontIcon) { + if (statusFontIcon == null) { + return null; + } + return statusFontIcon.getFontIcon() != null ? Integer.toString(statusFontIcon.getFontIcon().getCodepoint()) + : null; + } + } From 16fff8db979f7052e4a070248eb19fe2084b25b6 Mon Sep 17 00:00:00 2001 From: Jonathan Philip Knoblauch Date: Tue, 5 Apr 2016 10:50:31 +0200 Subject: [PATCH 23/31] Refactoring after review - removed else when not needed - return the if statement directly in the isDirectory method Signed-off-by: Jonathan Philip Knoblauch --- .../hawkbit/ui/artifacts/upload/UploadLayout.java | 5 +---- .../ui/management/targettable/BulkUploadHandler.java | 10 ++++------ .../RolloutGroupTargetsListGrid.java | 8 ++++---- 3 files changed, 9 insertions(+), 14 deletions(-) diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadLayout.java index 3fb735284..7376cce13 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadLayout.java @@ -222,10 +222,7 @@ public class UploadLayout extends VerticalLayout { } private boolean isDirectory(final Html5File file) { - if (Strings.isNullOrEmpty(file.getType()) && file.getFileSize() % 4096 == 0) { - return true; - } - return false; + return Strings.isNullOrEmpty(file.getType()) && file.getFileSize() % 4096 == 0; } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java index d52537a92..2369893c7 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java @@ -306,11 +306,10 @@ public class BulkUploadHandler extends CustomComponent final DistributionSetIdName dsSelected = (DistributionSetIdName) comboBox.getValue(); if (distributionSetManagement.findDistributionSetById(dsSelected.getId()) == null) { return i18n.get("message.bulk.upload.assignment.failed"); - } else { - deploymentManagement.assignDistributionSet(targetBulkUpload.getDsNameAndVersion().getId(), actionType, - forcedTimeStamp, targetsList.toArray(new String[targetsList.size()])); - return null; } + deploymentManagement.assignDistributionSet(targetBulkUpload.getDsNameAndVersion().getId(), actionType, + forcedTimeStamp, targetsList.toArray(new String[targetsList.size()])); + return null; } private String tagAssignment() { @@ -330,9 +329,8 @@ public class BulkUploadHandler extends CustomComponent } if (deletedTags.size() == 1) { return i18n.get("message.bulk.upload.tag.assignment.failed", deletedTags.get(0)); - } else { - return i18n.get("message.bulk.upload.tag.assignments.failed"); } + return i18n.get("message.bulk.upload.tag.assignments.failed"); } private boolean ifTagsSelected() { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsListGrid.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsListGrid.java index 0a1446169..fe17b3cba 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsListGrid.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsListGrid.java @@ -248,13 +248,13 @@ public class RolloutGroupTargetsListGrid extends AbstractGrid { if (rolloutGroup != null && rolloutGroup.getStatus() == RolloutGroupStatus.READY) { return HawkbitCommonUtil.getStatusLabelDetailsInString( Integer.toString(FontAwesome.DOT_CIRCLE_O.getCodepoint()), "statusIconLightBlue", null); - } else if (rolloutGroup != null && rolloutGroup.getStatus() == RolloutGroupStatus.FINISHED) { + } + if (rolloutGroup != null && rolloutGroup.getStatus() == RolloutGroupStatus.FINISHED) { return HawkbitCommonUtil.getStatusLabelDetailsInString( Integer.toString(FontAwesome.MINUS_CIRCLE.getCodepoint()), "statusIconBlue", null); - } else { - return HawkbitCommonUtil.getStatusLabelDetailsInString( - Integer.toString(FontAwesome.QUESTION_CIRCLE.getCodepoint()), "statusIconBlue", null); } + return HawkbitCommonUtil.getStatusLabelDetailsInString( + Integer.toString(FontAwesome.QUESTION_CIRCLE.getCodepoint()), "statusIconBlue", null); } } From 421bd9154ca545ace4e47fce05b4215ec7c12218 Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Tue, 5 Apr 2016 12:13:36 +0200 Subject: [PATCH 24/31] fix license header of UrlProtocol enum --- .../src/main/java/org/eclipse/hawkbit/api/UrlProtocol.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/UrlProtocol.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/UrlProtocol.java index 4dd84b7da..77c23ad0d 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/UrlProtocol.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/UrlProtocol.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.api; From 9c9bdf640650ef4108234551f2032c09cf427e1a Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Tue, 5 Apr 2016 12:20:49 +0200 Subject: [PATCH 25/31] fix json creator for PagedList for creating clients Signed-off-by: Michael Hirsch --- .../hawkbit/rest/resource/model/PagedList.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/PagedList.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/PagedList.java index 880ee0c16..757a6106e 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/PagedList.java +++ b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/PagedList.java @@ -14,9 +14,11 @@ import javax.validation.constraints.NotNull; import org.springframework.hateoas.ResourceSupport; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; /** * A list representation with meta data for pagination, e.g. containing the @@ -31,7 +33,9 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; @JsonInclude(Include.NON_NULL) public class PagedList extends ResourceSupport { + @JsonProperty private final List content; + @JsonProperty private final long totalElements; private final int size; @@ -41,14 +45,16 @@ public class PagedList extends ResourceSupport { * * @param content * the actual content of the list - * @param total + * @param totalElements * the total amount of elements * @throws NullPointerException * in case {@code content} is {@code null}. */ - public PagedList(@NotNull final List content, final long total) { + @JsonCreator + public PagedList(@JsonProperty("content") @NotNull final List content, + @JsonProperty("totalElements") final long totalElements) { this.size = content.size(); - this.totalElements = total; + this.totalElements = totalElements; this.content = content; } From bf168ffb706ec6ca9d438b283796073473d7ef29 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Tue, 5 Apr 2016 14:00:57 +0200 Subject: [PATCH 26/31] reduced duplicate code. --- .../model/DistributionSetMetadata.java | 52 ++-------- .../hawkbit/repository/model/MetaData.java | 98 +++++++++++++++++++ .../model/SoftwareModuleMetadata.java | 53 ++-------- 3 files changed, 111 insertions(+), 92 deletions(-) create mode 100644 hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/MetaData.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetMetadata.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetMetadata.java index 7b2e637b9..28afd5517 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetMetadata.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetMetadata.java @@ -8,10 +8,6 @@ */ package org.eclipse.hawkbit.repository.model; -import java.io.Serializable; - -import javax.persistence.Basic; -import javax.persistence.Column; import javax.persistence.ConstraintMode; import javax.persistence.Entity; import javax.persistence.FetchType; @@ -29,24 +25,16 @@ import javax.persistence.Table; @IdClass(DsMetadataCompositeKey.class) @Entity @Table(name = "sp_ds_metadata") -public class DistributionSetMetadata implements Serializable { +public class DistributionSetMetadata extends MetaData { private static final long serialVersionUID = 1L; - @Id - @Column(name = "meta_key", length = 128) - private String key; - - @Column(name = "meta_value", length = 4000) - @Basic - private String value; - @Id @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ds_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_metadata_ds")) private DistributionSet distributionSet; public DistributionSetMetadata() { - // Default constructor for JPA. + super(); } /** @@ -57,35 +45,18 @@ public class DistributionSetMetadata implements Serializable { * @param value */ public DistributionSetMetadata(final String key, final DistributionSet distributionSet, final String value) { - this.key = key; + super(key, value); this.distributionSet = distributionSet; - this.value = value; } public DsMetadataCompositeKey getId() { - return new DsMetadataCompositeKey(distributionSet, key); - } - - public String getKey() { - return key; - } - - public void setKey(final String key) { - this.key = key; + return new DsMetadataCompositeKey(distributionSet, getKey()); } public void setDistributionSet(final DistributionSet distributionSet) { this.distributionSet = distributionSet; } - public String getValue() { - return value; - } - - public void setValue(final String value) { - this.value = value; - } - public DistributionSet getDistributionSet() { return distributionSet; } @@ -93,9 +64,8 @@ public class DistributionSetMetadata implements Serializable { @Override public int hashCode() { final int prime = 31; - int result = 1; - result = prime * result + (distributionSet == null ? 0 : distributionSet.hashCode()); - result = prime * result + (key == null ? 0 : key.hashCode()); + int result = super.hashCode(); + result = prime * result + ((distributionSet == null) ? 0 : distributionSet.hashCode()); return result; } @@ -104,7 +74,7 @@ public class DistributionSetMetadata implements Serializable { if (this == obj) { return true; } - if (obj == null) { + if (!super.equals(obj)) { return false; } if (!(obj instanceof DistributionSetMetadata)) { @@ -118,14 +88,6 @@ public class DistributionSetMetadata implements Serializable { } else if (!distributionSet.equals(other.distributionSet)) { return false; } - if (key == null) { - if (other.key != null) { - return false; - } - } else if (!key.equals(other.key)) { - return false; - } return true; } - } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/MetaData.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/MetaData.java new file mode 100644 index 000000000..97ffacdcc --- /dev/null +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/MetaData.java @@ -0,0 +1,98 @@ +/** + * 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.repository.model; + +import java.io.Serializable; + +import javax.persistence.Basic; +import javax.persistence.Column; +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; + +/** + * Meta data for entities. + * + */ +@MappedSuperclass +public abstract class MetaData implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @Column(name = "meta_key", length = 128) + private String key; + + @Column(name = "meta_value", length = 4000) + @Basic + private String value; + + public MetaData(final String key, final String value) { + super(); + this.key = key; + this.value = value; + } + + public MetaData() { + // Default constructor needed for JPA entities + } + + public String getKey() { + return key; + } + + public void setKey(final String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(final String value) { + this.value = value; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((key == null) ? 0 : key.hashCode()); + result = prime * result + ((value == null) ? 0 : value.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof MetaData)) { + return false; + } + final MetaData other = (MetaData) obj; + if (key == null) { + if (other.key != null) { + return false; + } + } else if (!key.equals(other.key)) { + return false; + } + if (value == null) { + if (other.value != null) { + return false; + } + } else if (!value.equals(other.value)) { + return false; + } + return true; + } + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleMetadata.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleMetadata.java index c7af1f2ae..8783fec96 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleMetadata.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleMetadata.java @@ -8,9 +8,6 @@ */ package org.eclipse.hawkbit.repository.model; -import java.io.Serializable; - -import javax.persistence.Column; import javax.persistence.ConstraintMode; import javax.persistence.Entity; import javax.persistence.FetchType; @@ -28,16 +25,9 @@ import javax.persistence.Table; @IdClass(SwMetadataCompositeKey.class) @Entity @Table(name = "sp_sw_metadata") -public class SoftwareModuleMetadata implements Serializable { +public class SoftwareModuleMetadata extends MetaData { private static final long serialVersionUID = 1L; - @Id - @Column(name = "meta_key", length = 128) - private String key; - - @Column(name = "meta_value", length = 4000) - private String value; - @Id @ManyToOne(targetEntity = SoftwareModule.class, fetch = FetchType.LAZY) @JoinColumn(name = "sw_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_metadata_sw")) @@ -47,7 +37,7 @@ public class SoftwareModuleMetadata implements Serializable { * Default constructor for JPA. */ public SoftwareModuleMetadata() { - // default constructor for JPA. + super(); } /** @@ -60,21 +50,12 @@ public class SoftwareModuleMetadata implements Serializable { * of the meta data element */ public SoftwareModuleMetadata(final String key, final SoftwareModule softwareModule, final String value) { - this.key = key; + super(key, value); this.softwareModule = softwareModule; - this.value = value; } public SwMetadataCompositeKey getId() { - return new SwMetadataCompositeKey(softwareModule, key); - } - - public String getValue() { - return value; - } - - public void setValue(final String value) { - this.value = value; + return new SwMetadataCompositeKey(softwareModule, getKey()); } public SoftwareModule getSoftwareModule() { @@ -85,24 +66,10 @@ public class SoftwareModuleMetadata implements Serializable { this.softwareModule = softwareModule; } - public String getKey() { - return key; - } - - public void setKey(final String key) { - this.key = key; - } - - @Override - public String toString() { - return "SoftwareModuleMetadata [key=" + key + ", value=" + value + ", softwareModule=" + softwareModule + "]"; - } - @Override public int hashCode() { final int prime = 31; - int result = 1; - result = prime * result + ((key == null) ? 0 : key.hashCode()); + int result = super.hashCode(); result = prime * result + ((softwareModule == null) ? 0 : softwareModule.hashCode()); return result; } @@ -112,20 +79,13 @@ public class SoftwareModuleMetadata implements Serializable { if (this == obj) { return true; } - if (obj == null) { + if (!super.equals(obj)) { return false; } if (!(obj instanceof SoftwareModuleMetadata)) { return false; } final SoftwareModuleMetadata other = (SoftwareModuleMetadata) obj; - if (key == null) { - if (other.key != null) { - return false; - } - } else if (!key.equals(other.key)) { - return false; - } if (softwareModule == null) { if (other.softwareModule != null) { return false; @@ -135,5 +95,4 @@ public class SoftwareModuleMetadata implements Serializable { } return true; } - } From d8268e8b6bd0b8d6091a566afde4e8b53c96747f Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Tue, 5 Apr 2016 14:01:09 +0200 Subject: [PATCH 27/31] Used proper exception --- .../java/org/eclipse/hawkbit/simulator/SimulatorStartup.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatorStartup.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatorStartup.java index faff1cc6c..60f3055bd 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatorStartup.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatorStartup.java @@ -8,6 +8,7 @@ */ package org.eclipse.hawkbit.simulator; +import java.net.MalformedURLException; import java.net.URL; import org.eclipse.hawkbit.simulator.amqp.SpSenderService; @@ -47,7 +48,7 @@ public class SimulatorStartup implements ApplicationListener Date: Tue, 5 Apr 2016 14:42:00 +0200 Subject: [PATCH 28/31] fix license header in pom.xml Signed-off-by: Michael Hirsch --- hawkbit-security-integration/pom.xml | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/hawkbit-security-integration/pom.xml b/hawkbit-security-integration/pom.xml index 591552997..c17317b3d 100644 --- a/hawkbit-security-integration/pom.xml +++ b/hawkbit-security-integration/pom.xml @@ -1,6 +1,13 @@ - + 4.0.0 From 39fc74469f513f879d4e836aee7592cf3d19289e Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Tue, 5 Apr 2016 15:02:55 +0200 Subject: [PATCH 29/31] fix paged list json. Signed-off-by: Michael Hirsch --- .../hawkbit/rest/resource/model/PagedList.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/PagedList.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/PagedList.java index 757a6106e..9d5cc458c 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/PagedList.java +++ b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/PagedList.java @@ -36,7 +36,7 @@ public class PagedList extends ResourceSupport { @JsonProperty private final List content; @JsonProperty - private final long totalElements; + private final long total; private final int size; /** @@ -45,16 +45,15 @@ public class PagedList extends ResourceSupport { * * @param content * the actual content of the list - * @param totalElements + * @param total * the total amount of elements * @throws NullPointerException * in case {@code content} is {@code null}. */ @JsonCreator - public PagedList(@JsonProperty("content") @NotNull final List content, - @JsonProperty("totalElements") final long totalElements) { + public PagedList(@JsonProperty("content") @NotNull final List content, @JsonProperty("total") final long total) { this.size = content.size(); - this.totalElements = totalElements; + this.total = total; this.content = content; } @@ -69,7 +68,7 @@ public class PagedList extends ResourceSupport { * @return the total amount of elements */ public long getTotal() { - return totalElements; + return total; } public List getContent() { From 4884f18deb35403dec062619f4a0fdb259e982be Mon Sep 17 00:00:00 2001 From: Michael Hirsch Date: Tue, 5 Apr 2016 19:06:14 +0200 Subject: [PATCH 30/31] remove local variable which is never read only returned Signed-off-by: Michael Hirsch --- .../hawkbit/amqp/AmqpMessageHandlerService.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 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 c5fff29ad..41e70f91f 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 @@ -214,19 +214,18 @@ public class AmqpMessageHandlerService extends BaseAmqpService { } private LocalArtifact findLocalArtifactByFileResource(final FileResource fileResource) { - LocalArtifact localArtifact = null; if (fileResource.getSha1() != null) { - localArtifact = artifactManagement.findFirstLocalArtifactsBySHA1(fileResource.getSha1()); + return artifactManagement.findFirstLocalArtifactsBySHA1(fileResource.getSha1()); } else if (fileResource.getFilename() != null) { - localArtifact = artifactManagement.findLocalArtifactByFilename(fileResource.getFilename()).stream() - .findFirst().orElse(null); + return artifactManagement.findLocalArtifactByFilename(fileResource.getFilename()).stream().findFirst() + .orElse(null); } else if (fileResource.getSoftwareModuleFilenameResource() != null) { - localArtifact = artifactManagement + return artifactManagement .findByFilenameAndSoftwareModule(fileResource.getSoftwareModuleFilenameResource().getFilename(), fileResource.getSoftwareModuleFilenameResource().getSoftwareModuleId()) .stream().findFirst().orElse(null); } - return localArtifact; + return null; } private static Artifact convertDbArtifact(final DbArtifact dbArtifact) { From f4f9c10186a0763d9ecd35b8c9a53f7654d9aa89 Mon Sep 17 00:00:00 2001 From: Kai Zimmermann Date: Wed, 6 Apr 2016 10:57:23 +0200 Subject: [PATCH 31/31] Optimized equals. Signed-off-by: Kai Zimmermann --- .../model/DistributionSetMetadata.java | 15 +------------- .../hawkbit/repository/model/MetaData.java | 2 +- .../model/SoftwareModuleMetadata.java | 20 +------------------ 3 files changed, 3 insertions(+), 34 deletions(-) diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetMetadata.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetMetadata.java index 28afd5517..67a99506c 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetMetadata.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetMetadata.java @@ -34,16 +34,9 @@ public class DistributionSetMetadata extends MetaData { private DistributionSet distributionSet; public DistributionSetMetadata() { - super(); + // default public constructor for JPA } - /** - * Parameter constructor. - * - * @param key - * @param distributionSet - * @param value - */ public DistributionSetMetadata(final String key, final DistributionSet distributionSet, final String value) { super(key, value); this.distributionSet = distributionSet; @@ -71,15 +64,9 @@ public class DistributionSetMetadata extends MetaData { @Override public boolean equals(final Object obj) { - if (this == obj) { - return true; - } if (!super.equals(obj)) { return false; } - if (!(obj instanceof DistributionSetMetadata)) { - return false; - } final DistributionSetMetadata other = (DistributionSetMetadata) obj; if (distributionSet == null) { if (other.distributionSet != null) { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/MetaData.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/MetaData.java index 97ffacdcc..c41a0e8c9 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/MetaData.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/MetaData.java @@ -74,7 +74,7 @@ public abstract class MetaData implements Serializable { if (obj == null) { return false; } - if (!(obj instanceof MetaData)) { + if (!(this.getClass().isInstance(obj))) { return false; } final MetaData other = (MetaData) obj; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleMetadata.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleMetadata.java index 8783fec96..5ddd273d3 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleMetadata.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleMetadata.java @@ -33,22 +33,10 @@ public class SoftwareModuleMetadata extends MetaData { @JoinColumn(name = "sw_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_metadata_sw")) private SoftwareModule softwareModule; - /** - * Default constructor for JPA. - */ public SoftwareModuleMetadata() { - super(); + // default public constructor for JPA } - /** - * Standard constructor. - * - * @param key - * of the meta data element - * @param softwareModule - * @param value - * of the meta data element - */ public SoftwareModuleMetadata(final String key, final SoftwareModule softwareModule, final String value) { super(key, value); this.softwareModule = softwareModule; @@ -76,15 +64,9 @@ public class SoftwareModuleMetadata extends MetaData { @Override public boolean equals(final Object obj) { - if (this == obj) { - return true; - } if (!super.equals(obj)) { return false; } - if (!(obj instanceof SoftwareModuleMetadata)) { - return false; - } final SoftwareModuleMetadata other = (SoftwareModuleMetadata) obj; if (softwareModule == null) { if (other.softwareModule != null) {